【发布时间】: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