打飞机代码:代码优化-抽象出基类
import pygame
from pygame.locals import *
import time
import random
'''
代码优化:抽出基类
'''
class Plane(object):
def __init__(self, screen, imageName):
self.screen = screen
self.image = pygame.image.load(imageName).convert()
self.bulletList = []
def display(self):
self.screen.blit(self.image,(self.x,self.y))
needDelItemList = []
for i in self.bulletList:
if i.judge():
needDelItemList.append(i)
for i in needDelItemList:
self.bulletList.remove(i)
for bullet in self.bulletList:
bullet.display()
bullet.move()
class HeroPlane(Plane):
def __init__(self, screen):
super(HeroPlane, self).__init__(screen, "./feiji/hero1.png")
self.x = 230
self.y = 700
def moveLeft(self):
self.x -= 10
def moveRight(self):
self.x += 10
def sheBullet(self):
newBullet = Bullet(self.x, self.y, self.screen, "hero")
self.bulletList.append(newBullet)
class EnemyPlane(Plane):
def __init__(self, screen):
super(EnemyPlane, self).__init__(screen, "./feiji/enemy0.png")
self.x = 0
self.y = 0
self.direction = "right"
def move(self):
if self.direction == "right":
self.x += 4
elif self.direction == "left":
self.x -= 4
if self.x>480-50:
self.direction = "left"
elif self.x<0:
self.direction = "right"
def sheBullet(self):
num = random.randint(1,100)
if num == 88:
newBullet = Bullet(self.x,self.y,self.screen, "enemy")
self.bulletList.append(newBullet)
class Bullet(object):
def __init__(self,x,y,screen,planeName):
self.name = planeName
self.screen = screen
if self.name == "hero":
self.x = x+40
self.y = y-20
imageName = "./feiji/bullet.png"
elif self.name == "enemy":
self.x = x+30
self.y = y+30
imageName = "./feiji/bullet1.png"
self.image = pygame.image.load(imageName).convert()
def move(self):
if self.name == "hero":
self.y -= 4
elif self.name == "enemy":
self.y += 4
def display(self):
self.screen.blit(self.image,(self.x,self.y))
def judge(self):
if self.y>852 or self.y<0:
return True
else:
return False
def key_control(heroPlane):
for event in pygame.event.get():
if event.type == QUIT:
print("exit")
exit()
elif event.type == KEYDOWN:
if event.key == K_a or event.key == K_LEFT:
print('left')
heroPlane.moveLeft()
elif event.key == K_d or event.key == K_RIGHT:
print('right')
heroPlane.moveRight()
elif event.key == K_SPACE:
print('space')
heroPlane.sheBullet()
def main():
screen = pygame.display.set_mode((480,852),0,32)
background = pygame.image.load("./feiji/background.png").convert()
heroPlane = HeroPlane(screen)
enemyPlane = EnemyPlane(screen)
while True:
screen.blit(background,(0,0))
heroPlane.display()
enemyPlane.move()
enemyPlane.display()
enemyPlane.sheBullet()
key_control(heroPlane)
pygame.display.update()
time.sleep(0.01)
if __name__ == "__main__":
main()