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

如何去除Pig骰子游戏Python代码中while true与break改用循环条件终止

Pig骰子游戏循环改造方案

核心改造思路

  • 移除所有while True结构:新增显式布尔变量game_over作为主循环终止条件,触发条件为任意玩家得分超过100
  • 移除所有break语句:回合内的掷骰子循环新增pigged_out(掷到1)、reach_win_line(累计得分达标)两个标志变量,所有终止条件直接写入while的条件判断中
  • 同步修复原代码中玩家一的回合得分未关联全局分数的逻辑漏洞

修改后完整代码

import random
def roll_dice():
    return random.randint(1,6)
players = ['Player One', 'Player Two']
scores = {'Player One': 0, 'Player Two': 0}
random.shuffle(players)
# 新增主循环显式终止标志
game_over = False
while not game_over:
    for i in players:
        # 已产生获胜者时跳过剩余玩家回合
        if game_over:
            continue
        turn_score = 0
        if i == 'Player One':
            choice = input("Roll(r) or Hold(h)?: ")
            if choice == 'r':
                # 新增回合内显式终止标志
                pigged_out = False
                reach_win_line = False
                final_score = scores[i]
                # 所有终止条件直接写在循环判断逻辑中
                while turn_score <= 20 and not pigged_out and not reach_win_line:
                    dice_value = roll_dice()
                    turn_score += dice_value
                    if dice_value == 1:
                        turn_score = 0
                        pigged_out = True
                        print("-rolled a ", dice_value)
                        print("Pigged out!")
                    else:
                        print("Turn score is: ", turn_score)
                        total = final_score + turn_score
                        print("Your final score is: ", total)
                        if total > 100:
                            reach_win_line = True
        else:
            print("It is " +  str(i) + "'s turn.")
            pigged_out = False
            while turn_score < 20 and not pigged_out:
                dice_value = roll_dice()
                if dice_value == 1:
                    turn_score = 0
                    pigged_out = True
                    print("- rolled a ", dice_value)
                    print("Pigged out!")
                else:
                    turn_score += dice_value
                    print("-rolled a ", dice_value)
        scores[i] += turn_score
        print("Turn score is: ", turn_score)
        print('{} score: {} {} score: {}'.format(players[0], scores[players[0]], players[1], scores[players[1]]))
        if scores[i] > 100:
            game_over = True
winner = [winner for winner in scores if scores[winner] == max(scores.values())]
print(str(winner) + " is the winner!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 16:15:03