Python 如何在游戏中保持正交运动
我正在使用pygame创建一个游戏,希望限制用户只能左、右、上、下移动,但不能对角移动。我在下面提供的代码允许玩家在屏幕范围内移动。如何停止对角线运动Python 如何在游戏中保持正交运动,python,pygame,Python,Pygame,我正在使用pygame创建一个游戏,希望限制用户只能左、右、上、下移动,但不能对角移动。我在下面提供的代码允许玩家在屏幕范围内移动。如何停止对角线运动 class player: def __init__(self, x, y, width, height, colour): self.width = width # dimensions of player self.height = height # dimensions of player
class player:
def __init__(self, x, y, width, height, colour):
self.width = width # dimensions of player
self.height = height # dimensions of player
self.x = x # position on the screen
self.y = y # position on the screen
self.colour = colour # players colour
self.rect = (x, y, width, height) # all the players properties in one
self.vel = 1 # how far/fast you move with each key press
def draw(self, win):
pygame.draw.rect(win, self.colour, self.rect)
def move(self):
keys = pygame.key.get_pressed() # dictionary of keys - values of 0/1
if keys[pygame.K_LEFT]: # move left: minus from x position value
if self.x <= 5: # if player tries to go too far left
pass
else:
self.x -= self.vel
if keys[pygame.K_RIGHT]: # move right: add to x position value
if self.x == 785: # if player tries to go too far right
pass
else:
self.x += self.vel
if keys[pygame.K_UP]: # move up: minus from y position value
if self.y <= 105: # if player tries to go too far up
pass
else:
self.y -= self.vel
if keys[pygame.K_DOWN]: # move down from
if self.y >= 785: # if player tries to go too far down
pass
else:
self.y += self.vel
self.update()
def update(self):
self.rect = (self.x, self.y, self.width, self.height) # redefine where the player is
职业玩家:
定义初始值(自身、x、y、宽度、高度、颜色):
self.width=宽度#玩家尺寸
self.height=身高#球员尺寸
self.x=x#在屏幕上的位置
self.y=y#在屏幕上的位置
self.color=颜色#玩家颜色
self.rect=(x,y,width,height)#所有玩家属性都在一个
self.vel=1#每次按键移动的距离/速度
def抽签(自我,赢):
pygame.draw.rect(赢,自我着色,自我校正)
def移动(自我):
keys=pygame.key.get_pressed()#键字典-值为0/1
如果键[pygame.K_LEFT]:#向左移动:从x位置值减去
if self.x使控件映射的if块成为if else链,以防止多个键注册每次更新
def move(self):
keys = pygame.key.get_pressed() # dictionary of keys - values of 0/1
if keys[pygame.K_LEFT]: # move left: minus from x position value
if self.x <= 5: # if player tries to go too far left
pass
else:
self.x -= self.vel
elif keys[pygame.K_RIGHT]: # move right: add to x position value
if self.x == 785: # if player tries to go too far right
pass
else:
self.x += self.vel
elif keys[pygame.K_UP]: # move up: minus from y position value
if self.y <= 105: # if player tries to go too far up
pass
else:
self.y -= self.vel
elif keys[pygame.K_DOWN]: # move down from
if self.y >= 785: # if player tries to go too far down
pass
else:
self.y += self.vel
self.update()
def移动(自):
keys=pygame.key.get_pressed()#键字典-值为0/1
如果键[pygame.K_LEFT]:#向左移动:从x位置值减去
例如,如果self.x使用elif
,则用户按向上键和向右键,则只处理向右键而忽略向上键。