本章将进行基类的抽取。使代码更具有层次性和简化重复代码。
import pygame
import time
import random
from pygame.locals import *
1 - Base类的提取(所有类的基类)
所有类都有(x, y)坐标,图片的加载,即可以提取出来。
class Base(object):
"""docstring for Base"""
def __init__(self, screen_temp, x, y, image_name):
self.x = x
self.y = y
self.screen = screen_temp
self.image = pygame.image.load(image_name)
2 - BasePlane类的提取(所有飞机的基类)
将HeroPlane 和 EnemyPlane类中相同的功能进行提取。
class BasePlane(Base):
"""docstring for BasePlane"""
def __init__(self, screen_temp, x, y, image_name):
Base.__init__(self, screen_temp, x, y, image_name)
self.bullet_list = [] #存储发射出去的子弹的引用
def display(self):
self.screen.blit(self.image, (self.x, self.y))
bullet_list_out = []#越界子弹
for bullet in self.bullet_list:
bullet.display()
bullet.move()
if bullet.judge(): #判断子弹是否越界
bullet_list_out.append(bullet)
#删除越界子弹
for bullet in bullet_list_out:
self.bullet_list.remove(bullet)
提取后的HeroPlane 和 EnemyPlane的代码:
class HeroPlane(BasePlane):
def __init__(self, screen_temp):
BasePlane.__init__(self, screen_temp, 210, 700, "./feiji/hero1.png") #super().__init__()
def move_left(self):
self.x -= 5
def move_right(self):
self.x += 5
def fire(self):
self.bullet_list.append(Bullet(self.screen, self.x, self.y))
class EnemyPlane(BasePlane):
"""敌机的类"""
def __init__(self, screen_temp):
BasePlane.__init__(self, screen_temp, 0, 0, "./feiji/enemy0.png")
self.direction = "right" #用来存储飞机默认显示方向
def move(self):
if self.direction == "right":
self.x += 5
elif self.direction == "left":
self.x -= 5
# 方向判断
if self.x > 480-50:
self.direction ="left"
elif self.x < 0:
self.direction = "right"
def fire(self):
random_num = random.randint(1, 100)
if random_num == 8 or random_num == 20:
self.bullet_list.append(EnemyBullet(self.screen, self.x, self.y))
3 - BaseBullet类的提取
class BaseBullet(Base):
"""docstring for BaseBullet"""
def __init__(self, screen_temp, x, y, image_name):
Base.__init__(self, screen_temp, x, y, image_name)
def display(self):
self.screen.blit(self.image, (self.x, self.y))
class Bullet(BaseBullet):
def __init__(self, screen_temp, x, y):
BaseBullet.__init__(self, screen_temp, x+40, y-20, "./feiji/bullet.png")
def move(self):
self.y -= 15
def judge(self):
if self.y < 0:
return True
else:
return False
class EnemyBullet(BaseBullet):
def __init__(self, screen_temp, x, y):
BaseBullet.__init__(self, screen_temp, x+25, y+40, "./feiji/bullet1.png")
def move(self):
self.y += 5
def judge(self):
if self.y > 852:
return True
else:
return False
main()函数并没有变动。
pygame之《飞机大战》(四)