目录
一、pygame的安装
二、pygame基础操作
1.基本窗体设置
2.surface组件
3.event事件
在pycharm 左下角的终端上输入指令pip install pygame,按下回车键执行下载,推荐下载到虚拟环境上,即路径前方带有(venv)。或者不使用pycharm,在控制窗口输入执行该命令也可以(控制窗口打开方式:win+r输入cmd按下回车进入,切记需要进入python环境中才可执行命令)
使用pygame.display.set_mode()设置基本窗体,后续所有操作都要依附于该窗体,括号内填入窗体的大小, 需要以元组的方式传入(宽, 高)
使用fill方法设置窗体填充颜色,推荐使用颜色的RGB值, 也可以使用英文单词
import pygame
import sys
# 初始化pygame
pygame.init()
# 设置基础窗体,大小为300x200
screen = pygame.display.set_mode((300, 200))
# 为窗体填充颜色
screen.fill((255, 200, 170))
# 设置窗体循环
while True:
for event in pygame.event.get():
# 设置窗体关闭条件, 点击窗体右上角的x结束程序
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 更新屏幕内容
pygame.display.flip()
运行结果
surface组件可以理解为一个个小的对象,也就是你需要向主窗体上所添加的内容
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((300, 200))
screen.fill((255, 200, 170))
# 设置一个基础surface对象, 100x100的矩形
surface = pygame.surface.Surface((50, 50))
# 为矩形填充颜色(白色)
surface.fill((255, 255, 255))
# 加载字体并设置字号
font = pygame.font.Font("../font/simkai.ttf", 20)
# 设置文本内容以及文本颜色
text = font.render("hello world", True, (0, 0, 0))
# 加载一张图片
image = pygame.image.load("../image/2.jpg")
# 让矩形在窗体上显示,元组内为显示位置坐标
screen.blit(surface, (125, 25))
# 在主窗体上显示文字
screen.blit(text, (100, 0))
# 在主窗体上显示图片
screen.blit(image, (100, 100))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.flip()
最终效果如下
一般来说游戏操作都会使用键盘按键和鼠标等来执行,所谓的按下按键以及点击鼠标就是pygame中的event事件,pygame中的常见时间有以下几种
逻辑就是如果触发了某个事件,则执行对应的操作,比如我这里写了一个如果按下空格键则把背景颜色切换为绿色的事件
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((300, 200))
screen.fill((255, 200, 170))
# 设置一个基础surface对象, 100x100的矩形
surface = pygame.surface.Surface((50, 50))
# 为矩形填充颜色(白色)
surface.fill((255, 255, 255))
# 加载字体并设置字号
font = pygame.font.Font("../font/simkai.ttf", 20)
# 设置文本内容以及文本颜色
text = font.render("hello world", True, (0, 0, 0))
# 加载一张图片
image = pygame.image.load("../image/2.jpg")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 判断是否按下了键盘
if event.type == pygame.KEYDOWN:
# 如果按下的是空格,则执行背景颜色替换
if event.key == pygame.K_SPACE:
# 将背景颜色替换为绿色
screen.fill((50, 255, 50))
print("按下了空格键")
# 将surface对象放入循环内防止背景填充后被覆盖
screen.blit(surface, (125, 25))
screen.blit(text, (100, 0))
screen.blit(image, (100, 100))
pygame.display.flip()
这是按下空格之前的窗体
下面是按下空格之后的样子, 可以看到背景颜色被替换且控制台输出文字