一、pygame安装
pygame是做游戏的第三方库,首先安装pygame
pip install pygame -i https://pypi.tuna.tsinghua.edu.cn/simple
注意: -i及之后的是防止不能访问国外网站,转用清华源进行安装
安装成功大至会出现图中圈出来的Successfully字样
二、pygame第一个小程序
import pygame
pygame.init()
screen = pygame.display.set_mode([640, 480])
运行结果会闪现一个小窗口:
加两行代码,保持窗口:
while True:
pass
更优雅的结束:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
这里使用了pygame的事件机制,while循环中不停获取pygame的事件,当发现有事件类型是退出时,整个程序退出
三、在窗口中画图
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255]) # 填充为白色
# 在screen上画一个红色的圆,位置在(100,100)处坐标,
# 半径30,线宽为0表示完全用红色填充圆
pygame.draw.circle(screen, [255, 0, 0], [100, 100], 30, 0)
pygame.display.flip() # 将画的圆显示出来
while True: # 循环等待退出信息
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
此程序相比上个程序新增3行代码,
fill行表示整个窗口填充为白色
draw行是实际的画圆代码,screen表示画在哪个对象上,[255,0, 0]表示圆的颜色是红色,[100,100]表示画圆中心点的坐标,30是圆的半径,0表示此圆的宽度为0,即圆整个是红色填充。
flip()是一个类似输出的函数,将整幅图(白色的窗口和红色的圆)都显示出来。
四、pygame中的颜色
rgb的颜色表示法:红绿蓝三元色
颜色在pygame中的定义
from pygame.color import THECOLORS
挑出红绿蓝在color中的定义:
THECOLORS = {
...
'red': (
255,
0,
0,
255,
),
...
'green': (
0,
255,
0,
255,
),
...
'blue': (
0,
0,
255,
255,
),
...
}
3个点的省略号表示中间还有其它的定义,简单说明一下,'red'为字符串,指颜色名,rgb的值在r上为255, 其它2元上为0,最后一个255表示透明度,这里表示一点都不透明
五、pygame中的坐标
针对设定为640*480的窗口,左上角为坐标(0,0), 右下角为(640,480), 中间的坐标为(320, 240)
窗口从左向右用X表示,最左边X=0, 最右边X=640, 最中间X=320
从上到下用Y表示,最上边Y=0,最下边Y=480,中间Y=240
如下图所示:
现在我们将之前的圆画到窗口中间去:
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
pygame.draw.circle(screen, [255, 0, 0, 15], [320, 240], 30, 0) # 修改坐标为[320,240]使得居中
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
效果图:
六、形状和大小
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
# 320,240指的是坐标,100,80指的是这么大的长方形,0表示线宽为0,即没有边框
pygame.draw.rect(screen, [255, 0, 0], [320, 240, 100, 80], 0)
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
七、提升:半透明的圆环
"""
@subscribe: 画半透明圆的测试代码
"""
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
surface = pygame.Surface([640, 480], pygame.SRCALPHA)
pygame.draw.circle(surface, [255, 0, 0, 15], [320, 240], 30, 5)
screen.blit(surface, [0, 0])
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()