【问题标题】:Get a sprites position so that the next sprite can be placed near it获取一个精灵位置,以便下一个精灵可以放在它附近
【发布时间】:2020-09-13 13:56:56
【问题描述】:

我正在尝试在 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), 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()

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

【问题讨论】:

    标签: python pygame sprite


    【解决方案1】:

    草地应与网格对齐。在创建随机位置时设置 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多