# 資研 5/31 上課講義 ## Pygame >參考自 *Python 自學聖經-Python 入門教學* :::warning **前置作業** 1. 安裝 VScode、Python [**利用 VScode 撰寫 Python 教學**](https://hackmd.io/@smallshawn95/vscode_write_py) 2. 在終端機輸入 ``` python -m pip install pygame ``` 3. 安裝完成了! ::: ### 基本架構 #### 引入套件 ```python= import pygame ``` #### 啟動模組 ```python= pygame.init() ``` #### 設定視窗 - <font color="##005757">**建立視窗**</font> ```python= screen = pygame.display.set_mode('視窗大小') ``` >視窗大小傳入時要用 tuple 包起來 >若大小設定為 (640, 320) ,則意義為 **寬 640 長 320** - <font color="##005757">**設定標題**</font> ```python= pygame.display.set_caption('繪圖視窗標題') ``` #### 設定畫布 - <font color="##005757">**建立畫布**</font> ```python= background = pygame.Surface(screen.get_size()) ``` >通常畫布大小會和視窗大小相同 >利用 `screen.get_size()` 可回傳視窗大小 - <font color="##005757">**建立副本**</font> ```python= background = background.convert() ``` >建立副本可加速畫布在視窗的填滿速度 - <font color="##005757">**畫布顏色**</font> ```python= background.fill((0, 0, 0)) # 白色 ``` - <font color="##005757">**貼上畫布**</font> ```python= screen.blit(background, (0, 0)) ``` >(0, 0) 為畫布貼上的座標位置 >以左上角為主 #### 更新視窗 ```python= pygame.display.update() ``` >更新以上步驟以顯示視窗內容 #### 關閉視窗 利用迴圈時時判斷使用者是否關閉視窗 ```python= running = True while running: for event in pygame.event.get(): if event == pygame.QUIT: running = False pygame.quit() ``` >`pygame.event.get()`可回傳目前狀態 >`pygame.QUIT`代表使用者按下關閉鍵 >`pygame.quit()`結束整個程式 #### 基本程式碼 ```python= import pygame pygame.init() screen = pygame.display.set_mode((640, 320)) pygame.display.set_caption('I2TRC2') background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((255, 255, 255)) # 白色 screen.blit(background, (0, 0)) pygame.display.update() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit() ``` 
×
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