|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
下面代码,第一步选定棋子,第二步移动到指定位置。
运行显示: s1.do(cocos.actions.MoveTo((100 + x2 * 160, 220 + y2 * 160), duration=2))
NameError: name 's1' is not defined
- import pyglet
- import cocos
- from pyglet.gl import *
- from cocos.sprite import Sprite
- from cocos.scene import Scene
- from cocos.director import director
- def game_scene():
- scene = Scene()
- scene.add(GameLayer(), z=1)
- return scene
- class GameLayer(cocos.layer.ColorLayer):
- def __init__(self):
- super().__init__(128, 128, 128, 128)
- cocos.layer.Layer.is_event_handler = True
- self.first=True
- s1 = Sprite('red1.png')
- s1.position=100,220
- self.add(s1)
- def on_mouse_press(self,x, y, button, modifiers):
- if button == pyglet.window.mouse.LEFT:
- x = round((x - 100) / 160)
- y = round((y - 220) / 160)
- if self.first:
- x1 = x
- y1 = y
- self.first = False
- else:
- x2 = x
- y2 = y
- s1.do(cocos.actions.MoveTo((100 + x2 * 160, 220 + y2 * 160), duration=2))
- self.first = True
- def run_game():
- director.init(resizable=True, width=520, height=640, caption="szq")
- director.run(game_scene())
- if __name__ == "__main__":
- run_game()
复制代码
在您的代码中,`s1` 是在 `__init__` 方法内部定义的局部变量,因此在 `on_mouse_press` 方法中是无法访问的。您需要将 `s1` 定义为实例变量,这样可以在类的其他方法中访问它。可以通过将 `s1` 前面加上 `self.` 来实现。
以下是修改后的代码:
- import pyglet
- import cocos
- from pyglet.gl import *
- from cocos.sprite import Sprite
- from cocos.scene import Scene
- from cocos.director import director
- def game_scene():
- scene = Scene()
- scene.add(GameLayer(), z=1)
- return scene
- class GameLayer(cocos.layer.ColorLayer):
- def __init__(self):
- super().__init__(128, 128, 128, 128)
- cocos.layer.Layer.is_event_handler = True
- self.first = True
-
- # 将 s1 定义为实例变量
- self.s1 = Sprite('red1.png')
- self.s1.position = 100, 220
- self.add(self.s1)
- def on_mouse_press(self,x, y, button, modifiers):
- if button == pyglet.window.mouse.LEFT:
- x = round((x - 100) / 160)
- y = round((y - 220) / 160)
- if self.first:
- self.x1 = x
- self.y1 = y
- self.first = False
- else:
- x2 = x
- y2 = y
-
- # 使用 self.s1 而不是 s1
- self.s1.do(cocos.actions.MoveTo((100 + x2 * 160, 220 + y2 * 160), duration=2))
- self.first = True
- def run_game():
- director.init(resizable=True, width=520, height=640, caption="szq")
- director.run(game_scene())
- if __name__ == "__main__":
- run_game()
复制代码
现在 `s1` 被定义为 `self.s1`,这是一个实例变量,因此在 `on_mouse_press` 方法中也可以访问到它。请确保位图文件 `red1.png` 位于项目的正确
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
|
|