Python监听事件并作出响应代码

Python监听事件并作出响应代码python

# 事件:游戏启动以后用户针对游戏所作的操做
# 监听:捕捉到用户的操做,有针对性的作出响应
# pygame中经过pygame.event.get()能够得到用户当前所作动做的事件列表
 
import pygame
from pygame.locals import *
 
pygame.init()
 
# 建立游戏的窗口 480*700
screen=pygame.display.set_mode((480,700),0,0)
 
# 绘制背景图像
background = pygame.image.load("./shoot/background.png")
screen.blit(background,(0,0))
 
# 绘制大飞机
bigplane = pygame.image.load("./shoot/hero0.png")
screen.blit(bigplane,(200,500))
 
# 统一更新
pygame.display.update()
 
# 建立时钟对象
clock=pygame.time.Clock()
 
# 定义大飞机的初始位置
bigplane_rect=pygame.Rect(150,500,102,126)
 
while True:
    # 控制帧率
    clock.tick(60)
 
    # 事件监听
    for event in pygame.event.get():
        
        #判断用户是否点击了关闭按钮
        if event.type==pygame.QUIT:
            print("退出游戏!")
 
            # quit卸载全部模块
            pygame.quit()
 
            #退出系统
            exit()
 
    # 修改大飞机位置
    bigplane_rect.y-=1
 
    # 判断飞机的位置
    if bigplane_rect.y+bigplane_rect.height<=0:
        bigplane_rect.y=700
 
    screen.blit(background,(0,0))
    screen.blit(bigplane,bigplane_rect)
    pygame.display.update()
    # 为当前窗口增长事件
    # 利用pygame注册事件,其返回值是一个列表
    # 存放当前注册时获取的全部事件
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
 
pygame.quit()
相关文章
相关标签/搜索