Python开发Sorry!桌游遇TypeError及掷骰功能实现求助
问题解决:Sorry!桌面游戏报错修复与掷骰交互功能实现
一、修复TypeError错误
报错出现在第33行dice_uno, dice_dos = gamble_roll(),核心原因:
gamble_roll函数当前返回的是两个骰子数值的和(整数类型),但代码试图将单个整数解包成两个变量,触发无法迭代的错误。- 全局变量
dice_uno、dice_dos是骰子数值列表,循环内用同名变量会覆盖全局变量,引发逻辑混乱。
修复步骤:
- 修改
gamble_roll函数,返回两个骰子的单独数值而非和:
def gamble_roll(): roll_uno = dice_uno[random.randint(0, len(dice_uno)-1)] roll_dos = dice_dos[random.randint(0, len(dice_dos)-1)] return roll_uno, roll_dos # 返回元组,支持解包操作
- 循环内重命名变量,避免覆盖全局列表:
roll1, roll2 = gamble_roll()
- 后续判断逻辑同步替换为新变量
roll1、roll2。
二、添加按Enter键掷骰功能
利用input()函数实现,它会等待用户按下Enter键后继续执行。在每个玩家回合前添加提示:
for i in range(participants): input(f"{players[i]},按Enter键进行掷骰...") # 等待用户触发掷骰 roll1, roll2 = gamble_roll() # 后续行动逻辑...
三、其他潜在问题修复
player_movement函数条件错误:i != participants应改为i != player,否则无法正确检测其他玩家位置冲突:
def player_movement(player, gamble): sorry_board[player] += gamble for i in range(participants): if i != player and sorry_board[i] == sorry_board[player]: sorry_board[i] = 0
gambles[i] == 0是比较操作,需改为赋值gambles[i] = 0:
if gambles[i] == 2: sorry_board[i] = 0 gambles[i] = 0 # 修正为赋值操作
- 将
board_hud()移到玩家行动后调用,实时显示棋盘状态:
# 玩家行动完成后调用 player_movement(i, roll1) board_hud()
修改后的完整代码
import random participants = int(input("Enter the amount of players: ")) players = [] for i in range(participants): names = input(f"Enter the player's names: {i+1}: ") players.append(names) sorry_board = [0] * 50 dice_uno = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] dice_dos = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] def gamble_roll(): roll_uno = dice_uno[random.randint(0, len(dice_uno)-1)] roll_dos = dice_dos[random.randint(0, len(dice_dos)-1)] return roll_uno, roll_dos def player_movement(player, gamble): sorry_board[player] += gamble for i in range(participants): if i != player and sorry_board[i] == sorry_board[player]: sorry_board[i] = 0 def board_hud(): for i in range(participants): print(f"{players[i]}: {sorry_board[i]}") print("-"*30) gambles = [0] * participants while True: for i in range(participants): input(f"{players[i]},按Enter键进行掷骰...") roll1, roll2 = gamble_roll() print(f"掷出点数:{roll1} 和 {roll2}") if roll1 == roll2: gambles[i] += 1 if gambles[i] == 2: sorry_board[i] = 0 gambles[i] = 0 print(f"{players[i]} 连续两次掷出相同点数,回到起点!") else: player_movement(i, roll1) print(f"{players[i]} 前进{roll1}步") else: gambles[i] = 0 player_movement(i, roll1) print(f"{players[i]} 前进{roll1}步") board_hud() if sorry_board[i] >= 50: print(f"{players[i]} wins!") play_again = input("Would you like to play again? ") if play_again.lower() == "yes": sorry_board = [0] * 50 gambles = [0] * participants else: exit()
内容的提问来源于stack exchange,提问作者abraki94
相关产品推荐
相关产品推荐

