Pygame經常使用方法

import pygameide

# 初始化pygame庫,讓計算機硬件準備
pygame.init()字體


# ----------窗口相關操做-----------
# 建立窗口
window = pygame.display.set_mode([窗口寬,窗口高])orm

# 設置窗口標題
pygame.display.set_caption("窗口標題")對象

# 加載資源圖片,返回圖片對象
image = pygame.image.load("res/game.ico")
# 設置窗口圖標
pygame.display.set_icon(image)事件


# 指定座標,將圖片繪製到窗口
window.blit(image, (0, 0))圖片


# ----------圖像相關操做-----------
# 加載圖片文件,返回圖片對象
image = pygame.image.load("圖片路徑")ip

# 得到圖片矩形對象 -> Rect(x, y, width, height)
# 默認狀況下左上角的座標是 (0, 0)
rect = image.get_rect(centerx=x, centery=y)資源


# 在原位置基礎上,移動指定的偏移量 (x, y 增長)
rect.move_ip(num1, num2)get


# 判斷兩個矩形是否相交,相交返回True,不然返回False
flag = pygame.Rect.colliderect(rect1, rect2)it

# 將圖片對象按指定寬高縮放,返回新的圖片對象
trans_image = pygame.transform.scale(image, (WINDOWWIDTH, WINDOWHEIGHT))


# ----------事件相關操做-----------
# 常見事件類型:
# QUIT 關閉窗口
# KEYDOWN 鍵盤按鍵
# 得到當前全部持續按鍵 bools_tuple


# 得到全部事件的列表
event_list = pygame.event.get()

for event in event_list:
# 1. 鼠標點擊關閉窗口事件
if event.type == pygame.QUIT:
print("關閉了窗口")
sys.exit()

# 2. 鍵盤按下事件
if event.type == pygame.KEYDOWN:

# 判斷用戶按下的鍵是不是a鍵
if event.key == pygame.K_a:
print("按了 a ")

if event.key == pygame.k_UP:
print("按了 方向鍵上")


# 3. 得到當前鍵盤全部按鍵的狀態(按下,沒有按下),返回bool元組
pressed_keys = pygame.key.get_pressed()
(0, 0, 0, 0, 1, 0, 0, 0, 0)

if pressed_keys[pygame.K_w] or pressed_keys[pygame.K_UP]:
print("按了 w 鍵,或者 方向鍵上")


# ----------音效相關操做-----------
# 加載背景音樂
pygame.mixer.music.load("./res/bg2.ogg")
# 循環播放背景音樂
pygame.mixer.music.play(-1)
# 中止背景音樂
pygame.mixer.music.stop()

# 加載音效
boom_sound = pygame.mixer.Sound("./res/baozha.ogg")
# 播放音效
boom_sound.play()

boom_sound.stop()


三基色:Red Green Blue

0 ~ 255

# -------- 文字顯示操做

# 設置字體和大小
font = pygame.font.SysFont('SimHei', 42)

# render(text(文本內容), antialias(抗鋸齒), color(RGB)),返回文字對象
textobj = font.render("飛機大戰", 1, (255, 255, 255))

# 設置文字矩形對象位置
textrect = textobj.get_rect(centerx=300, centery=300)

# 在指定位置繪製指定文字對象window.blit(textobj, textrect)

相關文章
相關標籤/搜索