gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:55:07 25 4
gpt4 key购买 nike

我正在尝试在 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]
然后我添加一片草,以便我们可以开始产卵过程,我通过创建一个组来做到这一点。
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()

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

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com