Unable to make simple 2d map in Pygames

Viewed 27

I am trying to make a simple 2d game map in Pygame but have run into a problem with the tile layout. I tried to make the map with a 2d array but it is not working. They are all appearing on one line. My goal is to make a simple 2d map via an array with just the rects. Here is the code.

import pygame
pygame.init()

root = pygame.display.set_mode((500,500))
pygame.display.set_caption("Game")

surface = pygame.Surface((60, 60), pygame.SRCALPHA)
rect = pygame.draw.rect(surface, (255, 0, 0), (50, 50, 50, 50)) , (50, 50)

surface_one = pygame.Surface((60, 60), pygame.SRCALPHA)
rect_one = pygame.draw.rect(surface_one, (0, 255, 0), (50, 50, 50, 50)) , (50, 50)

def main():
    tileX = 0
    tileY = 0

    map = [[0,0,0,0],
            [1,1,1,1], 
            [1,0,1,0]]

    for x in map:
        for x in x:
            if x == 0:
                root.blit(surface, [tileX, tileY]) 
                tileX = tileX+16
            if x == 1:
                root.blit(surface_one, [tileX, tileY]) 
                tileX = tileX+16

    tileX = 0
    tileY += 30

    pygame.display.update()

run = True
while run:
    pygame.time.delay(100)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    main()
 
1 Answers

You must set tileX = 0 at the begin of the outer loop and increment tileY at the end of the outer loop and:

def main():

    map = [[0,0,0,0],
            [1,1,1,1], 
            [1,0,1,0]]

    tileY = 0
    for row in map:
        tileX = 0
        for x in row:
            if x == 0:
                root.blit(surface, [tileX, tileY]) 
            if x == 1:
                root.blit(surface_one, [tileX, tileY]) 
            tileX += 16
        tileY += 16

    pygame.display.update()

However, you can simplify the code using enumerate:

def main():

    map = [[0,0,0,0],
            [1,1,1,1], 
            [1,0,1,0]]

    for y, row in enumerate(map):
        tileX = 0
        for x, cell in enumerate(row):
            image = surface_one if cell == 1 else surface
            root.blit(image, [x*16, y*16]) 

    pygame.display.update()
Related