因此,我试图在随机位置创建一系列“ boid”,它们以随机速度飞行,但是我无法移动列表中的rect,尽管可以绘制它们。我正在使用提供的矢量模块,可以在here中找到整个代码和模块。我用于精灵的png

更新:我通过使用实例位置向量而不是类向量来进行正向移动。但是现在只画了一个小图。我怀疑在相同的确切位置会绘制更多的标本。

class Boid():
    def __init__(self, screen):

        self.bird = pygame.image.load("birdie.png")
        self._pos = Vector2D(random.randint(0, screen.get_width()),
                             random.randint(0, screen.get_height()))
        self._vel = Vector2D((random.randint(1, 10) / 5.0),
                             (random.randint(1, 10) / 5.0))
        self.speed = random.randint(1, 5)
        self.bird_rect = self.bird.get_rect(center=(self._pos.x, self._pos.y))
        self._boids = []

    def add_boid(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self._boids.append(Boid(screen))

    def move_boids(self):
        s = Screen()
        #self.bird_rect.move_ip(self._vel.x, self._vel.y)
        self._pos += (self._vel * self.speed)

        #bounds check
        if self._pos.x + self.bird_rect.width >= s.width:
            self._pos.x  = s.width - self.bird_rect.width
            self._vel.x *= -1
        elif self._pos.x <= 0:
            self._pos.x  = 0
            self._vel.x *= -1

        if self._pos.y - self.bird_rect.height <= 0:
            self._pos.y = self.bird_rect.height
            self._vel.y *= -1
        elif self._pos.y >= s.height:
            self._pos.y = s.height - self.bird_rect.height
            self._vel.y *= -1

    def draw_boids(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            print(len(self._boids))

        for boid in self._boids:
                self.boidRect = pygame.Rect(self.bird_rect)
                #edit: changed boid._pos.x and y to self._pos.x and y
                self.boidRect.x = self._pos.x
                self.boidRect.y = self._pos.y
                screen.blit(self.bird, self.boidRect)

最佳答案

您必须遍历self._boids列表中的所有boid并更新其_posbird_rect属性以移动它们。

def move_boids(self):
    s = Screen()
    for boid in self._boids:
        boid._pos += boid._vel * boid.speed
        boid.bird_rect.center = boid._pos

        # Bounds check.
        if boid._pos.x + boid.bird_rect.width >= s.width:
            boid._pos.x  = s.width - boid.bird_rect.width
            boid._vel.x *= -1
        elif boid._pos.x <= 0:
            boid._pos.x  = 0
            boid._vel.x *= -1

        if boid._pos.y - boid.bird_rect.height <= 0:
            boid._pos.y = boid.bird_rect.height
            boid._vel.y *= -1
        elif boid._pos.y >= s.height:
            boid._pos.y = s.height - boid.bird_rect.height
            boid._vel.y *= -1


您还可以稍微简化draw方法。

def draw_boids(self):
    # Blit all boids at their rects.
    for boid in self._boids:
        screen.blit(boid.bird, boid.bird_rect)

关于python - 如何在列表中移动pygame rect?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49432135/

10-16 21:40