Pressing a button to have constant movement

2019-07-11 05:26发布

问题:

I followed an online tutorial to make a snake game and want some help to make some changes. As of now, holding the left or right arrow keys will cause the snake to move. Would it be able to make the snake move to the left or right with only a tap of the button so the user doesn't have to hold down the arrow keys?

question = True
while not gameExit:

    #Movement
    for event in pygame.event.get():   
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                direction = "left"
                start_x_change = -block_size_mov 
                start_y_change = 0                                                             
            elif event.key == pygame.K_RIGHT:
                leftMov = False
                direction = "right"
                start_x_change = block_size_mov 
                start_y_change = 0

回答1:

The solution is to start off by storing the x,y coordinates of the sprite, set a modifier (increase or decrease amount) on keypress, and then add the modifier to the coordinates while looping. I've written a quick demo of such a system:

import pygame
from pygame.locals import *

pygame.init()
# Set up the screen
screen = pygame.display.set_mode((500,500), 0, 32)
# Make a simple white square sprite
player = pygame.Surface([20,20])
player.fill((255,255,255))

# Sprite coordinates start at the centre
x = y = 250
# Set movement factors to 0
movement_x = movement_y = 0

while True:
    screen.fill((0,0,0))
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_LEFT:
                movement_x = -0.05
                movement_y = 0
            elif event.key == K_RIGHT:
                movement_x = 0.05
                movement_y = 0
            elif event.key == K_UP:
                movement_y = -0.05
                movement_x = 0
            elif event.key == K_DOWN:
                movement_y = 0.05
                movement_x = 0

    # Modify the x and y coordinates
    x += movement_x
    y += movement_y

    screen.blit(player, (x, y))
    pygame.display.update()

Note that you need to reset the x movement modifier to 0 when changing y, and vice-versa - otherwise you end up with interesting diagonal movements!

For a snake game, you might want to modify the snake size as well as/instead of position - but you should be able to achieve something similar using the same structure.