Python 20×2人机棋盘游戏报错求助:IndexError索引越界
20×2棋盘游戏IndexError排查修复
问题背景
我正在开发一款人类玩家与电脑对战的20×2棋盘游戏,这是一款需使用骰子的简易棋盘游戏。运行代码时触发了IndexError: list index out of range错误,无法定位问题所在,恳请帮助排查修复。
报错信息
Traceback (most recent call last): File "c:\Users\abiruk\Downloads\main.py", line 77, in <module> move_pawn('human', dice) File "c:\Users\abiruk\Downloads\main.py", line 48, in move_pawn if board[row][pos] == 'X': IndexError: list index out of range
问题代码
import random import datetime # initialize the game board board = [['-' for _ in range(20)] for _ in range(2)] board[0][0] = 'X' # human player board[1][0] = 'X' # computer # initialize variables turn = 1 # human player goes first human_pos = 0 computer_pos = 0 human_moves = 0 computer_moves = 0 human_hits = 0 computer_hits = 0 # function to print the game board def print_board(): print('+----' * 20 + '+') for row in range(2): for col in range(20): print('|', board[row][col], ' ', end='') print('|') print('+----' * 20 + '+') # function to roll the dice def roll_dice(): return random.randint(1, 6) # function to move the player's pawn def move_pawn(player, steps): global human_pos, computer_pos if player == 'human': pos = human_pos row = 0 else: pos = computer_pos row = 1 board[row][pos] = '-' pos += int(steps/2) if pos >= 20: pos = 20 if player == 'human': human_pos = pos else: computer_pos = pos if board[row][pos] == 'X': pos = 0 board[row][pos] = 'X' if player == 'human': human_hits += 1 else: computer_hits += 1 else: board[row][pos] = 'X' # function to check if a player has won def check_win(player): if player == 'human': pos = human_pos else: pos = computer_pos if pos >= 20: return True else: return False # main game loop while True: print_board() if turn == 1: input('Press Enter to roll the dice') dice = roll_dice() print('You rolled a', dice) if dice == 6: move_pawn('human', dice) print_board() input('Press Enter to start the game') turn = 2 else: print('You need to roll a 6 to start the game') else: dice = roll_dice() print('Computer rolled a', dice) if dice == 6: move_pawn('computer', dice) print_board() input('Press Enter to start the game') turn = 1 else: move_pawn('computer', dice) print_board() if check_win('computer'): print('Computer wins!') break turn = 1 input('Press Enter to continue') if check_win('human'): print('You win!') break # count the number of moves and hits for each player human_moves = human_pos + human_hits computer_moves = computer_pos + computer_hits # save the game session to a text file date_time = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M') filename = date_time + '.txt' with open(filename, 'w') as f: f.write('Human\n') f.write('Total moves: ' + str(human_moves) + '\n') f.write
问题分析
报错的核心原因是:棋盘每行只有20个元素,列索引范围是0-19,但在move_pawn函数中,当pos >=20时直接将pos设为20,后续访问board[row][20]会超出列表索引范围,触发IndexError。
另外还有两处隐藏问题:
move_pawn中修改human_hits和computer_hits时未声明全局变量,会触发UnboundLocalError- 最后写入文件的代码不完整,
f.write没有实际内容
修复方案
1. 修正move_pawn函数逻辑
def move_pawn(player, steps): global human_pos, computer_pos, human_hits, computer_hits if player == 'human': pos = human_pos row = 0 else: pos = computer_pos row = 1 # 计算新位置 new_pos = pos + int(steps/2) # 若到达或超出终点,直接更新位置并返回(不操作棋盘) if new_pos >= 20: if player == 'human': human_pos = new_pos else: computer_pos = new_pos return # 未到达终点,先清除旧位置 board[row][pos] = '-' # 检查新位置是否有己方棋子 if board[row][new_pos] == 'X': new_pos = 0 board[row][new_pos] = 'X' if player == 'human': human_hits += 1 else: computer_hits += 1 else: board[row][new_pos] = 'X' # 更新玩家位置 if player == 'human': human_pos = new_pos else: computer_pos = new_pos
2. 补全文件写入代码
# save the game session to a text file date_time = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M') filename = date_time + '.txt' with open(filename, 'w') as f: f.write('Human\n') f.write('Total moves: ' + str(human_moves) + '\n') f.write('Total hits: ' + str(human_hits) + '\n\n') f.write('Computer\n') f.write('Total moves: ' + str(computer_moves) + '\n') f.write('Total hits: ' + str(computer_hits) + '\n')
3. 修正主循环规则逻辑(可选优化)
原代码中电脑未掷出6时直接移动,不符合“掷6才能开始”的规则,可调整电脑回合逻辑:
else: dice = roll_dice() print('Computer rolled a', dice) if dice == 6: move_pawn('computer', dice) print_board() input('Press Enter to continue') turn = 1 else: print('Computer needs to roll a 6 to start moving') input('Press Enter to continue') turn = 1
内容的提问来源于stack exchange,提问作者abhiruk prashan
相关产品推荐
相关产品推荐

