How to move the background image with keys in pygame?

Solution 1:

Get the sice of the background and the screen by get_size():

screen_size = screen.get_size()
bg_size = bg.get_size()

Define the initial start of the background in range [0, bg_size[0]-screen_size[0]]. e.g. center of the background:

bg_x = (bg_size[0]-screen_size[0]) // 2

Get the list of the key states by pygame.key.get_pressed():

keys = pygame.key.get_pressed()

Change bg_x dependent on the state of left and right:

if keys[pygame.K_LEFT]:
    bg_x -= 10
if keys[pygame.K_RIGHT]:
    bg_x += 10

Clamp bg_x to the range [0, bg_size[0]-screen_size[0]]:

 bg_x = max(0, min(bg_size[0]-screen_size[0], bg_x))

blit the background at -bg_x on the screen:

screen.blit(bg, (-bg_x, 0))

See the example:

import pygame

FPS = 60
screen = pygame.display.set_mode((1000, 1000))
bg = pygame.image.load('map.png')

screen_size = screen.get_size()
bg_size = bg.get_size()
bg_x = (bg_size[0]-screen_size[0]) // 2
bg_y = (bg_size[1]-screen_size[1]) // 2

clock = pygame.time.Clock()

while True:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        bg_x -= 10
    if keys[pygame.K_RIGHT]:
        bg_x += 10
    if keys[pygame.K_UP]:
        bg_y -= 10
    if keys[pygame.K_DOWN]:
        bg_y += 10
    bg_x = max(0, min(bg_size[0]-screen_size[0], bg_x)) 
    bg_y = max(0, min(bg_size[1]-screen_size[1], bg_y))

    screen.blit(bg, (-bg_x, -bg_y))
    pygame.display.flip()