Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How can I tell pygame to repeat a small image to fill the screen ? I tried using blit but it only puts one image on the screen and doesn't fill it.

question from:https://stackoverflow.com/questions/65859573/how-to-fill-the-background-with-a-small-image-in-pygame

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
236 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to use nested loops to blit the image multiple times like tiles. Get the width and height of the screen and the image with get_size(). Use range to generate the top left positions of the tiles:

screen_w, screen_h = screen.get_size()
image_w, image_h = image.get_size()

for x in range(0, screen_w, image_w):
    for y in range(0, screen_h, image_h):
        screen.blit(image, (x, y))

Minimal example:

import pygame

pygame.init()
screen = pygame.display.set_mode((300, 200))
image = pygame.image.load('Apple.png')

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    screen.fill((255, 255, 255))

    screen_w, screen_h = screen.get_size()
    image_w, image_h = image.get_size()

    for x in range(0, screen_w, image_w):
        for y in range(0, screen_h, image_h):
            screen.blit(image, (x, y))
   
    pygame.display.flip()

pygame.quit()
exit()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...