Невозможно выполнить функцию вызова в моем основном операторе для камня, ножниц, бумаги

Прежде чем кто-либо пометит этот вопрос как дубликат любого другого, относящегося к этому типу программы, знайте, что я искал и читал ответы на вопросы по этой теме и не смог найти ничего, что соответствовало бы моим потребностям.

В моей программе «Камень, ножницы, бумага» меня просят выяснить, выигрывает ли компьютер или игрок, или же у них ничья. Мы должны хранить выигрыш компьютера как -1, выигрыш игрока как 1 и ничью как 0. Я думал, что правильно написал эту функцию и правильно назвал ее в своей основной функции, однако, когда я запускаю свой код, он пропускает прямо через мой runGame функция и вместо этого переходит к бесконечному циклу, в котором игроку предлагается ввести свой выбор. Я не знаю, почему это происходит. Я должен отметить, что в рамках моей основной функции мы должны вести счетчик, чтобы видеть, сколько побед у компьютера и у игрока, и сколько раз они равны. У меня также возникают трудности с выполнением этого.

import random

# Function: Display Menu
# Input: none
# Output: none
# displays the game rules to the user
def displayMenu():
    print("Welcome! Let's play rock, paper, scissors.")
    print("The rules of the game are:")
    print("\tRock smashes scissors")
    print("\tScissors cut paper")
    print("\tPaper covers rock")
    print("\tIf both the choices are the same, it's a tie")

# Function: Get Computer Choice
# Input: none
# Output: integer that is randomly chosen, a number between 0 to 2
def getComputerChoice():
    computerChoice = random.randrange(0,3)
    return computerChoice

# Function: Get Player Choice
# Input: none
# Output: integer that represents the choice
# Asks the user for their choice: 0 for rock, 1 for paper, or 2 for scissors
def getPlayerChoice():
    playerChoice = int(input("Please choose (0) for rock, (1) for paper or (2) for scissors"))
    return playerChoice

# Function: Play Round
# Input: two integers--one representing the computer's choice and the other representing the player's choice
# Output: integer (-1 if computer wins, 1 if player wins, 0 if there is a tie)
# This method contains the game logic so it stimulates the game and determines a winner
def playRound(computerChoice, playerChoice):
    if playerChoice == 0 and computerChoice == 2:
        return 1
    elif computerChoice == 0 and playerChoice == 2:
        return -1
    elif playerChoice == 2 and computerChoice == 1:
        return 1
    elif computerChoice == 2 and playerChoice == 1:
        return -1
    elif playerChoice == 1 and computerChoice == 0:
        return 1
    elif computerChoice == 1 and playerChoice == 0:
        return 1
    else:
        return 0

# Function: Continue Game
# Input: none
# Output: boolean
# Ask the user is they want to continue (Y/N), and then return True or False accordingly
def continueGame():
    playAgain = input("Do you want to continue playing? Enter (y) for yes or (n) for no.")
    if playAgain.lower() == "y":
        return True
    elif playAgain.lower() == "n":
        return False

# Function: main
# Input: none
# Output: none
def main():
    playerCounter = 0
    computerCounter = 0
    tieCounter = 0

    displayMenu()
    p_choice = getPlayerChoice()
    if p_choice == 0:
        choicePlayer = "rock"
    elif p_choice == 1:
        choicePlayer = "paper"
    elif p_choice == 2:
        choicePlayer = "scissors"
    getComputerChoice()
    c_choice = getComputerChoice()
    if c_choice == 0:
        choiceComputer = "rock"
    elif c_choice == 1:
        choiceComputer = "paper"
    elif c_choice == 2:
        choiceComputer = "scissors"
    print("You chose", choicePlayer + ".")
    print("The computer chose", choiceComputer + ".")
    playRound(getComputerChoice(), getPlayerChoice())
    while playRound(c_choice, p_choice) == -1:
        computerCounter += 1
    while playRound(getPlayerChoice(), getPlayerChoice()) == 1:
        playerCounter += 1
    while playRound(getPlayerChoice(), getPlayerChoice()) == 0:
        tieCounter += 1
    continueGame()
    while continueGame() == True:
        displayMenu()
        getPlayerChoice()
        getComputerChoice()
        playRound(getComputerChoice(), getPlayerChoice())
        continueGame()
    while continueGame() == False:
        print()
        print("You won", playerCounter, "game(s).")
        print("The computer won", computerCounter, "game(s).")
        print("You tied with the computer", tieCounter, "time(s).")
        print()
        print("Thanks for playing!")

# Call Main
main()
Почему в Python есть оператор "pass"?
Почему в Python есть оператор "pass"?
Оператор pass в Python - это простая концепция, которую могут быстро освоить даже новички без опыта программирования.
Некоторые методы, о которых вы не знали, что они существуют в Python
Некоторые методы, о которых вы не знали, что они существуют в Python
Python - самый известный и самый простой в изучении язык в наши дни. Имея широкий спектр применения в области машинного обучения, Data Science,...
Основы Python Часть I
Основы Python Часть I
Вы когда-нибудь задумывались, почему в программах на Python вы видите приведенный ниже код?
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
Алиса и Боб имеют неориентированный граф из n узлов и трех типов ребер:
Оптимизация кода с помощью тернарного оператора Python
Оптимизация кода с помощью тернарного оператора Python
И последнее, что мы хотели бы показать вам, прежде чем двигаться дальше, это
Советы по эффективной веб-разработке с помощью Python
Советы по эффективной веб-разработке с помощью Python
Как веб-разработчик, Python может стать мощным инструментом для создания эффективных и масштабируемых веб-приложений.
1
0
30
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

У вас нет метода runGame, я полагаю, вы имеете в виду playRound. В таком случае, еще раз, в этой строке:

 playRound(getComputerChoice(), getPlayerChoice())

Вы снова вызываете методы getComputerChoice() и getPlayerChoice(), и это не то, что вам нужно. Из-за этого он снова просит вас ввести данные. Ты должен сделать:

playRound(c_choice, p_choice)

Есть некоторые проблемы с вашим кодом. Во-первых, вы многократно вызываете getComputerChoice(), getPlayerChoice() и continueGame() функции, когда в них нет необходимости. Во-вторых, у вас есть несколько странных циклов while, которые делают не то, что вы на самом деле думаете.

Вот как вы можете изменить свою функцию, чтобы иметь работающую программу.

def main():
    playerCounter = 0
    computerCounter = 0
    tieCounter = 0

    displayMenu()
    next_game = True

    while next_game:
        p_choice = getPlayerChoice()
        if p_choice == 0:
            choicePlayer = "rock"
        elif p_choice == 1:
            choicePlayer = "paper"
        elif p_choice == 2:
            choicePlayer = "scissors"
        c_choice = getComputerChoice()
        if c_choice == 0:
            choiceComputer = "rock"
        elif c_choice == 1:
            choiceComputer = "paper"
        elif c_choice == 2:
            choiceComputer = "scissors"
        print("You chose", choicePlayer + ".")
        print("The computer chose", choiceComputer + ".")

        result = playRound(p_choice, c_choice)
        if result == -1:
            computerCounter += 1
        elif result == 0:
            tieCounter += 1
        else:
            playerCounter += 1

        next_game = continueGame()

    print("You won", playerCounter, "game(s).")
    print("The computer won", computerCounter, "game(s).")
    print("You tied with the computer", tieCounter, "time(s).")
    print()
    print("Thanks for playing!")

Другие вопросы по теме