gpt4 book ai didi

python - 我试图在游戏中删除屏幕上的对象,但 "del ObjecName"不起作用

转载 作者:行者123 更新时间:2023-12-01 06:50:38 26 4
gpt4 key购买 nike

我对类(class)相当陌生,所以如果我的问题是非常基本的问题,我深表歉意。我想在敌人从屏幕上消失时将其删除。我在网上搜索了这个,发现了一个类似的 Stackoverflow 页面,我知道我需要做一些类似 del Enemy 的事情,但它似乎不起作用。我有

def __del__(self):
print("object deleted")

我的 Enemy 类中的方法,因此它应该输出它已被删除。

这是我尝试删除对象的函数:

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

是存储所有敌人的列表。请告诉我是否需要更多代码。谢谢!

最佳答案

只需重建敌人列表,去掉你不想要的敌人:

#checking if the enemy is off the screen
enemies = [enemy for enemy in enemies if enemy.y <= 650]

关于python - 我试图在游戏中删除屏幕上的对象,但 "del ObjecName"不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59021730/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com