获取精灵位置,以便下一个精灵可以放置在它附近

Get a sprites position so that the next sprite can be placed near it

我正在尝试在 Pygame 中构建一个模拟正在生长的草的模拟器。尝试获取当前 spite(草)的位置的目的是可以在其旁边添加一个新的 sprite(草)。

首先我创建一个 class 给草片一个位置。

class Grass(pygame.sprite.Sprite):
def __init__(self, width, height, pos_x, pos_y, color):
    super().__init__()
    self.image = pygame.Surface([width, height])
    self.image.fill(color)
    self.rect = self.image.get_rect()
    self.rect.center = [pos_x, pos_y]

然后我添加一片草,这样我们就可以开始产卵过程,我通过创建一个组来做到这一点。

grass_group = pygame.sprite.Group()
grass = Grass(20, 20, random.randrange(50, width - 50), random.randrange(50, height - 50), green)
grass_group.add(grass)
grass_group.draw(screen)

然后我想在旧草旁边每秒创建一片新草。

    if seconds <= (one_second + 100) and seconds >= (one_second - 100):
    one_second += 1000
    for i in range(len(grass_group)):
        for j in range(len(grass_group)):
            j.x = 
            j.y =
            i.x = random.choice(j.x - 20, j.x, j.x + 20)
            i.y = random.choice(j.y - 20, j.y, j.y + 20)
            i = Grass(20, 20, i.x, i.y, green)
            grass_group.add(i)
            grass_group.draw(screen)
            pygame.display.flip()

所以我需要找出所有旧草的位置,以便在它附近创建新的草。

草的和平应该对齐网格。创建随机位置时设置 step 参数:

grass = Grass(20, 20, 
    random.randrange(50, width - 50, 20),
    random.randrange(50, height - 50, 20),
    green)
grass_group.add(grass)

首先你必须找到所有可能的草地位置。实现以下算法:

  • 在嵌套循环中遍历可能的草地位置。
  • 测试草是否在pygame.Rect.collidepoint()的位置。
  • 如果该位置有草,则转到下一个位置。
  • 测试位置旁边是否有草。如果找到草,则将该位置添加到列表中。
def isGrass(x, y):
    return any(g for g in grass_group.sprites if g.rect.collidepoint(x, y))

def isNextToGrass(x, y):
    neighbours = [
        (x-20, y-20), (x, y-20), (x+20, y-20), (x-20, y),
        (x+20, y), (x-20, y+20), (x, y+20), (x+20, y+20)]
    return any(pos for pos in neighbours if isGrass(*pos))

def findGrassPositions():
    poslist = []
    for x in range(50, width - 50, 20):
        for y in range(50, height - 50, 20):
            if not isGrass(x, y):
                if isNextToGrass(x, y):
                    poslist.append((x, y))
    return poslist

使用算法找到草的所有可能位置,并从列表中取出 random.choice

if seconds <= (one_second + 100) and seconds >= (one_second - 100):
    one_second += 1000
    allposlist = findGrassPositions()
    if allposlist:
        new_x, new_y = random.choice(allposlist)
        new_grass = Grass(20, 20, new_x, new_y, green)
        grass_group.add(new_grass)
        

grass_group.draw(screen)
pygame.display.flip()