首页 > 解决方案 > 我在这个游戏中做错了什么?

问题描述

我正在尝试使用我的第一种脚本语言:python。我目前正在制作一个小游戏,您可以在其中猜测 1-100 的预定数字。它还会告诉您正确答案是更大还是更小。目前我的代码总是返回正确的数字较小,而事实并非如此。

编辑:非常感谢你帮助我!

import random

print("this is a game made by Sven")
print("you're supposed to guess the right number. it is between 0 & 101.")
print("lucky for you, you're getting hints.")
print("succes!")

rightnumber = (random.randint(1, 100))
print(rightnumber)

gok = int(input("type your guess here and press enter"))

def compareguess():
    if gok > rightnumber:
        print("wrong! the right number is smaller :)")
    elif gok == rightnumber:
        print("WOW! you guessed right!")
    else:
        print("wrong! the right number is bigger.")
compareguess()

def guessAgain():
    int(input("try again. type your guess and press enter."))
    compareguess()
    if rightnumber == gok:
        print("that was it! you won!")
    else: guessAgain()


if rightnumber == gok:
    print("that was it! you won!")
else: guessAgain()

标签: python

解决方案


您可以gok作为参数传递以避免全局变量。

问题是:

当您再次输入时:int(input("try again. type your guess and press enter.")),您不会将值分配给任何东西。所以gok保持不变,总是更大或更小

import random

print("this is a game made by Sven")
print("you're supposed to guess the right number. it is between 0 & 101.")
print("lucky for you, you're getting hints.")
print("succes!")

rightnumber = (random.randint(1, 100))

gok = int(input("type your guess here and press enter"))

def compareguess(gok):
    if gok > rightnumber:
        print("wrong! the right number is smaller :)")
    elif gok == rightnumber:
        print("WOW! you guessed right!")
    else:
        print("wrong! the right number is bigger.")
compareguess(gok)

def guessAgain():
    gok=int(input("try again. type your guess and press enter."))
    compareguess(gok)
    if rightnumber == gok:
        print("that was it! you won!")
    else: guessAgain()


if rightnumber == gok:
    print("that was it! you won!")
else: guessAgain()

另外,不要使用递归。相反,使用while循环。没有递归的缩短代码:

import random

print("this is a game made by Sven")
print("you're supposed to guess the right number. it is between 0 & 101.")
print("lucky for you, you're getting hints.")
print("succes!")

rightnumber = (random.randint(1, 100))
while True:
    gok = int(input("type your guess here and press enter"))
    if gok > rightnumber:
        print("wrong! the right number is smaller :)")
    elif gok == rightnumber:
        print("WOW! you guessed right!")
        break
    else:
        print("wrong! the right number is bigger.")

推荐阅读