初識Pygame
Pygame是跨平台的python模組。專門為電子遊戲設計,包括圖片、聲音等等……
安裝Pygame
需要pip安裝
常用模塊
模塊名 |
功能 |
Pygame.display |
pygame中用於控制窗口和屏幕顯示的模塊。 |
Pygame.draw |
pygame中繪製圖形的模塊。 |
Pygame.event |
用於處理事件與事件引發的pygame模塊 |
Pygame.image |
用於圖像傳輸的pygame模塊 |
pygame.key |
與鍵盤相關的pygame模塊 |
class pygame.Rect |
用於存儲橢圓坐標的pygame對象 |
class pygame.BufferProxy |
表示圖像的對象 |
pygame.Color |
用於描述顏色的對象 |
pygame.music |
音樂模塊 |
pygame.time |
時間模塊 |
建立第一個窗口
使用display與event
1 2 3 4 5 6 7 8 9 10 11 12 13
| import sys import pygame
pygame.init() size = width, height = 320, 240 screen = pygame.display.set_mode(size)
while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit()
pygame.quit()
|
第一個遊戲視窗 :point_down:
pygame基本使用
製造窗口,並設計一個小球遊戲
在while的無線迴圈下,視窗會一直保留著
建立遊戲視窗
1 2 3 4 5 6 7 8 9 10 11 12 13
| import sys import pygame
pygame.init() size = width, height = 640, 480 screen = pygame.display.set_mode(size)
while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit()
pygame.quit()
|
添加小球
先去下載好圖片(ball.jpg)
開始添加
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import sys import pygame
pygame.init() size = width, height = 640, 480 screen = pygame.display.set_mode(size) color = (0, 0, 0)
ball = pygame.image.load("ball.jpg") ballract = ball.get_rect()
while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit()
screen.fill(color) screen.blit(ball, ballract) pygame.display.flip() pygame.quit()
|
結果
讓小球動起來
1 2 3 4 5
| speed = [5, 5]
ballract = ballract.move(speed)
|
結果(小球一閃而過)
檢測框架,遇到碰撞時反彈
1 2 3 4 5 6 7
| if ballract.left < 0 or ballract.right > width: speed[0] = -speed[0]
if ballract.top < 0 or ballract.bottom > height: speed[1] = -speed[1]
|
結果 => 水球濺
再來是增加時間控制運行
1 2 3 4
| clock = pygame.time.Clock()
clock.tick(60)
|
結果