python - 获取 Sprite 位置,以便下一个 Sprite 可以放置在它附近

标签 python pygame sprite

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

首先,我创建一个类,为草片指定一个位置。

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]

然后我添加一 block 草,以便我们可以开始生成过程,我通过创建一个组来完成此操作。

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)

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

    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()

关于python - 获取 Sprite 位置,以便下一个 Sprite 可以放置在它附近,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63871620/

相关文章:

python-3.x - ModuleNotFoundError : No module named 'pygame'

python - pygame圈子没有改变

android - 在 Andengine 中将图像加载为 Sprite

css - 控制悬停区域和 CSS 图像 Sprite

python - 阅读 Python 中的每四行

c# - 从 Python 调用 C# 中的特定属性重载

python - 为什么Python中导入的类属性没有改变?

python - 非线性 pyplot imshow 颜色

python - 如何计算 pygame.Surface 的屏幕中间?

objective-c - SpriteKit - SKSpriteNode physicsBody 未形成 CGPath