如何在pygame中使用键移动背景图像? [英] How to move the background image with keys in pygame?

查看:109
本文介绍了如何在pygame中使用键移动背景图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 pygame 中制作游戏.在这个游戏中,背景图像很大.在屏幕上,玩家只能看到大约 1/20 的背景图像.我想要,当玩家按下向左、向右、向上或向下箭头键时,背景图像分别移动,但是,当玩家到达图像末尾时它停止移动.我不知道该怎么做.

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

提前致谢:-

推荐答案

通过get_size()获取背景和屏幕的sice:

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

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

在 [0, bg_size[0]-screen_size[0]] 范围内定义背景的初始开始.例如背景中心:

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

通过pygame.key.get_pressed()获取关键状态列表:

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

keys = pygame.key.get_pressed()

根据leftright的状态改变bg_x:

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

钳位 bg_x 到范围 [0, bg_size[0]-screen_size[0]]:

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 屏幕上-bg_x 处的背景:

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

看例子:

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

这篇关于如何在pygame中使用键移动背景图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆