按下按钮即可持续移动 [英] Pressing a button to have constant movement

查看:60
本文介绍了按下按钮即可持续移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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

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

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.

这篇关于按下按钮即可持续移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆