gpt4 book ai didi

python - Python 代码中石头、剪刀、布的问题

转载 作者:行者123 更新时间:2023-12-01 03:58:53 26 4
gpt4 key购买 nike

我正在使用python编写代码,我们被要求使用外部选项文件(石头、剪刀、布)创建一个石头、剪刀、布的游戏,如下所示:反对让代码使用任何用户输入。但是,由于某种原因,我的代码不起作用。当有人输入"is"时,它会打印“让我们现在玩吧”,但仅此而已。没有其他事情发生。

当用户提供"is"作为输入时,为什么游戏没有完成?

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()

最佳答案

请注意,在下面的第 5 行,您将 computer_input 设置为 sample() 的结果:

def main():
a = []
infile = open("input2.txt", "r")
for line in infile:
a.append(line)
computer_input = sample()

但是几行之后,您将其设置为 "":

    user_input = ""
computer_input = ""

您的 while 循环正在检查 computer_input 的值,但它假设它将是一个数字。它没有处理空字符串的情况。我建议删除该行。

另请注意,您的 while 循环正在检查 user_input 的值,但您似乎从未真正将输入读取到该变量中。

关于python - Python 代码中石头、剪刀、布的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36949269/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com