一、pygame使用流程
import pygame :导入pygame模块
pygame.init() :初始化,使用之前必须初始化
screen = pygame.display.set_mode((800,600)) : 设置窗口大小
screen.fill((0,0,255)) : 设置背景为蓝色
设置主循环,设置事件监听,更新窗口。
# 导入所需的模块
import pygame, sys
# 导入所有pygame.locals里的变量(如QUIT变量)
from pygame.locals import *
# 初始化pygame
pygame.init()
# 设置窗口的大小,单位为像素
screen = pygame.display.set_mode((800, 600))
# 设置窗口标题
pygame.display.set_caption('test')
# 程序主循环
while True:
# 获取事件
for event in pygame.event.get():
# 判断事件是否为退出事件
if event.type == QUIT:
# 退出pygame
pygame.quit()
# 退出系统
sys.exit()
# 绘制屏幕内容
pygame.display.update()
二、pygame导入图像并设置动画
robots_taank.png:
import pygame
pygame.init()
screen = pygame.display.set_mode((800,600))
img=pygame.image.load(r'F:\Code\VSCode\Python\Game\Tank\res\robots_tank.png')
#表述在(0,0)坐标处取一个width=32,heigth=32的矩形
rect1=pygame.Rect(0,0,32,32)
#获取子图像(rect1图像)
img_up=img.subsurface(rect1)
# 设置窗口标题
pygame.display.set_caption('Tank')
# 创建游戏时钟
clock=pygame.time.Clock()
# 设置帧率
FPS=30
#图像在窗口的坐标
site = [0, 0]
#设置图像的移动速度
speed = 2
#设置反向
direction = 'down'
while True:
screen.fill((255, 255, 255))
if direction == 'down':
#判断是否超出边界,超出则停止
if site[1]<600:
site[1] += speed
if direction == 'up':
if site[1]>0:
site[1] -= speed
if direction == 'left':
if site[0]>0:
site[0] -= speed
if direction == 'right':
if site[0]<800:
site[0] += speed
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
direction='up'
if event.key == pygame.K_DOWN:
direction='down'
if event.key == pygame.K_LEFT:
direction='left'
if event.key == pygame.K_RIGHT:
direction='right'
# 设置每秒刷新FPS次
clock.tick(FPS)
screen.blit(img_up, site)
pygame.display.flip()
运行结果:
三、pygame按钮及页面跳转
class Page:
def __init__(self, screen, button_position, button_size, next_page):
self.screen = screen
self.button_position = button_position
self.button_size = button_size
self.next_page = next_page
def draw(self):
# 绘制页面背景
pygame.draw.rect(self.screen, BLACK, (0, 0, SCREEN_WIDTH, SCREEN_HEIGHT))
# 绘制按钮
pygame.draw.rect(self.screen, WHITE, (self.button_position[0], self.button_position[1], self.button_size[0], self.button_size[1]))
def update(self, event):
# 检测按钮是否被点击
if event.type == pygame.MOUSEBUTTONDOWN:
if self.button_position[0] < event.pos[0] < self.button_position[0] + self.button_size[0] and self.button_position[1] < event.pos[1] < self.button_position[1] + self.button_size[1]:
# 按钮被点击,切换到下一个页面
self.next_page.draw()
# 创建两个页面
page1 = Page(pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)), (SCREEN_WIDTH // 2 - 50, SCREEN_HEIGHT // 2 - 25), (100, 50), page2)
page2 = Page(pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)), (SCREEN_WIDTH // 2 - 50, SCREEN_HEIGHT // 2 - 25), (100, 50), page1)
# 主循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
page1.update(event)
page2.update(event)
pygame.display.update()