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

带计数器的掷骰子程序开发求助:遇6追加投掷逻辑问题

解决你的掷骰子程序逻辑问题

嘿,作为编程新手能写出这样的代码已经很棒了!咱们来一步步搞定你卡在的“掷出6追加投掷”的逻辑问题,先看看原代码里的几个小坑,再给你修正后的完整代码:

原代码里的关键问题

  • 输入校验循环错误:当用户输入非法数字时,你用break退出了输入循环,这会导致直接进入投掷流程,但此时numDices还是非法值!正确的做法是输入不合法时不退出循环,让用户重新输入。
  • 投掷逻辑混乱:你在for循环里每次都新建dicesArray,而且设置reset=True后只会跳出内层的while True,不会重新执行追加的投掷,导致追加的2次骰子根本没被投掷。
  • 退出语法错误:最后if exit==True: break写在了最外层while True的外面,这会直接报错,语法上不允许。

修正后的完整代码

import random

def main():
    while True:
        # 第一步:正确校验骰子数量输入
        num_dices = 0
        while num_dices < 1 or num_dices > 5:
            try:
                num_dices = int(input("How many dices to throw? (1-5) "))
                if num_dices < 1 or num_dices > 5:
                    print("Wrong input, try again (must be 1-5)")
            except ValueError:
                print("Please enter a valid number!")
        
        total = 0
        remaining_rolls = num_dices  # 用这个变量跟踪剩余需要投掷的次数,包括追加的
        
        print("\nStarting your rolls...")
        while remaining_rolls > 0:
            roll = random.randint(1, 6)
            remaining_rolls -= 1  # 每次投掷后剩余次数减1
            
            # 处理不同点数的逻辑
            if roll == 6:
                print(f"You rolled a six! Rolling two new dices.")
                remaining_rolls += 2  # 追加2次投掷
                # 掷出6不计入总分,所以不用加也不用减
            else:
                total += roll
                roll_names = {1: "one", 2: "two", 3: "three", 4: "four", 5: "five"}
                print(f"You rolled a {roll_names[roll]}, the total is: {total}")
        
        # 显示最终结果
        print(f"\nThe total sum is {total} after all rolls.")
        print()
        
        # 处理重启或退出
        restart = input("Press Enter to restart, or enter '9' to quit: ")
        if restart == "9":
            print("Thanks for playing!")
            break
        else:
            print("\n--- Restarting game ---")

if __name__ == "__main__":
    main()

关键改进点解释

  • 输入校验优化:用while循环持续检查输入,直到用户输入1-5的整数,还加了try-except处理非数字输入的情况,程序更健壮。
  • 剩余投掷次数跟踪:用remaining_rolls变量代替直接修改初始骰子数,这样掷出6时直接给这个变量加2,就能自然进入下一次投掷循环,完美实现追加投掷的逻辑。
  • 总分逻辑简化:掷出6时直接跳过加分,不用先加再减,逻辑更清晰易懂。
  • 结构化代码:把整个游戏放进main()函数里,代码更整洁,也符合Python的最佳实践。
  • 退出逻辑修正:把退出判断放在最外层循环里,不会出现语法错误,流程更顺畅。

你可以运行这段代码试试,完全符合你的需求:选择1-5个骰子、非法输入校验、掷出6追加2次投掷且不计入总分、每次显示点数和当前总分。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 19:37:54