plane_sprites:
import random
import pygame
SCREEN_RECT=pygame.Rect(0,0,480,700)
游戏基类:
class GameSprite(pygame.sprite.Sprite):
def __init__(self, img_name,speed=1):
super().__init__()
self.image=pygame.image.load(img_name)
self.rect=self.image.get_rect()
self.speed=speed
def update(self):
self.rect.top+=self.speed
@staticmethod
def img_names(prefix,count):
names=[]
for i in range(1,count+1):
names.append('./images/'+prefix+str(i)+'.png')
return names
背景:
class Bg(GameSprite):
def __init__(self, is_alt=False):
super().__init__("./images/background.png")
if is_alt:
self.rect.bottom=0
def update(self):
super().update()
if self.rect.y>=SCREEN_RECT.height:
self.rect.bottom=0
飞机类:
class Plane(GameSprite):
def __init__(self, live_names,destroy_names,life, speed):
super().__init__(live_names[0], speed)
#生命值
self.life=life
#加载正常状态
self.__live_imgs=[]
for file_name in live_names:
img=pygame.image.load(file_name)
self.__live_imgs.append(img)
#加载摧毁状态
self.__destory_imgs=[]
for file_name in destroy_names:
img=pygame.image.load(file_name)
self.__destory_imgs.append(img)
#初始状态
self.images=self.__live_imgs
self.show_img_i=0
#循环播放
self.loop_show=True
#是否被摧毁
self.be_destroyed=False
def update(self):
super().update()
self.update_imgs()
def update_imgs(self):
pre_i=int(self.show_img_i)
#缓慢加载
self.show_img_i+=0.05
cnt=len(self.images)
if self.loop_show:
self.show_img_i%=cnt
elif self.show_img_i>cnt-1:
self.show_img_i=cnt-1
self.be_destroyed=True
current_i=int(self.show_img_i)
#图片索引加到1了
if pre_i!=current_i:
self.image=self.images[current_i]
def destroyed(self):
self.images=self.__destory_imgs
self.show_img_i=0
self.loop_show=False
敌机:
class Enemy1(Plane):
def __init__(self):
live_names=["./images/enemy1.png"]
destroy_names=GameSprite.img_names('enemy1_down',4)
speed=random.randint(1, 3)
super().__init__(live_names,destroy_names,2,speed)
self.rect.bottom=0
self.rect.x=random.randint(0,SCREEN_RECT.width-self.rect.width)
def update(self):
super().update()
if self.be_destroyed:
self.kill()
if self.rect.bottom>=SCREEN_RECT.bottom:
self.kill()
主角:
class Hero(Plane):
def __init__(self):
live_names=GameSprite.img_names('me',2)
destroy_names=GameSprite.img_names('me_destroy_',4)
super().__init__(live_names,destroy_names,0,0)
self.rect.bottom=SCREEN_RECT.bottom-20
self.rect.centerx=SCREEN_RECT.centerx
self.bullets=pygame.sprite.Group()
def update(self):
self.update_imgs()
self.rect.left+=self.speed
if self.rect.left<0:
self.rect.left=0
elif self.rect.right>=SCREEN_RECT.right:
self.rect.right=SCREEN_RECT.right
def fire(self):
bul=Bullet()
bul.rect.bottom=self.rect.y-20
bul.rect.centerx=self.rect.centerx
self.bullets.add(bul)
子弹:
class Bullet(GameSprite):
def __init__(self):
live_names="./images/bullet1.png"
super().__init__(live_names,-2)
def update(self):
super().update()
if self.rect.bottom<=0:
self.kill()
plane_main:
import pygame
from plane_sprites import *
FRAME_PRE_SEC=60
CREATE_ENEMY_EVENT=pygame.USEREVENT
HERO_FIRE_EVENT=pygame.USEREVENT+1
设置游戏:
class PlaneGame(object):
def __init__(self):
print('游戏初始化...')
pygame.init()
self.score=0
self.screen=pygame.display.set_mode(SCREEN_RECT.size)
self.clock=pygame.time.Clock()
self.__create_sprites()
self.__create_user_events()
def __create_sprites(self):
#创建背景(背景移动)
self.bg_group=pygame.sprite.Group(Bg(),Bg(True))
#敌机
self.enemy_group=pygame.sprite.Group()
self.destroy_group=pygame.sprite.Group()
#飞机
self.hero=Hero()
self.hero_group=pygame.sprite.Group(self.hero)
@staticmethod
def __create_user_events():
#设置定时器事件,每一秒创建敌机
pygame.time.set_timer(CREATE_ENEMY_EVENT,1000)
#英雄每0.2s发射子弹
pygame.time.set_timer(HERO_FIRE_EVENT,200)
def start_game(self):
print('游戏开始...')
while True:
self.clock.tick(FRAME_PRE_SEC)
self.__event_handler()
self.__update_sprites()
self.__check_collide()
pygame.display.update()
def __event_handler(self):
for event in pygame.event.get():
if event.type==pygame.QUIT:
PlaneGame.__game_over()
elif event.type==CREATE_ENEMY_EVENT:
self.enemy_group.add(Enemy1())
elif event.type==HERO_FIRE_EVENT:
self.hero.fire()
# elif event.type==pygame.KEYDOWN and event.key==pygame.K_RIGHT:
# print('向右移动')#不能连续按
if self.hero.be_destroyed:
PlaneGame.__game_over()
keys_pressed=pygame.key.get_pressed()
# if keys_pressed[pygame.K_RIGHT]:
# self.hero.speed=3
# elif keys_pressed[pygame.K_LEFT]:
# self.hero.speed=-3
# else:
# self.hero.speed=0
dir=keys_pressed[pygame.K_RIGHT]-keys_pressed[pygame.K_LEFT]
self.hero.speed=dir*2
def __check_collide(self):
enemies=pygame.sprite.groupcollide(self.enemy_group,
self.hero.bullets,
False,
True).keys()
for enemy in enemies:
enemy.life-=1
if enemy.life<=0:
enemy.add(self.destroy_group)
enemy.remove(self.enemy_group)
enemy.speed=1
enemy.destroyed()
self.score+=100
for i in pygame.sprite.spritecollide(self.hero,self.enemy_group,True):
print('英雄牺牲了...')
self.hero.destroyed()
def __update_sprites(self):
for group in [self.bg_group, self.hero_group,
self.hero.bullets, self.enemy_group,
self.destroy_group]:
group.update()
group.draw(self.screen)
font=pygame.font.SysFont(None,30)#30大小
dy='score:{}'.format(self.score)
s=font.render(dy,True,'purple')
self.screen.blit(s,(350,10))
@staticmethod
def __game_over():
print('游戏结束')
pygame.quit()
exit()
执行:
if __name__=='__main__':
PlaneGame().start_game()