我正在用pygame构建游戏,其中涉及使用箭头键移动红色矩形(播放器(。我已经获得了播放器使用箭头键移动的播放器(箭头键控制速度,Enter键确认此举(,但是我需要能够限制玩家每回合能够移动的数量。我需要做到这一点,以便新的速度/位置最多只能是20 px上/下/向下和20px左/右(20 px表示两次按下箭头键(。
当前,播放器根据箭头键设定的速度移动,但是速度与箭头键无限地增加/降低。我需要在将箭头键沿任一方向(向上/向下,向左/右(下方按下2次时,我需要停止更改。
。这是控制速度的代码:
if event.type == pygame.KEYDOWN:
if p1_turn:
if event.key == pygame.K_RIGHT:
p1_velocity_x += 10
if event.key == pygame.K_LEFT:
p1_velocity_x -= 10
这是确认更改的代码(实际上移动播放器(:
if event.key == pygame.K_RETURN:
if p1_turn:
p1.y += p1_velocity_y
p1.x += p1_velocity_x
p1_turn = False
p2_turn = True
如前所述,应该有某种机制来阻止速度超过20px,从原始x速度和原始y速度提高/减小。
只需使用 if statements
:
original_vel_x = 0
if p1_turn:
if event.key == pygame.K_RIGHT:
if p1_velocity_x <= original_vel_x + 20: # I used <= in case it's being increased with floats
p1_velocity_x += 10
else:
print('Cannot Move')
import pygame
...
#Change those to whatever you want.
maximux_x = 20
minimum_x = 10
#This holds the players velocity on x.
p1_velocity_x = 0
def ChangeVelocity(change):
global p1_velocity_x
#cacl new x.
new_x = p1_velocity_x + change
if new_x < minimum_x:
return
if new_x > maximux_x:
return
#Change is inside the restrictions, so apply the change.
p1_velocity_x += change
...
if event.type == pygame.KEYDOWN:
if p1_turn:
if event.key == pygame.K_RIGHT:
ChangeVelocity(10)
if event.key == pygame.K_LEFT:
ChangeVelocity(-10)
为了更好地控制,您应该使用类创建精灵对象。一个示例如下所示:
import pygame
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
class Player:
def __init__(self):
self.pos = Vector(0,0)
self.maxX = 20
self.maxY = 10
def MoveOnX(self, change):
global p1_velocity_x
#cacl new x.
new_x = self.pos.x + change
if new_x < self.maxX:
return
if new_x > self.maxY:
return
#Change is inside the restrictions, so apply the change.
self.pos.x += change
#Create a new player and spawn him at (5,5)
player = Player()
player.pos.x = 5
player.pos.y = 5
if event.type == pygame.KEYDOWN:
if p1_turn:
if event.key == pygame.K_RIGHT:
player.MoveOnX(10)
if event.key == pygame.K_LEFT:
player.MoveOnX(-10)