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

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

python - How to move the background image with keys in pygame?

I am making a game in pygame. In this game, the background image is large. On the screen, player only sees about 1/20th of the background image. I want, when player presses the left, right, up or down arrow keys, the background image moves respectively, but, it stops moving when player reaches the end of the image. I have no idea how to do this.

My code up to this point :-

import pygame

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

clock = pygame.time.Clock()

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

Thanks in Advance :-

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...