我开始用python编写代码,然后使用pyzero制作一个简单的游戏。游戏结束后,我想删除某些类型类的所有现有实例,以允许游戏重新开始。我有该类所有实例的列表,但是使用remove(self)似乎会导致我无法解决的逻辑问题。
class Ball(Actor):
ball_list = []
def __init__(self, actor):
Actor.initiate_actor(self,"ball")
Ball.ball_list.append(self)
self.alive = True
def kill(self):
if self.alive:
self.alive = False
Ball.ball_list.remove(self)
def new_game():
global game_over, score
for actor in Ball.ball_list:
actor.kill()
score = 0
game_over = False
def draw():
global game_over
if game_over:
screen.clear()
screen.draw.text("Game Over", center = (WIDTH/2, HEIGHT/2), color = 'white')
else:
screen.clear()
backdrop.draw()
for actor in Ball.ball_list:
if actor.alive:
actor.draw()
答案 0 :(得分:0)
实际上,您在迭代列表时会从列表中删除对象。阅读How to remove items from a list while iterating?,以获取有关此主题的更多信息。
在从原始列表中删除项目时,创建列表的浅表副本(using System;
using System.IO;
using IWshRuntimeLibrary;
using File = System.IO.File;
public static class Shortcut
{
public static void CreateShortcut(string originalFilePathAndName, string destinationSavePath)
{
string fileName = Path.GetFileNameWithoutExtension(originalFilePathAndName);
string originalFilePath = Path.GetDirectoryName(originalFilePathAndName);
string link = destinationSavePath + Path.DirectorySeparatorChar + fileName + ".lnk";
var shell = new WshShell();
var shortcut = shell.CreateShortcut(link) as IWshShortcut;
if (shortcut != null)
{
shortcut.TargetPath = originalFilePathAndName;
shortcut.WorkingDirectory = originalFilePath;
shortcut.Save();
}
}
public static void CreateStartupShortcut()
{
CreateShortcut(System.Reflection.Assembly.GetEntryAssembly()?.Location, Environment.GetFolderPath(Environment.SpecialFolder.Startup));
}
public static void DeleteShortcut(string originalFilePathAndName, string destinationSavePath)
{
string fileName = Path.GetFileNameWithoutExtension(originalFilePathAndName);
string originalFilePath = Path.GetDirectoryName(originalFilePathAndName);
string link = destinationSavePath + Path.DirectorySeparatorChar + fileName + ".lnk";
if (File.Exists(link)) File.Delete(link);
}
public static void DeleteStartupShortcut()
{
DeleteShortcut(System.Reflection.Assembly.GetEntryAssembly()?.Location, Environment.GetFolderPath(Environment.SpecialFolder.Startup));
}
}
,请参见More on Lists)并遍历列表的副本:
Ball.ball_list[:]
无论如何,由于您要从列表中删除所有元素,因此只需调用def new_game():
global game_over, score
for actor in Ball.ball_list[:]:
actor.kill()
score = 0
game_over = False
clear()
或删除所有元素(请参见del
)
Ball.ball_list.clear()
分别创建一个新的空列表
del Ball.ball_list[:]
请注意,garbage collection释放了未使用的对象的内存,因此从(所有)列表中删除一个对象就足够了。此外,不必重置将被破坏的对象的属性。