Pygame 是一个跨平台的 Python 模块, 专为电子游戏设计. Pygame 在已经非常优秀的 SDL 库的基础上增加了许多功能.
安装命令:
pip install pygame
导入 Pygame 包:
import pygame
pygame.locals
模块包括了 pygame 中定义的各种常量.
导入所有常量
from pygame.locals import *
pygame.init()
是启动 pygame 并初始化的命令, 类似 python 中的__init__
.
例子:
# 导入模块
import pygame# 初始化 pygame
pygame.init()
pygame.display.set_mode()
是初始化 pygame 窗口的命令.
格式:
pygame.display.set_mode(size=(0, 0), flags=0, depth=0, display=0, vsync=0)
参数:
例子:
# 显示一个分辨率 600*400 的窗口
screen = pygame.display.set_mode((600, 400))
import pygame
import sys# 导入pygame中的常量
from pygame.locals import *# 初始化pygame
pygame.init()# 设置游戏窗口的尺寸, set_mode 函数的参数用元组表示尺寸 (width和height)
pygame.display.set_mode((600, 600))# 捕获游戏的事件
typelist = [QUIT]while True:# 获取事件for event in pygame.event.get():# 接收到退出事件, 退出程序if event.type in typelist:sys.exit() # 退出
pygame.font.Font()
可以帮助我们来设置字体和字体大小.
格式:
pygame.font.Font(filename, size)
参数:
例子:
# 设置字体和字号
myFont = pygame.font.Font(None, 60)
screen.fill()
用于填充 pygame 窗口背景色的命令.
格式:
screen.fill(color, rect=None, special_flags=0)
参数:
例子:
screen.fill((0, 0, 200)
Font.render()
用于创建文本并转换为图像.
格式:
Font.render(text, antialias, color, background=None)
参数:
例子:
textImage = myFont.render("Hello Pygame", True, (255, 255, 0)
screen.blit()
用于将图像显示到我们要显示的地方.
格式:
screen.blit(source, dest, area=None, special_flags=0)
参数:
例子:
screen.blit(textImage, (10, 60))
pygame.display.update()
用于更新显示.
代码:
import pygame
from pygame.locals import *
import sysyellow = (255, 255, 0) # 文字颜色
blue = (0, 0, 200) # 背景颜色# 初始化 pygame
pygame.init()# 设置窗口尺寸
screen = pygame.display.set_mode((600, 400))# 设置字体和字号
myFont = pygame.font.Font(None, 60)# 将文字转换为图像, 消除锯齿
textImage = myFont.render("Hello Pygame", True, yellow)# 填充背景
screen.fill(blue)# 显示文字
screen.blit(textImage, (10, 60))# 更新显示
pygame.display.update()# 捕获游戏事件
typelist = [QUIT]while True:# 获取事件for event in pygame.event.get():# 接收到退出事件, 退出程序if event.type in typelist:sys.exit() # 退出
输出结果:
代码:
import pygame
from pygame.locals import *
import sysyellow = (255, 255, 0) # 文字颜色
blue = (0, 0, 200) # 背景颜色# 初始化 pygame
pygame.init()# 设置窗口尺寸
screen = pygame.display.set_mode((600, 400))# 设置字体和字号 (仿宋)
myFont = pygame.font.Font("C:\Windows\Fonts\simfang.ttf", 60)# 将文字转换为图像, 消除锯齿
textImage = myFont.render("你好 Pygame", True, yellow)# 填充背景
screen.fill(blue)# 显示文字
screen.blit(textImage, (10, 60))# 更新显示
pygame.display.update()# 捕获游戏事件
typelist = [QUIT]while True:# 获取事件for event in pygame.event.get():# 接收到退出事件, 退出程序if event.type in typelist:sys.exit() # 退出
输出结果: