一、知识回顾
1.pygame应用
2.面向对象
什么是类?
什么是对象?
- a.怎么声明类?
class 类名(父类列表): ---- 类名命名方式:首字母大写的驼峰式命名
类说明
属性
方法
-
b.通过类创建对象
对象名 = 类名() ---- 类名() -> 构造方法
调用构造方法创建对象的时候,会自动调用类的init_方法,给对象的属性赋初值。 -
c.__init__方法
不用自己去调用,参数有哪些,参数要不要默认值,全看在创建对象的时候是否需要给相应属性赋初值和是否必须赋初值。 -
d.关于属性
类的字段:(不同的对象对应的值相同,声明成类的字段)
类的字段由类来使用
对象属性:(不同的对象对应的值可能不一样,这样的属性可以声明成对象属性)
对象的属性由对象使用
增删改查
查: 对象名.__getattr__ 如果属性不存在会报错
getattr(对象,属性,默认值) 如果属性不存在返回默认值
__slots__ 限制属性
对象/类.__dict__ 在没有设置__slots__时可以以字典的形式返回对象的属性名和对应的值
类.__name__ 获取类名
对象.__class__ 获取对象的类
对象.__class__.__name__ 获取对象的类名
类.__doc__ 获取类的说明
类.__base__ 获取类的父类
类.__module__ 获取类所在的模块
私有属性:
假私有属性: _属性名
getter\setter: 想要在获取对象属性之前,或者给属性赋值前想要进行额外操作时
getter:
@property
def 属性名(去掉下划线)(self):
额外操作
return self._属性名
setter: 有getter才能添加setter
@属性名(去掉下划线).setter
def 属性名(去掉下划线)(self, value):
额外操作
self.属性名 = value
- e.类的方法
对象方法: 对象来调用
def 方法名(self):
内容
类方法: 类来调用
@classmethod
def 方法名(cls):
内容
静态方法:
@staticmethod
def 方法名():
内容
- f.继承(支持多继承,但是一般都是单继承)
让子类直接拥有父类所有的属性和方法(私有的除外,私有的能继承但是无法使用,等于不继承),slots也不能继承
重写:在子类中重新实现父类的方法
完全重写
保留父类功能,再添加功能:
super().父类的东西
多态:一种现象,一种事物的多种形态,继承就会产生多态现象 - g.运算符重载
让对象实现运算功能,大多情况下大于小于用的多。
3.正则表达式
-
a.符号(. \w \d \s \b \W \D \S \B [] [^] + * ? {N} {N,} {N,M} () |)
-
b.re模块中的方法:
匹配:match()、fullmatch()
查找:findall()
切割:split()
替换:sub()
二、歌词
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):
minute = float(time[:2])
second = float(time[3:])
self._time = minute * 60 + second
# 重载 <
def __lt__(self, other):
return self._time < other._time
# 自定义类的对象的打印
def __str__(self):
return str(self._time) + ':' + self.lrc
class AnalysisLyric:
"""解析歌词"""
def __init__(self, file_path):
self.all_lyrics = []
self.file_path = file_path
def __analysis_lyric(self):
"""解析歌词"""
with open(self.file_path, 'r', encoding='utf-8') as f:
# 一行一行地读文件内容
lyric = f.readline()
while lyric:
# print(lyric)
# 对当前行的内容进行操作(切片)
self.__operate_lyric(lyric)
lyric = f.readline()
# 已经将文件中的所有内容都读完了,并且转换成歌词对象并且存入了all_lyric中
# 排序 降序
self.all_lyrics.sort(reverse=True)
# for lrc in self.all_lyrics:
# print(lrc)
def __operate_lyric(self, lyric):
# 切片
# pattern = r'[\]]'
lyric_operated = lyric.split(']')
# 取歌词
lrc = lyric_operated[-1]
# 遍历所有的时间
for index in range(len(lyric_operated)-1):
# 创建歌词对象
lyrics = Lyrics()
# 设置歌词和时间属性
lyrics.lrc = lrc
lyrics.time = lyric_operated[index][1:]
# 保存歌词对象
self.all_lyrics.append(lyrics)
# time_lyric = {lyric_operated[index][1:]: lrc}
# print(time_lyric)
# print(lyric_operated)
def show_lrc(self, time):
if not self.all_lyrics:
self.__analysis_lyric()
for lrc in self.all_lyrics:
if lrc.time < time:
return lrc.lrc
if __name__ == '__main__':
lan_lian_hua = AnalysisLyric('./files/蓝莲花.txt')
# lan_lian_hua.analysis_lyric()
time1 = 0
while True:
time.sleep(1)
time1 += 1
print(lan_lian_hua.show_lrc(time1))
if time1 == 200:
break
三、坦克
1.颜色
from random import randint
class Color:
"""颜色类"""
white = 255, 255, 255
black = 0, 0, 0
green = 0, 255, 0
red = 255, 0, 0
blue = 0, 0, 255
gray = 100, 100, 100
light_gray = 200, 200, 200
@staticmethod
def rgb_color(r, g, b):
return r, g, b
@staticmethod
def random_color():
return randint(0, 255), randint(0, 255), randint(0, 255)
2.程序入口
import pygame
from TankWar import color
from TankWar.tank import Tank
def game():
pygame.init()
screen = pygame.display.set_mode((800, 450))
screen.fill(color.Color.black)
pygame.display.set_caption('坦克大战')
my_tank = Tank((100, 100))
pygame.display.flip()
while True:
# 事件检测
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit(0)
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.black)
my_tank.move(screen)
my_tank.show(screen)
pygame.time.delay(50)
pygame.display.update()
if __name__ == '__main__':
game()
3.坦克
"""
python中的枚举类:声明一个类,继承Enum
1.类中只能有类字段用来存储一些固定的值
2.可以使用@unique修饰,让类中的字段的值唯一
3.字段的值保存在字段的value属性中
4.类变成枚举类后,只有字段对象的对象(不能自己去创建其他的对象)
"""
from enum import Enum, unique
import pygame
@unique
# 修饰后,类中的字段的值必须唯一
class Direction(Enum):
"""方向类"""
up = 273
down = 274
right = 275
left = 276
# print(Direction.up.value)
class Bullet:
"""子弹类"""
def __init__(self):
self.image = ''
class Tank:
"""坦克类"""
# screen = pygame.display.set_mode((800, 450))
image_up = pygame.image.load('../TankWar/image/p1tankU.gif')
image_down = pygame.image.load('../TankWar/image/p1tankD.gif')
image_right = pygame.image.load('../TankWar/image/p1tankR.gif')
image_left = pygame.image.load('../TankWar/image/p1tankL.gif')
def __init__(self, pos):
self.image = Tank.image_up
self.x = pos[0]
self.y = pos[1]
self.x_speed = 0
self.y_speed = -10
self._direction = Direction.up
self.is_move = False
self.all_bullet = []
def shoot(self):
"""
发射子弹
1.创建一个子弹对象
2.根据坦克的方向设置子弹方向和子弹的初始位置
3.保存子弹
"""
pass
def move(self, screen):
"""坦克移动"""
if not self.is_move:
return
new_x = self.x + self.x_speed
new_y = self.y + self.y_speed
# 判断越界
sw, sh = screen.get_size()
tw, th = self.image.get_size()
if new_x <= 0:
new_x = 0
elif new_x >= sw - tw :
new_x = 0
if new_y <= 0:
new_y = 0
elif new_y >= sh - th:
new_y = 0
self.x = new_x
self.y = new_y
# 显示坦克
def show(self, screen):
screen.blit(self.image, (self.x, self.y))
@property
def direction(self):
return self._direction
@direction.setter
def direction(self, direction):
self._direction = direction
if direction == Direction.up.value:
self.image = Tank.image_up
self.x_speed = 0
self.y_speed = -10
elif direction == Direction.down.value:
self.image = Tank.image_down
self.x_speed = 0
self.y_speed = 10
elif direction == Direction.right.value:
self.image = Tank.image_right
self.x_speed = 10
self.y_speed = 0
elif direction == Direction.left.value:
self.image = Tank.image_left
self.x_speed = -10
self.y_speed = 0
网友评论