Skip to main content
 首页 » 编程设计

python之如何在列表中移动 pygame 矩形

2024年09月07日7zfyouxi

所以我试图在随机位置创建一系列以随机速度飞行的“boids”,但是我在移动列表中的矩形时遇到了一些麻烦,尽管我可以绘制它们。我正在使用提供的矢量模块,可以找到完整的代码和模块 here . png我正在使用 Sprite 。

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

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 并更新它们的 _pos 和 bird_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)