Угадайка на Python

В настоящее время я делаю упражнение на python с learnpython.org: у меня проблемы с дополнительным упражнением, выделенным жирным шрифтом:

Создайте случайное число от 1 до 9 (включая 1 и 9). Попросите пользователя угадать число, а затем скажите ему, угадал ли он слишком низко, слишком высоко или точно. (Подсказка: не забудьте использовать уроки пользовательского ввода из самого первого упражнения)

Дополнительно:

Продолжайте игру, пока пользователь не наберет «выход».

Отслеживайте, сколько предположений сделал пользователь, и когда игра закончится, распечатайте это.

Вот мой код:

import random


def gameTracker():
    global playedGames
    playedGames = 1
    playedGames = playedGames+1

def generateNumber():
    global generatednumber
    generatednumber = random.randint(1, 9)

def generateuserGuess():
    global userguess
    userguess = int(input('Pick a number between 1-9: '))


def generationProcess():
    global userguess
    if int(userguess) == generatednumber:
        print('You have guessed the number. Congratulations.')
        gameTracker()
        global playAgain
        playAgain = input('Want to play again? y/n: ')
        if playAgain == 'y':
            generateNumber()
            userguess = input('Pick a new number between 1-9: ')
            generationProcess()
        if playAgain == 'n':
            print('The game has ended. You have played: ')
            print(int(playedGames))
            print('games')

    if int(userguess) > generatednumber:
        print('You have guessed too high.')
        global conConfirm
        conConfirm = str(input('Guess again?: c/quit: '))
        conGame()

    if int(userguess) < generatednumber:
        print('You have guessed too low.')
        conConfirm = str(input('Guess again?: c/quit: '))
        conGame()


def conGame():
    if conConfirm == 'c':
        global userguess
        userguess = int(input('Your new guess please: '))
        generationProcess()

    if conConfirm == 'quit':
          print('The game has ended. You have played: ')
          print(int(playedGames))
          print('games')

generateNumber()
generateuserGuess()
generationProcess() 

Когда пользователь нажимает «n» или «выйти» после игры, он не распечатывает правильное количество игр, что означает, что gameTracker() написано плохо / неправильно, но он также по какой-то причине печатает количество раз, когда игра была сыграна * что происходит после playAgain == 'n'.

Как я буду делать эту работу?


person Alekong    schedule 19.02.2017    source источник
comment
Мой последний код для этого упражнения можно найти здесь: codepad.org/4T6v7C56 Я немного схитрил и импортировал sys модуль для sys.exit, и он останавливает рекурсию. Код не такой красивый, но работает. Если вы обнаружили ошибку или что-то в ней во время игры, дайте мне знать.   -  person Alekong    schedule 19.02.2017


Ответы (3)


работая с вашими globals и function returns. Я исправил некоторые ошибки в вашем коде и добавил несколько комментариев. просматривать!

import random

#create variable for num of played games
playedGames = 0

#creat variable to count number of guesses per game
guesses = 0
#create function to generate new random num
def generateNumber():
    return random.randint(1, 9)

#askk initial question

generatednumber = generateNumber()

userguess = int(input('Pick a number between 1-9: '))

def generationProcess():
    global userguess, guesses, playedGames,generatednumber

    while True:


        if userguess == generatednumber:
            print('You have guessed the number. Congratulations.')
            playedGames += 1
            global playAgain
            playAgain = input('Want to play again? y/n: ')
            if playAgain == 'y':
                generatednumber = generateNumber()
                userguess = input('Pick a new number between 1-9: ')
                generationProcess()
            if playAgain == 'n':
                print('The game has ended. You have played: '+ str(playedGames)+' games')

        elif int(userguess) > generatednumber:
            print('You have guessed too high.')
            guesses+=1
            conConfirm = str(input('Guess again?: c/quit: '))
            conGame(conConfirm)

        elif int(userguess) < generatednumber:

            guesses+=1
            print('You have guessed too low.')
            conConfirm = str(input('Guess again?: c/quit: '))
            conGame(conConfirm)


def conGame(conConfirm):
    global userguess
    if conConfirm == 'c':
        userguess = int(input('Your new guess please: '))
        generationProcess()

if conConfirm == 'quit':
    print('The game has ended. You have played: ' + str(playedGames) + ' games')


generationProcess()
person Chigo Godwin Anyaso    schedule 19.02.2017
comment
Этот парень очень хорошо объясняет ошибки в моем коде. Он также дает несколько хороших советов: - Объявите все глобальные переменные вместе в generationProcess() - Используйте while True и elif вместо оператора new if - Используйте = + 1 с playedGames - Передайте ввод conConfirm в функцию conGame, чтобы избежать рекурсии В целом лучшее решение, в то время как другие также предлагают понимание того, что было не так с моим конкретным фрагментом кода. - person Alekong; 19.02.2017
comment
@Alekong, спасибо, не забудьте нажать кнопку голосования в знак признательности! - person Chigo Godwin Anyaso; 19.02.2017
comment
Я сделал это, но, к сожалению, из-за того, что у меня менее 15 репутации, голосование не будет видно. - person Alekong; 19.02.2017

Вы должны увеличить количество игр, сыгранных в методе generateNumber(), после его объявления в методе gameTracker(). Таким образом, вы можете отслеживать, сколько игр было сыграно независимо от того, в сколько играли! Это выглядело бы примерно так:

def gameTracker():
    global playedGames
    playedGames = 0

def generateNumber():
    global generatednumber
    generatednumber = random.randint(1, 9)
    playedGames += 1
person briblue3    schedule 19.02.2017
comment
Это сработало. Я полностью отказался от gameTracker (), и теперь это выглядит так: global playedGames playedGames = 0 def generateNumber(): global generatednumber generatednumber = random.randint(1, 9) global playedGames playedGames += 1 playedGames += 1 было чем-то, чего я не мог понять. - person Alekong; 19.02.2017

В вашем gameTracker() коде вы инициализируетеplayedGames значением 1, а затем увеличиваете его. Таким образом, похоже, что он всегда будет хранить значение 2.

Вы получаете несколько выходов из-за вашей рекурсии. После последнего рекурсивного вызова управление программой возвращается к оператору if, и значение переменной, по-прежнему равное 'n' или 'quit', снова выводит детали. Вы можете инициализировать переменную другим значением после условий выхода, чтобы избежать этого.

import random

playedGames = 0

def gameTracker():
    global playedGames
    playedGames = playedGames+1

def generateNumber():
    global generatednumber
    generatednumber = random.randint(1, 9)
    gameTracker()

def generateuserGuess():
    global userguess
    userguess = int(input('Pick a number between 1-9: '))


def generationProcess():
    global userguess
    global generatednumber
    if int(userguess) == generatednumber:
        print('You have guessed the number. Congratulations.')
        global playAgain
        playAgain = input('Want to play again? y/n: ')
        if playAgain == 'y':
            generateNumber()
            userguess = input('Pick a new number between 1-9: ')
            generationProcess()
        if playAgain == 'n':
            print('The game has ended. You have played: ')
            print(int(playedGames))
            print('games')
            playAgain = 'x'


    if int(userguess) > generatednumber:
        print('You have guessed too high.')
        global conConfirm
        conConfirm = input('Guess again?: c/quit: ')
        conGame()

    if int(userguess) < generatednumber:
        print('You have guessed too low.')
        conConfirm = str(input('Guess again?: c/quit: '))
        conGame()


def conGame():
    global conConfirm
    if conConfirm == 'c':
        global userguess
        userguess = int(input('Your new guess please: '))
        generationProcess()

    if conConfirm == 'quit':
          print('The game has ended. You have played: ')
          print(int(playedGames))
          print('games')
          conConfirm = 'x'

generateNumber()
generateuserGuess()
generationProcess() 
person Specas    schedule 19.02.2017
comment
Это объясняет происходящую рекурсию. Я понимаю, почему это происходит сейчас, спасибо. - person Alekong; 19.02.2017