gpt4 book ai didi

python - pyglet:按下按钮时更改 Sprite 实例的图像

转载 作者:太空宇宙 更新时间:2023-11-03 14:30:43 24 4
gpt4 key购买 nike

此代码在黑色背景上显示图像 assassin1.png。我一按下键,图像就向右移动,一松开键,图像就停止移动。

我一按下该键,它也应该变为图像 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()

最佳答案

我查看了 pyglet's source code我认为问题出在这里:

self.img = pyglet.image.load(...

图像存储在 self.image 变量中,而不是 self.img。所以改为:

self.image = pyglet.image.load(...

应该更新 Sprite 正在使用的图像。

关于python - pyglet:按下按钮时更改 Sprite 实例的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11308382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com