Search code examples
pythonpython-3.xpygameblitpacman

pygame.draw.rect on image


I am writing a python 3.7 pygame pacman clone. Right now, I hard-coded the level in a 2d array for collision detection, and every frame I do:

screen.fill((0,0,0))
for x in range(GRID_W):
    for y in range(GRID_H):
        num=tiles[x][y]
        if num is WALL or num is GHOST_HOUSE_BORDER:
            pygame.draw.rect(screen,(255,0,255),[x*TILE_W,y*TILE_H,TILE_W,TILE_H])

This is really slow for some reason. I think that pygame draws the rects pixel-by-pixel in a 2d for loop, which would be very inneficient.

Is there a way to do this rendering before the main loop, so I just blit an image to the screen? Or is there a better way to do it?

My computer is a Macbook Pro:

Processor 2.9 GHz Intel Core i7
Memory 16 GB 2133 MHz LPDDR3
Graphics Radeon Pro 560 4096 MB, Intel HD Graphics 630 1536 MB

It can run intense OpenGL and OpenCL applications just fine, so pygame should not be a stretch.


Solution

  • The slowing down has nothing to do with the drawing being slow. It's actually because your map gets bigger.

    In your file, you have several classes that have attributes speed (for example, line 192, your player has a self.speed). If you increase the size of your map without increasing your sprite's speeds, they will look like they are moving slower. They are actually moving the exact same speed, just not the same speed relative to the map.

    If you want your game to be able to scale the size display screen, you also need to scale everything based on that same scaling factor. Otherwise, increasing/decreasing the size of your game will also affect all the interactions in your game (moving, jumping, etc... depending on the game).

    I'd recommend putting a SCALE constant at the top of your file and multiplying all of your sizing and moving things by it. That way the game still feels the same no matter what size you want to play on.