美文网首页
Day17recode和pygame

Day17recode和pygame

作者: Heyjoky | 来源:发表于2018-10-22 20:09 被阅读0次

    回顾和补充

    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))
    

    抽象类和抽象方法

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

    怎么声明抽象类:类继承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()
    

    pygame的图片显示

    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()
    

    pygame的文字显示

    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的图形显示

    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.鼠标事件:

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

    2.键盘事件

    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.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))

    相关文章

      网友评论

          本文标题:Day17recode和pygame

          本文链接:https://www.haomeiwen.com/subject/dlcnzftx.html