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()
相關文章
相關標籤/搜索