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

Python战争卡牌游戏计分器问题:重复游玩时分数持续重置

解决战争卡牌游戏分数重置问题

问题根源

  1. 分数计数器p1_score_counter和p2_score_counter定义在game()函数内部,每次调用函数都会重新初始化为0,导致无法累积分数。
  2. 存在三处语法/逻辑错误:
    • 第二个玩家输入提示重复写了Input Player 1 name,应为Input Player 2 name
    • 分数累加使用=+1,这是赋值为1而非累加1,正确写法是+=1
    • 直接比较卡牌字符串(如"10"和"2"字符串比较会得到错误结果),需用卡牌对应的数值比较

修改后的完整代码

print("Welcome to the Battle Card Game")
player1 = input("Input Player 1 name:")
player2 = input("Input Player 2 name:")

# 将分数计数器定义在函数外部,实现持续累积
p1_score_counter = 0
p2_score_counter = 0

def game():
    global p1_score_counter, p2_score_counter
    import random
    values = {"1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10, "Jack": 11, "Queen": 12, "King": 13, "Ace": 14}
    p1_card = random.choice(list(values.keys()))
    p2_card = random.choice(list(values.keys()))

    print(player1, "Has a", p1_card)
    print(player2, "Has a", p2_card)

    # 用卡牌对应的数值比较大小
    if values[p1_card] > values[p2_card]:
        print(player1, "wins")
        p1_score_counter += 1
    elif values[p1_card] < values[p2_card]:
        print(player2, "wins")
        p2_score_counter += 1
    else:
        print("It's a Tie!")

    print(player1, "Score is", p1_score_counter)
    print(player2, "Score is", p2_score_counter)


while True:
    game()
    if input("Repeat the program? (Y/N)").strip().upper() != 'Y':
        break

运行示例

Welcome to the Battle Card Game
Input Player 1 name:Alice
Input Player 2 name:Bob
Alice Has a 5
Bob Has a 3
Alice wins
Alice Score is 1
Bob Score is 0
Repeat the program? (Y/N)Y
Alice Has a Jack
Bob Has a 10
Alice wins
Alice Score is 2
Bob Score is 0
Repeat the program? (Y/N)Y
Alice Has a 7
Bob Has a King
Bob wins
Alice Score is 2
Bob Score is 1
Repeat the program? (Y/N)N

关键修改说明

  • 将分数变量移到函数外部,通过global关键字在函数内引用,确保分数在多次游戏间持续累积。
  • 修正玩家输入提示的文本错误,避免混淆。
  • 替换分数累加的错误语法,确保分数正确增加。
  • 改用卡牌对应的数值进行大小比较,修复字符串比较导致的逻辑错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 23:51:17