user1357159
user1357159

Reputation: 319

Repeating Tile Background pygame

Is there a feature similar to this in pygame?

screen.fill(pygame.image.load('brick.bmp').convert()) 

I would like to fill the window (background) with an image to produce an effect similar to this:

enter image description here

My only idea would be to blit each brick onto the screen, but i think that would slow down the game. Does anyone have an idea how to do this (and also provide some example code)?

Heres a snippet of a method that works but goes slow

    While True:
        for y in range(0,600,32):
            for x in range(0,800,32):
                screen.blit( self.img,(x,y))
        ...
        pygame.display.flip()

Upvotes: 7

Views: 10231

Answers (3)

CodeWizard777
CodeWizard777

Reputation: 69

I have this really simple function that works on resizable windows too:

def tileBackground(screen: pygame.display, image: pygame.Surface) -> None:
    screenWidth, screenHeight = screen.get_size()
    imageWidth, imageHeight = image.get_size()
    
    # Calculate how many tiles we need to draw in x axis and y axis
    tilesX = math.ceil(screenWidth / imageWidth)
    tilesY = math.ceil(screenHeight / imageHeight)
    
    # Loop over both and blit accordingly
    for x in range(tilesX):
        for y in range(tilesY):
            screen.blit(image, (x * imageWidth, y * imageHeight))

Upvotes: 0

Ray
Ray

Reputation: 1667

I can't find this feature in Pygame. However, I have a way to improve the performence of your method. You can create a surface first. Let's call it bgSurface. Then you blit all bricks to bgSurface using your double loop method. Then in the main loop, you do screen.blit(bgSurface, (0, 0)). Have a try.

Upvotes: 2

SingleNegationElimination
SingleNegationElimination

Reputation: 156158

blit each brick onto the screen, but i think that would slow down the game.

Not as much as you probably think. bliting is very fast. Even if there were some sort of "fill" command, it would still amount to copying the image to a surface until the surface is covered.

If the background image is stationary, you can render to an off-screen surface when your program starts, and instead of erasing the screen by filling with a solid color, just blit the pre-rendered background instead.

Upvotes: 6

Related Questions