gpt4 book ai didi

python - 如何保持正交运动pygame

转载 作者:行者123 更新时间:2023-12-02 22:26:49 24 4
gpt4 key购买 nike

我正在使用 pygame 创建一个游戏,并希望限制用户只能向左、向右、向上、向下移动,但不能对角移动。我在下面提供的代码允许玩家在屏幕范围内移动。如何停止对角线移动?

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

最佳答案

将用于控制的 if block 映射为 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()

关于python - 如何保持正交运动pygame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60711314/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com