这是更新pygame中精灵的最佳方式吗?

时间:2014-09-12 15:57:28

标签: python pygame

切入所有不相关的部分,这就是我实施它的方式:

done=False
while(done==False)
    #here goes some code for listening to the events
    if (some condition fulfilled) then
           screen.blit(background, [0,0])
           screen.blit(some_sprite,[x,y])
      elif (more conditions)
           do something else
      else
           do even more stuff

   pygame.display.flip()

如果没有此条件语句中的后台更新,则此精灵不会被删除,当然,我在屏幕上获得了多个副本。我有一种强烈的怀疑,这到目前为止还不是处理这种情况的最佳方式,因为每次我需要做其他事情时不会改变的图像似乎是浪费资源。

我很感激任何建议

1 个答案:

答案 0 :(得分:2)

根据个人经验,这里是我推荐的内容。我建立了一个基于平铺的游戏并对其进行了过度设计。我的最终解决方案看起来有点像这样:

class Graphic(object):
    def __init__(*some_args):
        self.owner = which_object_owns_this_graphic
        self.priority = some_int
        # if more than one graphic are stacked on each other, which one to display?
        self.surface = surface_to_draw_on
        self.graphic = sprite_to_draw
    @property
    def x(self): return self.owner.x
    @property
    def y(self): return self.owner.y
    def draw(self):
        self.surface.blit(self.graphic, (self.x, self.y))

class Tile(object):
    def __init__(*some_args):
        self.x = x
        self.y = y
        self.graphic = some_default_Graphic_with_priority_minusone
        self.contains = [self]
        # list of objects that live here right now
    @property
    def topmost(self):
        """returns the graphic of the object with highest priority that is contained here"""

global_update_list = []
# anytime a tile is moved into or out of, place it here

然后在我的事件循环中:

for tile in global_update_list:
    tile.topmost.draw()
global_update_list = []

这使我无法在每次移动时重新绘制屏幕,​​我可以重新绘制移出的图块以及移动到的图块。