Erik77
Erik77

Reputation: 109

Is there an better way to create a tilemap in pygame?

When i try to blit my tiles it says "list index out of range". I have no idea what to do since im new to this.

Error message:

window.blit(tilemap.textures[tilemap.tilemap[row][column]], (columntilemap.tilesize, rowtilemap.tilesize)) IndexError: list index out of range

I tried to change the values of mapwidth and mapheight but that did not do the trick. I have 2 scripts. Main and tilemaping. There is maybe an error because of that. Note (I have initalized pygame in the full code so that is not the problem)

main.py

import pygame as pg

# Importing files
import constants
import classes
import tilemap

# Functions
def draw_game():
    """ This function draws everything on the screen """

    global window, clock

    # The background
    window.blit(constants.img_background, (0, 0))

    # Tiles
    for row in range(tilemap.mapheight):

        for column in range(tilemap.mapwidth):

            window.blit(tilemap.textures[tilemap.tilemap[row][column]], (column*tilemap.tilesize, row*tilemap.tilesize))




    # Updating
    clock.tick(60)
    pg.display.update()

tilemap.py

import pygame as pg
import constants

GRASS = 0
WATER = 1




textures = {
    GRASS : pg.image.load("image\\grass.png"),
    WATER : pg.image.load("image\\water.png")

    }


tilemap = [
    [GRASS, GRASS, GRASS, WATER],
    [GRASS, GRASS, WATER, GRASS],
    [GRASS, WATER, GRASS, GRASS],
    [WATER, GRASS, GRASS, GRASS]    
    ]



tilesize = 40
mapwidth = 2
mapheight = 5

Upvotes: 1

Views: 9608

Answers (1)

Rabbid76
Rabbid76

Reputation: 210909

tilemap is a list. The list has 4 elements and each element of the list is a list with 4 elements, too.

 tilemap = [
       [GRASS, GRASS, GRASS, WATER],
       [GRASS, GRASS, WATER, GRASS],
       [GRASS, WATER, GRASS, GRASS],
       [WATER, GRASS, GRASS, GRASS]
    ]

So the "width" and the "height" of the tilemap is 4:

mapwidth = 4
mapheight = 4

But you don't need that variables at all, because you can get the length of the list by len():

for row in range( len(tilemap.tilemap) ):

    for column in range( len(tilemap.tilemap[row]) ):

        window.blit(tilemap.textures[tilemap.tilemap[row][column]],
                    (column*tilemap.tilesize, row*tilemap.tilesize))

If you want to put more tiles on the map, then it is sufficient to add more tiles to tilemap:

e.g.

tilemap = [
       [WATER, WATER, WATER, WATER, WATER, WATER],
       [WATER, GRASS, GRASS, GRASS, WATER, WATER],
       [WATER, GRASS, GRASS, WATER, GRASS, WATER],
       [WATER, GRASS, WATER, GRASS, GRASS, WATER],
       [WATER, WATER, GRASS, GRASS, GRASS, WATER],
       [WATER, WATER, WATER, WATER, WATER, WATER]
    ]
mapwidth = len(tilemap.tilemap)
mapheight = len(tilemap.tilemap[0])

Upvotes: 1

Related Questions