简体   繁体   English

IndexError:列表索引超出范围

[英]IndexError: list index out of range

While stumbling my way through a tutorial, I've had a recurring issue (I say recurring, because it seemed to spontaneously resolve itself after I'd given up for the day and later on begin appearing again, I don't know what I did to make that happen) with the error: 虽然绊倒了我的教程,但我有一个反复出现的问题(我说反复出现,因为它似乎在我放弃了一天之后自发地解决了,后来再次开始出现,我不知道我是什么做错了以下事情:

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

Relevant code below: 相关代码如下:

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

It ended up at the point where I was comparing the code I had written character-by-character to the example code written in the tutorial, with no luck. 最后,我将我逐个字符编写的代码与教程中编写的示例代码进行比较,但没有运气。 This is the first time 'map' is used in the program, and I'm pretty lost when it comes to lists in python. 这是第一次在程序中使用'map',而且在python中的列表中我很丢失。

As a final note, I've poked about through other questions in the same spirit, but I couldn't apply them to my situation due to my limited knowledge. 作为最后一点,我以同样的精神探讨了其他问题,但由于我的知识有限,我无法将它们应用到我的情况中。

Atleast one of room.x1 + 1 , room.x2 , room.y1 + 1 and room.y2 exceeds your map. 至少其中一个room.x1 + 1room.x2room.y1 + 1room.y2超出你的地图。 Either check your map size or limit the access. 检查地图大小或限制访问权限。

Option 1: 选项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

Option 2: 选项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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM