我的Python数字猜谜游戏

时间:2016-07-08 10:29:18

标签: python

我一直在尝试为Python制作一个数字猜谜游戏,到目前为止,它已经完全相当不错。但是让我烦恼的是,它会在每次猜测时重置数字以使其不同,但我希望它保持不变,然后人们可以花一些时间猜测它。

import os
import time

print("this is a random number generator")
number1 =int(input("please pick a NUMBER between 1 and 99"))
from random import randint
number2 = int(randint(1,99))
if number1 == number2:
    print(" congrats! you got it right")
elif number1 < number2:
    print ("too low try again")
elif number1 > number2:
    print ("too high try again")

if number1 not in range(1,99):
    print("you idiot! Pick a number IN THE RANGE")

while number1 != number2:


    print("this is a random number generator")
    number1 =int(input("please pick a NUMBER between 1 and 99"))
    from random import randint
    number2 = int(randint(1,99))
    if number1 == number2:
        print(" congrats! you got it right")
    elif number1 < number2:
        print ("too low try again")
    elif number1 > number2:
        print ("too high try again")

    if number1 not in range(1,99):
        print("you idiot! Pick a number IN THE RANGE")



time.sleep(10)
os.system("exit")

3 个答案:

答案 0 :(得分:3)

由于number2 = int(randint(1,99))周期内有while,因此每次都会创建一个新号码。把那条线放在while之外,这个数字将保持不变,直到有人猜到它为止

答案 1 :(得分:2)

你的代码有很多问题:import语句应该在开头,并且有很多重复的代码,这使得它很难阅读。

您的问题来自于在number2 = int(randint(1,99))循环的每个周期调用while这一事实。

这可以改进为:

import os
import time
from random import randint

print("This is a random number generator")
number2 = int(randint(1,99))
while True:
    try:
        number1 =int(input("Please pick a NUMBER between 1 and 99\n"))
        if number1 not in range(1,99):
            print("You idiot! Pick a number IN THE RANGE")
        if number1 == number2:
            print("Congrats! You got it right")
            break
        elif number1 < number2:
            print ("Too low, try again")
        elif number1 > number2:
            print ("Too high, try again")
    except (ValueError, NameError, SyntaxError):
        print("You idiot! This is not a number")

time.sleep(10)
os.system("exit")

答案 2 :(得分:0)

此外,无需在每次需要from random import randint时导入randint()。将它放在import time

旁边的顶部