Pygame 学习练习(一):什么是事件?

来源:互联网 发布:javasuo所使得软件 编辑:程序博客网 时间:2024/06/05 16:10

重点:Pygme中的所有事件类型





练习1:方向键移动图片

#!/usr/bin/python#-*-coding:utf-8-*-background_image_filename = "/home/yg/Pictures/sushiplate.jpg"#记录图片路径import pygamefrom pygame.locals import *from sys import exitmudi = """本段代码是利用事件学习,用户按下键盘方向键,然后移动屏幕中的图片。"""pygame.init()screen = pygame.display.set_mode((800,800),0,32)background = pygame.image.load(background_image_filename)x,y = 0,0#move记录移动值move_x,move_y = 0,0 while True:for event in pygame.event.get():print "event = ",event.type#print K_RIGHT 这样输出,K_RIGHT代表某一个特定的数字#print QUITif event.type == QUIT:exit()#在pygame.event.get()从时间队列中获取事件出来,然后判断是什么类型事件#event.get()函数每次执行后返回eventlistif event.type == KEYDOWN:if event.key == K_RIGHT:move_x = -1elif event.key == K_UP:move_y = 1elif event.key == K_DOWN:move_y = -1elif event.key == K_LEFT:move_x = 1elif event.type == KEYUP:move_x = 0move_y = 0x += move_xy += move_y#fill()是Surface对象的一个方法,他代表了'fill Surface with a solid color‘#后面的参数代表RGB颜色值,0,0,0 代表黑色,255.255.255代表screen.fill((255,255,255))#blit()文档上这样说明"Draws a source Surface onto this Surface",#blit(source, dest, area=None, special_flags = 0) -> Rect#source为要贴的surface对象,screen.blit(background,(x,y))#经过实验加入注释掉这个方法,那么就会一团黑。#zhege     pygame.display.update()

效果




练习2:通过F键切换全/窗口屏幕

#!/usr/bin/python#-*-coding:utf-8-*-import pygamefrom sys import exitfrom pygame.locals import *pygame.init()Pic = (449,300)#记录图片分辨率,为了填充好窗口screen = pygame.display.set_mode(Pic,0,32)pygame.display.set_caption("Fullscreen Testing")#设置窗口的标题background_image_filename = "/home/yg/Pictures/1.jpg"background = pygame.image.load(background_image_filename).convert()Fullscreen =  Falsewhile True:for event in pygame.event.get():if event.type == QUIT:exit()if event.type == KEYDOWN:#当事件类型为键盘按下时候,event会有三个属性,unicode,key,mod,unicode会记录按了哪个键,#可以用print str(event)打印出来看上面的几个属性信息,print str(event)if event.unicode == u'f':#判断是否按了这个键,按了的话符合条件然后就设置全屏幕Fullscreen = not Fullscreen #Fullscreen用的太机智了,下一次按就会符合另外一个条件,达到按F可以交替全/非全屏幕if Fullscreen:screen = pygame.display.set_mode(Pic,FULLSCREEN,32)else:screen = pygame.display.set_mode(Pic,0,32)screen.blit(background,(0,0)) #把背景图片花到surface对象(屏幕那个框框)上。pygame.display.update()#每次循环都更新一下

效果:



0 0
原创粉丝点击