IndexError: list index out of range | Snake game

IndexError: list index out of range | Snake game

我正在学习 Python,这就是我编写贪吃蛇游戏的原因。我应该想在游戏区域内放置一张地图。我以字符串形式输入地图,然后将其分解以形成行列表。问题是我收到错误索引错误:列表索引超出范围。有人可以帮助我吗?

import os
import random
import readchar

POS_X = 0
POS_Y = 1

NUM_MAP_OBJECTS = 11

obstacle_definition = """\
###############    #########
        #########      #####
####        #######    #####
######  ############  ######
########       #####  ######
###########    #############
####        #########
#########    ###############
#######               ######
############    ############
############    ############
              ##############
#       ########        ####
#############       ########
##################      ####\
"""

my_position = [6, 3]
tail_length = 0
tail = []
map_objects = []

end_game = False
died = False

# Create obstacle map
obstacle_definition = [list(row) for row in obstacle_definition.split("\n")]

MAP_WIDTH = len(obstacle_definition[0])
MAP_HEIGHT = len(obstacle_definition)

# Main Loop
while not end_game:
    os.system("clear")
    # Generate random objects on the map
    while len(map_objects) < NUM_MAP_OBJECTS:
        new_position = [random.randint(0, MAP_WIDTH), random.randint(0, MAP_HEIGHT)]

        if new_position not in map_objects and new_position != my_position:
            map_objects.append(new_position)

    # Draw map
    print("+" + "-" * MAP_WIDTH * 3 + "+")

    for coordinate_y in range(MAP_HEIGHT):
        print("|", end="")

        for coordinate_x in range(MAP_WIDTH):

            char_to_draw = "  "
            object_in_cell = None
            tail_in_cell = None

            for map_object in map_objects:
                if map_object[POS_X] == coordinate_x and map_object[POS_Y] == coordinate_y:
                    char_to_draw = " *"
                    object_in_cell = map_object

            for tail_piece in tail:
                if tail_piece[POS_X] == coordinate_x and tail_piece[POS_Y] == coordinate_y:
                    char_to_draw = " @"
                    tail_in_cell = tail_piece

            if my_position[POS_X] == coordinate_x and my_position[POS_Y] == coordinate_y:
                char_to_draw = " @"

                if object_in_cell:
                    map_objects.remove(object_in_cell)
                    tail_length += 1

                if tail_in_cell:
                    end_game = True
                    died = True

            if obstacle_definition[coordinate_y][coordinate_x] == "#":
                char_to_draw = "##"

            print("{}".format(char_to_draw), end="")
        print("|")

    print("+" + "-" * MAP_WIDTH * 3 + "+")
    # print(f"La cola: {tail}")

    # Ask user where he wnats to move
    # direction = input("¿Dónde te quieres mover? [WASD]: ")
    direction = readchar.readchar()
    print(direction)

    if direction == "w":
        tail.insert(0, my_position.copy())
        tail = tail[:tail_length]
        my_position[POS_Y] -= 1
        my_position[POS_Y] %= MAP_HEIGHT
    elif direction == 's':
        tail.insert(0, my_position.copy())
        tail = tail[:tail_length]
        my_position[POS_Y] += 1
        my_position[POS_Y] %= MAP_HEIGHT
    elif direction == "a":
        tail.insert(0, my_position.copy())
        tail = tail[:tail_length]
        my_position[POS_X] -= 1
        my_position[POS_X] %= MAP_WIDTH
    elif direction == "d":
        tail.insert(0, my_position.copy())
        tail = tail[:tail_length]
        my_position[POS_X] += 1
        my_position[POS_X] %= MAP_WIDTH
    elif direction == "q":
        end_game = True

    os.system("clear")

if died:
    print(".: ¡Has muerto! :c :.")

错误如下:

line 85, in <module>
    if obstacle_definition[coordinate_y][coordinate_x] == "#":
IndexError: list index out of range

问题出在您的 obstacle_definition 变量上:

obstacle_definition = """\
###############    #########
        #########      #####
####        #######    #####
######  ############  ######
########       #####  ######
###########    #############
####        #########          << this line is the problem!
#########    ###############
#######               ######
############    ############
############    ############
              ##############
#       ########        ####
#############       ########
##################      ####\
"""

这个错误是因为这一行在技术上与其他行不一样,因为末尾没有空格。试试这个:

obstacle_definition = """\
###############    #########
        #########      #####
####        #######    #####
######  ############  ######
########       #####  ######
###########    #############
####        ################
#########    ###############
#######               ######
############    ############
############    ############
              ##############
#       ########        ####
#############       ########
##################      ####\
"""

您应该学习如何调试代码。您在第 6 行的蛇形图中缺少空格。

obstacle_definition = """\
###############    #########
        #########      #####
####        #######    #####
######  ############  ######
########       #####  ######
###########    #############
####        #########         <--- no spaces here, line just ends after the last '#'
#########    ###############
#######               ######
############    ############
############    ############
              ##############
#       ########        ####
#############       ########
##################      ####\
"""

正确版本

obstacle_definition = """\
###############    #########
        #########      #####
####        #######    #####
######  ############  ######
########       #####  ######
###########    #############
####        #########       
#########    ###############
#######               ######
############    ############
############    ############
              ##############
#       ########        ####
#############       ########
##################      ####\
"""