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)