1
此代碼在黑色背景上顯示圖像assassin1.png
。只要按下鍵,圖像就會向右移動,並在釋放鍵後立即停止移動。pyglet:按下按鈕時更改sprite實例的圖像
只要我按下鍵,它也應該改爲圖像assassin2.png
,當我釋放鍵時,它應該改回assassin1.png
。 但是,此代碼在移動時從不顯示assassin2.png
圖像。爲什麼這樣,我該如何解決這個問題?
import pyglet
class Assassin(pyglet.sprite.Sprite):
def __init__(self, batch, img):
pyglet.sprite.Sprite.__init__(self, img, x = 50, y = 30)
def stand(self):
self.img = pyglet.image.load("assassin1.png")
return self
def move(self):
self.img = pyglet.image.load('assassin2.png')
return self
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 = Assassin(batch = self.batch_draw, img = pyglet.image.load("assassin1.png"))
self.keys_held = []
self.schedule = pyglet.clock.schedule_interval(func = self.update, interval = 1/60.)
def on_draw(self):
self.clear()
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.move()
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.stand()
print "The 'RIGHT' key was released"
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()
不錯的一個!謝謝,你做了我的一天。我一直在努力與這一個。 – Bentley4