pygame之事件與設備輪詢

 

一、pygame事件
1.簡介
    pygame事件可以處理遊戲中的各種事情。其實在前兩節的博客中,我們已經使用過他們了。如下是pygame的完整事件列表:
QUIT

ACTIVEEVENT;
KEYDOWN;
MOUSEMOTION;
MOUSEBUTTONUP;
MOUSEBUTTONDOWN;
JOYAXISMOTION;
JOYBALLMOTION;
JOYHATMOTION........

更多的事件可以去查pygame的文檔。http://www.pygame.org/docs/index.html

2.實時事件循環

pygame中的事件處理是放在一個實時的循環中來完成的。將代碼都放在一個while True的循環中,但是這樣會造成死循環,所以在裏面加一句sys.exit()來退出。

for event in pygame.event.get()

 上面的代碼將會創建當前等待處理的事件的一個列表,然後使用for循環來遍歷裏面的事件。這樣,我們將會根據事件產生的順序依次地進行不同的操作。常見的事件是按鍵按下,按鍵釋放以及鼠標移動。通常需要最先處理QUIT事件(在用戶關閉窗口的時候會產生該事件。)

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

3.鍵盤事件

鍵盤事件包括最典型的keyup 和 keydown 當按鍵按下的時候響應KEYDOWN事件,按鍵彈起的時候響應KEYDOWN事件。通常可以設置一個事件變量,然後根據keyup或者keydown給它賦不同的值。

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

默認的話pygame不會重複地去響應一個被一直按住的鍵,只是在按鍵第一次被按下的時候響應一次,如果需要重複響應一個按鍵的話下面的操作:

pygame.key.set_repeat(10)
#參數是一個以毫秒爲單位的值

4.鼠標事件

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

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

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

 

 

二、設備輪詢

在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()

例1: 

#導包
import pygame
from pygame.locals import *
import sys
import random

#初始化
pygame.init()

screen = pygame.display.set_mode((600,500))
pygame.display.set_caption("my games")
myfont = pygame.font.Font(None, 80)



black = 0, 0, 0
white = 255, 255, 255

#定義字符ASCII碼獲取字母
num = random.randint(97, 122)
char = chr(num)
txtImage = myfont.render(char, True, white)

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
#鍵盤事件
        elif event.type == KEYDOWN:
            print(event.unicode)
            print("鍵盤被按下")
        elif event.type == KEYUP:
            print("鍵盤被擡起")
        #鼠標事件
        #鼠標移動
        elif event.type == MOUSEMOTION:
            #獲得座標位置
            print(event.pos)
            #獲取鼠標移動量
            print(event.rel)
        # elif event.type == MOUSEBUTTONDOWN:
        #     print(event.pos)
    #獲取鼠標按鈕的狀態
    keys = pygame.key.get_pressed()

#設備輪詢
    if keys[K_ESCAPE]:
        pygame.quit()
        sys.exit()
    elif keys[num]:
        num = random.randint(97, 122)
        char = chr(num)
        txtImage = myfont.render(char, True, white)

    screen.fill(black)
    screen.blit(txtImage, (100,100))

    pygame.display.update()

 在這個程序中,我們使用到了一些新的模塊和函數,讓我們來了解一下。
Random.randint(x,y);看名字知道這個函數的作用了,它可以返回一個x~y之間的隨機數。
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。

鼠標拖拽橢圓移動 

import pygame
from pygame.locals import *
import sys
import math


pygame.init()


size = (800, 600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("my games")
myfont = pygame.font.Font(None, 80)



black = 0, 0, 0
white = 255, 255, 255
#圓心
circleHeart = (500, 400)
#半徑
radius = 80
#移動設置爲False
moving = False
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == MOUSEMOTION:
            if moving:
                moveXY = event.rel
                circleHeart = (circleHeart[0] + moveXY[0],circleHeart[1]+moveXY[1])

        elif event.type == MOUSEBUTTONDOWN:
            length = (circleHeart[0]-event.pos[0])*(circleHeart[0]-event.pos[0])+(circleHeart[1]-event.pos[1])*(circleHeart[1]-event.pos[1])
            #開平方
            length = math.sqrt(length)
            if event.button ==1 and length < radius:
                moving = True
        elif event.type == MOUSEBUTTONUP:
            if event.button ==1:
                moving = False
    screen.fill(black)


    pygame.draw.circle(screen, white, circleHeart, radius, 3)
    pygame.display.update()
import pygame
import sys

# 初始化
pygame.init()

size = width,height = 1000,600 # 設置屏幕尺寸
WHITE = 255,255,255
BLACK = 0,0,0


screen = pygame.display.set_mode(size) # 創建surface對象
pygame.display.set_caption('畫圓及拖拽') # 創建標題

# 圓心位置定義
position = size[0] // 2 , size[1] // 2

moving = False

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN: # 獲取點擊鼠標事件
            if event.button == 1: # 點擊鼠標左鍵
                moving = True
        if event.type == pygame.MOUSEBUTTONUP: # 獲取鬆開鼠標事件
            if event.button == 1: # 鬆開鼠標左鍵
                moving = False
    if moving:
        position = pygame.mouse.get_pos() # 更新圓心位置爲鼠標當前位置



    screen.fill(WHITE) # 填充屏幕
    # 畫各種尺寸顏色的圓
    pygame.draw.circle(screen, BLACK, position, 50, 1)

    # 刷新屏幕
    pygame.display.flip()

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章