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

Python开发‘泥潭骰子’游戏:计分筛选与骰子数量动态调整问题

泥潭骰子游戏(Stuck in the Mud Dice Game)修复实现

下面是修复后的完整代码,解决了筛选计分和动态调整骰子数量的问题,同时完善了游戏循环和退出逻辑:

import random
import sys

# 全局变量:当前掷骰子数量、累计总分
current_dice = 5
total_score = 0

def roll_dice():
    global current_dice, total_score
    stuck_dice = 0  # 本轮陷入泥潭(掷出2/5)的骰子数
    round_score = 0

    print(f"\n当前可用骰子数: {current_dice}")
    for idx in range(current_dice):
        num = random.randint(1, 6)
        print(f"骰子 {idx + 1}: {num}")
        # 仅1、3、4、6计入得分
        if num in (1, 3, 4, 6):
            round_score += num
        else:
            stuck_dice += 1

    # 更新累计总分和下一轮可用骰子数(最少为0)
    total_score += round_score
    current_dice = max(current_dice - stuck_dice, 0)

    print(f"本轮得分: {round_score}")
    print(f"累计总分: {total_score}")

    # 所有骰子都陷入泥潭时,重置游戏
    if current_dice == 0:
        print("\n所有骰子都陷入泥潭!游戏结束,最终总分:", total_score)
        current_dice = 5
        total_score = 0

def game_menu():
    while True:
        print("\n=== 泥潭骰子游戏 ===")
        print("1. 掷骰子")
        print("2. 退出游戏")
        try:
            choice = int(input("请选择操作: "))
            if choice == 1:
                roll_dice()
            elif choice == 2:
                print("感谢游玩,再见!")
                sys.exit()
            else:
                print("无效选项,请输入1或2")
        except ValueError:
            print("请输入有效的数字!")

# 启动游戏
game_menu()

关键修改说明

  • 筛选计分逻辑:判断骰子点数是否在(1,3,4,6)中,仅这类点数计入本轮得分并累加到总分
  • 动态调整骰子数量:统计本轮掷出的2和5的数量,用当前骰子数减去该数量,确保不会出现负数
  • 游戏循环:菜单函数加入while True循环,每次操作后回到菜单,直到选择退出
  • 异常处理:处理输入非数字的情况,避免程序崩溃
  • 游戏重置:当所有骰子都陷入泥潭(数量为0)时,自动重置骰子数和总分,方便重新开始

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 03:25:22