我正在创建一个游戏,我有一些函数可以接受参数并返回一个值。我想检查游戏是否已经结束。游戏结束的时间是 bins = [0, 0, 0, 0, 0]
. 我已经尝试了所有的方法,但不能让gameIsOver在主函数中为真。我到底做错了什么?
bins = [7, 7, 7, 7, 7]
gameIsOver = False
def checkGameEnd(listOfBins):
if listOfBins[0] == 0 and listOfBins[1] == 0 and listOfBins[2] == 0 and listOfBins[3] == 0 and listOfBins[4] == 0:
gameDidEnd = True
return True
else:
gameDidEnd = False
return False
def _main_():
print(displayGame(bins))
checkGameEnd(bins)
player_1 = "Player 1"
player_2 = "Player 2"
while didEndGame == False:
turnPlayer1_bin = int(input(player_1 + ", which bin do you want to remove matches from?\t"))
turnPlayer1_matches = int(input(player_1 + ", how many matches will you remove from bin " + str(turnPlayer1_bin) + "?\t"))
removeMatches(turnPlayer1_bin, turnPlayer1_matches, bins)
print(displayGame(bins))
checkGameEnd(bins)
if didEndGame == True:
print(player_2 + ", you win!")
turnPlayer2_bin = int(input(player_2 + ", which bin do you want to remove matches from?\t"))
turnPlayer2_matches = int(input(player_2 + ", how many matches will you remove from bin " + str(turnPlayer2_bin) + "?\t"))
removeMatches(turnPlayer2_bin, turnPlayer2_matches, bins)
print(displayGame(bins))
checkGameEnd(bins)
if didEndGame == True:
print(player_1 + ", you win!")
_main_()
你的 didEndGame
变量没有更新。你必须把它分配给检查函数。
didEndGame = checkGameEnd(bins)
checkGameEnd(bins)
可以返回 True
但你没有把它分配给 didEndGame
. 而且你也不用打 didEndGame == False
或 True
. 用下面的代码片段改变你的while循环。
while not didEndGame:
turnPlayer1_bin = int(input(player_1 + ", which bin do you want to remove matches from?\t"))
turnPlayer1_matches = int(input(player_1 + ", how many matches will you remove from bin " + str(turnPlayer1_bin) + "?\t"))
removeMatches(turnPlayer1_bin, turnPlayer1_matches, bins)
print(displayGame(bins))
didEndGame = checkGameEnd(bins)
if didEndGame:
print(player_2 + ", you win!")
修正你的代码,创建一个工作版本
def checkGameEnd(bins):
return [0]*5 == bins # check for bins is all zeros
def displayGame(bins):
print('Bins:', *range(5))
print('Vals:', *bins)
def removeMatches(turnPlayer1_bin, turnPlayer1_matches, bins):
bins[turnPlayer1_bin] -= turnPlayer1_matches
def main():
# Initialize bins
bins = [7, 7, 7, 7, 7]
displayGame(bins)
player_1 = "Player 1"
player_2 = "Player 2"
while True:
turnPlayer1_bin = int(input(player_1 + ", which bin do you want to remove matches from?\t"))
turnPlayer1_matches = int(input(player_1 + ", how many matches will you remove from bin " + str(turnPlayer1_bin) + "?\t"))
removeMatches(turnPlayer1_bin, turnPlayer1_matches, bins)
displayGame(bins)
if checkGameEnd(bins):
print(player_2 + ", you win!")
break
turnPlayer2_bin = int(input(player_2 + ", which bin do you want to remove matches from?\t"))
turnPlayer2_matches = int(input(player_2 + ", how many matches will you remove from bin " + str(turnPlayer2_bin) + "?\t"))
removeMatches(turnPlayer2_bin, turnPlayer2_matches, bins)
displayGame(bins)
if checkGameEnd(bins):
print(player_1 + ", you win!")
break
main()