简体   繁体   English

Pygame 事件处理关键事件

[英]Pygame event handling key events

I am making a game and using pygame.我正在制作游戏并使用 pygame。 My goal is to move a rectangle with the arrow keys.我的目标是用箭头键移动一个矩形。 How can this be accomplished?如何做到这一点?

this answer is partly copied from programarcadegames.com , if you want to make a game with pygame, you should have a look at the courses.这个答案部分复制自programarcadegames.com ,如果你想用 pygame 制作游戏,你应该看看课程。

[assuming you already have a main loop, if not, start the course mentioned above from scratch:] outside the main loop, set the initial location and movement speed for both x and y position. [假设你已经有一个主循环,如果没有,从头开始上面提到的课程:] 在主循环之外,设置 x 和 y 位置的初始位置和移动速度。

x_speed = 0
y_speed = 0
x_pos = 10
y_pos = 10

Now you need (or rather, should already have) an event loop inside your main loop to process all pygame events that could possibly occur.现在您需要(或者更确切地说,应该已经拥有)主循环内的事件循环来处理可能发生的所有 pygame 事件。 Note that this should be the first thing to happen in your main loop.请注意,这应该是主循环中发生的第一件事。

Within the event loop, check for KEYDOWN events (keystroke) and KEYUP events (keyrelease).在事件循环中,检查 KEYDOWN 事件(击键)和 KEYUP 事件(keyrelease)。

for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        # As long as an arrow key is held down, the respective speed is set to 3 (or minus 3)
        if event.key == pygame.K_LEFT:
            x_speed = -3
        elif event.key == pygame.K_RIGHT:
            x_speed = 3
        elif event.key == pygame.K_UP:
            y_speed = -3
        elif event.key == pygame.K_DOWN:
            y_speed = 3
    elif event.type == pygame.KEYUP:
        # As soon as an arrow key is released, reset the respective speed to 0
        if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
            x_speed = 0
        elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
            y_speed = 0

Now adjust add the speed to your position.现在调整将速度添加到您的位置。 If no arrow key is held down, the speed was set to 0 in the eventloop, so your position won't be affected.如果没有按住箭头键,则事件循环中的速度设置为 0,因此您的位置不会受到影响。 Then draw your rectangle with the position you just modified.然后用您刚刚修改的位置绘制矩形。

x_pos = x_pos + x_speed
y_pos = y_pos + y_speed

pygame.draw.rect(yourdisplay, yourcolor, (x_pos, y_pos, yourwidth, yourheight))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM