首页 > 解决方案 > 在 Python 返回分数时遇到石头剪刀布代码问题

问题描述

我正在用 Python 创建一个石头剪刀布程序,这部分当然非常简单。问题在于我需要在列表末尾返回分数。我让玩家可以根据他们的输入选择玩多少次,最后根据玩过的次数给出最终分数。每当我运行代码时,我都会在每场比赛后获得分数,以确保它运行正确,但是当我输入“2”退出时,分数显示为 0 0 0。任何帮助将不胜感激。这是代码。

import random as r


def main():
    """
    Asks user if they want to play and keeps track of score until player exits
    """
    tie_score = 0
    human = 0
    opponent = 0

    choice = input('Enter 1 to play or 2 to exit: ')

    play_again = ['1', '2']
    while choice not in play_again:

        # determine if user input is valid to start the game
        print('Invalid choice.')
        choice = input('Enter 1 to play or 2 to exit: ')
    else:
        while choice == '1':
            play_game(tie_score, human, opponent)

            choice = input('Enter 1 to play or 2 to exit: ')


def computer_choice():
    """
    computer generates rock, paper, or scissors by using random module
    """
    options = ['Rock', 'Paper', 'Scissors']
    choice = r.choice(options)
    return choice


def play_game(tie_score, human, opponent):
    """
    Determines win, lose, or tie based on user input. Returns score
    """

    user_options = ['Rock', 'Paper', 'Scissors']

    user = input('Enter Rock, Paper, or Scissors: ')
    computer = computer_choice()

    while user not in user_options:
        # Validates user input, allowing only rock, paper, or scissors
        print('Please enter Rock, Paper, or Scissors')
        user = input('Enter Rock, Paper, or Scissors: ')
    else:
        # determines who wins, or tie
        if user == computer:
            print('Computer chooses %s, tie' % computer)
            tie_score += 1
        elif (user == 'Rock') and (computer == 'Scissors'):
            print('Computer chooses %s, win' % computer)
            human += 1
        elif (user == 'Paper') and (computer == 'Rock'):
            print('Computer chooses %s, win' % computer)
            human += 1
        elif (user == 'Scissors') and (computer == 'Paper'):
            print('Computer chooses %s, win' % computer)
            human += 1
        else:
            print('Computer chooses %s, lose' % computer)
            opponent += 1
    return tie_score, human, opponent


main()

标签: python

解决方案


这里的问题是您从未真正保存从play_game()函数返回的分数。当您调用play_game()函数main()时,您需要为结果分配一个变量,例如:

scores = play_game()

然后您可以访问分数,以便将它们添加到主函数中的列表中,以便在主 while 循环退出时打印或返回:

def main():
    ...
    score_list = []
    ...
    scores = play_game()
    score_list.append(scores)

一般来说,最好不要简单地将代码转储到问题中,最好只给出函数名称并用最​​简单的术语解释它们的作用。将来,请尝试限制您发布的代码量。


推荐阅读