(Python3)- PyGame 基本參數學習-1

(Python3)- PyGame 基本參數學習-1

(Python3)- PyGame 基本參數學習-1

 

 

PyGame 是一種 Python 用來製作遊戲的模組,它能讓開發者可以用更簡單的方式加入文字、圖案、聲音等元素並進行事件處理來開發遊戲。 首先,我們先來進行環境設定,先確保你的作業系統有安裝 Python3。

 

$ pip install pygame

 

在開始 PyGame Hello World 之前先認識 PyGame 幾大核心元素:

  1. pygame.Surface:Surface 資料型別,代表一個矩形的影像,用來繪製在螢幕上
  2. pygame.Rect:Rect 資料型別,用來定位矩形空間的位置和可以用來偵測物件是否碰撞的
  3. pygame.event:事件模組,用來處理使用者觸發事件,包含自定義事件
  4. pygame.font:文字模組,用來顯示文字,可用來顯示儀表板資料
  5. pygame.draw:繪圖模組,可以畫出多邊形圖形,可當作背景物件
  6. pygame.image:圖片模組,用來處理載入圖片等相關操作,可當作角色精靈(sprite)
  7. pygame.time:時間模組,包含控制遊戲迴圈迭代速率,確保反饋不會太快消逝

 

接著我們直接使用 PyGame 製作一個 hello world 畫面,這樣讀者可以更清楚整個設計的架構:

import sys

import pygame
from pygame.locals import QUIT

# 初始化
pygame.init()
# 建立 window 視窗畫布,大小為 800x600
window_surface = pygame.display.set_mode((800, 600))
# 設置視窗標題為 Hello World:)
pygame.display.set_caption('Hello World:)')
# 清除畫面並填滿背景色
window_surface.fill((255, 255, 255))

# 宣告 font 文字物件
head_font = pygame.font.SysFont(None, 60)
# 渲染方法會回傳 surface 物件
text_surface = head_font.render('Hello World!', True, (0, 0, 0))
# blit 用來把其他元素渲染到另外一個 surface 上,這邊是 window 視窗
window_surface.blit(text_surface, (10, 10))

# 更新畫面,等所有操作完成後一次更新(若沒更新,則元素不會出現)
pygame.display.update()

# 事件迴圈監聽事件,進行事件處理
while True:
    # 迭代整個事件迴圈,若有符合事件則對應處理
    for event in pygame.event.get():
        # 當使用者結束視窗,程式也結束
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

 

 

 

免責聲明:

1.本影像檔案皆從網上搜集轉載,不承擔任何技術及版權問題。

2.如有下載連結僅供寬頻測試研究用途,請下載後在24小時內刪除,請勿用於商業。

3.若侵犯了您的合法權益,請來信通知我們,我們會及時刪除,給您帶來的不便,深表歉意。



1 thought on “(Python3)- PyGame 基本參數學習-1”

  • I like what you guys are up too. This type of clever work and coverage!
    Keep up the good works guys I’ve included you guys to our blogroll.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *