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

问题描述

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

首先,我创建一个使草块有位置的类。

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),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,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),height - 50,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,(x+20,(x-20,y),y+20),y+20)]
    return any(pos for pos in neighbours if isGrass(*pos))

def findGrassPositions():
    poslist = []
    for x in range(50,20):
        for y in range(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,new_x,new_y,green)
        grass_group.add(new_grass)
        

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