# pygame 套件筆記 ## 基本模板 ```python import pygame as pg #pygame初始化 pg.init() #設定視窗 width, height = 640, 480 screen = pg.display.set_mode((width, height)) pg.display.set_caption("Sean's game") #建立畫布bg bg = pg.Surface(screen.get_size()) bg = bg.convert() bg.fill((255,255,255)) #白色 #顯示 screen.blit(bg, (0,0)) pg.display.update() #關閉程式的程式碼 running = True while running: for event in pg.event.get(): if event.type == pg.QUIT: running = False pg.quit() ``` ## 編成步驟 ### 引入資料庫 ```python import pygame as pg ``` ### pygame初始化 ```python pg.init() ``` ### 依設定顯示視窗 ```python screen = pg.display.set_mode((weight,height)) ``` ### 遊戲標題 ```python pg.display.set_caption("這邊打標題就好") ``` ### 關閉函式 ```python while running: for event in pg.event.get(): if event.type == pg.QUIT: running = False pg.quit() ``` ## 常用函式 ### 建立畫布 ```python 背景變數 = pg.Surface(screen.get_size()) #get_size取得畫布大小 背景變數 = 背景變數.convert() #convert()建立副本,加快畫布在視窗顯示速度 背景變數.fill((0,0,0)) #後三數字為色碼 視窗變數.blit(背景變數, 繪製位置) #繪製位置通常為(0,0) pg.display.update() #最後要update ``` ## 繪圖函式 ### 畫一個矩形的形狀 ```python pygame.draw.rect(畫布, 顏色, [x坐標, y坐標, 寬度, 高度], 線寬) ``` ### 畫出任意數量的形狀 ```python pygame.draw.polygon ``` ### 圍繞一個點畫一個圓圈 ```python pygame.draw.circle(畫布, 顏色, (x坐標, y坐標), 半徑, 線寬) ``` ### 在矩形內繪製圓形 ```python pygame.draw.ellipse(畫布, 顏色, [x坐標, y坐標, x直徑, y直徑], 線寬) ``` ### 繪製一條直線段 ```python pygame.draw.line(畫布, 顏色, (x坐標1, y坐標1), (x坐標2, y坐標2), 線寬) ``` - 可加s變成多條直線段 ### 繪製精細的抗鋸齒線 ```python pygame.draw.aaline ``` - 可加s變成多條抗鋸齒線 ### 繪製圓弧形 ```python pygame.draw.arc(畫布, 顏色, [x坐標, y坐標, x直徑, y直徑], 起始角, 結束角, 線寬) ``` ### 加入文字 ```python 字體變數 = pg.font.SysFont(字體名稱, 字體尺寸) 文字變數 = 字體變數.render(文字, 平滑值, 文字顏色, 背景顏色) 視窗變數.blit(文字變數, (320,240)) ``` ### 載入img ```python 圖片變數 = pygame.image.load(圖片檔案路徑) 圖片變數.convert() #也可以用convert()增加繪製速度 ``` ### 讀取img ```python 背景變數.blit(圖片變數, (20,10)) ```