"""交互
一个两层的场景。一个显示当前被按下的键(一次,一个或多个),另一个显示鼠标位置的文本,然后单击以移动文本。
"""
import cocos
import pyglet
from cocos.director import director
class KeyDisplay(cocos.layer.Layer):
# 允许图层接收Director.window事件
is_event_handler = True
def __init__(self):
super(KeyDisplay, self).__init__()
self.text = cocos.text.Label('', x=100, y=280)
# 记录按键set集合
# self.key_pressed = []
self.key_pressed = set()
self.update_text()
self.add(self.text)
def update_text(self):
"""更新text"""
# 转为符号字符串
key_names = [pyglet.window.key.symbol_string(k) for k in self.key_pressed]
text = 'Keys:' + ','.join(key_names)
self.text.element.text = text
# 事件处理器, 向层添加事件处理器就是一个添加名为 on_<event name(事件名)> 的方法
def on_key_press(self, key, modifiers):
"""按下一个键
'key'是一个常量,指示按下哪个键,来自 pyglet.window.key
'modifiers(修饰符)'是一个按位或几个常量,指示哪些修饰符在按下时处于活动状态(ctrl,shift,capslock等)
"""
# self.key_pressed.append(key)
self.key_pressed.add(key)
self.update_text()
def on_key_release(self, key, modifiers):
"""释放一个键
'key'是一个常量,指示按下哪个键,来自 pyglet.window.key
'modifiers(修饰符)'是一个按位或几个常量,指示哪些修饰符在按下时处于活动状态(ctrl,shift,capslock等)
"""
self.key_pressed.remove(key)
self.update_text()
class MouseDisplay(cocos.layer.Layer):
"""
其他:
on_mouse_release : 当按键松开
on_mouse_scroll : 当滚轮转动
on_mouse_leave : 当鼠标指针移除窗口
on_mouse_enter : 当鼠标指针移入窗口
"""
is_event_handler = True
def __init__(self):
super(MouseDisplay, self).__init__()
self.posx = 100
self.posy = 240
self.text = cocos.text.Label('No mouse events', font_size=18, x=self.posx, y=self.posy)
self.add(self.text)
def update_text(self, x, y):
text = 'Mouse @ %d,%d' % (x, y)
self.text.element.text = text
self.text.element.x = self.posx
self.text.element.y = self.posy
def on_mouse_motion(self, x, y, dx, dy):
"""当鼠标移动到应用程序窗口上并且没有按鼠标按键时
(x,y)是鼠标的物理坐标 ,鼠标事件处理器从pyglet接收其物理坐标
(dx,dy)是鼠标至上次调用后经过的的距离向量
"""
self.update_text(x, y)
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
"""此函数在鼠标在应用程序窗口上移动并按下鼠标按键时被调用
(x,y)是鼠标的物理坐标
(dx,dy)是鼠标至上次调用后经过的的距离向量
'buttons' 是一个按位或pyglet.window.mouse常量-->LEFT,MIDDLE,RIGHT
'modifiers' 是一个按位或pyglet.window.key修饰符常量(值如 'SHIFT', 'OPTION', 'ALT')
"""
self.update_text(x, y)
def on_mouse_press(self, x, y, buttons, modifiers):
"""按下鼠标按键不仅更新鼠标位置,还改变标签的位置
(x,y)是鼠标的物理坐标
'buttons' 是一个按位或pyglet.window.mouse常量-->LEFT,MIDDLE,RIGHT
'modifiers' 是一个按位或pyglet.window.key修饰符常量(值如 'SHIFT', 'OPTION', 'ALT')
"""
self.posx, self.posy = director.get_virtual_coordinates(x, y)
self.update_text(x, y)
if __name__ == '__main__':
cocos.director.director.init(resizable=True) # 可调整大小
keyDisplay_layer = KeyDisplay()
mouseDisplay_layer = MouseDisplay()
# 接收层列表
main_scene = cocos.scene.Scene(keyDisplay_layer, mouseDisplay_layer)
# 运行场景
cocos.director.director.run(main_scene)