我尝试在我的猜谜游戏中添加一个简单的“再次玩”功能

2024-09-29 01:33:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在我的猜谜游戏中添加一个Doyouwantoplayear功能,但它停止了工作:(请帮助。我对python非常陌生,所以我打赌我犯了很多不经意的错误:S

import random

n = random.randint(1, 100)

play_game = input("Do you want to play ? Y/N :")
play_game = play_game.upper()
print("play_game")

while play_game == 'Y':
    guess = int(input("Guess a number between 1 och 100: "))
while n != "gissning":
    if guess < n:
        print("You guessed to low")
        guess = int(input("Guess a number between 1 och 100: "))
    elif guess > n:
        print ("You guessed to high")
        guess = int(input("Guess a number between 1 och 100: "))
    else:
        print("Gratz you guessed it")
        break
    
while play_game == 'Y':
    # your game 

    play_game = input("Do you want to play again? Y/N :").upper()

Tags: toyougamenumberinputplayrandombetween
2条回答

事实上,代码中有一些小问题,但是通过一些逻辑,您可以解决它

首先,您不需要三个分开的while循环,因为当您退出其中一个循环时,除非重新启动代码,否则您将永远无法再次访问它。实际上,您需要嵌套循环。外部的一个将验证用户是否想再次玩,而内部的一个将继续猜测,直到它匹配随机数

第二,您希望将n随机数与guess用户输入进行比较。在代码中,您正在比较n != "gissning",这永远不会是真的,因为n是一个数字"gissning"是一个字符串

考虑到这一点,您可以稍微更改代码,并实现如下功能:

import random

print("play_game")
play_game = input("Do you want to play ? Y/N :").upper()
highscore = 0

while play_game == 'Y':
    n = random.randint(1, 100)
    guess = int(input("Guess a number between 1 och 100: "))
    score = 1
    while n != guess:
        if guess < n:
            print("You guessed to low")
        elif guess > n:
            print("You guessed to high")
        guess = int(input("Guess a number between 1 och 100: "))
        score += 1
    else:
        print("Gratz you guessed it")
        highscore = score if score < highscore or highscore == 0 else highscore
        print('Your score this turn was', score)
        print('Your highscore is', highscore)
        play_game = input("Do you want to play again? Y/N :").upper()

希望这对你有所帮助。祝你旅途好运!如果您还有任何问题,请告诉我们

下一个输入提示应该在外部while循环中。当已经是n==guess时,还需要打印“Gratz You guess it”以及提示,并在内部while循环外部打印

import random

play_game = input("Do you want to play ? Y/N :")
play_game = play_game.upper()

while play_game == 'Y':
  print("play_game")
  n = random.randint(1, 100)

  guess = int(input("Guess a number between 1 och 100: "))
  while n != guess:
    if guess < n:
        print("You guessed to low")
        guess = int(input("Guess a number between 1 och 100: "))
    elif guess > n:
        print ("You guessed to high")
        guess = int(input("Guess a number between 1 och 100: "))

  print("Gratz you guessed it")

  play_game = input("Do you want to play ? Y/N :")
  play_game = play_game.upper()
  

相关问题 更多 >