【问题标题】:Pygame deleting an object in a listPygame 删除列表中的对象
【发布时间】:2014-07-18 11:06:21
【问题描述】:

上周我刚开始使用 OOP 风格进行编程,当时我决定制作一款小游戏。但现在我似乎被困住了。我将解释我到目前为止所拥有的:

当玩家点击按钮时,会在玩家旁边创建一个子弹对象,并将子弹对象添加到 bullets[] 列表中。然后子弹以指定方向水平穿过屏幕。如果子弹与玩家或墙壁发生碰撞,则将其从 bullets[] 列表中删除。到目前为止,一切顺利。

现在我似乎无法弄清楚如何在子弹离开屏幕时从 bullets[] 列表中删除它(屏幕定义在 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 

【问题讨论】:

    标签: python list oop object pygame


    【解决方案1】:

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

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

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

    【讨论】:

    • 哇,感谢您的快速回复,这就像一个魅力。我还有一个问题。作为 OOP 的新手,我是否还需要删除该对象?还是只存在于列表中?为了避免游戏运行时间较长时出现卡顿
    • 我最近做了一个有很多延迟的游戏,所以我必须做一些事情来修复它。这与从列表中删除它相同,因为列表不再包含它。当然,它仍然在屏幕上绘制,但不会造成延迟,因为它已经已经被绘制了,目前还没有被绘制。
    猜你喜欢
    • 1970-01-01
    • 2021-12-02
    • 2021-08-03
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    相关资源
    最近更新 更多