python 如何使随机整数每次重滚

wljmcqd8  于 2023-01-24  发布在  Python
关注(0)|答案(1)|浏览(115)

我是一个初学者的编码一般,并试图学习python,所以我一直在学习如何使一些基本的游戏,以弄清楚的事情和实践我的基础...我做了一个游戏,猜测的数字是在0-100的随机区间生成,并给予反馈,如果你猜得更高或更低,以缩小到您的结果。我设法让游戏工作,我开始尝试添加一个可重玩性框架,所以当你猜对了游戏会自动重新启动,并生成一个新的数字来猜测,但是,我无法生成新号码。最初我让数字在循环外生成,并做了一个看似有效的循环,但数字保持不变,将其添加到循环中,它会随着每次猜测而改变。所以我尝试添加一个辅助def并指向它,使数字在那里重新生成,但它似乎仍然没有生成新的数字,如果我删除def重放def游戏之外的生成,则不再将num视为有效变量。我不确定如何完成此操作,任何建议都将是有帮助的。

import random
num = random.randint(0,100)

def Game():
    print("Guess the Number: ")
    guess = input()
    guess = int(guess)
    if guess==num:
        print ("CORRECT!!!!!")
        Replay()
    elif guess>num:
        print ("Sorry to high... Try again")
        Game()
    elif guess<num:
        print ("Sorry to low... Try Again")
        Game()

def Replay():
    num = random.randint(0,100)
    Game()

Replay()
j2qf4p5b

j2qf4p5b1#

这是一个代码编写的更正确的例子:

from random import *

def Game():
    replay = 0
    while replay == 0:
        num = randint(0, 100)  # if you want the number to revert every time you make a mistake, leave the line as it is otherwise put this assignment before the loop.
        guess = int(input("Choose a integer number from 0 to 100: "))
        if guess == num:
            print(f"{guess} is mysterious number")
            replay = 1
        elif guess > num:
            print(f"Sorry but {guess} is high, the number was {num}, try again if you want (0=yes, 1=no)")
            replay = int(input())
        elif guess < num:
            print (f"Sorry but {guess} is low, the number was {num}, try again if you want (0=yes, 1=no)") 
            replay = int(input())
            
            
Game()

相关问题