如何在列表中移动pygame矩形?

2024-03-29 02:32:20 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试图在随机的位置创建一系列的“boid”,它们以随机的速度飞行,但是我在移动列表中的矩形时遇到了一些问题,尽管我可以绘制它们。我使用的是提供的向量模块,整个代码和模块都可以找到here。我用来做精灵的png。你知道吗

更新:我得到了一个矩形移动,通过使用实例位置向量而不是类向量。但现在只画了一个boid。我怀疑在同一个确切的位置画了更多的boid。你知道吗

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)

Tags: posrectselfgetdefrandomwidthscreen
1条回答
网友
1楼 · 发布于 2024-03-29 02:32:20

您必须迭代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)

相关问题 更多 >