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

Python Pig骰子游戏开发问题:每次玩家回合total_score重置为0

Pig骰子游戏total_score重置问题修复

问题描述

开发Pig骰子游戏时,total_score变量在每位玩家回合开始时都会重置为0,导致玩家分数无法累计。

问题根源

  1. 单个变量无法区分玩家分数:原代码用单个total_score存储所有玩家分数,所有玩家共用同一个值,无法独立累计各自得分。
  2. 值传递导致修改无效:Python中整数是不可变类型,函数参数传递的是变量副本,process_player_turn内修改total_score不会影响main函数中的原变量。
  3. 胜利判断逻辑错误:原代码在掷骰子过程中用未更新的total_score判断胜利,逻辑时机不对。

修复后的完整代码

import random

def print_instructions():
    print("""Welcome to Pig Dice. Get 2 to 10 players and one 6 sided die. During a player's turn, they may roll the die as many times as they wish. At the end of their turn, add all of their points together and pass the die to the next person. However, if they roll a one, they lose all points gained, and that turn ends. First one to score 100 points wins.""")


def get_player_names():
    print("You will need 2 to 10 players!")
    done = False
    players = []
    while not done:
        player = input("Names of players(hit enter to quit): ")
        if len(player) > 0:
            players.append(player)
        else:
            done = True
    print()
    return players

def process_player_turn(player_name, player_scores):
    turn_score = 0
    choice = input(f"{player_name} would you like to roll or pass? ")
    while choice.lower() == "roll":
        player_value = random.randint(1,6)
        print(f"{player_name} rolled a {player_value}")
        
        if player_value == 1:
            turn_score = 0
            print(f"{player_name} rolled a 1! Turn over!")
            print(f"Total score: {player_scores[player_name]}")
            break
        
        turn_score += player_value
        current_total = player_scores[player_name] + turn_score
        print(f"Current turn score: {turn_score}, potential total: {current_total}")
        
        choice = input(f"{player_name} would you like to roll again? ")
        
    else:
        player_scores[player_name] += turn_score
        print(f"Total score: {player_scores[player_name]}, Turn ended.")
    
    # 检查是否获胜
    if player_scores[player_name] >= 100:
        print(f"{player_name}'s score: {player_scores[player_name]}, {player_name} Wins!")
        return True
    
    print()
    return False


def main():
    print_instructions()
    player_names = get_player_names()
    # 用字典存储每个玩家的总分,初始为0
    player_scores = {name: 0 for name in player_names}

    done = False
    while not done:
        for player_name in player_names:
            done = process_player_turn(player_name, player_scores)
            if done:
                break


if __name__ == "__main__":
    main()

关键修改点

  • 使用字典存储玩家分数:创建player_scores字典,每个玩家对应独立的分数值,解决多玩家分数混淆问题。
  • 调整变量作用域:turn_score在每个玩家回合开始时初始化,避免不同玩家回合间的干扰。
  • 修正胜利判断逻辑:在玩家回合结束后(无论是掷出1还是主动pass),检查当前玩家的总分是否达到100。
  • 优化输入处理:将choice转为小写,避免大小写输入导致的判断错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 16:30:18