Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 按下按钮使其不断移动_Python 3.x_Pygame - Fatal编程技术网

Python 3.x 按下按钮使其不断移动

Python 3.x 按下按钮使其不断移动,python-3.x,pygame,Python 3.x,Pygame,我按照一个在线教程制作了一个蛇游戏,希望得到一些帮助来进行一些修改。现在,按住向左或向右箭头键将导致蛇移动。只需轻触按钮就可以让蛇向左或向右移动,这样用户就不必按住箭头键了吗 question = True while not gameExit: #Movement for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == py

我按照一个在线教程制作了一个蛇游戏,希望得到一些帮助来进行一些修改。现在,按住向左或向右箭头键将导致蛇移动。只需轻触按钮就可以让蛇向左或向右移动,这样用户就不必按住箭头键了吗

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

解决方案是首先存储精灵的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,反之亦然-否则,最终会出现有趣的对角线移动


对于蛇类游戏,您可能希望修改蛇的大小以及/而不是位置-但您应该能够使用相同的结构实现类似的效果。

稍后我将对其进行测试!