Pyglet:如何让同一个类的精灵实例共享坐标?

时间:2012-06-30 14:11:47

标签: python class pyglet

如何使此代码正常工作:只需安装pyglet并将assassin1.pngassassin2.pngassassin3.png更改为存储在保存此代码的目录中的图像名称文件。

import pyglet

def sprite_type(type_ = "standing"):
    if type_ == "moving-forward":
        moving_forward_image_list = [pyglet.image.load('assassin2.png'), pyglet.image.load('assassin3.png')]
        moving_forward_animation = pyglet.image.Animation.from_image_sequence(moving_forward_image_list, 0.3) 
        return moving_forward_animation
    if type_ == "standing":
        standing_animation = pyglet.image.load("assassin1.png")
        return standing_animation

class Assassin(pyglet.sprite.Sprite):        
    def __init__(self, batch, img):
        pyglet.sprite.Sprite.__init__(self, img, x = 50, y = 30)

class Game(pyglet.window.Window):
    def __init__(self):
        pyglet.window.Window.__init__(self, width = 315, height = 220)
        self.batch_draw = pyglet.graphics.Batch()
        self.player_dict = {"standing": Assassin(batch = self.batch_draw, img = sprite_type()), "moving-forward": Assassin(batch = self.batch_draw, img = sprite_type(type_ = "moving-forward"))}
        self.player = self.player_dict["standing"]
        self.fps_display = pyglet.clock.ClockDisplay()
        self.keys_held = []      
        self.schedule = pyglet.clock.schedule_interval(func = self.update, interval = 1/60.) 

    def on_draw(self):
        self.clear()
        self.fps_display.draw()
        self.batch_draw.draw()
        self.player.draw()  

    def on_key_press(self, symbol, modifiers):
        self.keys_held.append(symbol)
        if symbol == pyglet.window.key.RIGHT:
            self.player = self.player_dict["moving-forward"]
            print "The 'RIGHT' key was pressed"

    def on_key_release(self, symbol, modifiers):
        self.keys_held.pop(self.keys_held.index(symbol))
        self.player = self.player_dict["standing"]

    def update(self, interval):
        if pyglet.window.key.RIGHT in self.keys_held:
            self.player.x += 50 * interval

if __name__ == "__main__":
    window = Game()
    pyglet.app.run()

此代码显示assassin1.png,而位置(50 30)没有按键,当按住右键时角色向前移动,每隔0.3秒显示2张图像assassin2.png和{{1}切换为给出行走角色的错觉。此外,还显示了fps。

目前,当您释放该键时,该角色将返回原始位置(50,30)。当您再次按下该键时,角色会从行走角色最后停止的位置移动。

我理解为什么会发生这种情况,因为步行动画角色和站立角色是同一班级的两个不同实例。 我首先想到使用类变量我能够存储位置。但我似乎无法想出一个有效的解决方案。有没有人有任何想法我能做什么?

编辑1(@Hugh Bothwell)

assassin3.png

1 个答案:

答案 0 :(得分:1)

你需要一个具有运动状态的角色,而不是拥有站立角色和行走角色。