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

Python Craps游戏输出异常求助:无法得到预期结果

Python Craps游戏输出异常问题修复

问题根源分析

  • 骰子范围错误:rollDice函数中random.randint(1,7)会生成1-7的数,而标准骰子是1-6,应改为random.randint(1,6)。
  • 条件判断逻辑错误:
    • 整数sum与字符串(如'2')比较,永远不相等,导致胜负判断完全错误;
    • 逻辑或写法错误,if sum == '2' or '3' or '12'等价于if (sum == '2') or True or True,永远为真,正确写法应为sum == 2 or sum == 3 or sum == 12。
  • 重复调用函数导致重复输出:
    • determine_win_or_lose中多次调用determinePointValueResult(sum),每次调用都会重新掷骰子并输出;
    • 主循环中三次调用determine_win_or_lose(x,y),导致同一局游戏重复执行三次,产生重复输出。
  • determinePointValueResult逻辑错误:
    • 初始sum等于传入的point,循环条件sum !=7 and sum !=point不成立,直接跳过循环;
    • 判断sum == '7'使用字符串,应改为整数7。

修正后的代码

import random

def rollDice():
    roll_1 = random.randint(1, 6)  # 修正骰子范围为1-6
    roll_2 = random.randint(1, 6)
    return roll_1, roll_2

def determine_win_or_lose(dice1, dice2):
    sum_dice = dice1 + dice2
    print(f"You rolled {dice1} + {dice2} = {sum_dice}")
    # 修正条件判断:使用整数比较,正确逻辑或写法
    if sum_dice == 2 or sum_dice == 3 or sum_dice == 12:
        return 0
    elif sum_dice == 7 or sum_dice == 11:
        return 1
    else:
        print(f"Point is {sum_dice}")
        # 仅调用一次函数并保存结果,避免重复掷骰
        result = determinePointValueResult(sum_dice)
        return result

def determinePointValueResult(point):
    while True:
        x, y = rollDice()
        sum_dice = x + y
        print(f"You rolled {x} + {y} = {sum_dice}")
        if sum_dice == point:
            return 1
        elif sum_dice == 7:
            return 0

#==== MAIN =====
win = 0
lose = 0

game = int(input("How many games do you want to play > "))

for i in range(game): 
    x, y = rollDice()
    # 仅调用一次函数并保存结果,避免重复执行
    game_result = determine_win_or_lose(x, y)
    if game_result == 1:
        print("You win")
        win += 1
    elif game_result == 0:
        print("You lose")
        lose += 1

print(f"Game results: {win} wins and {lose} losses")

修正说明

  1. 重命名sum为sum_dice,避免与内置函数sum冲突;
  2. 使用f-string简化输出格式,更易读;
  3. determinePointValueResult改为无限循环,直到掷出point或7,逻辑更清晰;
  4. 所有函数仅调用一次并保存结果,彻底解决重复输出问题;
  5. 修正所有类型匹配问题,确保整数与整数比较。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 04:06:24