? ? 什么是pygame桥温?pygame是一個(gè)python中的一個(gè)游戲庫楞捂,用于2D游戲的開發(fā)!下面是關(guān)于pygame的一些常用方法兄渺。
首先? 需要導(dǎo)入
import pygame
#====窗口的相關(guān)操作====
# 創(chuàng)建一個(gè)窗口
screen = pygame.display.set_mode(width,hight)? ?#width 窗口的寬? hight 窗口的高
# 設(shè)置窗口標(biāo)題
pygame.display.set_caption("窗口標(biāo)題")
# 加載資源圖片缝龄,返回圖片對象
image = pygame.image.load("圖片的路徑")
# 設(shè)置窗口圖標(biāo)
pygame.display.set_icon(image)
# 指定坐標(biāo),將圖片繪制到窗口
window.blit(image, (0, 0))
# ----------圖像相關(guān)操作-----------
# 加載圖片文件挂谍,返回圖片對象
image = pygame.image.load("圖片路徑")
# 獲得圖片矩形對象 -> Rect(x, y, width, height)
# 默認(rèn)情況下左上角的坐標(biāo)是 (0, 0)
rect = image.get_rect(centerx=x, centery=y)
# 在原位置基礎(chǔ)上叔壤,移動指定的偏移量 (x, y 增加)
rect.move_ip(num1, num2)
# 判斷兩個(gè)矩形是否相交,相交返回True口叙,否則返回False
flag = pygame.Rect.colliderect(rect1, rect2)
# 將圖片對象按指定寬高縮放炼绘,返回新的圖片對象
trans_image = pygame.transform.scale(image, (WINDOWWIDTH, WINDOWHEIGHT))
# ----------事件相關(guān)操作和游戲的監(jiān)聽-----------
# 常見事件類型:
# QUIT 關(guān)閉窗口
# KEYDOWN 鍵盤按鍵
# 獲得當(dāng)前所有持續(xù)按鍵 bools_tuple
# 獲得所有事件的列表
event_list = pygame.event.get()
for event in event_list:
? ? # 1. 鼠標(biāo)點(diǎn)擊關(guān)閉窗口事件
? ? if event.type == pygame.QUIT:
? ? ? ? print("關(guān)閉了窗口")
? ? ? ? exit()
? ? # 2. 鍵盤按下事件
? ? if event.type == pygame.KEYDOWN:
? ? ? ? # 判斷用戶按下的鍵是否是a鍵
? ? ? ? if event.key == pygame.K_a:
? ? ? ? ? ? print("按了 a ")
? ? ? ? if event.key == pygame.K_UP:
? ? ? ? ? ? print("按了 方向鍵上")
# 3. 獲得當(dāng)前鍵盤所有按鍵的狀態(tài)(按下,沒有按下)妄田,返回bool元組
pressed_keys = pygame.key.get_pressed()
if pressed_keys[pygame.K_w] or pressed_keys[pygame.K_UP]:
? ? print("按了 w 鍵俺亮,或者 方向鍵上")
# ----------音效相關(guān)操作-----------
# 加載背景音樂
pygame.mixer.music.load("./res/音樂文件名")
# 循環(huán)播放背景音樂
pygame.mixer.music.play(-1)
# 停止背景音樂
pygame.mixer.music.stop()
# 加載音效
boom_sound = pygame.mixer.Sound("./res/音效名")
# 播放音效
boom_sound.play()
boom_sound.stop()
三基色:Red Green Blue
0 ~ 255
# -------- 文字顯示操作
font = pygame.font.SysFont('SimHei', 字體大小)
# render(text(文本內(nèi)容), antialias(抗鋸齒), color(RGB)),返回文字對象
textobj = font.render(text, 1, (200, 200, 200))
# 設(shè)置文字矩形對象位置
textrect = textobj.get_rect()
textrect.move_ip(水平偏移量, 豎直偏移量)
# 在指定位置繪制指定文字對象
window.blit(textobj, textrect)
# 更新界面
pygame.display.update()