问题
I am fairly new to classes so I apologise if my problem is something very basic. I want to delete the Enemy when it goes off the screen. I searched this online and found a similar Stackoverflow page which I understood I need to do something like del Enemy
however It doesn't seem to work. I have
def __del__(self):
print("object deleted")
method in my Enemy class so it should output that it has been deleted.
Here is my function in which I try to delete the object:
def enemy_actions(enemies, enemy_clock):
if enemy_clock == 1:
free_lanes = 0
free_lane_positions = []
new_enemies_lanes = []
print("creating enemies")
#going through all lanes
for i in lanes:
lane_taken = i[1]
if not lane_taken:
#counting how many free lanes there are
free_lanes = free_lanes + 1
#adding free lane position to a list
free_lane_positions.append(i[0])
#if atleast 2 lanes are free then we randomly select how many new enemies we will add
if free_lanes > 1:
#randomly selecting how many enemies will be added
number_of_enemies = random.randint(1,len(free_lane_positions) - 1)
#repeating action for the number of enemies required
for i in range(number_of_enemies):
#randomly selecting lanes for enemies
lane_x = random.choice(free_lane_positions)
#adding it to the list of taken lanes
new_enemies_lanes.append(lane_x)
#removing taken up lane from list of free lanes
free_lane_positions.remove(lane_x)
#marking lane_x as taken in lanes
for i in lanes:
if i[0] == lane_x:
i.remove(False)
i.append(True)
#(self, place, x, y, length, width, path, speed):
#building enemy
for i in new_enemies_lanes:
Enemy = enemy(screen, i, enemy_y_start, 60, 60, enemy_path, random.randint(8,13))
enemies.append(Enemy)
#chekcing if the nemy if of the screen
for Enemy in enemies:
if Enemy.y > 650:
del Enemy
enemies
is a list tostore all enemies. Please tell me if more code is required. Thanks!
回答1:
Just rebuild the enemies list without the ones you don’t want:
#checking if the enemy is off the screen
enemies = [enemy for enemy in enemies if enemy.y <= 650]
来源:https://stackoverflow.com/questions/59021730/i-am-trying-to-delete-an-object-in-my-game-when-it-of-the-screen-but-del-objecn