This is a complete solution with a scrolling background:
import pygame
pygame.init()
width = 800
height = 600
black = (0, 0, 0)
white = (255, 255, 255)
ship_width = 56
ship_height = 64
disp = pygame.display.set_mode((width, height))
pygame.display.set_caption("space_game")
clock = pygame.time.Clock()
background = pygame.image.load('background.png')
background_height = background.get_rect().height
ship = pygame.image.load('ship.png')
def game_loop():
x = width * 0.45
y = height * 0.80
x_ch = 0
y_ch = 0
x_bg = 0
game_exit = False
while not game_exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
x_ch = -5
if event.key == pygame.K_d:
x_ch = 5
if event.key == pygame.K_w:
y_ch = -5
if event.key == pygame.K_s:
y_ch = 5
if (event.key == pygame.K_ESCAPE) or (event.key == pygame.K_q):
game_exit = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
x_ch = 0
if event.key == pygame.K_w or event.key == pygame.K_s:
y_ch = 0
if (x + x_ch) > width - ship_width or (x + x_ch) < 0:
x_ch = 0
if (y + y_ch) > height - ship_height or (y + y_ch) < 0:
y_ch = 0
x += x_ch
y += y_ch
x_loop = x_bg % background_height
disp.blit(background, (0, x_loop - background_height))
if x_loop < height:
disp.blit(background, (0, x_loop))
x_bg += 5
disp.blit(ship, (x, y))
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
The result:
A ship with transparent background:
The starry background:
I am posting this answer in case someone needs a working example as a starting point.