python - Pygame-检测是否按下了一个键?

标签 python pygame

所以我正在做一件简单的事情,并且一直在关注 youtube 上的教程。我可以使用 WASD 移动女妖(我使用 Halo 中的图像作为我的船),但我必须重复敲击按键,而我希望能够通过按住按键来移动它。这是代码;

import pygame
from pygame.locals import *

pygame.init()

screen = pygame.display.set_mode((1440,900))

pygame.display.update()

black=(0,0,0)
white=(255,255,255)

##loads the background
background = pygame.image.load("G:/starfield.jpg")
###loads sprite of a spaceship that will move.
banshee = pygame.image.load("G:/banshee.png")
x=1
y=1

                                 
while True:
    gamexit = False

    while not gamexit:
        screen.blit(background,(0,0))
        screen.blit(banshee,(x,y))
        pygame.display.update()
        # if it touches the sides of the window, the window closes
        if x==1440 or x==0 or y==900 or y==0:
                pygame.quit()
                quit()
        else:
            for event in pygame.event.get():
                pressed= pygame.key.get_pressed()
                if event.type == pygame.QUIT:
                    gamexit=True
                    pygame.quit()
                    quit()
                elif event.type==KEYDOWN:
                    # moves banshee up if w pressed, same for the other WASD keys below
                    if event.key==K_w:
                        y=y-5
                        x=x
                        screen.blit(banshee,(x,y))
                        pygame.display.update()
                    elif event.key==K_a:
                        x=x-5
                        y=y
                        screen.blit(banshee,(x,y))
                        pygame.display.update()
                    elif event.key==K_d:
                        x=x+5
                        y=y
                        screen.blit(banshee,(x,y))
                        pygame.display.update()
                    elif event.key==K_s:
                        y=y+5
                        x=x
                        screen.blit(banshee,(x,y))
                        pygame.display.update()

我已经尝试了很多不同的方法来做到这一点(在这里和其他地方),但收效甚微。有什么我可以在这里做的,不需要重写一大段代码吗?

谢谢。

最佳答案

使用 pygame.key.get_pressed() 检查键是否被按下要容易得多,因为您不需要自己通过事件跟踪键的状态。

我通常会创建一个字典,将键映射到它们应该移动对象的方向。

这样查询pygame.key.get_pressed()的结果就很简单了。

您可以使用一些简单的矢量数学来归一化移动方向,因此您以与仅沿 x 或 y 轴相同的速度沿对角线移动。

此外,使用 Rect 来存储对象的位置更容易,因为 pygame 提供了许多与 Rect 类一起使用的有用函数。

import pygame, math
from pygame.locals import *

# some simple functions for vetor math
# note that the next pygame release will ship with a vector math module included!

def magnitude(v):
    return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))

def add(u, v):
    return [ u[i]+v[i] for i in range(len(u)) ]

def normalize(v):
    vmag = magnitude(v)
    return [ v[i]/vmag  for i in range(len(v)) ]

pygame.init()

screen = pygame.display.set_mode((1440,900))
screen_r = screen.get_rect()

pygame.display.update()

black=(0,0,0)
white=(255,255,255)

background = pygame.image.load("G:/starfield.jpg")##loads the background

# here we define which button moves to which direction
move_map = {pygame.K_w: ( 0, -1),
            pygame.K_s: ( 0,  1),
            pygame.K_a: (-1,  0),
            pygame.K_d: ( 1,  0)}

banshee = pygame.image.load("G:/banshee.png")  

# create a Rect from the Surface to store the position of the object
# we can pass the initial starting position by providing the kwargs top and left
# another useful feature is that when we create the Rect directly from the
# Surface, we also have its size stored in the Rect
banshee_r = banshee.get_rect(top=50, left=50)

speed = 5

gameexit = False

while not gameexit:

    # exit the game when the window closes
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameexit = True

    # if it touches the sides of the window, end the game
    # note how easy this part becomes if you use the Rect class
    if not screen_r.contains(banshee_r):
        gameexit = True

    # get all pressed keys
    pressed = pygame.key.get_pressed()

    # get all directions the ship should move
    move = [move_map[key] for key in move_map if pressed[key]]

    # add all directions together to get the final direction
    reduced = reduce(add, move, (0, 0))
    if reduced != (0, 0):

        # normalize the target direction and apply a speed
        # this ensures that the same speed is used when moving diagonally
        # and along the x or y axis. Also, this makes it easy to
        # change the speed later on.
        move_vector = [c * speed for c in normalize(reduced)]

        # move the banshee
        # Another useful pygame functions for Rects
        banshee_r.move_ip(*move_vector)

    screen.blit(background,(0,0))
    # we can use banshee_r directly for drawing
    screen.blit(banshee, banshee_r)
    pygame.display.update()

关于python - Pygame-检测是否按下了一个键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30914765/

相关文章:

python - 有条件地隐藏 One2many 字段 Odoo/OpenERP

python - Pygame 属性,init()

python - 为什么我无法在 python 中为 'Python Programming for the absolute beginner' 这本书安装 pygame 和 livewires ?

python - Pygame 运行游戏的速度非常慢

android - 如何使用 PGS4A 从 Pygame 创建 APK?

python - 在 Pandas 中添加一个新列作为现有列的最大值

python - 如何使用 OpenAI 最大上下文长度为 2049 个 token ?

python - 两个相同的字典在腌制后有所不同(通过使用 diff)

python - mysql.connector.errors.ProgrammingError : 1054 (42S22): Unknown column 'X' in 'where clause'

python - 在pygame中播放两个声音文件