为何运行Python贪吃蛇代码时出现list index out of range错误?
修复贪吃蛇代码中的list index out of range错误
错误位置
执行以下代码段时触发list index out of range错误:
for y in snakeLocation: print(snakeLocation[y]) moveSquareSnake = snakeLocation[y] x[moveSquareSnake] = "S"
核心原因
snakeLocation是存储蛇身对应棋盘位置的列表(比如初始值[20, None]),但你在遍历的时候把列表元素当成了索引来访问snakeLocation[y]:
- 当y取到20时,
snakeLocation只有2个元素(索引0、1),20超出了列表的索引范围 - 当y取到None时,直接无法作为索引使用
此外代码还有其他几处语法和逻辑错误,导致无法正常运行。
修复方案
- 正确遍历蛇身列表:直接使用列表中的元素(因为元素本身就是棋盘位置),无需再通过索引取值
- 移除无效的None值:初始化蛇身时只保留有效位置
- 修正蛇身移动的循环逻辑:用反向索引遍历实现蛇身跟随移动
- 修正赋值与比较的混淆:把
extendSnake == "True"改成赋值操作extendSnake = "True" - 修正碰撞判断逻辑:判断蛇头是否吃到水果、是否撞到自己
- 声明全局变量score:确保在函数内可以修改全局分数
修正后的完整代码
from tabulate import tabulate import random snakeDirection = "right" extendSnake = "False" fruitLocation = 0 score = 0 game = "Playing" # 初始化棋盘,36个位置对应6x6网格 x = [None] * 36 def fruitPlaceFunction(): global fruitLocation # 随机生成水果位置,避免落在蛇身上 while True: fruitLocation = random.randint(0, 35) if fruitLocation not in snakeLocation: break x[fruitLocation] = "F" def gameLoop(): global snakeLocation, extendSnake, game, score # 初始化蛇身,初始长度1,位置在20(第四行第三列) if 'snakeLocation' not in globals() or game == "Over": snakeLocation = [20] game = "Playing" # 吃到水果后延长蛇身 if extendSnake == "True": extendSnake = "False" snakeLocation.append(fruitLocation) # 标记蛇身在棋盘上的位置 for pos in snakeLocation: x[pos] = "S" # 如果水果不存在,重新生成 if x[fruitLocation] != "F": fruitPlaceFunction() # 构建棋盘数据并打印 boardData = [ x[0:6], x[6:12], x[12:18], x[18:24], x[24:30], x[30:36] ] print(tabulate(boardData, tablefmt='grid')) print("") # 获取用户输入的方向 print("请输入 \"Up\", \"Down\", \"Left\", 或 \"Right\" ") snakeDirection = input().lower() while snakeDirection not in ["right", "left", "up", "down"]: print("无效方向,请输入 \"Up\", \"Down\", \"Left\", 或 \"Right\" ") snakeDirection = input().lower() # 蛇身移动:从尾巴到头部,每个位置继承前一个位置的坐标 for i in range(len(snakeLocation)-1, 0, -1): snakeLocation[i] = snakeLocation[i-1] # 处理蛇头移动 head_pos = snakeLocation[0] # 先清除原来的蛇头位置 x[head_pos] = None if snakeDirection == "up": new_head = head_pos - 6 if new_head < 0: game = "Over" else: snakeLocation[0] = new_head elif snakeDirection == "down": new_head = head_pos + 6 if new_head > 35: game = "Over" else: snakeLocation[0] = new_head elif snakeDirection == "left": new_head = head_pos - 1 # 判断是否撞到左边界(每行的最后一个索引是5,11,...29) if new_head in [-1,5,11,17,23,29]: game = "Over" else: snakeLocation[0] = new_head elif snakeDirection == "right": new_head = head_pos + 1 # 判断是否撞到右边界(每行的第一个索引是6,12,...36) if new_head in [6,12,18,24,30,36]: game = "Over" else: snakeLocation[0] = new_head # 判断是否撞到自己 if snakeLocation[0] in snakeLocation[1:]: game = "Over" # 判断是否吃到水果 if snakeLocation[0] == fruitLocation: x[fruitLocation] = None extendSnake = "True" score += 1 # 游戏主循环 while game == "Playing": gameLoop() if game == "Over": print("游戏结束") print(f"得分: {score}")
内容的提问来源于stack exchange,提问作者Caleb Whyte
相关产品推荐
相关产品推荐

