美文网首页
day15 总结 - 面向对象和pygame

day15 总结 - 面向对象和pygame

作者: Gary134 | 来源:发表于2018-11-26 14:19 被阅读0次

    01.recode

    1.类方法和静态方法

    对象方法:
    a.直接声明在类中
    b.自带self参数
    c.使用对象调用

    类方法:
    a.声明@classmethod后面
    b.自带cls参数
    c.使用类调用

    静态方法:
    a.声明@staticmethod后面
    b.没有自带的参数
    c.使用类调用

    2.私有化

    加__

    3.getter和setter

    a.属性名加_
    b.@property后面声明函数,函数名属性名,没有其他参数,需要返回值
    c.对象.属性(不带_)

    a.属性名加_
    b.@getter名.setter后面声明函数,函数名属性名,有一个参数,不需要返回值
    c.对象.属性(不带_) = 值

    4.继承

    class 子类(父类):
    内的内容

    继承就是让子类直接拥有父类的属性和方法

    5.添加方法和属性
    class A:
        def __init__(self):
            self.a = 0
            self.b = ''
    
    
    class B(A):
        def __init__(self):
            super().__init__()
            self.c = 10
    
    
    b = B()
    

    02.多继承

    1.多继承

    多继承: 让一个类同时继承多个类

    注意:实际开发的时候,一般不使用多继承

    class Animal:
        num = 61
    
        def __init__(self, name='名字', age=0, color=''):
            self.name = name
            self.age = age
            self.color = color
    
        def show_info(self):
            print('=====')
            # print('名字:%s 年龄:%d 颜色:%s' % (self.name, self.age, self.color))
    
    
    class Fly:
        info = '飞'
    
        def __init__(self, distance=0, speed=0):
            self.distance = distance
            self.speed = speed
    
        @staticmethod
        def show():
            print('会飞!')
    
    # 让Birds同时继承Animal和Fly
    class Birds(Fly, Animal):
        pass
    
    
    bird1 = Birds()
    # 对象属性只能继承第一个类的对象属性
    print(bird1.speed)
    
    # 两个类的字段都能继承
    print(Birds.num, Birds.info)
    
    # 两个类的方法都能继承
    Birds.show()
    bird1.show_info()
    

    0
    61 飞
    会飞!
    =====

    2.多态

    类的特点:封装、继承、多态

    封装:可以对多条数据(属性)和多个功能(方法)进行封装
    继承:可以让一个类拥有另外一个类的属性和方法
    多态:有继承就有多态(一个事物的多种形态)


    03.运算符重载

    1.别的语言的函数和函数的重载

    C++/java声明函数的语法:
    返回值类型 函数名(参数类型1 参数名1, 参数类型2 参数名2){
    函数体
    }

    int func1(){
        
    }
    void func1(int a){
    
    }
    
    void func1(char a){
    
    }
    int func1(int a, int b){
        
    }
    

    上面这4个函数是不同的函数(可以同时存在)

    python中的函数不支持重载

    def func1():
        pass
        
    def func1(a):
        pass
        
    def func1(a, b)
        pass
    

    最终只保留最后这一个func1,前面的会被覆盖

    2.运算符重载

    python中使用运算的时候,实质是在调用相应的魔法方法。(python中每个运算符都对应一个魔法方法)
    运算符重载:在不同的类中实现同一个运算符对应的魔法方法,来让类的对象支持相应的运算

    class Student(object):
        def __init__(self, name='', score=0, age=0):
            self.name = name
            self.score = score
            self.age = age
    
        #  + 重载
        """
        数据1 + 数据2 -- 数据1会传给self, 数据2会传给other
        """
        def __add__(self, other):
            # self + other
            return self.score + other.score
    
        # - 运算
        def __sub__(self, other):
            # self - other
            return self.age - other.age
    
        # 注意:>和<一般情况下只需要重载一个,另外一个自动支持
        # < 运算
        def __lt__(self, other):
            return self.score < other.score
    
        #  > 运算
        def __gt__(self, other):
            return self.age > other.age
    
        def __repr__(self):
            return '<'+(str(self.__dict__)[1:-1])+'>'
    
    
    stu1 = Student('小花', 90, 16)
    stu2 = Student('小明', 80, 18)
    stu3 = Student('小红', 87, 23)
    stu4 = Student('小🐶', 30, 15)
    print(stu1 + stu2)
    
    print(stu1 - stu2)
    
    all_students = [stu1, stu2, stu3, stu4]
    all_students.sort()
    
    
    print(all_students)
    
    print(max(all_students))
    

    170
    -2
    [<'name': '小🐶', 'score': 30, 'age': 15>, <'name': '小明', 'score': 80, 'age': 18>, <'name': '小红', 'score': 87, 'age': 23>, <'name': '小花', 'score': 90, 'age': 16>]
    <'name': '小红', 'score': 87, 'age': 23>


    04.内存管理机制

    1.堆和栈

    内存区域中分堆区间和栈区间;栈区间的内存的开辟和释放是自动的,堆区间的内存是手动开辟手动释放的;
    内存管理管理的是堆区间的内存;

    2.数据的存储

    a.python中所有的数据都是对象,都是保存在堆中的

    b.python中所有的变量存储的都是存在堆中的数据的地址。存了对象的地址的变量又叫对象的引用

    c.默认情况下创建对象就会在堆中去开辟空间存储数据,并且将地址返回值;
    如果对象是数字,字符串会做缓存,而且使用的是会先去缓存中看之前有没有存过,如果有就直接返回之前的数据的地址,没有才开辟新的空间存储数据

    3.数据的销毁

    python中通过'垃圾回收机制'来管理内存的释放
    原理:看一个对象是否销毁,就看这个的对象的引用计数是否为0。为0就销毁,不为0就不销毁

    引用计数:对象的引用个数

    注意:垃圾回收其实就是回收引用计数是0的对象,但是系统不会时时刻刻的检测对象的引用计数是否是0。
    而是隔一段时间检测一次,如果检测到垃圾就回收

    from sys import getrefcount
    
    getrefcount(对象) - 获取指定对象的引用计数
    
    """
    1.增加引用计数: 使用变量存对象的地址
    """
    list1 = [1]    # 对象[1]的引用计数是1
    print(getrefcount(list1))
    list2 = list1  # 对象[1]的引用计数是2
    print(getrefcount(list1))
    list3 = [list1, 100]  # 对象[1]的引用计数是3
    print(getrefcount(list1))
    
    """
    2.减少引用计数
    a. 删除引用
    b. 让当前对象的引用成为别的对象的引用
    """
    print(id(list3[1]))
    del list3[0]
    print(getrefcount(list1))
    
    
    list2 = 100
    print(id(list2))
    print(getrefcount(list1))
    
    list3 = 100
    print(id(list3))
    
    print(getrefcount(100))
    

    2
    3
    4
    1555749472
    3
    1555749472
    2
    1555749472
    9


    05.游戏最小系统

    import pygame
    
    # 1.游戏初始化
    pygame.init()
    
    # 2.创建游戏窗口
    """
    set_mode(窗口大小)  - 窗口大小是一个元祖,有两个元素:width, height
    set_mode((宽度, 高度)) 
    宽度和高度的单位是像素
    """
    window = pygame.display.set_mode((400, 600))
    # 将窗口填充成指定的颜色
    """
    fill(颜色) - fill((r,g,b))
    计算机颜色:计算机三原色 - 红,绿,蓝(rgb)
              颜色值就是由三个数字组成,分别代表红,绿,蓝,数字范围是:0-255
              
    python中的颜色是一个元祖,元祖中有是三个颜色,分别是r,g, b
    (255, 255, 255)  - 白色
    (0, 0, 0) - 黑色
    (255, 0, 0) - 红色
    (0, 255, 0) - 绿
    """
    window.fill((255, 255, 255))
    
    # 将窗口展示到显示设备上
    pygame.display.flip()
    
    # 3.创建游戏循环
    while True:
        # 4.检测事件
        for event in pygame.event.get():
            # ===区分不同的事件,做出不一样的反应===
            # 判断关闭按钮点击事件是否发生
            if event.type == pygame.QUIT:
                exit()
    

    06.在窗口上显示图片

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

    =========显示图片===========

    1.加载图片

    pygame.image.load(图片地址) - 加载指定路径下的图片,返回一个图片对象

    image_obj = pygame.image.load('files/luffy.jpg')
    window.blit(image_obj, (0, 0))
    
    2.渲染图片

    blit(渲染对象, 位置)
    渲染对象 - 图片对象(显示什么)
    位置 - 元祖,(x, y)

    3.获取图片的大小

    图片对象.get_size() - 获取图片大小,返回值是一个元祖:(width, height)

    image_w, image_h = image_obj.get_size()
    # window.blit(image_obj, ((400-image_w)/2, (600-image_h)/2))
    
    4.图片缩放和旋转

    a.缩放
    pygame.transform.scale(图片对象, 大小) - 将指定的图片缩放在指定的大小, 返回新的图片对象

    new_image = pygame.transform.scale(image_obj, (50, 150))
    window.blit(new_image, (0, 110))
    

    b.旋转缩放
    pygame.transform.rotozoom(图片对象, 旋转角度, 缩放比例)

    new_image2 = pygame.transform.rotozoom(image_obj, 0, 0.5)
    window.blit(new_image2, (0, 270))
    
    new_image3 = pygame.transform.rotozoom(image_obj, 45, 1.5)
    window.blit(new_image3, (0, 330))
    
    pygame.display.flip()
    
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
    
    结果显示

    07.在窗口上显示文字

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

    =======显示文字=========

    1.创建字体对象(选笔)

    a.系统字体
    pygame.font.SysFont(字体名, 字体大小, 是否加粗=False,是否倾斜=False) - 返回字体对象

    b.自定义字体
    pygame.font.Font(字体文件路径, 字体大小)

    # font = pygame.font.SysFont('Times', 50, italic=True)
    font = pygame.font.Font('files/aa.ttf', 40)
    
    2.根据字体创建文字对象

    render(文字内容, 是否平滑, 文字颜色)

    text = font.render('hello pygame 你好!', True, (255, 0, 0))
    
    3.将文字渲染到窗口上
    window.blit(text, (100, 100))
    
    
    pygame.display.flip()
    
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
    
    显示结果

    08.显示图形

    import pygame
    from color import Color
    import math
    
    # 游戏最小系统
    pygame.init()
    window = pygame.display.set_mode((400, 600))
    window.fill((255, 255, 255))
    

    ======显示图形=========

    1.画直线

    line(画在哪儿, 线的颜色, 起点, 终点, 线宽=1)

    pygame.draw.line(window, Color.green, (0, 0), (100, 100), 10)
    

    lines(画在哪儿, 线的颜色, 是否闭合, 点列表, 线宽=1)
    依次连接点列表中所有的点(是否闭合决定是否连接起点和终点)

    points = [(10, 10), (100, 70), (100, 170), (40, 230), (40, 320)]
    pygame.draw.lines(window, Color.red, True, points, 5)
    
    2.画圆

    circle(画在哪儿, 颜色, 圆心坐标, 半径, 线宽=0)
    注意:线宽为0的时候画实心圆

    pygame.draw.circle(window, Color.yellow, (100, 100), 80, 3)
    
    3.画弧线

    arc(画在哪儿,颜色,矩形(Rect),起始弧度,终止弧度,线宽=1)
    矩形 - (x, y, width, height); x,y是矩形坐上角的坐标,width,height是矩形的宽高

    pygame.draw.arc(window, Color.blue, (150, 300, 50, 100), 0, math.pi, 10)
    
    
    pygame.display.flip()
    
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
    
    显示结果

    09.事件和动画

    import pygame
    from color import Color
    
    pygame.init()
    window = pygame.display.set_mode((400, 600))
    window.fill((255, 255, 255))
    
    # 在这儿写的代码是静态的(界面上的内容)
    x = 100
    y = 100
    width = 100
    height = 80
    pygame.draw.rect(window, Color.green, (x, y, width, height))
    
    pygame.display.flip()
    
    while True:
    
        y += 3
        # width -= 2
        window.fill(Color.white)  # 覆盖原来的状态
        pygame.draw.rect(window, Color.rand_color(), (x, y, width, height))
        pygame.display.update()   # 重新显示
    
        # 有事件产生的时候才会进入for循环
        for event in pygame.event.get():
            # 1.type属性
            """
            不同的type值对应不同类型的事件
            QUIT - 关闭按钮被点击事件
            
            a.鼠标相关事件  - 按的位置
            MOUSEMOTION - 鼠标移动
            MOUSEBUTTONDOWN - 鼠标按下
            MOUSEBUTTOUP - 鼠标弹起
            
            event.pos - 获取鼠标事件产生的位置
            
            b.键盘事件 - 按的是哪个键
            KEYDOWN - 按键按下
            KEYUP - 按键弹起
            
            event.key - 被按的键对应的字符的编码值
            
            """
            if event.type == pygame.QUIT:
                exit()
    
            elif event.type == pygame.MOUSEMOTION:
                # print('鼠标移动', event.pos)
                # pygame.draw.circle(window, Color.rand_color(), event.pos, 30)
                # pygame.display.flip()
                pass
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # 鼠标按下要做什么就写在这儿
                print('鼠标按下', event.pos)
                pygame.draw.circle(window, Color.rand_color(), event.pos, 30)
                pygame.display.flip()
            elif event.type == pygame.MOUSEBUTTONUP:
                print('鼠标弹起!', event.pos)
    
            elif event.type == pygame.KEYDOWN:
                print('按键按下')
                print(event.key, chr(event.key))
    
            elif event.type == pygame.KEYUP:
                print('按键弹起')
                print(event.key, chr(event.key))
    

    鼠标按下 (111, 160)
    鼠标弹起! (111, 160)
    鼠标按下 (120, 191)
    鼠标弹起! (165, 260)
    鼠标按下 (183, 229)
    鼠标弹起! (189, 262)
    按键按下
    119 w
    按键弹起
    119 w
    按键按下


    10.产生随机颜色

    from random import randint
    
    
    class Color:
        white = (255, 255, 255)
        black = (0, 0, 0)
        red = (255, 0, 0)
        yellow = (255, 255, 0)
        green = (0, 255, 0)
        blue = (0, 0, 255)
    
        def __init__(self, r, g, b):
            self.r = r
            self.g = g
            self.b = b
    
        @staticmethod
        def rand_color():
            return randint(0, 255), randint(0, 255), randint(0, 255)
    

    相关文章

      网友评论

          本文标题:day15 总结 - 面向对象和pygame

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