Как снова получить игру с угадыванием случайных чисел до l oop при вводе пользователем и как создать ловушку для ошибок? - PullRequest
1 голос
/ 22 апреля 2020

Так что это моя программа угадывания случайных чисел, которую я сделал. Он просит пользователя ввести два числа в качестве границы, один высокий и один низкий, затем программа выберет число между этими двумя. Затем пользователь должен попытаться угадать число, выбранное программой. 1) Как заставить его спросить пользователя, хотят ли они играть снова, и после ввода «да» программа запускается заново, а после ввода «нет» программа заканчивается? 2) Как создать ловушку с ошибкой, которая сообщает пользователю «Эй, вы не ввели номер!» и заканчивается программа?

def main(): # Main Module

    print("Game Over.")

def introduction():
    print("Let's play the 'COLD, COLD, HOT!' game.")
    print("Here's how it works. You're going to choose two numbers: one small, one big. Once you do that, I'll choose a random number in between those two.")
    print("The goal of this game is to guess the number I'm thinking of. If you guess right, then you're HOT ON THE MONEY. If you keep guessing wrong, than you're ICE COLD. Ready? Then let's play!")
    small = int(input("Enter your smaller number: "))
    large = int(input("Enter your bigger number: "))
    print("\n")

    return small, large

def game(answer):

    c = int(input('Input the number of guesses you want: '))

    counter = 1 # Set the value of the counter outside loop.

    while counter <= c:
        guess = int(input("Input your guess(number) and press the 'Enter' key: "))
        if answer > guess:
            print("Your guess is too small; you're ICE COLD!")
            counter = counter + 1
        elif answer < guess:
            print("Your guess is too large; you're still ICE COLD!")
            counter = counter + 1
        elif answer == guess:
            print("Your guess is just right; you're HOT ON THE MONEY!")
            counter = c + 0.5
    if (answer == guess) and (counter < c + 1):
        print("You were burning hot this round!")
    else:
        print("Wow, you were frozen solid this time around.", "The number I \
was thinking of was: " , answer)

def Mystery_Number(a,b): 

    import random

    Mystery_Number = random.randint(a,b) # Random integer from Python

    return Mystery_Number # This function returns a random number

A,B = introduction()

number = Mystery_Number(A,B) # Calling Mystery_Number

game(number) # Number is the argument for the game function

main()

1 Ответ

0 голосов
/ 22 апреля 2020

Сначала вы должны заставить игру вернуть что-то, если они угадают:

def game(answer):
    guess = int(input("Please put in your number, then press enter:\n"))
    if answer > guess:
        print("Too big")
        return False
    if answer < guess:
        print("Too small")
        return False
    elif answer == guess:
        print("Your guess is just right")
        return True

Затем вы обновите функцию 'main', чтобы она включала новую функцию 'game':

def main():
    c = int(input("How many guesses would you like?\n"))
    for i in range(c):
        answer = int(input("Your guess: "))
        is_right = game(answer)
        if is_right: break
    if is_right: return True
    else: return False

Затем вы бы добавили функцию run_game для запуска main несколько раз за раз:

def run_game():
    introduction()
    not_done = False
    while not_done:
        game()
        again = input('If you would like to play again, please type any character')
        not_done = bool(again)

Наконец, для перехвата ошибок вы должны сделать что-то вроде этого :

try:
    x = int(input())
except:
    print('That was not a number')
    import sys
    sys.exit(0)
...