pygame之事件(二)

来源:互联网 发布:树莓派 tensorflow 编辑:程序博客网 时间:2024/05/22 15:58

上一篇讲了鼠标,这一章看看键盘。

下面的代码是用键盘控制背景图片的移动。这图和上一篇的图片一样,因此省略运行效果图。

#coding=utf-8'''Created on 2011-1-1@author: Administrator'''background_image_filename=r'E:\image\sushiplate.jpg'from pygame.locals import *from sys import exitimport pygamepygame.init()screen = pygame.display.set_mode((640,468),0,32)pygame.display.set_caption("Hello World")background = pygame.image.load(background_image_filename).convert()x,y = 0,0move_x,move_y = 0,0while True:    for event in pygame.event.get():        if event.type == QUIT:            exit()        if event.type == KEYDOWN:            #键盘有按下            if event.key == K_LEFT:                move_x = -1            elif event.key == K_RIGHT:                move_x=1            elif event.key == K_UP:                move_y=-1            elif event.key == K_DOWN:                move_y =1        elif event.type == KEYUP:            if event.key == K_LEFT:                move_x = 0            elif event.key == K_RIGHT:                move_x = 0            elif event.key == K_UP:                move_y = 0            elif event.key == K_DOWN:                move_y = 0                        #计算新坐标        x+=move_x        y+=move_y        screen.fill((0,0,0))        screen.blit(background,(x,y))        pygame.display.update()


KEYDOWN和KEYUP都包含三个值:

    key:这表示是按下或释放的或。每一个物理按键都是K_开始,如K_a,K_z,请参见www.pygame.org/docs/ref/key.html

    mod:这是使用诸如Alt,Ctrl,Shift之类的功能键,都以KMOD_开始,如KMOD_SHIFT,KMOD_ALT,KMOD_CTRL.这些键都使用按位与操作。如 mod & KMOD_CTRL来判断CTRL是否被按下.www.pygame.org/docs/ref/key.html提供详细说明。

    unicode:键盘使用unicode编码(不常用)。


事件过滤(暂时看不懂,以后有用的时候补全)



原创粉丝点击