17总 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()), 添加对象属性

class Perosn(object):
    def __init__(self):
        self._age = 0

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        self._age = value

补充1: 抛出异常

class MyError(Exception):
    def __str__(self):
        return '需要一个偶数,但是给了一个奇数'


number = int(input('请输入一个偶数:'))
if number & 1:
    raise MyError

补充2:多继承

class Animal:
    num = 10
    def __init__(self, age):
        self.age = age

    def run(self):
        print('可以跑')

print(Animal.__dict__)

class Fly:
    def __init__(self, height):
        self.height = height

    def can_fly(self):
        print('可以飞')


class Bird(Animal, Fly):
    def __init__(self, color):
        super().__init__(10)
        self.color = color

注意:多继承的时候,只能继承第一个父类的对象属性(创建对象的时候调用的是第一个父类的对象方法)

一般在需要继承多个类的功能的时候用

b1 = Bird('abc')
# b1.age = 18
# b1.height = 200
print(b1.age)
# print(b1.height)
b1.can_fly()
b1.run()


class Student:
    def __init__(self, name='', age=0, tel=''):
        self.name = name
        self.age = age
        self.tel = tel
        self.sex = '男'

    def show_info(self):
        print(self.__dict__)

    def __repr__(self):

        return '<'+str(self.__dict__)[1:-1]+'>'


all_students = [Student('小明', 18, '1278763'),
                Student('xiaohua', 12, '127723')
                ]


class Dog:
    def __init__(self):
        self.name = ''
        self.age = 0
        self.color = ''
        self.type = ''
    def __repr__(self):
        return '<'+str(self.__dict__)[1:-1]+'>'

import json

将对象保存到本地

def object_json(file, content):
with open('./'+file, 'w', encoding='utf-8') as f:
new = []
for stu in content:
new.append(stu.dict)
json.dump(new, f)

object_json('test.json', all_students)

将字典列表转换成对象列表

def json_object(file, type):
    with open('./'+file, 'r', encoding='utf-8') as f:
        list1 = json.load(f)
        all_value = []
        for dict1 in list1:
            object = type()
            for key in dict1:
                setattr(object, key, dict1[key])
            all_value.append(object)
    return all_value


# print(json_object('test.json', Student))
# print(json_object('test2.json', Dog))


stu = Student('xiaoming', 12, '231273')  # Student.json

dog1 = Dog()   # Dog.json
dog1.name = 'XiaoHua'
dog1.age = 3
dog1.color = '黄色'
dog1.type = '斗狗'

将不同类型的对象添加到不同的json文件中

def add_object_json2(obj: object):
    file_name = obj.__class__.__name__+'.json'

    # 获取原文中的内容
    try:
        with open('./'+file_name, encoding='utf-8') as f:
            list1 = json.load(f)
    except FileNotFoundError:
        list1 = []

    with open('./'+file_name, 'w', encoding='utf-8') as f:
        list1.append(obj.__dict__)
        json.dump(list1, f)



add_object_json2(stu)
add_object_json2(dog1)


def get_all_info(type):
    file = type.__name__+'.json'
    with open('./'+file, 'r', encoding='utf-8') as f:
        list1 = json.load(f)
        all_value = []
        for dict1 in list1:
            object = type()
            for key in dict1:
                setattr(object, key, dict1[key])
            all_value.append(object)
    return all_value

print('学生:', get_all_info(Student))
print('狗:', get_all_info(Dog))

问题:怎么将对象写入json文件中?怎么将json中的字典读出后转换成相应的对象?

1.抽象类和抽象方法:

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

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

2pygame图片显示:

import pygame

display --> 屏幕相关
event --> 事件
draw --> 图形
image --> 图片
font --> 字体
···

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/luffy4.jpg')

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

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

"""
c.对图片进行缩放和旋转(按比例缩放)
rotozoom(图片对象, 角度, 比例)
比例:原图的多少倍,放大:大于1, 缩小:小于1
角度:0 ~ 360 (逆时针旋转)
"""
new_image2 = pygame.transform.rotozoom(image, 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() # 程序结束

"""author = 余婷"""

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()
"""author = 余婷"""
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()

"""author = 余婷"""
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, 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))
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容

  • 1recode 1.json数据json数据的要求:a.一个json对应一个数据b.json中的数据一定是json...
    大漠判官1阅读 313评论 0 0
  • 1.recode 1.json数据json数据的要求:a.一个json对应一个数据b.json中的数据一定是jso...
    芽菜包66阅读 207评论 0 0
  • recode """ 1.json数据 json数据的要求:a.一个json对应一个数据b.json中的数据一定是...
    我才是鳄鱼宝宝阅读 222评论 0 0
  • 晓道阅读 211评论 0 0
  • 一、while 循环,让指定的代码重复执行 二、while语句写法: 初始条件设置 —— 通常是重复执行的 计数器...
    姓高名旭升阅读 168评论 0 0