pythonmacosindex-error

IndexError: list index out of range | Snake game


I'm learning Python and that is why I'm programming the snake game. I'm supposed to want to place a map within the play area. I input the map in String form and then break it to form rowed lists. The problem is that I get the error Index Error: list index out of range. Somebody could help me?

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 :.")

The error is as follows:

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

Solution

  • You should learn how to debug your code. You are missing the spaces in your snake map on the 6th row.

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

    correct version

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