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

Tkinter开发Wanderer游戏触发IndexError列表索引越界报错求助

报错原因

  • 边界校验与地图访问顺序颠倒:move_skeleton 函数中先执行m[int(y/72)][int(x/72)]访问地图矩阵,后判断x、y是否在合法范围内。如果坐标本身已经越界,访问矩阵时直接触发索引越界错误。
  • 边界判断逻辑有误:判断条件中重复写了两次y<9 * 72,缺少了x<9 * 72的校验,x轴超出边界的情况无法被拦截。
  • 移动坐标赋值逻辑错误:代码中random_movement存储的是骷髅要移动到的目标绝对坐标,但用了+=赋值,相当于把目标坐标叠加到当前坐标上,会导致角色坐标瞬间超出画布范围。

修复方案

将game.py中的move_skeleton函数修改为如下代码:

import random # 确保已导入random模块
def move_skeleton(self):
    m = Map.matrix
    if self.hero.count % 2 == 0 :
        for char in self.characters:
            # 四个方向的目标坐标
            movement= [[char.x -72, char.y],[char.x, char.y -72] ,[char.x +72, char.y],[char.x , char.y +72]]
            good_movement = []
            for neighbor in movement:
                x , y = neighbor
                # 先判断边界合法,再访问地图矩阵
                if y>=0 and  y<9 * 72 and x >=0 and x<9*72 and m[int(y/72)][int(x/72)] !=1:
                    good_movement.append(neighbor)
            # 兜底判断:没有合法移动选项时跳过
            if not good_movement:
                continue
            random_movement = good_movement[random.randint(0, len(good_movement)-1)]
            # 直接赋值为目标坐标,不要叠加
            char.x = random_movement[0]
            char.y = random_movement[1]

建议同步调整main.py中英雄移动的判断顺序,先判断边界合法再访问地图矩阵,避免英雄触发同类索引越界问题,示例如下:

# 以leftKey为例,其余三个方向的判断逻辑同步调整顺序即可
def leftKey(event):
    # 先判断x>0,再访问地图矩阵
    if coords(hero)[0] > 0 and m[coords(hero)[1]][coords(hero)[0] - 1] != 1:
        hero.move(x=-72)
        hero.set_image(hero_left)
        game.move_skeleton()
        draw_canvas()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 17:45:04