简体   繁体   中英

Pygame event handling key events

I am making a game and using 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.

[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_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. 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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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