Подозреваемый порядок функций / пока цикл глюков из игры - PullRequest
0 голосов
/ 18 января 2019

Я НАМЕРЕН СВОЙ КОД ДЛЯ ...

  • Спросите имя пользователя и имя магазина
  • Показать экран меню, где игрок должен - Введите любую клавишу, чтобы начать игру.
  • Генерация номера и сброс «попыток», когда игрок вводит любое приглашение

  • В игре:

  • Игрок делает ставки и угадывает.

  • Если не так, вернитесь к предположению и сделайте ставку. Переменные баланса и попытки вычитают как ставку, так и -1 попытку.

  • Если предположение совпадает с сгенерированным числом, экран выигрыша. Игрок получает переменный приз, добавленный к его балансу.

  • Оба выигрыша / проигрыша отображают меню «выбора», и игроку предлагается снова сыграть, ответив да или нет.

  • Если да, баланс обновляется с учетом выигрыша / проигрыша, генерируется новый номер и баланс обновляется. Попытки также сбрасываются.

  • Если нет, игрок возвращается в меню.

  • Если попытается == 0, то приглашение выбора «да / нет» снова появится, потому что игрок проиграл, и баланс обновляется с потерей.

ПРОБЛЕМА ЕСТЬ ...

  • Я подозреваю, что порядок функций и / или цикла перезапуска / завершения игры не соответствует порядку.

  • Все работает, кроме одной вещи: вводя да / нет, когда игра либо выиграла, либо проиграла при достижении 0 попыток, это происходит:

PIC: 0 enter image description here

Я пытался изменить переменные game_state, операторы if / elif и даже пытался добавить больше функций / циклов while, но у меня ничего не работает.

Я новичок в python и достиг конца моей веревки.

МОЙ КОД:

#pylint:disable=W0613
#pylint:disable=W0312
#pylint:disable=W0611
from random import randint
import math
######### NUMBER GUESSING GAME ##########

START_BALANCE = 500

POSITIVES = ["yes", "yeah", "y", "yep", "roger", "yea", "positive", "play"]
NEGATIVES = ["no", "nope", "n", "nah", "negative"]

choice = ("\nPlay again? Y/N:     ").upper()
userName = input ("Welcome to NumGuess! What is your name?\n")
userName = userName.title()

def menu():
    print(''' \n                        Hello {}!\n
                * The rules are very simple *
--         The AI generates a number from 1 - 100.       --
--    You will have to make a bet and enter your guess.  --
--   You have 10x tries. If you fail, you lose your bet. --
--   The AI will let say if you guessed 'low' or 'high'  --
--    Correct guess = prize. Wrong guess = lost bet.     --

                       - Good Luck! - 
'''.format(userName))

def menuPlay():

    try:
        menuPlay = input("Press any key to start the game.")
#   except (ValueError):
    #   return menuPlay()
    except TypeError:
        return menuPlay()
    else:
        if menuPlay.upper() != "":
            return

def xNumbers():
    number = randint(1,100)
    return number

def xTries():
    tries = 3
    return tries

def xBets():
    print("-------------------------------------")
    bet = int(input("Enter your bet:     "))
    return bet

def xGuesses():
    guess = int(input("Enter your guess:    "))
    return guess


menu()
menuPlay()
tries = xTries() 
number = xNumbers()

def main(tries, balance):
    print("\nYour balance is: {}$.\nYou have {}x tries left.\n".format(balance, tries))
    bet = xBets()
    guess = xGuesses()

    print("\nnumber: {}, guess: {}, bet: {}".format(number, guess, bet)) ##just to check if things are working

    if tries <=1:
        print("\nGAME OVER! - YOU ARE OUT OF TRIES!\n - The number was: {}.".format(number))
        input(choice)
        return [balance]

    if guess == number:
        prize = bet * float(3.75)
        prize = math.ceil(prize)
        balance += prize
        print("Congratulations! You win: {}$".format(prize))
        print("Your new balance is: {}$\n".format(balance))

    elif guess < number:
        print("Wrong guess!")
        print("- Your guess is too low!")
        tries -= 1
        balance -= bet
        main(tries, balance)
    elif guess > number:
        print("Wrong guess!")
        print("- Your guess is too high!")
        tries -= 1
        balance -= bet
        main(tries, balance)    

    player_Choice = input(choice)

    if player_Choice in POSITIVES: #If player wants to play again.
        print("New round started!")
        return [True, balance] #return True & updated balancd to while loop.

    else: # If player inputs NO to play again.
        print("\nThanks for playing!\n")
        return [False, balance] #return False & updated balnce to while loop - should end the game.
        # BONUS: If this could return to menuPlay() with an updated balance, that would be ideal.


game_state = [True, START_BALANCE]

while game_state[0]:
    game_state = main(tries, game_state[1])     

`

Спасибо за помощь новичку!

Ответы [ 2 ]

0 голосов
/ 18 января 2019

Ваша проблема в этих вызовах:

input(choice)

должно быть

choice = input("\nPlay again? Y/N:     ")

Ваш код использует переменную choice для обозначения как приглашения, так и ответа пользователя на приглашение (if choice in POSITIVES:).

0 голосов
/ 18 января 2019

Проблема if choice in POSITIVES. Ваша переменная choice всегда указывает на строку "\nPlay again? Y/N: ", и выбранный игроком набор никогда не записывается.

Чтобы исправить это, вы должны

  1. Сохранить ответ игрока, когда вы звоните input(choice) - т.е. player_choice = input(choice).
  2. Проверка по этой переменной, т.е. if player_choice in POSITIVES
...