我想使用我的玩家类的移动方法并拥有敌人的复制玩家动作。我希望敌人基本上跟随玩家,直到满足某个条件,例如3分钟过去,之后我希望敌人回溯所有步骤。以下是我在玩家班级中的移动方法
class PacMan(pygame.sprite.Sprite):
def __init__(self, x, y, radius):
super().__init__()
self.image = pygame.Surface([radius, radius])
self.image.fill([250, 250, 0])
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.queue = [-speed1, 0]
self.direction = [-speed1, 0]
def change_direction(self, x, y):
self.queue = [x, y]
def move(self, level):
self.rect.x += self.queue[0]
self.rect.y += self.queue[1]
hitlist = pygame.sprite.spritecollide(self, level.wall_list, False)
if hitlist:
self.rect.x -= self.queue[0]
self.rect.y -= self.queue[1]
self.rect.x += self.direction[0]
self.rect.y += self.direction[1]
seclist = pygame.sprite.spritecollide(self, level.wall_list, False)
if seclist:
self.rect.x -= self.direction[0]
self.rect.y -= self.direction[1]
else:
self.direction[0] = self.queue[0]
self.direction[1] = self.queue[1]
if self.rect.x < -pacman_length:
self.rect.x = board_dimensions[0] - wall_length
self.rect.y = self.rect.y
if self.rect.x > board_dimensions[0]:
self.rect.x = wall_length
接下来,除了一次向右移动4个像素之外,其他功能不会发挥作用
class Ghost(pygame.sprite.Sprite):
def __init__(self, x, y, color,):
super().__init__()
self.color = color
self.image = pygame.Surface([pacman_length, pacman_length])
self.image.fill(color)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.direction = [0, speed1]
self.moves = [False, True, True, False]
self.edible = False
self.wait = False
self.waitcount = 0
self.speed = speed1
def move(self, level):
status1 = False
status2 = True
self.rect.move_ip(4, 0)
x_change = 0
y_change = 0
for i in startingmovements:
print (i)
print(i[0])
print (i[1])
def change_color(self, color):
self.image.fill(color)
我使用while循环实际上让角色像这样移动:
player.move(board)
for i in board.ghost_list:
i.move(board)
和
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.change_direction(-4, 0)
elif event.key == pygame.K_RIGHT:
player.change_direction(4, 0)
elif event.key == pygame.K_DOWN:
player.change_direction(0, 4)
elif event.key == pygame.K_UP:
player.change_direction(0, -4)
elif event.key == pygame.K_SPACE:
我理解代码有一个简单的解决方案,但我只是在其中一个时间似乎无法掌握答案。给予任何帮助真的很感激
答案 0 :(得分:0)
解决方案是将列表作为属性放入pac-man类。例如,self.steps=[]
。太平洋人会列出他的坐标,以便鬼魂可以跟踪他。
已实施到您的代码中:
class PacMan(pygame.sprite.Sprite):
def __init__(self, x, y, radius):
super().__init__()
self.image = pygame.Surface([radius, radius])
self.image.fill([250, 250, 0])
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.queue = [-speed1, 0]
self.direction = [-speed1, 0]
#add some starting values
self.steps=[]
现在让我们添加一个函数让pac-man列出他的步骤。
def update_steps():
#add current position
self.steps.insert(0,(self.rect.x,self.rect.y))
#delete old steps
del self.steps[:-1]
现在为鬼功能:
def update_pos(steps):
self.rect.x=steps[:-1[1]]
self.rect.y=steps[:-1[2]]
另外,请务必先更新ghost而不是pac-man。
我希望这有帮助!