Pygame

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

Pygame簡介

pygame是一個Python的套件,主要用來創建 2D 遊戲和多媒體應用程式。它提供了一系列的功能,使開發者能夠輕鬆地處理圖形、音效、動畫以及使用者互動等方面。

建立開發環境

  1. 確定使否已安裝Python
python --version
  1. 開啟要建立環境的路徑
cd <路徑位置>
  1. 輸入下方指令建立一個新的環境
python -m venv <環境名稱>
  1. 進入虛擬環境路徑並啟動
cd <路徑位置>\Scripts // 切換玩路徑後再執行 activate.bat
  1. 切換完成後輸入下面指令安裝套件
pip install pygame

這樣就完成環境設定了

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

基本Pygame指令

基本範例程式碼

下面是官方提供的基本的範例程式碼,包括最基本的pygame需要的東西.後面會依序介紹他們的功能

# Example file showing a basic pygame "game loop" import pygame # pygame setup pygame.init() screen = pygame.display.set_mode((1280, 720)) clock = pygame.time.Clock() running = True while running: # poll for events # pygame.QUIT event means the user clicked X to close your window for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # fill the screen with a color to wipe away anything from last frame screen.fill("purple") # RENDER YOUR GAME HERE # flip() the display to put your work on screen pygame.display.flip() clock.tick(60) # limits FPS to 60 pygame.quit()

初始化pygame物件

pygame.init()

顯示視窗

  1. 設定顯示視窗物件(指定視窗的高度與寬度, flag是用來設定顯示模式的例如全螢幕等等)
screen = pygame.display.set_mode((width, height), flags=0)
  1. 設定視窗標題
pygame.display.set_caption("遊戲標題")
  1. 顯示更新畫面(可以選擇是否只更新哪個區塊,如未設定則整個畫面更新)
pygame.display.update(rectangle=None)
  1. 獲取畫面資訊(解析度,顯示方式等)
info = pygame.display.Info()
  1. 切換螢幕顯示方式(全螢幕🔁視窗)
pygame.display.toggle_fullscreen()
  1. 設定視窗的icon
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)

設定畫布

Surface是Pygame中一個非常重要的物件,它代表了所有可顯示的畫面、圖像或介面元素。幾乎所有在Pygame中的圖形繪製,都是在Surface上進行的。

  1. 創建Surface
# 創建一個 800x600 的空白 Surface surface = pygame.Surface((800, 600))
  1. 繪製圖形和顏色
surface.fill((255, 0, 0))  # 填充紅色
pygame.draw.rect(surface, (0, 255, 0), (50, 50, 200, 100))  # 繪製綠色矩形
  1. Surface圖像
image = pygame.image.load('image.png')
surface.blit(image, (0, 0))  # 將圖像繪製到surface上
  1. 複製Surface
new_surface = surface.copy()  # 複製 Surface
  1. 旋轉Surface
rotated_surface = pygame.transform.rotate(surface, 90)  # 旋轉 Surface
  1. 透明度
surface.set_alpha(128)  # 設定透明度(範圍:0-255,0為完全透明)
  1. 繪製Surface到視窗中
screen = pygame.display.set_mode((800, 600))
screen.blit(surface, (0, 0))  # 將 surface 繪製到螢幕
pygame.display.update()  # 更新螢幕顯示

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
前面說明完了最基本的語法,有了這些語法我們可以開始製作簡易的動畫了

基本動畫

基本控制事件(滑鼠鍵盤)

角色控制(Sprite)

簡易小遊戲