pygame

###一、复习上周学习的内容

####1.json数据
json数据的要求:
a.一个json对应一个数据
b.json中的数据一定是json支持的数据类型

数字:整数和小数
字符串:双引号引起来的内容
数组:[120, “anc”, true, [1, 2], {“a”:123}]
字典: {“abc”:120, “aa”:”abc”, “list”:[1, 2]}
布尔: true/false
null: 空(None)

json模块:
load(文件对象) –> 将文件中的内容读出来,转换成python对应的数据
dump(内容, 文件对象) –> 将内容以json格式,写入到文件中

loads(字符串) –> 将json格式字符串转换成python数据 ‘{“a”: 12}’
dumps(python数据) –> 将python数据转换成json格式的字符串

####2.异常处理
try-except-finally语法捕获异常
raise语法抛出异常

a.
try:
代码1
except:
代码2

try:
代码1
except (异常类型1,异常类型2…):
代码2

try:
代码1
except 异常类型1:
代码2
except 异常类型2:
代码3

b. raise 错误类型
错误类型:必须是Exception的子类(系统的错误类型和自定义的类型)
自定义错误类型:写一个类继承Exception,重写str方法定制错误提示语

####3.类和对象
a.类的声明
class 类名(父类列表):
类的内容

b.创建对象
对象 = 类名()

c.类的字段和对象的属性
类的字段:
对象的属性:init方法,self.属性=值

d.对象方法,类方法,静态方法
对象方法:
类方法:@classmethod
静态方法:@staticmethod

e.对象属性的增删改查
f.私有化:名字前加__
g.getter和setter
h.常用的内置属性: 对象._ _ dict_ _, 对象. _ _ class _ _, 类. _ _ name _ _
i.继承:所有类都默认继承object,继承哪些东西,重写(super()), 添加对象属性

###二、抽象类和抽象方法
抽象类:只能被继承不能实例化(不能创建对象)
抽象方法:声明的时候不用实现,在子类中必须去重写的方法

怎么声明抽象类:类继承abc模块中的ABCMeta,继承的时候需要加参数metaclass。
并且要通过abstractmethod来声明抽象方法
子类继承一个抽象类,必须在子类中实现抽象类中所有的抽象方法
metaclass -> 元类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import abc

class Shape(metaclass=abc.ABCMeta):
# 声明抽象方法
@abc.abstractmethod
def draw(self):
pass

@abc.abstractmethod
def area(self):
pass

class Circle(Shape):
def draw(self):
print('画图形')

def area(self):
print('面积')

# 抽象类不能实例化
# s1 = Shape()

c1 = Circle()

###三、pygame图片显示
display –> 屏幕相关
event –> 事件
draw –> 图形
image –> 图片
font –> 字体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import pygame
# 1.初始化游戏
pygame.init()

# 2.创建窗口对象
"""
set_mode(size) --> size是元祖:(长,宽), 单位是像素
"""
screen = pygame.display.set_mode((600, 400))

"""
fill(颜色) --> 填充指定的颜色, 元祖(red, green, blue)
计算机使用的是计算机三原色(红、绿、蓝) --> rgb颜色, 对应的值的范围是0-255

红色:(255, 0, 0)
绿色: (0, 255, 0)
白色:(255, 255, 255)
黑色:(0, 0, 0)
黄色: (255, 255, 0)
"""
screen.fill((255, 255, 255))

# 4.显示图片
"""
1.加载图片
load(图片地址) -> 返回图片对象
"""
image = pygame.image.load('./files/01.jpg')

"""
a.获取图片的大小
图片.get_size() --> 返回图片的大小,结果是元祖
"""
image_width, image_height = image.get_size()

"""
b.对图片进行缩放
transform.scale(图片对象, 大小) --> 将指定的图片缩放成指定的大小, 返回一个新的图片对象
注意:这种缩放,可能会让图片发生形变
"""
new_image1 = pygame.transform.scale(image, (800, 600))

"""
c.对图片进行缩放和旋转(按比例缩放)
rotozoom(图片对象, 角度, 比例)
比例:原图的多少倍,放大:大于1, 缩小:小于1
角度:0 ~ 360 (逆时针旋转)
"""
new_image2 = pygame.transform.rotozoom(new_image1, 0, 0.5)

"""
2.渲染图片
blit(渲染对象,渲染位置)
渲染位置 -> 元祖,(x坐标, y坐标)
"""
screen.blit(new_image2, (100, 100))

angle = 0

"""
3.展示内容,只要想将内容展示在屏幕上,都必须调用这个方法
"""
pygame.display.flip()

# 3.游戏循环(不断检测是否有事件发生)
while True:
# 不断检测事件的产生
for event in pygame.event.get():
# 不同类型的事件,event的type属性不同
if event.type == pygame.QUIT:
exit() # 程序结束

###四、pygame的文字显示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import pygame

pygame.init()
screen = pygame.display.set_mode((600, 400))
screen.fill((255, 255, 255))
pygame.display.flip()

# 显示文字
"""
1.创建字体对象
SysFont(字体名, 字体大小, 是否加粗=False, 是否倾斜=False) --> 创建系统字体对象

Font(字体文件路径, 字体大小) --> 自定义字体
字体文件:后缀是.ttf文件
"""
# font = pygame.font.SysFont('宋体', 50, italic=True)
font = pygame.font.Font('./files/aa.ttf', 50)

"""
2.根据字体创建文字对象
字体对象.render(文字,是否抗锯齿,颜色)
"""
text = font.render('你好,python', True, (0, 255, 0))

"""
3.在窗口上渲染文字
"""
screen.blit(text, (100, 100))

"""
4.展示在屏幕上
"""
pygame.display.flip()

while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()

###五、pygame图形显示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import pygame
import random

def rand_color():
"""随机颜色"""
return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)

pygame.init()
screen = pygame.display.set_mode((600, 400))
screen.fill((255, 255, 255))

# 画图(pygame.draw)
"""
1.画线
def line(Surface, color, start_pos, end_pos, width=1)
Surface: 窗口, 图片, 文字对象
color:线的颜色
start_pos,end_pos: 起点和终点(坐标)
width:宽度
"""
pygame.draw.line(screen, (0, 0, 0), (50, 50), (100, 100), 5)

"""
def lines(Surface, color, closed, pointlist, width=1)
closed: 是否连接起点和终点
pointlist: 列表,列表中的元素是点对应的元祖
"""
points = [(50, 100), (200, 100), (250, 200), (120, 250), (30, 160)]
pygame.draw.lines(screen, (255, 0, 0), True, points, 6)

"""
2.画圆
def circle(Surface, color, pos, radius, width=0)
pos: 圆心位置
radius: 半径
width: 默认0(填充)
"""
pygame.draw.circle(screen, (255, 255, 0), (100, 200), 80, 0)


"""
def arc(Surface, color, Rect, start_angle, stop_angle, width=1)
Rect: (x, y, w, h)
start_angle, stop_angle: 弧度(0->0, 90->pi/2, 45 -> pi/4)
"""
from math import pi
screen.fill((255, 255, 255)) # 将之前画的全部覆盖掉
pygame.draw.arc(screen, rand_color(), (100, 100, 100, 100), pi/4, pi/4*3, 4)


pygame.display.flip()

while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()

###六、pygame事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import pygame

"""
1.鼠标事件:
事件类型:event.type
MOUSEBUTTONDOWN --> 鼠标按下
MOUSEBUTTONUP --> 鼠标弹起
MOUSEMOTION --> 鼠标移动
关心鼠标的位置:event.pos

键盘事件
"""
import random
def rand_color():
"""随机颜色"""
return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)


pygame.init()
screen = pygame.display.set_mode((600, 400))
screen.fill((255, 255, 255))
pygame.display.flip()

while True:
# 只要有事件产生就会进入for循环
for event in pygame.event.get():
# 根据判断type的值来判断是什么事件产生了
if event.type == pygame.QUIT:
exit()

# =================鼠标事件=================
elif event.type == pygame.MOUSEBUTTONDOWN:
# 鼠标按下后要做什么事情就写在这儿...
print('鼠标按下:', event.pos)
pygame.draw.circle(screen, rand_color(), event.pos, random.randint(10, 40))
pygame.display.flip()

elif event.type == pygame.MOUSEBUTTONUP:
# 鼠标按下后弹起
print('鼠标弹起', event.pos)
elif event.type == pygame.MOUSEMOTION:
# 鼠标移动
print('鼠标移动', event.pos)
pygame.draw.circle(screen, rand_color(), event.pos, random.randint(10, 40))
pygame.display.flip()
# pygame.draw.circle(screen, rand_color(), event.pos, 30)
# pygame.display.flip()

# ==================键盘事件======================
elif event.type == pygame.KEYDOWN:
print('按键按下:', event.key, chr(event.key))

elif event.type == pygame.KEYUP:
print('按键弹起:', event.key, chr(event.key))