Search code examples
pythonpython-2.7pygametiled

How do I display a tiled map in Pygame using Tiled and pytmx?


I'm aware there is a similar question but the answers were not specific enough to be useful in my case.

I am trying to create a program that can display a tiled map created in Tiled and uploaded into Pygame using pytmx. The only issue I'm having is blitting the images onto the screen in Pygame.

This is the error I keep receiving: Traceback (most recent call last): File "C:\Users\b\Desktop\Frozen Map Textures\test.py", line 32, in screen.blit(images[i],(x*32,y*32)) TypeError: argument 1 must be pygame.Surface, not None

If anybody knows how to fix the issue is, I would be very grateful! Thanks for all your help!

The code is below:

import pygame
from pytmx import load_pygame
import random


white = (255,255,255)


#create window
screenSize = (800,600)
screen = pygame.display.set_mode(screenSize)
pygame.display.set_caption("GameName")
screen.fill(white)


gameMap = load_pygame("Frozen.tmx")


#creates list of single tiles in first layer
images = []
for y in range(50):
    for x in range(50):
        image = gameMap.get_tile_image(x,y,0)
        images.append(image)


#displays tiles in locations
i = 0
for y in range(50):
    for x in range(50):
        screen.blit(images[i],(x*32,y*32))
        i += 1


#main loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    pygame.display.flip()

pygame.quit()

Solution

  • I am not very familiar with pytmx, but I think the problem is that variable i runs from 0 to 2600 in the first for-loop (you have 2600 items / images / tiles in the images list). But when you create the list of tile locations (imageLocs), i only runs from 0 to 49, so you have a list 50 different locations.

    This means you don´t have "enough" locations for each tile.

    In addition to that you don´t need to increment any variables in a for i in rang(value)-loop in python, because i runs throw (i.e. gets assigned to) all values the range() function returns.

    You could update your code to avoid this problem:

    #Original code    
    
    #create a list of 2600 single tiles in first layer
    images = []
    
    for y in range(50):
        for x in range(50):
            image = gameMap.get_tile_image(x,y,0)
            images.append(image)
    
    #blit all tiles onto the screen
    i = 0 #runs from 0 to 2600
    
    for y in range(50):
        for x in range(50):
            screen.blit(images[i],(x * 32, y * 32))
            i += 1
    
    #Orginal code
    

    I hope this helps :)