繁体   English   中英

我尝试在我的猜谜游戏中添加一个简单的重玩功能

[英]I tried adding a simple play again feature to my guessing game

我试图在我的猜谜游戏中添加一个你想再玩一次的功能,但它停止工作了:( 请帮忙。我对 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()

其实你的代码有一些小问题,但是稍微有点逻辑你就可以搞清楚了。

首先,你不想要三个分开的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()

希望这可以帮助你。 祝你的 Python 之旅好运! 如果您有任何其他问题,请告诉我们。

下一个输入提示应该在外循环中。 当它已经是 n == guess 时,您还需要打印“Gratz you guessed 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()
  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM