Pressing a button to have constant movement

后端 未结 1 2014
天命终不由人
天命终不由人 2021-01-21 22:02

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

1条回答
  •  攒了一身酷
    2021-01-21 22:21

    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.

    0 讨论(0)
提交回复
热议问题