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

请求精简Yahtzee掷骰子代码:实现保留骰子的循环掷骰逻辑

Yahtzee掷骰代码精简方案

精简后的完整代码

import random
from os import system

# 清屏函数,适配Windows和Linux/macOS
clear = lambda: system('cls' if system('ver') == 0 else 'clear')

Dice = ['⚀', '⚁', '⚂', '⚃', '⚄', '⚅']
total_turns = 3

# 初始化第一次全掷骰子
current_dice = [random.choice(Dice) for _ in range(5)]
print(f"初始掷骰结果: {current_dice}")

for turn in range(1, total_turns):
    remaining_turns = total_turns - turn
    print(f"你还剩 {remaining_turns} 次掷骰机会。")
    keep = input("请选择要保留的骰子(输入1-5的数字,空格分隔): ").split()
    
    # 处理保留的骰子,转换为列表索引(0-4)
    keep_indices = [int(idx) - 1 for idx in keep if idx.isdigit() and 1 <= int(idx) <=5]
    
    # 生成新的骰子:保留选中的,其余重新掷
    new_dice = []
    for i in range(5):
        if i in keep_indices:
            new_dice.append(current_dice[i])
        else:
            new_dice.append(random.choice(Dice))
    
    current_dice = new_dice
    clear()
    print(f"当前掷骰结果: {current_dice}")

# 最后一次掷骰后显示最终结果
print("\n最终掷骰结果: ", current_dice)

关键优化点说明

  • 复用单个列表维护状态:用current_dice全程跟踪当前骰子的状态,避免重复创建first_roll、second_roll等多个列表,逻辑更紧凑。
  • 循环简化重复逻辑:通过循环处理后两次重掷,把重复的掷骰、保留逻辑收拢到循环体内,彻底消除代码冗余。
  • 输入校验增强:增加了对用户输入的简单校验(确保是1-5的有效数字),避免无效输入导致程序报错。
  • 交互提示统一:标准化剩余次数的提示信息,让用户更清晰当前操作节奏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:36:27