【Python游戏编程02--pygame中的IO/数据】

一、pygame事件

1、pygame事件可以处理游戏中的各种事情,完整的事件列表如下:

QUIT,ACTIVEEVENT,KEYDOWN,KEYDOWN,MOUSEMOTION,MOUSEBUTTONUP,MOUSEBUTTONDOWN,JOYAXISMOTION,

JOYBALLMOTION,JOYHATMOTION........

查看文档:https://fishc.com.cn/thread-62173-1-4.html

2、事实循环事件

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()

3、键盘事件

键盘事件包括典型的keyup和keydown,当按键按下的时候响应KEYDOWN事件,按键弹起的时候KEYUP事件,通常可以设置一个事件变量,然后根据keyup或者keydown给他赋不同的值

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
        elif event.type == KEYUP:
            key_flag = True
        elif event.type == KEYDOWN:
            key_flag = False

默认情况下,pygame不会重复的响应一个一直被按下的键,只有在第一次被按下时,才会被响应一次,如果需要重复按键的话执行下面的操作

pygame.key_set.repeat(10)
#参数是一个以毫秒为单位的值

4、鼠标事件

pygame支持一些鼠标事件,他们包括MOUSEMOTION,MOUSEBUTTONUP,MOUSEBUTTONDOWN.

扫描二维码关注公众号,回复: 5705537 查看本文章

在MOUSEMOTION中包含了一些属性:event.pos,event.rel,event.buttons

pygame.mouse.get_pressed()  ——  获取鼠标按键的情况(是否被按下)
pygame.mouse.get_pos()  ——  获取鼠标光标的位置
pygame.mouse.get_rel()  ——  获取鼠标一系列的活动
pygame.mouse.set_pos()  ——  设置鼠标光标的位置
pygame.mouse.set_visible()  ——  隐藏或显示鼠标光标
pygame.mouse.get_focused()  ——  检查程序界面是否获得鼠标焦点
pygame.mouse.set_cursor()  ——  设置鼠标光标在程序内的显示图像
pygame.mouse.get_cursor()  ——  获取鼠标光标在程序内的显示图像
 for event in pygame.event.get():
        if event.type == MOUSEMOTION:
             mouse_x,mouse_y = event.pos
             move_x,move_y = event.rel

MOUSEBUTTONDOWN里面的属性:

event.type == MOUSEBUTTONDOWN:
            mouse_down = event.button
            mouse_down_x,mouse_down_y = event.pos

MOUSEBUTTONUP里面的属性:

event.type == MOUSEBUTTONUP:
            mouse_up = event.button
            mouse_up_x,mouse_up_y = event.pos

https://fishc.com.cn/thread-62179-1-4.html

二、设备轮询

在pygame中除了pygame事件,还可以使用设备轮询的方法来检测是否有事件发生。而且在python里面是没有switch语句的,因此当需要处理的事件过多时,我们肯定不会去一条一条的去写if...elif....else来匹配,而设备轮询正好解决了这个棘手的问题。

1、轮询键盘

在pygame中,使用pygame.key.get_pressed()来轮询键盘接口,这个方法会返回布尔值的一个列表,其中每个键一个标志。使用键常量值来匹配按键,这样的好处就是不必遍历时间系统就可以检测多个键的按下

keys = pygame.key.get_pressed()

if keys[K_ESCAPE]:

   pygame.quit()

        sys.exit()

2、轮询鼠标

同样,我们可以使用类似的方法去轮询鼠标事件。

这里有3个相关的函数:

(1)pygame.mouse.get_pos(),这个函数会返回鼠标当前的坐标x,y;

(2)pygame.mouse.get_rel();

rel_x ,rel_y = pygame.mouse.get_rel().利用这个函数可以读取鼠标的相对移动。

(3)btn_one,btn_two,btn_three = pygame.mouse.get_pressed();

利用这个函数,可以获取鼠标按钮的状态。比如当左键按下的时候btn_one 的值会被赋值为1,鼠标按键弹起是会被赋值为0。

猜你喜欢

转载自www.cnblogs.com/frankruby/p/10620342.html