首页 > 解决方案 > 我试图让计算机在我的游戏列表中生成一个数字,但它总是出现故障

问题描述

我正在制作我的第一个 python 项目,它基本上是一个非常简单的数字猜测终端游戏,我目前正在制作 3 个级别中的第一个。

这个游戏的工作原理是让python在一定范围内生成一个随机数,然后玩游戏的人必须猜出这个数字,终端会回复“恭喜你猜对了”或“哎呀,你猜对了”数字错误'。

每当我运行程序时,即使我知道我只有 1 个数字可供选择,终端也会说我弄错了,尽管我知道 100% 这不是真的。我已经尝试了许多不同的方法。我正在考虑更改数字的格式,例如在一个范围内或类似的范围内,但它仍然无法识别我的数字是正确的。

我的代码不是最好的,但我一直在努力让它变得更好,所以这里是代码:

import random
import numpy
import time

def get_name():
name = input("Before we start, what is your name?")
print("You said your name was: " + name)

# The Variable 'tries' is the indication of how many tries you have left
tries = 1

while tries < 6:

    def try_again(get_number, random, tries):
        # This is to ask the player to try again
        answer = (input(" Do you want to try again?"))

        if answer != "no":
            print("Alright!, well I am going to guess that you want to play again")
            tries = tries + str(1)
            print("You have used up: " + tries + " Of your tries. Remember, when you use 5 tries the game ends")
            get_number(get_name, random, try_again)

    def find_rand_num(get_number, random, tries):

        num_list = [1,1]
        number = random.choice(num_list)

        # Asks the player for the number
        ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10  "))
        print(ques)

        if input == number:
            print("Congratulations! You got the number correct!")
            try_again(get_number, random, tries)

        elif input != number:
            tries += 1
            print("Oops, you got the number wrong")
            try_again(get_number, random, tries)
        
    def get_number(get_name, random, try_again, tries, find_rand_num):
    
        # This chooses the number that the player will have to guess                
        print("The computer is choosing a random number between 1 and 10... beep beep boop")
        find_rand_num(get_number, random, tries)


    get_name()
    get_number(get_name, random, try_again, tries, find_rand_num)

我最近开始学习编程,因为我爸爸也是一名程序员,我希望有一天能和他一样优秀。在数字生成问题之后,我还有一些其他错误。我很想听听你关于如何使这部分工作的想法。感谢您的宝贵时间,祝您度过愉快的一天!

标签: python

解决方案


您将 input() 的结果分配给ques,但是您没有使用 ques。错误在于“如果输入==数字”。这不是检查您之前输入调用的结果。它正在检查函数本身(输入)是否等于一个整数,它永远不会。

你只是想检查'number == ques'。但是,这也不太行得通。输入返回一个字符串值,并且您正在尝试将其与整数进行比较。您需要将其转换为 int,例如“if number == int(ques)”。


推荐阅读