我的Python程序有点小问题。它会玩石头布剪刀。代码非常大,所以我将把它缩短为一个示例程序,但是可以在https://github.com/Ph0enix0/doitall/blob/master/computerpungramming/rockpaperscissors.py上查看完整的代码
(count为已玩游戏的数量)
count = 0
user_wins = 0
comp_wins = 0
def game():
comp_answer = ['rock', 'paper', 'scissors']
user_answer = input('Rock, paper, or scissors?')
if user_answer = 'rock':
count += 1
if comp_answer = 'paper':
print('Paper! I win!)
comp_wins += 1
#The rest of the comparisons are here
while 1 == 1:
game()
如果我把变量放在game()中,它们每次都会重置。帮助?
发布于 2015-03-31 08:33:52
您需要在函数内部移动变量并定义scissors_wins
def game():
'''
The actual game code. The code randomly chooses
rock, paper, or scissors. Then, it checks if the user's choice
beats the computer's. If it does, the user wins, and vice versa.
'''
#User picks rock, paper, or scissors.
user_answer = input('Rock, paper, or scissors? ')
#Tell the code that the game is not finished. Used for while loops.
game_finished = False
count = 0
user_wins = 0
comp_wins = 0
scissors_wins = 0
您的游戏已经有一个循环,所以除非您在while 1 == 1
中执行某些操作,否则只需调用game()
是的,每次你调用函数的时候,变量都会被重置为0。
如果您希望win count在多次运行中保持不变,请在函数外部使用dict声明:
d = {"user":0,"comp":0,"scissor":0}
然后在每个游戏结束时更新:
d["user"] += user_wins
或者在函数中增加每个变量的计数,而不是使用变量。
而且,您似乎从未中断过循环,因此您的代码将无限循环。我想您还想不止一次要求用户输入,所以将user_answer = input('Rock, paper, or scissors? ')
移到循环中。
类似于以下内容:
d = {"user":0,"comp":0,"scissor":0}
D= {"user":0,"comp":0,"scissor":0}
def game():
'''
The actual game code. The code randomly chooses
rock, paper, or scissors. Then, it checks if the user's choice
beats the computer's. If it does, the user wins, and vice versa.
'''
#Tell the code that the game is not finished. Used for while loops.
game_finished = False
count = 0
user_wins = 0
comp_wins = 0
scissors_wins = 0
#Game isn't finished, so the code continues.
while not game_finished:
user_answer = input('Rock, paper, or scissors? ')
# update dict with totals when loop breaks
发布于 2015-03-31 08:34:26
game
函数不能更改外部变量(count
、user_wins
、comp_wins
)。让函数返回必要的值。
count = 0
user_wins = 0
comp_wins = 0
def game():
...
return count, user_wins, comp_wins
count, user_wins, comp_wins = game()
发布于 2015-03-31 08:33:12
你会想要改变
if comp_answer = 'paper':
至
if comp_answer == 'paper':
这可能就是抛出错误的原因。在检查if条件的任何其他地方将=更改为==。
https://stackoverflow.com/questions/29358616
复制相似问题