Wednesday 9 December 2015

Pygame: Setting a background image

Some times, you want to put a background image to the gaming window. Following post explains you, how to put a background image to the window.

Step 1: Load the image.
background_image = pygame.image.load("ocean.png")

‘pygame.image.load’ method is used to load an image. You can call this method in any of following ways.

load(filename)
file name is full path of file name to load.

load(fileobj, namehint=””)
You can load the file by passing as python file-like object.

Usually, you load image by calling convert method like below.

background_image = pygame.image.load("ocean.jpg").convert()

convert method used to create a copy that will draw more quickly on the screen

Step 2: Call blit method to draw image on screen.

screen.blit(background_image, [0, 0])
# import pygame
import pygame

# initialize game engine
pygame.init()

window_width=400
window_height=400

animation_increment=10
clock_tick_rate=20

# Open a window
size = (window_width, window_height)
screen = pygame.display.set_mode(size)

# Set title to the window
pygame.display.set_caption("Hello World")

dead=False

clock = pygame.time.Clock()
background_image = pygame.image.load("ocean.bmp").convert()

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

    screen.blit(background_image, [0, 0])

    pygame.display.flip()
    clock.tick(clock_tick_rate)

Output


Note:

‘ocean.png’ should be in same directory, where python file resides.



Previous                                                 Next                                                 Home

8 comments:

  1. I'm lost on player scrolling thing , too late to ask ?

    ReplyDelete
  2. when i run it shows nothing but when i quit it shows the background
    like when i quit the window it shows
    it quits and shows the background at the same time

    ReplyDelete
  3. add
    sys.exit()

    ReplyDelete
  4. Hey guys i don;t think i see my background in my code tho or does it have to be the same size or what?
    The image is a svg type does it even support that?

    ReplyDelete
  5. How can i make the background behind oder things like my character? i got my background but characters are behind it, i think?

    ReplyDelete