我有一个数字游戏的代码,我看不出我做错了什么,但每当我运行它告诉我,我太低,无论我选择什么数字。有人能告诉我我做错了什么吗?谢谢!另外,我知道有些部分可能是多余的,但我不知道它们是否真的停止了代码的工作。你知道吗
import random
print("Welcome, to the worst game you will ever play. For some reason, you've got to pick a number between 1 and 10. "
"Pick 11, I dare you.")
print("The aim is to win with the lowest possible score.")
score = 0
player_attempts = 0
play = True
while play:
computer_number = random.randint(1, 11)
player_number = int(input("OK. What do you think the number is?"))
player_number = int(player_number)
while player_number != computer_number:
if player_number == computer_number and player_attempts == 0:
print("Wow. You actually did it. And it only took you " +
str(player_attempts) + "try. I'm impressed. I thought you were just one of those weirdos who "
"downloads a dodgy free game to escape from society...")
score += 1
player_attempts += 1
print("Your score is " + str(score) + ". Maybe. I could be lying. How would you know?")
play = False
elif int(player_number) == int(computer_number) and int(player_attempts) >= 0:
print("Wow. You actually did it. And it only took you " + str(player_attempts) +
"tries. I'm impressed. I thought you were just one of those weirdos who "
"downloads a dodgy free game to escape from society...")
score += 1
player_attempts += 1
print("Your score was " + str(score) + ". Maybe. I could be lying. How would you know?")
play = False
elif int(player_number) > int(computer_number):
print("You overshot. But really, does it matter? You should stop, get out of the basement, enter society. "
"Or have another go.")
score += 1
player_attempts += 1
print("Your score is " + str(score) + ".")
again = str(input("Try again."))
if again == "no":
play = False
elif again == "yes":
play = True
elif int(player_number) < int(computer_number):
print("You were too low. Underachieving. Sound familiar?")
score += 1
player_attempts += 1
print("Your score is " + str(score) + ".")
again = str(input("Try again."))
if again == "no":
play = False
elif again == "yes":
play = True
elif int(player_number) == 11:
print("Wow. You really chose 11. You are actually more intelligent than I had originally thought...")
again = str(input("Try again."))
if again == "no":
play = False
elif again == "yes":
play = True
对于计算机来说,不可能产生真正的随机数。相反,我们使用一个名为seeding的方法将一个不断变化的值(如当前时间)输入到随机数生成器,这样它每次都返回不同的值。你知道吗
修改
while
循环以为random
生成器对象播种,如下所示:这应该用系统时间初始化
random
对象,这样每次执行代码都会产生一个不同的伪随机值。你知道吗我注意到一件事
因为前两个if语句永远不会执行,因为
while player_number != computer_number:
与前两个条件冲突。你知道吗您的代码结构如下所示
现在,如果你马上猜出这个数字,你就避开了内部的
while
循环,转到下一个计算机生成的随机数。但是如果你选择了一个不同于计算机的数字,你就进入了内部循环,你永远被困在那里,因为你不改变player_number
或computer_number
。解决方案是什么?去掉内环。这是完全没有必要的,因为您可以用if-elif构造检查这个条件。你知道吗另一方面,赋值变量
input()
已经是一个字符串变量,不需要用str(input()
转换它。如果您将带有int(input())
的输入转换成一个整数,那么您就不必在调用这个整数变量时反复进行这个整数转换。你知道吗相关问题 更多 >
编程相关推荐