You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python石头剪刀布程序退出时返回得分全为0问题求助

问题原因

你遇到的得分归零问题由三个错误导致:

  • 整数是Python中的不可变类型,你向play_game传递的三个得分变量都是值副本,函数内对副本的修改不会同步到main函数的原始变量
  • 你调用play_game时没有接收它返回的更新后得分,每局计算的新得分直接被丢弃
  • 代码中没有添加用户退出后输出最终得分的逻辑

修复方案

只需要修改两处即可:

  1. 调用play_game时,用返回的新得分覆盖main中的原始变量
  2. 在退出游戏循环后添加最终得分打印逻辑

修复后完整代码

import random as r


def main():
    """
    询问用户是否开始游戏,记录得分直到用户退出
    """
    tie_score = 0
    human = 0
    opponent = 0

    choice = input('输入1开始游戏,输入2退出: ')

    play_again = ['1', '2']
    while choice not in play_again:
        print('输入无效,请重新选择')
        choice = input('输入1开始游戏,输入2退出: ')
    else:
        while choice == '1':
            # 接收返回的更新后得分
            tie_score, human, opponent = play_game(tie_score, human, opponent)
            choice = input('输入1再玩一局,输入2退出: ')
    # 打印最终得分
    print(f"最终得分:平局 {tie_score} 次,玩家胜 {human} 次,电脑胜 {opponent} 次")


def computer_choice():
    """
    电脑随机生成石头、剪刀、布选项
    """
    options = ['Rock', 'Paper', 'Scissors']
    choice = r.choice(options)
    return choice


def play_game(tie_score, human, opponent):
    """
    根据用户输入判断胜负,返回更新后的得分
    """
    user_options = ['Rock', 'Paper', 'Scissors']
    user = input('输入Rock(石头)、Paper(布)或Scissors(剪刀): ')
    computer = computer_choice()

    while user not in user_options:
        print('输入无效,请输入Rock、Paper或Scissors')
        user = input('输入Rock(石头)、Paper(布)或Scissors(剪刀): ')
    else:
        if user == computer:
            print(f'电脑出了{computer},平局')
            tie_score += 1
        elif (user == 'Rock') and (computer == 'Scissors'):
            print(f'电脑出了{computer},你赢了')
            human += 1
        elif (user == 'Paper') and (computer == 'Rock'):
            print(f'电脑出了{computer},你赢了')
            human += 1
        elif (user == 'Scissors') and (computer == 'Paper'):
            print(f'电脑出了{computer},你赢了')
            human += 1
        else:
            print(f'电脑出了{computer},你输了')
            opponent += 1
    return tie_score, human, opponent


main()

内容的提问来源于stack exchange,提问作者CJackson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 17:15:00