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

Python猜拳游戏分数不更新故障:始终显示双方分数为0

问题原因与修复方案

核心问题1:计分板未实时更新

你定义的scoreboard是在初始化user_score和comp_score后生成的静态字符串,后续分数变化时,这个字符串不会自动同步新的分数值。每次分数变动后,必须重新生成计分板的字符串才能显示最新分数。

核心问题2:循环终止条件错误

当前循环条件while user_score < 3 or comp_score < 3意味着只要任意一方分数没到3就会一直循环,这会导致游戏无法正常结束(比如玩家到3分后,电脑分数没到,游戏仍会继续)。正确的逻辑应该是双方都没到3分时才继续游戏,所以要把or改成and。

修复后的完整代码

import random
def rps():
    user_score = 0 
    comp_score = 0
    # 修正循环终止条件:双方均未达3分时继续游戏
    while user_score < 3 and comp_score < 3:
        choice = ['r', 'p', 's']
        user = input('Choose [r] [p] or [s]: ')
        user = user.lower()
        comp = random.choice(choice)
        outcome = f"You chose {user} and I chose {comp}"
        
        if user == comp:
            # 每次打印前重新生成计分板
            scoreboard = f'You: {user_score} \nComp: {comp_score}'
            print(scoreboard)
            print(outcome)
            print('Tie Game')
        elif (user == 'r' and comp == choice[2]) or (user == 'p' and comp == choice[0]) or (user == 's' and comp == choice[1]):
            user_score += 1
            # 分数更新后立即生成最新计分板
            scoreboard = f'You: {user_score} \nComp: {comp_score}'
            print(scoreboard)
            print(outcome, '\nYou win!')
        else:
            comp_score += 1 
            # 分数更新后立即生成最新计分板
            scoreboard = f'You: {user_score} \nComp: {comp_score}'
            print(scoreboard)
            print(outcome, '\nI win')
    # 游戏结束时打印最终计分板
    final_scoreboard = f'You: {user_score} \nComp: {comp_score}'
    print(final_scoreboard)

rps()

额外优化建议

可以把计分板生成逻辑封装成一个小函数,避免重复代码:

def get_scoreboard(user_score, comp_score):
    return f'You: {user_score} \nComp: {comp_score}'

之后在需要打印计分板的地方,直接调用print(get_scoreboard(user_score, comp_score))即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 00:10:25