吳裕雄--天生自然python學習筆記:python 用pygame模塊檢測鍵盤事件和鼠標事件


用戶可通過鍵盤輸入來操控游戲中角色的運動,取得鍵盤事件的方法有以下兩種 :

 

 

 

 

 

 常用的按鍵與鍵盤常數對應表 :

按下右箭頭鍵,藍色小球會 向 右移動:按住右箭頭鍵不放 , 球體會快速 向 右移
動, 若到達邊界則停止移動:按左箭頭鍵,藍色小球會 向 左移動 ,到達邊界則 停止。

 

 

 

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 70))
pygame.display.set_caption("鍵盤事件")

background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((255,255,255))

ball = pygame.Surface((30,30))  #建立球的矩形背景區
ball.fill((255,255,255))  #矩形區域背景為白色
pygame.draw.circle(ball, (0,0,255), (15,15), 15, 0)  #畫藍色球

rect1 = ball.get_rect()  #取得球的矩形背景區域
rect1.center = (320,35)  #球的初始位置
x, y = rect1.topleft  #球左上角坐標
dx = 5  #球移動距離

clock = pygame.time.Clock()

running = True
while running:
    clock.tick(30)  #每秒執行30次
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    keys = pygame.key.get_pressed()  #檢查按鍵是按下
    if keys[pygame.K_RIGHT] and rect1.right < screen.get_width():  #按向右鍵且未達右邊界
        rect1.centerx += dx  #向右移動
    elif keys[pygame.K_LEFT] and rect1.left > 0:  #按向左鍵且未達左邊界
        rect1.centerx -= dx  #向左移動
        
    screen.blit(background, (0,0))  #清除繪圖窗口
    screen.blit(ball, rect1.topleft)
    pygame.display.update()
pygame.quit()

鼠標事件
游戲中的角色除了可用鍵盤來操作外,還可以用鼠標來操作。鼠標事件包括鼠
標按鍵事件及鼠標移動事件兩大類。

開始時藍色球不會移動,單擊或按下鼠標左鍵后,移動 鼠 標則球會跟着 鼠標移
動;按鼠標右鍵后 , 球不會跟着鼠標移動 。

 

 

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 300))
pygame.display.set_caption("鼠標移動事件")

background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((255,255,255))

ball = pygame.Surface((30,30))  #建立球的矩形背景繪圖區
ball.fill((255,255,255))  #矩形區域背景為白色
pygame.draw.circle(ball, (0,0,255), (15,15), 15, 0)  #畫藍色實心圓作為球體

rect1 = ball.get_rect()  #取得球的矩形背景區域
rect1.center = (320,150)  #設置球的起始位置
x, y = rect1.topleft  #球左上角坐標

clock = pygame.time.Clock()

running = True
playing = False  #開始時球不能移動
while running:
    clock.tick(30)  #每秒執行30次
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    buttons = pygame.mouse.get_pressed()
    if buttons[0]:  #按下左鍵后拖動鼠標球可移動
        playing = True
    elif buttons[2]:  #按下右鍵后拖動鼠標球不能移動
        playing = False
    if playing == True:  #球可移動狀態
        mouses = pygame.mouse.get_pos()  #取得鼠標坐標
        rect1.centerx = mouses[0]  #把鼠標的x坐標作為球中心的X坐標
        rect1.centery = mouses[1] #把鼠標的y坐標作為球中心的y坐標
    screen.blit(background, (0,0))  #清除繪圖窗口
    screen.blit(ball, rect1.topleft)  #重新繪制
    pygame.display.update()  #顯示
pygame.quit()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM