1 安装
游戏开发引擎
pip install pygame

2 最小框架


3 极简框架

sys:

set_mode:

while:

pygame.event.get()

event.type:


import pygame
pygame.init() #初始化程序
pygame.display.set_mode((600,400)) #设置窗体大小
pygame.display.set_caption('python之家') #设置标题名称
while True: #循环
for event in pygame.event.get(): #获取事件
if event.type == pygame.QUIT: #退出事件
sys.exit()
pygame.display.update() #更新
4 小球游戏

图片地址:
https://python123.io/PY15/PYG02-ball.gif







import pygame
size = width , height = 600,400 #
speed = [1,1] #设置 速度 横坐标与纵坐标
screen = pygame.display.set_mode(size) #
BLACK=0,0,0 #黑色
pygame.display.set_caption('pygame 壁球')
ball = pygame.image.load('PYG02-ball.gif')
ball_rect = ball.get_rect()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
ball_rect = ball_rect.move(speed[0],speed[1])#移动1个单位
if ball_rect.left<0 or ball_rect.right >width:
speed[0] = -speed[0] #边缘取反
if ball_rect.top <0 or ball_rect.bottom>height:
speed[1] = - speed[1] #碰到边缘取反
screen.fill(BLACK) #补充为黑色 如果不写 则填充 白色
screen.blit(ball,ball_rect) #将图像绘制在矩形surface中
pygame.display.update() #更新
5 帧率修改


import pygame,sys
pygame.init()
size = width , height = 600,400 #设置长宽
speed = [1,1]
BLACK = 0,0,0
screen = pygame.display.set_mode(size)#背景设置
pygame.display.set_caption("Python Game")
ball = pygame.image.load('PYG02-ball.gif')
ball_rect = ball.get_rect() #surface对象
fps = 300
fclock = pygame.time.Clock()#创建clock对象
#初始化
while True:
for event in pygame.event.get():
if event.type ==pygame.QUIT:
sys.exit()
ball_rect=ball_rect.move(speed[0],speed[1])
if ball_rect.left<0 or ball_rect.right >width:
speed[0]=-speed[0]
if ball_rect.top<0 or ball_rect.bottom>height:
speed[1]=-speed[1]
screen.fill(BLACK) #背景颜色更新
screen.blit(ball,ball_rect) #将surface 图像填充
pygame.display.update() #更新
fclock.tick(fps) #更新频率设置
6 键盘使用
通过键盘上下左右 增加对应方向的速度


网友评论