【Pygame系列】别样的飞机大战:太空陨石VS大型战机对决(内含源码)

导语

图片

​​​

12月的心境:一半优,一半喜。

12月的天空: 一半晴,一半雨。

12月的风 : 已不再那么的轻柔 ,带有无言的烦躁!甚至裹着疼痛的雨。

2022年的尾巴 :已悄悄来临!

临近新的一年,小编为大家准备了一套系列《从简易到豪华版——3个版的“飞机大战”小游戏》

大家可以先自行💭想象~嘿嘿。等我慢慢更新这个系列,今天先给大家更新一个基础版本的飞机大

战吧!

其实说是基础的话也不是很基础:界面特别精致、然后还有相应的防护盾等功能,只是因为第一款

的飞机大战是天上掉下陨石然后敌机的话没得,等我给大家下次升级在给大家写哈!

那么——我们就正式开始干活儿吧👇👇👇👇👇👇

图片

​​​

正文

故事背景:(纯虚构,勿认真)

12月30号晚上凌晨,🌏发生陨石坠落。现场视频显示,当晚夜空忽然被照亮,一道红光从空中划

过,几秒后迅速消失。经过研究,预计今天还会有新一波的大量陨石从天而降,甚至这大量陨石的

降落威胁到了人们的生活,造成了多起医疗事故,所以最后出动了保卫战战队进行宇宙的陨石消灭

计划!我们要尽可能的击碎甚至消灭这些大量的陨石………..计划开始……..

一、游戏规则

我们设计了一款基于Python的Pygame模块开发的飞机大战游戏。

飞机大战游戏是一款休闲益智类游戏,既简单又耐玩。在初始界面,我们有开始游戏和退出游戏两

个选项。

开始游戏后,玩家可以用上下左右方向键的控制飞机在屏幕上向任意方向移动,通过空格键射击陨

石得分,有护盾加生命以及闪电⚡加攻击炮弹,初始化生命为3次在屏幕右上角可以看到当前生

命,中间可以看得分。

二、准备中

1)素材图片

2)来点儿Music

三、代码演示

​
from __future__ import division
import pygame
import random
from os import pathimg_dir = path.join(path.dirname(__file__), 'assets')
sound_folder = path.join(path.dirname(__file__), 'sounds')WIDTH = 480
HEIGHT = 600
FPS = 60
POWERUP_TIME = 5000
BAR_LENGTH = 100
BAR_HEIGHT = 10WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)pygame.init()
pygame.mixer.init()  ## For sound
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Space Shooter")
clock = pygame.time.Clock()     ## For syncing the FPSfont_name = pygame.font.match_font('arial')def main_menu():global screenmenu_song = pygame.mixer.music.load(path.join(sound_folder, "menu.ogg"))pygame.mixer.music.play(-1)title = pygame.image.load(path.join(img_dir, "main.png")).convert()title = pygame.transform.scale(title, (WIDTH, HEIGHT), screen)screen.blit(title, (0,0))pygame.display.update()while True:ev = pygame.event.poll()if ev.type == pygame.KEYDOWN:if ev.key == pygame.K_RETURN:breakelif ev.key == pygame.K_q:pygame.quit()quit()elif ev.type == pygame.QUIT:pygame.quit()quit() else:draw_text(screen, "Press [ENTER] To Begin", 30, WIDTH/2, HEIGHT/2)draw_text(screen, "or [Q] To Quit", 30, WIDTH/2, (HEIGHT/2)+40)pygame.display.update()#pygame.mixer.music.stop()ready = pygame.mixer.Sound(path.join(sound_folder,'getready.ogg'))ready.play()screen.fill(BLACK)draw_text(screen, "GET READY!", 40, WIDTH/2, HEIGHT/2)pygame.display.update()def draw_text(surf, text, size, x, y):## selecting a cross platform font to display the scorefont = pygame.font.Font(font_name, size)text_surface = font.render(text, True, WHITE)       ## True denotes the font to be anti-aliased text_rect = text_surface.get_rect()text_rect.midtop = (x, y)surf.blit(text_surface, text_rect)def draw_shield_bar(surf, x, y, pct):# if pct < 0:#     pct = 0pct = max(pct, 0) ## moving them to top# BAR_LENGTH = 100# BAR_HEIGHT = 10fill = (pct / 100) * BAR_LENGTHoutline_rect = pygame.Rect(x, y, BAR_LENGTH, BAR_HEIGHT)fill_rect = pygame.Rect(x, y, fill, BAR_HEIGHT)pygame.draw.rect(surf, GREEN, fill_rect)pygame.draw.rect(surf, WHITE, outline_rect, 2)def draw_lives(surf, x, y, lives, img):for i in range(lives):img_rect= img.get_rect()img_rect.x = x + 30 * iimg_rect.y = ysurf.blit(img, img_rect)def newmob():mob_element = Mob()all_sprites.add(mob_element)mobs.add(mob_element)class Explosion(pygame.sprite.Sprite):def __init__(self, center, size):pygame.sprite.Sprite.__init__(self)self.size = sizeself.image = explosion_anim[self.size][0]self.rect = self.image.get_rect()self.rect.center = centerself.frame = 0 self.last_update = pygame.time.get_ticks()self.frame_rate = 75def update(self):now = pygame.time.get_ticks()if now - self.last_update > self.frame_rate:self.last_update = nowself.frame += 1if self.frame == len(explosion_anim[self.size]):self.kill()else:center = self.rect.centerself.image = explosion_anim[self.size][self.frame]self.rect = self.image.get_rect()self.rect.center = centerclass Player(pygame.sprite.Sprite):def __init__(self):pygame.sprite.Sprite.__init__(self)## scale the player img downself.image = pygame.transform.scale(player_img, (50, 38))self.image.set_colorkey(BLACK)self.rect = self.image.get_rect()self.radius = 20self.rect.centerx = WIDTH / 2self.rect.bottom = HEIGHT - 10self.speedx = 0 self.shield = 100self.shoot_delay = 250self.last_shot = pygame.time.get_ticks()self.lives = 3self.hidden = Falseself.hide_timer = pygame.time.get_ticks()self.power = 1self.power_timer = pygame.time.get_ticks()def update(self):## time out for powerupsif self.power >=2 and pygame.time.get_ticks() - self.power_time > POWERUP_TIME:self.power -= 1self.power_time = pygame.time.get_ticks()## unhide if self.hidden and pygame.time.get_ticks() - self.hide_timer > 1000:self.hidden = Falseself.rect.centerx = WIDTH / 2self.rect.bottom = HEIGHT - 30self.speedx = 0     ## makes the player static in the screen by default. # then we have to check whether there is an event hanlding being done for the arrow keys being ## pressed ## will give back a list of the keys which happen to be pressed down at that momentkeystate = pygame.key.get_pressed()     if keystate[pygame.K_LEFT]:self.speedx = -5elif keystate[pygame.K_RIGHT]:self.speedx = 5#Fire weapons by holding spacebarif keystate[pygame.K_SPACE]:self.shoot()## check for the borders at the left and rightif self.rect.right > WIDTH:self.rect.right = WIDTHif self.rect.left < 0:self.rect.left = 0self.rect.x += self.speedxdef shoot(self):## to tell the bullet where to spawnnow = pygame.time.get_ticks()if now - self.last_shot > self.shoot_delay:self.last_shot = nowif self.power == 1:bullet = Bullet(self.rect.centerx, self.rect.top)all_sprites.add(bullet)bullets.add(bullet)shooting_sound.play()if self.power == 2:bullet1 = Bullet(self.rect.left, self.rect.centery)bullet2 = Bullet(self.rect.right, self.rect.centery)all_sprites.add(bullet1)all_sprites.add(bullet2)bullets.add(bullet1)bullets.add(bullet2)shooting_sound.play()""" MOAR POWAH """if self.power >= 3:bullet1 = Bullet(self.rect.left, self.rect.centery)bullet2 = Bullet(self.rect.right, self.rect.centery)missile1 = Missile(self.rect.centerx, self.rect.top) # Missile shoots from center of shipall_sprites.add(bullet1)all_sprites.add(bullet2)all_sprites.add(missile1)bullets.add(bullet1)bullets.add(bullet2)bullets.add(missile1)shooting_sound.play()missile_sound.play()def powerup(self):self.power += 1self.power_time = pygame.time.get_ticks()def hide(self):self.hidden = Trueself.hide_timer = pygame.time.get_ticks()self.rect.center = (WIDTH / 2, HEIGHT + 200)# defines the enemies
class Mob(pygame.sprite.Sprite):def __init__(self):pygame.sprite.Sprite.__init__(self)self.image_orig = random.choice(meteor_images)self.image_orig.set_colorkey(BLACK)self.image = self.image_orig.copy()self.rect = self.image.get_rect()self.radius = int(self.rect.width *.90 / 2)self.rect.x = random.randrange(0, WIDTH - self.rect.width)self.rect.y = random.randrange(-150, -100)self.speedy = random.randrange(5, 20)        ## for randomizing the speed of the Mob## randomize the movements a little more self.speedx = random.randrange(-3, 3)## adding rotation to the mob elementself.rotation = 0self.rotation_speed = random.randrange(-8, 8)self.last_update = pygame.time.get_ticks()  ## time when the rotation has to happendef rotate(self):time_now = pygame.time.get_ticks()if time_now - self.last_update > 50: # in millisecondsself.last_update = time_nowself.rotation = (self.rotation + self.rotation_speed) % 360 new_image = pygame.transform.rotate(self.image_orig, self.rotation)old_center = self.rect.centerself.image = new_imageself.rect = self.image.get_rect()self.rect.center = old_centerdef update(self):self.rotate()self.rect.x += self.speedxself.rect.y += self.speedy## now what if the mob element goes out of the screenif (self.rect.top > HEIGHT + 10) or (self.rect.left < -25) or (self.rect.right > WIDTH + 20):self.rect.x = random.randrange(0, WIDTH - self.rect.width)self.rect.y = random.randrange(-100, -40)self.speedy = random.randrange(1, 8)        ## for randomizing the speed of the Mob## defines the sprite for Powerups
class Pow(pygame.sprite.Sprite):def __init__(self, center):pygame.sprite.Sprite.__init__(self)self.type = random.choice(['shield', 'gun'])self.image = powerup_images[self.type]self.image.set_colorkey(BLACK)self.rect = self.image.get_rect()## place the bullet according to the current position of the playerself.rect.center = centerself.speedy = 2def update(self):"""should spawn right in front of the player"""self.rect.y += self.speedy## kill the sprite after it moves over the top borderif self.rect.top > HEIGHT:self.kill()## defines the sprite for bullets
class Bullet(pygame.sprite.Sprite):def __init__(self, x, y):pygame.sprite.Sprite.__init__(self)self.image = bullet_imgself.image.set_colorkey(BLACK)self.rect = self.image.get_rect()## place the bullet according to the current position of the playerself.rect.bottom = y self.rect.centerx = xself.speedy = -10def update(self):"""should spawn right in front of the player"""self.rect.y += self.speedy## kill the sprite after it moves over the top borderif self.rect.bottom < 0:self.kill()## now we need a way to shoot## lets bind it to "spacebar".## adding an event for it in Game loop## FIRE ZE MISSILES
class Missile(pygame.sprite.Sprite):def __init__(self, x, y):pygame.sprite.Sprite.__init__(self)self.image = missile_imgself.image.set_colorkey(BLACK)self.rect = self.image.get_rect()self.rect.bottom = yself.rect.centerx = xself.speedy = -10def update(self):"""should spawn right in front of the player"""self.rect.y += self.speedyif self.rect.bottom < 0:self.kill()###################################################
## Load all game imagesbackground = pygame.image.load(path.join(img_dir, 'starfield.png')).convert()
background_rect = background.get_rect()
## ^^ draw this rect first player_img = pygame.image.load(path.join(img_dir, 'playerShip1_orange.png')).convert()
player_mini_img = pygame.transform.scale(player_img, (25, 19))
player_mini_img.set_colorkey(BLACK)
bullet_img = pygame.image.load(path.join(img_dir, 'laserRed16.png')).convert()
missile_img = pygame.image.load(path.join(img_dir, 'missile.png')).convert_alpha()
# meteor_img = pygame.image.load(path.join(img_dir, 'meteorBrown_med1.png')).convert()
meteor_images = []
meteor_list = ['meteorBrown_big1.png','meteorBrown_big2.png', 'meteorBrown_med1.png', 'meteorBrown_med3.png','meteorBrown_small1.png','meteorBrown_small2.png','meteorBrown_tiny1.png'
]for image in meteor_list:meteor_images.append(pygame.image.load(path.join(img_dir, image)).convert())## meteor explosion
explosion_anim = {}
explosion_anim['lg'] = []
explosion_anim['sm'] = []
explosion_anim['player'] = []
for i in range(9):filename = 'regularExplosion0{}.png'.format(i)img = pygame.image.load(path.join(img_dir, filename)).convert()img.set_colorkey(BLACK)## resize the explosionimg_lg = pygame.transform.scale(img, (75, 75))explosion_anim['lg'].append(img_lg)img_sm = pygame.transform.scale(img, (32, 32))explosion_anim['sm'].append(img_sm)## player explosionfilename = 'sonicExplosion0{}.png'.format(i)img = pygame.image.load(path.join(img_dir, filename)).convert()img.set_colorkey(BLACK)explosion_anim['player'].append(img)## load power ups
powerup_images = {}
powerup_images['shield'] = pygame.image.load(path.join(img_dir, 'shield_gold.png')).convert()
powerup_images['gun'] = pygame.image.load(path.join(img_dir, 'bolt_gold.png')).convert()######################################################################################################
### Load all game sounds
shooting_sound = pygame.mixer.Sound(path.join(sound_folder, 'pew.wav'))
missile_sound = pygame.mixer.Sound(path.join(sound_folder, 'rocket.ogg'))
expl_sounds = []
for sound in ['expl3.wav', 'expl6.wav']:expl_sounds.append(pygame.mixer.Sound(path.join(sound_folder, sound)))
## main background music
#pygame.mixer.music.load(path.join(sound_folder, 'tgfcoder-FrozenJam-SeamlessLoop.ogg'))
pygame.mixer.music.set_volume(0.2)      ## simmered the sound down a littleplayer_die_sound = pygame.mixer.Sound(path.join(sound_folder, 'rumble1.ogg'))
##################################################### TODO: make the game music loop over again and again. play(loops=-1) is not working
# Error : 
# TypeError: play() takes no keyword arguments
#pygame.mixer.music.play()#############################
## Game loop
running = True
menu_display = True
while running:if menu_display:main_menu()pygame.time.wait(3000)#Stop menu musicpygame.mixer.music.stop()#Play the gameplay musicpygame.mixer.music.load(path.join(sound_folder, 'tgfcoder-FrozenJam-SeamlessLoop.ogg'))pygame.mixer.music.play(-1)     ## makes the gameplay sound in an endless loopmenu_display = False## group all the sprites together for ease of updateall_sprites = pygame.sprite.Group()player = Player()all_sprites.add(player)## spawn a group of mobmobs = pygame.sprite.Group()for i in range(8):      ## 8 mobs# mob_element = Mob()# all_sprites.add(mob_element)# mobs.add(mob_element)newmob()## group for bulletsbullets = pygame.sprite.Group()powerups = pygame.sprite.Group()#### Score board variablescore = 0#1 Process input/eventsclock.tick(FPS)     ## will make the loop run at the same speed all the timefor event in pygame.event.get():        # gets all the events which have occured till now and keeps tab of them.## listening for the the X button at the topif event.type == pygame.QUIT:running = False## Press ESC to exit gameif event.type == pygame.KEYDOWN:if event.key == pygame.K_ESCAPE:running = False# ## event for shooting the bullets# elif event.type == pygame.KEYDOWN:#     if event.key == pygame.K_SPACE:#         player.shoot()      ## we have to define the shoot()  function#2 Updateall_sprites.update()## check if a bullet hit a mob## now we have a group of bullets and a group of mobhits = pygame.sprite.groupcollide(mobs, bullets, True, True)## now as we delete the mob element when we hit one with a bullet, we need to respawn them again## as there will be no mob_elements left out for hit in hits:score += 50 - hit.radius         ## give different scores for hitting big and small metoersrandom.choice(expl_sounds).play()# m = Mob()# all_sprites.add(m)# mobs.add(m)expl = Explosion(hit.rect.center, 'lg')all_sprites.add(expl)if random.random() > 0.9:pow = Pow(hit.rect.center)all_sprites.add(pow)powerups.add(pow)newmob()        ## spawn a new mob## ^^ the above loop will create the amount of mob objects which were killed spawn again########################### check if the player collides with the mobhits = pygame.sprite.spritecollide(player, mobs, True, pygame.sprite.collide_circle)        ## gives back a list, True makes the mob element disappearfor hit in hits:player.shield -= hit.radius * 2expl = Explosion(hit.rect.center, 'sm')all_sprites.add(expl)newmob()if player.shield <= 0: player_die_sound.play()death_explosion = Explosion(player.rect.center, 'player')all_sprites.add(death_explosion)# running = False     ## GAME OVER 3:Dplayer.hide()player.lives -= 1player.shield = 100## if the player hit a power uphits = pygame.sprite.spritecollide(player, powerups, True)for hit in hits:if hit.type == 'shield':player.shield += random.randrange(10, 30)if player.shield >= 100:player.shield = 100if hit.type == 'gun':player.powerup()## if player died and the explosion has finished, end gameif player.lives == 0 and not death_explosion.alive():running = False# menu_display = True# pygame.display.update()#3 Draw/renderscreen.fill(BLACK)## draw the stargaze.png imagescreen.blit(background, background_rect)all_sprites.draw(screen)draw_text(screen, str(score), 18, WIDTH / 2, 10)     ## 10px down from the screendraw_shield_bar(screen, 5, 5, player.shield)# Draw livesdraw_lives(screen, WIDTH - 100, 5, player.lives, player_mini_img)## Done after drawing everything to the screenpygame.display.flip()       pygame.quit()

四、游戏效果

1)视频展示效果

Pygame系列:别样的飞机大战:太空陨石VS大型战机对决!

2)截图展示效果

游戏界面:

正常的效果

加了护盾+⚡:

总结

好啦!这款飞机大战就学到这里正式结束~加班加点给大家升级一下,做一个有敌机的互相对战!

嘿嘿~喜欢的记得收藏哦~

源码基地——

滴滴我即可啦!看我主页(pc端也可以自取滴)~

🎉往期推荐阅读——

项目合集1.0  各种游戏源码都在这里免费拿!

项目合集1.1 各种人工只能方面的源码项目点这里!

项目合集1.2 各种表白的项目源码都在这里看!

项目合集1.3  各种Turtle的代码都在找这里呀!

🎄文章汇总——

项目1.0 Python—2021 |已有文章汇总 | 持续更新,直接看这篇就够了

(更多内容+源码都在文章汇总哦!!欢迎阅读~)

Published by

风君子

独自遨游何稽首 揭天掀地慰生平