我做了一个猜谜游戏,出于某种原因,尽管我使用了全局性的东西,但它一直告诉我它没有定义,但我早些时候就定义了



这是代码。有人请帮忙。我很困惑。guess变量是每次猜测后剩余的猜测次数。我试过global,但它仍然不起作用。我在这一点上迷失了方向。请帮忙。

import random 
# WELCOMING USER
print(" WELCOME TO THE NUMBER GUESSING GAME !! ")
print("The number you'll be guessing is between the range 1 - 100 ")
# SELECTING THE CORRECT GUESS RANDOMLY
correct_number = random.randint(1,100)
# ASKING THE USER FOR PREFERED DIFFICULTY AND SETTING NO OF GUESSES 
difficulty_mode  = input("Do you want the game to be easy or hard ? : ").lower()
guess = 0
#testing purposes
print(correct_number)
if difficulty_mode  == "hard":
guess = 5 
print("You have 5 guesses")
elif difficulty_mode == "easy" :
guess = 10
print(f"You have {guess} guesses")
else:
print("Wrong input")
# CREATING A FUNCTION TO REDUCE NO OF GUESSES 
def reducing_guesses () :
global guess
guess -= 1
print(f"You have {guess} no. of guesses remaining ")
# CREATING A WHILE LOOP TO RUN GAME 
isTrue = True 
loop_rounds = 0
# ACTUAL WHILE LOOP
while isTrue  == True :
if guess == 0:
isTrue = False
winning_or_loose = 0
if loop_rounds > 0 :
user_guess = int(input("Guess again : "))
if user_guess  == correct_number :
isTrue == False
print(f"You win! You guessed:{user_guess} and it was correct ")
winning_or_loose = 1
else:
reducing_guesses()
if loop_rounds  == 0 :
user_guess = int(input("Make a guess :"))
if user_guess == correct_number :
isTrue  = False 
print(f"You win! You guessed:{user_guess} and it was correct ")
winning_or_loose = 1 
else:
reducing_guesses()

您所要做的就是将user_guess = 0winning_or_loose = 0放在while循环之前的某个位置,它会修复您的游戏。您的主要问题似乎是您一直在尝试使用从未创建过的变量。

然而,您的代码有很多冗余,并且组织得不好。您没有适当的系统来处理用户输入的错误数据。如果不重新启动,就无法再次玩游戏。请考虑以下版本的游戏。我将它作为一个优化的示例提供给您。它并不完美。它说明了如何去除大约一半的代码以获得相同(或更好(的结果。

您可能想要加入一个系统,该系统告诉用户correct_number是高于还是低于他们的猜测。目前,您的游戏几乎不可能获胜。这就像试图扮演一个根本没有灯光的3D射击游戏。以下代码中未实现此建议。

import random 
#GAME LOOP
while True:
# WELCOMING USER
print(" WELCOME TO THE NUMBER GUESSING GAME !! ")
print("The number you'll be guessing is in the range 1 - 100 ")

#ALL VARIABLES
won            = 0
guess          = 0
user_guess     = 0
loop_rounds    = 0
msg            = ('Make a guess : ', 'Guess again : ')
correct_number = random.randint(1,100)

# ASKING THE USER FOR PREFERED DIFFICULTY AND SETTING NO OF GUESSES 
while (in_ := input("Do you want the game to be easy or hard ? : ").lower()) not in ('easy','hard'):
print("Wrong input")

guess = (10,5)[in_=='hard']

#ROUND LOOP
while guess>0:
print(f"You have {guess} no. of guesses remaining ")

while not (in_ := input(msg[loop_rounds>0])).isdigit():
print('Input a number between 1 and 100')

user_guess = int(in_)

if user_guess == correct_number :
print(f"You win! You guessed:{user_guess} and it was correct ")
won += 1 
break

guess -= 1
loop_rounds += 1

#LOST           
if user_guess != correct_number:
print('You failed to guess the number.')

#PLAY AGAIN
if input('Try again(y,n)? ') == 'n':
break

相关内容

最新更新