Search code examples
pythonrenderdrawpygamerect

PyGame not rendering shapes?


I have made the following code to render the map using tiles, it loops through the file and translates letters into tiles (rectangles);

currtile_x = 0
currtile_y = 0
singlerun = 1

if singlerun == 1:
    singlerun = 0
    with open('townhall.map', 'r') as f:
        for line in f:
                for character in line:
                    if character == "\n":
                        currtile_y += 10
                    else:
                        if character == "x":
                            pygame.draw.rect(screen, (1,2,3), (currtile_x, currtile_y, 10, 10), 0)
                            currtile_x += 10
                        else: 
                            if character == "a":
                                pygame.draw.rect(screen, (0,255,255), (currtile_x, currtile_y, 10, 10), 0)
                                currtile_x += 10

Here is the townhall.map file:

xxxxx
xaaax
xaaax
xaaax
xxxxx

Solution

  • Your code works well when event loop code is added to it. Since you haven't posted the whole program, everything I can do is to post a working program that contains your code.

    import pygame
    from pygame.locals import *
    
    pygame.init()
    screen = pygame.display.set_mode((300, 300))
    
    currtile_x = 0
    currtile_y = 0
    with open('townhall.map') as f:
        for line in f:
            for character in line:
                if character == '\n':
                    currtile_y += 10
                    currtile_x = 0
                elif character == 'x':
                    pygame.draw.rect(screen, (0,0,0), (currtile_x, currtile_y, 10, 10), 0)
                    currtile_x += 10
                elif character == 'a':
                    pygame.draw.rect(screen, (0,255,255), (currtile_x, currtile_y, 10, 10), 0)
                    currtile_x += 10
    
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
        pygame.display.update()