下面是类NPC
class NPC:
def __init__(self):
self.x = randint(0,800)
self.y = randint(0,60)
self.velocity_x = 5
self.drop_y = 60
self.img = "my image path here"
npc = NPC()
num_npc = 5
list = []
for i in range(num_npc):
list.append(npc)在游戏循环中,只显示一个静止的图像。我正在尝试编写面向对象的旧代码,但找不到呈现npc的最佳方法
下面是我使用的旧代码,它按预期工作
npc_img = []
npc_x = []
npc_y = []
npc_vel_x = []
npc_vel_y = []
num_of_npc = 5
for i in range(num_of_npc):
npc_img.append("my img path")
npc_x.append(random.randint(0, 800))
npc_y.append(random.randint(0, 60))
npc_vel_x.append(4)
npc_vel_y.append(40)发布于 2020-07-10 10:31:25
你的代码已经非常正确了。但是,您创建NPC对象实例的方式并不完全正确。我猜你的意思是将5个NPC添加到列表中,而不是5个对同一NPC对象的引用。这就是你的问题标题所说的!
npc = NPC()
...
for i in range(num_npc):
list.append(npc) # <<-- HERE, same object, 5 times代码应该在循环内调用NPC构造函数,而不是在它外部调用。
for i in range( num_npc ):
new_npc = NPC()
list.append( new_npc )在重写代码时,将坐标和图像尺寸保留在Pygame Rect中可能是值得的,因为这样可以方便地进行碰撞检测和其他更好的事情。
类似于:
class NPC:
def __init__(self):
self.image = pygame.image.load( "image path here" ).convert_alpha()
self.rect = self.image.get_rect()
self.rect.x = randint(0,800)
self.rect.y = randint(0,60)
self.velocity_x = 5
self.drop_y = 60
def draw( self, screen ):
screen.blit( self.image, self.rect )
def hitBy( self, arrow_rect ):
hit = self.rect.colliderect( arrow_rect )
return hit发布于 2020-07-10 09:05:18
如果我没理解错的话,像这样的东西应该是有效的:
class NPC:
def __init__(self):
self.x = randint(0,800)
self.y = randint(0,60)
self.velocity_x = 5
self.drop_y = 60
self.image_list = []
self_image_load_dict = {}
def add_image(self, image_path):
self.image_list.append(image_path)
def load_images(self):
self.image_load_dict[]
for i in len(self.get_image_list()):
self.image_load_dict[i] = pygame.image.load(self.get_image_list()[i])
def get_image_list(self):
return self.image_list
def get_image_load_dict(self):
return self.image_load_dict我使用了fstring,这样可以更容易地加载图像并跟踪图像编号:
npc = NPC()
for i in range(NUMBER_OF_NPC):
npc.add_image(f"image_path_{i}")现在您在对象列表中有了image_paths,我假设您想要加载它们,因此使用load_images方法。
注意:如果需要,您可以创建用于加载图像的其他方法。例如,如果你有“左”和“右”运动的动画
我希望这能回答你的问题,如果我遗漏了什么,请在评论中说。
https://stackoverflow.com/questions/62825224
复制相似问题