# Pygame遊戲設計 ###### tags: `人生苦短,我學Python` ## 初識Pygame * Pygame是跨平台的python模組。專門為電子遊戲設計,包括圖片、聲音等等...... ## 安裝Pygame * 需要pip安裝 ```python= pip install pygame ```  ## 常用模塊 | 模塊名 | 功能| | ------------------------ | -------------------------------------- | |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 ```python= 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的無線迴圈下,視窗會一直保留著 * 建立遊戲視窗 ```python= 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)  * 開始添加 ```python= 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() ``` * 結果  ## 讓小球動起來 ```python= # while 外面 speed = [5, 5] # while 裡面 ballract = ballract.move(speed) ``` * 結果(小球一閃而過)  ## 檢測框架,遇到碰撞時反彈 ```python= # 左右 if ballract.left < 0 or ballract.right > width: speed[0] = -speed[0] ## 上下 if ballract.top < 0 or ballract.bottom > height: speed[1] = -speed[1] ``` * 結果 => 水球濺  ## 再來是增加時間控制運行 ```python= # while 外面 clock = pygame.time.Clock() # while 裡面 clock.tick(60) ``` * 結果  {%hackmd S1DMFioCO %}
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up