解析歌词文件类2 --> 保存时间和对应...">
美文网首页Python
综合练习(歌词解析和坦克大战--部分功能)

综合练习(歌词解析和坦克大战--部分功能)

作者: GHope | 来源:发表于2018-08-06 20:54 被阅读53次

    歌词解析

    lrc歌词文件

    """
    分析:面向对象
    1、需要几个类
    类1 --> 解析歌词文件
    类2 --> 保存时间和对应的词
    类3 -->

    import re
    import time
    
    
    class Lyrics:
        def __init__(self):
            self.lrc = ''
            self._time = 0
    
        @property
        def time(self):
            return self._time
    
        @time.setter
        def time(self, time):
            fen = float(time[:2])
            miao = float(time[3:])
            self._time = fen * 60 + miao
    
        # 自定义类的对象的打印
        def __str__(self):
            return str(self._time) + '' + self.lrc
    
        # 重载<(sort函数使用中所需)
        def __lt__(self, other):
            return self.time < other.time
    
    
    class AnalysisLyrics:
        """解析歌词"""
    
        # all_lrc = []  # 类的字段只能解析一首歌(继续解析会涉及覆盖)
    
        def __init__(self, path):  # 对象的属性实现同时解析多个歌词
            self.all_lrc = []
            self.path = path
    
        def __analysis_lyrics(self):
            """解析歌词"""
            # 打开歌词文件
            with open(self.path, 'r', encoding='utf-8')as f:
                # 一行一行的读取文件中的内容
                line = f.readline()  # 读第一行
                while line:  # 判断是否读取到内容
                    # 对当前内容进行切片 -- 封装后导入
                    self.__operate_line(line)
                    # print(line)
                    line = f.readline()  # 读取下一行
    
            # 验证歌词文件是否读取完毕且转换成歌词对象保存到all_lrc中
            # for lrc in self.all_lrc:
            #     print(lrc)
            # 根据时间排序(True:降序,False:升序)
            self.all_lrc.sort(reverse=True)
    
        def __operate_line(self, line):
            # 切割
            lines = re.split(r']', line)
            # 取词
            lrc = lines[-1]
            # 遍历所有的时间
            for index in range(len(lines) - 1):
                # print(lrc, lines[index])
                # 创建歌词对象
                lyrics = Lyrics()
                # 设置歌词和时间属性
                lyrics.lrc = lrc
                lyrics.time = lines[index][1:]
                # 保存歌词对象
                self.all_lrc.append(lyrics)
    
        def show_lrc(self, time):
            # 如果已经解析过了,就不用二次解析了
            if not self.all_lrc:
                self.__analysis_lyrics()
            # 去时间对应的歌词
            for item in self.all_lrc:
                if item.time < time:
                    return item.lrc
    
    
    if __name__ == '__main__':
        xw = AnalysisLyrics('./蓝莲花.txt')
    
        time1 = 0
        while True:
            time.sleep(1)
            time1 += 3
            print(xw.show_lrc(time1))
    

    坦克大战

    随机类

    # -*- coding: utf-8 -*-
    # @Time    : 2018/8/6 16:00
    # @Author  : G.Hope
    # @Email   : 1638327522@qq.com
    # @File    : color.py
    # @Software: PyCharm
    from random import randint
    
    
    class Color:
        """颜色类"""
        white = 255, 255, 255
        green = 0, 255, 0
        red = 255, 0, 0
        black = 0, 0, 0
        gray = 100, 100, 100
        light_gray = 200, 200, 200
    
        @staticmethod
        def rgb_color(r, g, b):
            """rgb颜色值"""
            return r, g, b
    
        @staticmethod
        def rand_color():
            """随机颜色"""
            return randint(0, 255), randint(0, 255), randint(0, 255)
    
        @staticmethod
        def rand_tank():
            """随机坐标"""
            return randint(0, 500), randint(0, 400)
    
    
    if __name__ == '__main__':
        pass
    
    

    坦克类

    
    # -*- coding: utf-8 -*-
    # @Time    : 2018/8/6 16:13
    # @Author  : G.Hope
    # @Email   : 1638327522@qq.com
    # @File    : tank.py
    # @Software: PyCharm
    
    # python中的枚举类
    """
    类中只能有类字段来存储一些固定的值
    可以使用@unique修饰,让类中的字段唯一
    字段的值保存在字段的value属性中
    类变成枚举后,只有字段对象的对象(不能自己再去创建其它的对象)
    """
    
    
    # from enum import Enum, unique
    #
    #
    # @unique
    # # 修饰后,类中的字段的值必须唯一(不能有方法)
    # class Direction(Enum):
    class Direction:
        """方向类"""
        up = 273
        down = 274
        right = 275
        left = 276
    
    
    import pygame
    
    
    class Tank:
        """坦卡类"""
        screen = pygame.display.set_mode((1000, 800))
        image_up = pygame.image.load('.\imge\p1tankU.gif')
        image_down = pygame.image.load('.\imge\p1tankD.gif')
        image_left = pygame.image.load('.\imge\p1tankL.gif')
        image_right = pygame.image.load('.\imge\p1tankR.gif')
        image_bullet = pygame.image.load('.\imge\\10.gif')
        image_green_up = pygame.image.load('.\imge\p2tankF.gif')
        image_green_down = pygame.image.load('.\imge\p2tankD.gif')
        image_green_left = pygame.image.load('.\imge\p2tankL.gif')
        image_green_right = pygame.image.load('.\imge\p2tankR.gif')
    
        def __init__(self, pos):
            self.image = Tank.image_up
            self.x = pos[0]
            self.y = pos[1]
            self.speed_x = 0
            self.speed_y = -1
            self._direction = Direction.up
            self.is_move = False
            self.all_bullet = []
    
        def shoot(self, screen):
            """发射子弹"""
    
            # 1、创建一个子弹对象
            # 2、根据坦克的方向设置子弹方向和子弹的初始位置
            # 3、保存子弹
            class Bullet:
                image = Tank.image_bullet
                x = self.x + 23
                y = self.y + 23
                x0 = self.speed_x * 2
                y0 = self.speed_y * 2
    
            self.all_bullet.append(Bullet)
    
        def move_shoot(self, screen):
            for bullet in self.all_bullet[:]:
                newx = bullet.x + bullet.x0
                newy = bullet.y + bullet.y0
                sw, sh = screen.get_size()
                tw, th = bullet.image.get_size()
                # 判断是否越界
                if newx <= 0 or newx >= sw - 2 * tw or newy <= 0 or newy >= sh - 2 * th:
                    del bullet
                    continue
                else:
                    bullet.x = newx
                    bullet.y = newy
    
        def show_shoot(self, screen):
            for bullet in self.all_bullet:
                screen.blit(self.image_bullet, (bullet.x, bullet.y))
    
        def move(self, screen):
            if not self.is_move:
                return
            newx = self.x + self.speed_x
            newy = self.y + self.speed_y
            sw, sh = screen.get_size()
            tw, th = self.image.get_size()
            # 判断是否越界
            if newx <= 0:
                newx = 0
            elif newx >= sw - tw:
                newx = sw - tw
    
            if newy <= 0:
                newy = 0
            elif newy >= sh - th:
                newy = sh - th
    
            self.x = newx
            self.y = newy
    
        def move_other(self, screen):
            newx = self.x + self.speed_x
            newy = self.y + self.speed_y
            sw, sh = screen.get_size()
            tw, th = self.image.get_size()
            # 判断是否越界
            if newx <= 0 or newx >= sw - tw:
                self.speed_x *= -1
    
            if newy <= 0 or newy >= sh - th:
                self.speed_y *= -1
    
            self.x = newx
            self.y = newy
    
        def show(self, screen):
            """显示坦克"""
            screen.blit(self.image, (self.x, self.y))
    
        def show_other(self, screen):
            """显示绿军坦克"""
            screen.blit(Tank.image_green_up, (self.x, self.y))
    
        @property
        def direction(self):
            return self._direction
    
        @direction.setter
        def direction(self, direction):
            self._direction = direction
            if direction == Direction.up:
                self.image = Tank.image_up
                self.speed_x = 0
                self.speed_y = -1
            elif direction == Direction.down:
                self.image = Tank.image_down
                self.speed_x = 0
                self.speed_y = 1
            elif direction == Direction.left:
                self.image = Tank.image_left
                self.speed_x = -1
                self.speed_y = 0
            elif direction == Direction.right:
                self.image = Tank.image_right
                self.speed_x = 1
                self.speed_y = 0
    
        @direction.setter
        def direction_other(self, direction):
            self._direction = direction
            if self.speed_x > 0:
                self.image = Tank.image_green_left
    
            elif self.speed_x < 0:
                self.image = Tank.image_green_right
    
            elif self.speed_y > 0:
                self.image = Tank.image_green_down
    
            elif self.speed_y < 0:
                self.image = Tank.image_green_up
    
    
    if __name__ == '__main__':
        pass
    
    

    主程序

    # -*- coding: utf-8 -*-
    # @Time    : 2018/8/6 15:51
    # @Author  : G.Hope
    # @Email   : 1638327522@qq.com
    # @File    : playGame.py
    # @Software: PyCharm
    """
    1、通过键盘控制坦克上下左右移动
    2、坦克发射子弹
    3、出现敌机
    4、敌机发射子弹,并自由移动
    """
    
    import pygame
    from 坦克大战 import color
    from 坦克大战.tank import Tank, Direction
    
    
    def game():
        pygame.init()
        screen = pygame.display.set_mode((1000, 800))
        screen.fill(color.Color.white)
        pygame.display.set_caption('坦克大战')
    
        my_tank = Tank((450, 700))
        other1 = Tank(color.Color.rand_tank())
        other2 = Tank(color.Color.rand_tank())
        other3 = Tank(color.Color.rand_tank())
    
        pygame.display.flip()
        while True:
            # 事件检测
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()
    
                if event.type == pygame.KEYDOWN:
                    my_tank.direction = event.key
                    my_tank.is_move = True
    
                if event.type == pygame.KEYUP:
                    my_tank.is_move = False
    
            # 游戏循环
            screen.fill(color.Color.white)
            my_tank.move(screen)
            my_tank.shoot(screen)
            my_tank.move_shoot(screen)
            my_tank.show_shoot(screen)
            my_tank.show(screen)
            other1.show_other(screen)
            other1.move_other(screen)
    
            pygame.display.update()
    
    
    if __name__ == '__main__':
        game()
    
    

    相关文章

      网友评论

        本文标题:综合练习(歌词解析和坦克大战--部分功能)

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