目录
首先,在开始编写代码前引入 pygame 模块 :import pygame
1.创建一个可以关闭的窗体
使用pygame之前必须初始化
# 引入模块
import pygame
import sys
# 使用pygame之前必须初始化
pygame.init()
# 设置窗体大小 (填充色默认为黑色)
screen = pygame.display.set_mode((500, 300))
# 死循环 防止代码运行完毕后关闭窗体
while True:
# 循环获取事件,监听事件
for event in pygame.event.get():
# 判断用户是否点了关闭按钮
if event.type == pygame.QUIT:
# 卸载所有模块
pygame.quit()
# 终止程序
sys.exit()
# 更新屏幕内容
pygame.display.flip()
2.添加背景色,窗体中显示小红方格
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((500, 300))
# 主窗体添加背景色
screen.fill("blue")
# 自己定义的小方格 (宽,高)
face = pygame.Surface((50, 50))
# 小方格的颜色 (默认黑色)
face.fill("red")
# 把小方格添加到主窗体上 (小方格左上角起点位置)
screen.blit(face, (50, 50))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.flip()
3.屏幕显示文字文本
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((500, 300))
screen.fill("blue")
# 第一个是字体类型,第二个是字体大小
font = pygame.font.Font('C:/Windows/Fonts/simhei.ttf', 50)
# 第一个是文本内容, 第二个是字体是否平滑,第三个是字体颜色,第四个是字体背景颜色
text = font.render("第一个游戏窗口", True, (255, 0, 0), "yellow")
# 获取text的矩形
textRect = text.get_rect()
# 定义文本位置
textRect.center = (250, 150)
# 把文本添加到主窗体中
screen.blit(text, textRect)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.flip()
4.显示图片,在图片上画圆
这有两点:1,要在主窗体显示照片 2,在把圆画在图片上
显示图片可以用下面的代码:
image = pygame.image.load("img/2.jpg") # 图片路径
mage = image.get_rect() # 获取图片的矩形
mage.center = (250, 150) # 定义图片的位置
screen.blit(image, mage) # 把图片放在主窗体上(图片,位置)
这样就可以左第二个条件了:
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((500, 300))
image = pygame.image.load("img/2.jpg") # 图片路径
mage = image.get_rect() # 获取图片的矩形
mage.center = (250, 150) # 定义图片的位置
# (要放在谁的上面,自己的填充色,位置,半径)
circle = pygame.draw.circle(image, "red", (10,10), 10)
screen.blit(image, mage) # 把图片放在主窗体上(图片,位置)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.flip()
5.窗体的标题和图标
图标图片大小是32*32
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((500, 300))
# 设置窗体标题
pygame.display.set_caption("我是标题")
# 先得到图片之后再把图片绘制到图标上
image = pygame.image.load("img/2.jpg")
# 把图片绘制到图标上
pygame.display.set_icon(image)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 更新屏幕内容
pygame.display.flip()