0

在学习教程的过程中,我遇到了一个反复出现的问题(我说的是反复出现,因为它似乎在我放弃一天之后自发地解决了,后来又开始出现了,我不知道我在做什么确实做到了)与错误:

Traceback (most recent call last):
  File "roguelike.py", line 215, in <module>
    make_map()
  File "roguelike.py", line 131, in make_map
    create_room(new_room)
  File "roguelike.py", line 84, in create_room
    map[x][y].blocked = False
IndexError: list index out of range

相关代码如下:

def create_room(room):
    global map
    #set all tiles inside the room to passable
    for x in range(room.x1 + 1, room.x2):
        for y in range(room.y1 + 1, room.y2):
            map[x][y].blocked = False
            map[x][y].block_sight = False

最后,我将逐个字符编写的代码与教程中编写的示例代码进行比较,但没有运气。这是程序中第一次使用“map”,当谈到 python 中的列表时,我很迷茫。

最后一点,我以同样的精神探讨了其他问题,但由于我的知识有限,我无法将它们应用于我的情况。

4

1 回答 1

0

room.x1 + 1、和room.x2中的至少一个超出您的地图。检查您的地图大小或限制访问。room.y1 + 1room.y2

选项1:

class RoomOutsideError(Exception):
    pass

# ...

def create_room(room):
    global map
    #set all tiles inside the room to passable

    # check for limits and raise exception
    #    (this will need handling outside this function)
    max_x, max_y = len(map) - 1, len(max[0]) - 1
    if room.x1+1 > max_x or room.x2 > max_x or \
       room.y1+1 > max_y or room.y2 > max_y:
           raise RoomOutsideError("Room outside map.")

    for x in range(room.x1 + 1, room.x2):
        for y in range(room.y1 + 1, room.y2):
            map[x][y].blocked = False
            map[x][y].block_sight = False

选项 2:

def create_room(room):
    global map
    #set all tiles inside the room to passable

    # limit room coordinates. This is free of additional handlings but
    # might create odd rooms in the corner of the map.
    max_x, max_y = len(map) - 1, len(map[0]) - 1
    for x in range(room.x1 + 1, room.x2):
        for y in range(room.y1 + 1, room.y2):
            map[min(max_x, x)][min(max_y, y)].blocked = False
            map[min(max_x, x)][min(max_y, y)].block_sight = False
于 2015-03-01T17:22:20.930 回答