# /usr/bin/env python
# -*- coding:utf-8 -*-
# Author : yimi
import pygame,time,random
from pygame.locals import *
class BasePlane(object):
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)
self.bullet_list = []
class Base(object):
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)
class HeroPlane(object):
def __init__(self,screen_temp):
BasePlane.__init__(self,screen_temp,180,580,'./feiji/hero1.png')
def display(self):
self.screen.blit(self.image,(self.x,self.y))
for bullet in self.bullet_list:
bullet.display()
bullet.move()
if bullet.judge():
self.bullet_list.remove(bullet)
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(object):
def __init__(self,screen_temp):
BasePlane.__init__(self,screen_temp,0,0,'./feiji/enemy0.png')
self.direction='right'
def display(self):
self.screen.blit(self.image,(self.x,self.y))
for bullet in self.bullet_list:
bullet.display()
bullet.move()
if bullet.judge():
self.bullet_list.remove(bullet)
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==78 or random_num==20:
self.bullet_list.append(EnemyBullet(self.screen,self.x,self.y))
class EnemyBullet(object):
def __init__(self,screen_temp,x,y):
Base.__init__(self, screen_temp, x+20, y+40, './feiji/bullet1.png')
def display(self):
self.screen.blit(self.image,(self.x,self.y))
def move(self):
self.y+=5
def judge(self):
if self.y > 700:
return True
else:
return False
class Bullet(object):
def __init__(self,screen_temp,x,y):
Base.__init__(self, screen_temp, x+40, y-20, './feiji/bullet.png')
def display(self):
self.screen.blit(self.image,(self.x,self.y))
def move(self):
self.y-=10
def judge(self):
if self.y < 0:
return True
else:
return False
def key_control(hero_temp):
for event in pygame.event.get():
# 判断是否是点击了退出按钮
if event.type == QUIT:
print("exit")
exit()
# 判断是否是按下了键
elif event.type == KEYDOWN:
# 检测按键是否是a或者left
if event.key == K_a or event.key == K_LEFT:
print('left')
hero_temp.move_left()
# 检测按键是否是d或者right
elif event.key == K_d or event.key == K_RIGHT:
print('right')
hero_temp.move_right()
# 检测按键是否是空格键
elif event.key == K_SPACE:
print('space')
hero_temp.fire()
def main():
screen = pygame.display.set_mode((480,700),0,32)
background = pygame.image.load('./feiji/background.png')
hero=HeroPlane(screen)
enemy=EnemyPlane(screen)
while True:
screen.blit(background,(0,0))
hero.display()
enemy.display()
enemy.move()
enemy.fire()
pygame.display.update()
key_control(hero)
time.sleep(0.03)
if __name__=='__main__':
main()
运行结果: