我正在用python
编写一个代码,在这个代码中,我们被要求使用一个外部选项文件(石头、布、剪刀)来创建一个石头、布、剪刀的游戏,而不是让代码使用任何用户输入。但是,由于某些原因,我的代码不起作用。当有人输入“是”时,它会打印“让我们现在玩”,但仅此而已。没有别的事情发生。你知道吗
当用户提供“是”作为输入时,为什么游戏没有完成?你知道吗
from random import randrange
def sample():
computer_input = randrange(1,3)
return computer_input
def main():
a = []
infile = open("input2.txt", "r")
for line in infile:
a.append(line)
computer_input = sample()
tied = 0 #games tied
user_won = 0 #games won by user
comp_won = 0 #games won by computer
user_input = ""
computer_input = ""
print("Rules of the game...")
print("Would you like to turn up with a game of rock, paper, or scissors? ;) Yes or no? -->")
answer = input()
if (answer == "yes"):
play = True
print("Let us now play.")
## elif(answer == "no" or "No"):
## play = False
## print("Sorry. Maybe we can play next time ;)")
## else:
## play = False
## print("Please try again!")
## main()
while True:
if(computer_input == "1"):
if(user_input == a[0]):
tied = tied + 1
print("Game is tied!")
elif(user_input == a[1]):
user_won = user_won + 1
print("You won! Paper covers Rock")
elif(user_input == a[2]):
comp_won = comp_won + 1
print("You lost! Rocks knocks out scissors")
## else:
## print("Try again!")
elif (computer_input == "2"):
if (user_input == a[0]):
comp_won = comp_won + 1
print("You lost! Paper covers Rock")
elif(user_input == a[1]):
tied = tied + 1
print("Game is tied!")
elif(user_input == a[2]):
user_won = user_won + 1
print("You won! Scissors cuts Paper")
## else:
## print("Try again!")
else :
if(user_input == a[0]):
user_won = user_won + 1
print("You won! Rock knocks out scissors")
elif(user_input == a[1]):
comp_won = comp_won + 1
print("You lost! Scissors cuts Paper")
elif(user_input == a[2]):
tied = tied + 1
print("Game is tied!")
## else:
## print("Try again!")
##
##print("Game over")
##print("Statistics")
##print("Games tied -->", tied)
##print("Game won by comp -->", comp_won)
##print("Game won by user -->", user_won)
##
main()
这个代码有很多很多问题。你知道吗
每次定义或使用变量时,都应该对 为什么要这样定义,或者变量的用途到底是什么 将要完成。你知道吗
你有一个循环,这似乎表明你的意思超过 当您运行一次代码时要玩的游戏的一轮。 但是只有一个地方可以让电脑做出选择 一个数字1、2或3,它只出现一次。 (除此之外,正如已经指出的那样,您可以更改 计算机选择
""
甚至不读取一次数字。)在代码的逻辑中,没有明显的方法可以跳出循环。你知道吗
现在还不清楚你认为你应该读什么 用户的输入文件。将文件的内容放在数组
a
行中 一行一行,但你只看a[0]
,a[1]
,和a[2]
。 文件的前三行应该包含什么? 为什么只有三行?问是否user_input == a[0]
? (我有预感,你应该设置每个 舍入到a
的成员,而不是比较a
的成员。)(还请注意,您设置
user_input = ""
的时间更早,因此除非您阅读 将空字符串放入a
的条目中,表达式如下user_input == a[0]
将始终为false。)设置
play = True
有什么意义?(甚至设置play = False
在注释掉的代码中?)你从来没有做过 将读取play
的值。你知道吗在变量
tied
中保持计数有什么意义,user_won
和computer_won
?你也从来没有读过这些变量, 除非你设定了新的值。你知道吗如果你用非常清晰的语言编写一些较小的函数可能会有所帮助 目的、输入和输出。
sample()
函数很有前途,但是 其他一切都在main()
。 例如,考虑到计算机的选择和 玩家的选择,可能是一个函数。 通过编写这样一个函数,您可以从中删除几十行代码main()
中的循环,用一行代码替换它们。 当 循环中的代码块很短。你知道吗注意,在下面的第5行,您将
computer_input
设置为sample()
的结果:但几行之后,您将其设置为
""
:while循环正在检查
computer_input
的值,但它假定它是一个数字。它没有大小写来处理空字符串。我建议去掉那条线。你知道吗还要注意的是,while循环正在检查
user_input
的值,但您似乎从来没有实际读取该变量的输入。你知道吗相关问题 更多 >
编程相关推荐