因此,我创建了一个模拟石头,纸,剪刀游戏的代码。当我第一次打开程序时,它可以工作!从一开始就新鲜,它有效。
问题是当第二次运行时。由于某种原因,我的“ while”不再起作用。当任何玩家达到3胜时,while循环都应停止。您可以看到我达到了17胜13胜,而且事情并没有停止……
这仅在程序的首次运行后发生。
代码:
###########function of the random module
import random
###########possible options of play and the number of single wins to win the match
options = ["stone", "paper", "scissors"]
win_the_game = 3
############function that randomly returns one of the 3 options
def machine_play(a):
return(random.choice(a))
############function that asks your choice: 'stone', 'paper' or 'scissors'
def user_play():
a = input("Enter your choice: ")
if a not in options:
print("Not a valid option, try again ('stone', 'paper', 'scissors')")
while a not in options:
a = input("Enter your choice: ")
if a not in options:
print("Not a valid option, try again ('stone', 'paper', 'scissors')")
return a
############function that resolves a combat
def combat(mchoice,uchoice):
if mchoice == uchoice:
return 0
elif uchoice == "stone":
if mchoice == "scissors":
return 2
else:
return 1
elif uchoice == "paper":
if mchoice == "stone":
return 2
else:
return 1
elif uchoice == "scissors":
if mchoice == "paper":
return 2
else:
return 1
############variables that accumulate the wins of each participant
machine_wins = 0
user_wins = 0
####################### The final loop or program ######################
while machine_wins or user_wins < win_the_game:
user_choice = user_play()
machine_choice = random.choice(options)
print("The machine choice is: ", machine_choice)
the_game = combat(machine_choice, user_choice)
if the_game == 1:
machine_wins += 1
elif the_game == 2:
user_wins += 1
else:
print("Its a tie!! continue")
print("\nUser wins: ", user_wins, "\nMachine wins: ", machine_wins)
答案 0 :(得分:4)
while machine_wins or user_wins < win_the_game:
此解析为
while machine_wins or (user_wins < win_the_game):
只要machine_wins是“真实的”(即肯定的),游戏就会永远持续下去。我相信您需要的是
while machine_wins < win_the_game and \
user_wins < win_the_game: