Pygame删除列表中的对象

时间:2014-05-29 02:47:13

标签: python list oop object pygame

上周我决定制作一款小游戏时,我刚开始以OOP风格编程。但现在我似乎陷入困境。我将解释到目前为止我所拥有的:

当玩家点击按钮时,会在玩家旁边创建一个子弹对象,并将子弹对象添加到项目符号[]列表中。然后子弹沿指定方向水平穿过屏幕。如果子弹与玩家或墙壁碰撞,它将从子弹[]列表中删除。到目前为止,非常好。

现在我似乎无法弄清楚如何在子弹[]列表离开屏幕时移除子弹(屏幕定义在0和xmax之间)。此外,在我从列表中删除子弹后,我是否也应该自行删除该对象,还是自动完成?

到目前为止

代码:

    class BULLET(object):

#Constructor for the bullet, bullets are stored into array 'bullets'
#   The direction is stored to keep track of which player fired the bullet
def __init__(self,location,direction,color):
    self.rect = pg.Rect(location[0],location[1],xmax/160,xmax/160)
    self.bullet_type="normal"
    self.direction=direction
    self.color=color
    bullets.append(self)

#Moves the bullet horizontally across the screen, in the specified direction
#   The move function also checks for collision with any walls or players
#   The move function removes the bullet object from the list and destroys it
#   when it leaves the left or right side of the screen
def move(self,bullet_speed):
    self.rect.x += bullet_speed

    for wall in walls:
        if self.rect.colliderect(wall.rect):
            index=wall.rect.collidelist(bullets)
            del bullets[index]
            #Do I need to delete the object too? or just the list item?

    for player in players:
        if self.rect.colliderect(player.rect):
            index=player.rect.collidelist(bullets)
            if player.immune_timer <= 0:
                del bullets[index]
                player.immunity(500)
                player.life -= 1

    if self.rect.centerx > xmax or self.rect.centerx <0:
        #This is where I would like this instance of the bullet object to be deleted
        #   and to have the object removed from the bullets[] list 

1 个答案:

答案 0 :(得分:1)

我建议你做的是在你的主循环中:

bullets = [bullet for bullet in bullets if 0 < bullet.rect.centerx < xmax]

这只会保留列表中的项目。