按下按钮可以持续移动

时间:2018-03-08 21:34:13

标签: python-3.x pygame

我按照在线教程制作蛇游戏,并希望得到一些帮助以进行一些更改。截至目前,按住左箭头键或右箭头键将导致蛇移动。是否可以通过只需按一下按钮使蛇向左或向右移动,这样用户就不必按住箭头键了?

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 个答案:

答案 0 :(得分:3)

解决方案是首先存储精灵的x,y坐标,在按键上设置修改器(增加或减少量),然后在循环时将修改器添加到坐标。我写了一个这样一个系统的快速演示:

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

请注意,更改y时需要将x移动修改器重置为0,反之亦然 - 否则最终会产生有趣的对角线移动!

对于蛇形游戏,你可能想要修改蛇的大小以及/而不是位置 - 但你应该能够使用相同的结构来实现类似的东西。