如何将deck(52(数组从Newgame函数传递到deckshuffle函数
FUNCTION newgame
'New game
RANDOMIZE TIMER
CALL cardsuit
'heart$ = CHR$(3): diamond$ = CHR$(4): club$ = CHR$(5): spade$ = CHR$(6)
quitgame = 0
DIM playercards(maxhand), dealercards(maxhand), deck(52)
END FUNCTION
FUNCTION deckshuffle
'first card
CALL carddeck(deck(1))
deck(1) = INT(RND * 52)
deckindex = 2
DO
DO
cardok = 1
newcard = INT(RND * 52)
FOR j = 1 TO (deckindex - 1) STEP 1
IF newcard = deck(j) THEN
cardok = 0
EXIT FOR
END IF
NEXT j
LOOP UNTIL cardok = 1
deck(deckindex) = newcard
deckindex = deckindex + 1
LOOP UNTIL deckindex > 52
deckindex = 1
PRINT "* * * DECK SHUFFLED * * *"
END FUNCTION
目前,当我尝试执行程序时,我收到"数组未定义"错误。
通过在调用 sub/function 参数时向 sub/function 参数添加括号来将数组传递给SUB
或FUNCTION
,如下所示deck()
:
DIM playercards(maxhand), dealercards(maxhand), deck(52)
CALL deckshuffle(deck())
END FUNCTION
SUB deckshuffle (deck())
...
我不完全确定PRINT deckshuffle(deck())
应该显示什么,所以我有理由确定你的意思是制作deckshuffle
和newgame
子,而不是函数。 毕竟,函数旨在返回值。 如果没有返回值,则应使用 sub
。此外,您的函数没有定义参数,这就是您可能会收到错误的原因:
FUNCTION newgame
' This is a function with 0 arguments.
...
END FUNCTION
SUB deckshuffle (deck())
' This is a subroutine with 1 argument:
' - an array of numbers named "deck"
...
END SUB
FUNCTION myATN (x)
' This is a function with 1 argument:
' - a number named "x"
myATN = ATN(x)
END FUNCTION
您还可以在主程序中使用DIM SHARED
(在任何子/函数之外(,并且不再需要担心子/函数参数:
DIM SHARED playercards(maxhand), dealercards(maxhand), deck(52)
...
CALL newgame
SUB newgame
...
END SUB
SUB deckshuffle
...
END SUB
下面是一个随机化一副纸牌的子例程:
' init deck
DIM deck(1 TO 54)
' store deck
FOR L = 1 TO 54
deck(L) = L
NEXT
' randomize deck
FOR L = 1 TO 20
X = INT(RND * 54 + 1)
Y = INT(RND * 54 + 1)
SWAP deck(X), deck(Y)
NEXT
' spades/hearts/diamonds/clubs
FOR L = 1 TO 54
X = deck(L)
SELECT CASE X
CASE 1 TO 13
M = X
S$ = "spades"
CASE 14 TO 26
M = X - 13
S$ = "hearts"
CASE 27 TO 39
M = X - 26
S$ = "diamonds"
CASE 40 TO 52
M = X - 39
S$ = "clubs"
CASE 53, 54
PRINT "Joker"
M = 0
END SELECT
SELECT CASE M
CASE 1 ' ace
PRINT "Ace of "; S$
CASE 2 TO 10 ' 2-10
PRINT M; " of "; S$
CASE 11 ' jack
PRINT "Jack of "; S$
CASE 12 ' queen
PRINT "Queen of "; S$
CASE 13 ' king
PRINT "King of "; S$
END SELECT
NEXT
END
下面是使用数组函数的示例甲板洗牌程序:
DIM deck(1 TO 54)
CONST ShuffleTimes = 10
FOR L = 1 TO 54
deck(L) = L
NEXT
CALL shuffle(deck())
FOR L = 1 TO 54
PRINT deck(L);
NEXT
END
SUB shuffle (deck())
FOR L = 1 TO ShuffleTimes
X = INT(RND * 54 + 1)
Y = INT(RND * 54 + 1)
SWAP deck(X), deck(Y)
NEXT
END SUB
您可以将数组作为参数传递,进行一些计算,值将反映在调用程序中
'main program
DIM arr(1 TO 10)
'initialize array
temp = test(arr())
'print the array
FOR i = 1 TO UBOUND(arr)
PRINT i
NEXT
END
'the function takes array as argument, then initializes 1 to 10
FUNCTION test (temp())
FOR i = 1 TO UBOUND(temp)
temp(i) = i 'set the array with the value of i
NEXT i
test = 0 'returning 0
END FUNCTION