当前位置:网站首页>[pyGame actual combat] aircraft shooting masterpiece: fierce battle in the universe is imminent... This super classic shooting game should also be taken out and restarted~
[pyGame actual combat] aircraft shooting masterpiece: fierce battle in the universe is imminent... This super classic shooting game should also be taken out and restarted~
2022-07-23 15:22:00 【Gu Muzi acridine】
Introduction
Hello, hello ! Good afternoon, ~ I'm kimiko .
Previously, I introduced Python Produced football match 、 skiing 、 Contra 、 Super Mary and dozens of other games , The effect is not bad ,
The response was very enthusiastic . Sure enough, the game still attracts everyone's attention !
Complete material for all articles + The source code is in

So today we continue to learn to use Python Make a very interesting and scientific game : Fierce battle in the universe
Space games . Both interesting , And can learn programming , The main thing is that children will definitely like it ~
Gamers will fly a starship , Shuttle through the gorgeous and mottled universe , Facing various tasks and challenges , It can finish
It's this mission ? We might as well guess, or you can try it yourself ?! Let's move on to today's theme !
Text
One 、 Introduction of the principle
First of all, the background of the game , You can see , There are several areas that need to be implemented :
The first is the background , Because the background of the game is always changing , So it must be a dynamic background ;
The second is music , There is music of bullets , Explosive music of missile hit and impact ;
The third is the spaceship , Including our main ship 、 Enemy spacecraft, etc , There are also big boss Missile attack , Our main ship can launch
Bullets attack enemy ships ( Destroy an enemy plane by three points ), It can also hit enemy ships , Once our main ship is hit or collided
blow , You will deduct health value once ( Only one debugging can be set here ), HP reduced to 0, be Game Over!
Two 、 material ( picture 、 Music, etc )
There are mainly these roles , The spacecraft ( Including our main ship 、 Enemy ships and other different shapes )、 The bullet 、 Missiles and other props ( Different make
type ).

3、 ... and 、 Code display
There are mainly two pieces py The following are posted for everyone
1)main.py The main program
from mySprite import *
# initialization
def init():
pygame.init()
global isRun
isRun = True
global text_font, over_font, over_render, restar_render, star
text_font = pygame.font.SysFont('arial', 20)
over_font = pygame.font.SysFont('arial', 40)
over_render = over_font.render('Game Over', 1, (255, 20, 20), None)
restar_render = text_font.render('Press R key for restart game', 1, (80, 209, 80), None)
star = pygame.image.load('./img/star.png')
bg0 = Background()
bg1 = Background(True)
global back_group, fly, fly_group, score_render, enemy_group, boom_group
back_group = sprite.Group(bg0, bg1)
fly = Fly()
fly_group = sprite.Group(fly)
score_render = text_font.render(str(fly.score), 1, (172, 209, 204), None)
enemy_group = sprite.Group()
boom_group = sprite.Group()
pygame.time.set_timer(10, 1000)
pygame.time.set_timer(15, 500)
# Handling events
def dealEvent():
GAMECLOCK.tick(70)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if isRun:
if event.type == 10:
enemy = Enemy()
enemy_group.add(enemy)
elif event.type == 15:
fly.fire()
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_r]:
main_game()
if keys_pressed[pygame.K_RIGHT]:
fly.speed = 2
elif keys_pressed[pygame.K_LEFT]:
fly.speed = -2
else:
fly.speed = 0
# collision detection - Between ELF groups - Between elves and elves
def checkCollide():
bullet_shot_enemy = pygame.sprite.groupcollide(fly.bullets, enemy_group, True, True)
if bullet_shot_enemy:
pygame.mixer.init()
for bullet in bullet_shot_enemy:
rect = bullet.rect
boom = Boom(rect.centerx, rect.centery)
boom_group.add(boom)
pygame.mixer.music.load('./img/bao.mp3')
pygame.mixer.music.play(1)
fly.score += 3
global score_render
score_render = text_font.render(str(fly.score), 1, (172, 209, 204), None)
enemies = pygame.sprite.spritecollide(fly, enemy_group, True)
if enemies:
global isRun
isRun = False
SCREEN.blit(over_render,
((WINDOW.width - over_render.get_width()) / 2,
(WINDOW.height - over_render.get_height()) / 2 - 10))
SCREEN.blit(restar_render, ((WINDOW.width - restar_render.get_width()) / 2,
(WINDOW.height - restar_render.get_height()) / 2 + over_render.get_height()))
pygame.display.update()
# Sprite painting update
def update():
if isRun:
back_group.draw(SCREEN)
back_group.update()
fly_group.draw(SCREEN)
fly_group.update()
fly.bullets.draw(SCREEN)
fly.bullets.update()
enemy_group.draw(SCREEN)
enemy_group.update()
boom_group.draw(SCREEN)
boom_group.update()
boom_group.empty()
SCREEN.blit(score_render, (WINDOW.width - 60, 20))
SCREEN.blit(star, (WINDOW.width - 85, 20))
pygame.display.update()
# The main function
def main_game():
init()
while True:
dealEvent()
checkCollide()
update()
main_game()2)MySprite.py
import pygame
from pygame import sprite
import random
WINDOW = pygame.Rect(0, 0, 466, 700)
SCREEN = pygame.display.set_mode(WINDOW.size)
pygame.display.set_caption('FlyFight')
GAMECLOCK = pygame.time.Clock() # Game clock
# My spirit
class MySprite(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.y += self.speed
# Background Genie
class Background(MySprite):
def __init__(self, next=False):
super().__init__('./img/background.png')
if next:
self.rect.y = -self.rect.height
def update(self):
super().update()
if self.rect.y >= 700:
self.rect.y = -self.rect.height
# Bullet Genie
class Bullet(MySprite):
def __init__(self):
super().__init__('./img/bullet.png', -2)
def update(self):
super().update()
if self.rect.bottom < 0:
self.kill()
# Scout spirit
class Fly(MySprite):
def __init__(self):
super().__init__('./img/fly.png', 0)
# Set the initial position of the reconnaissance aircraft
self.rect.centerx = WINDOW.centerx
self.rect.bottom = WINDOW.bottom-10
# Define the bullet sprite Group
self.bullets = pygame.sprite.Group()
self.score = 0
def update(self):
self.rect.x += self.speed
if self.rect.right > WINDOW.width:
self.rect.right = WINDOW.width
elif self.rect.x < 0:
self.rect.x = 0
def fire(self):
bullet = Bullet()
# Set the initial position of the bullet
bullet.rect.centerx = self.rect.centerx
bullet.rect.bottom = self.rect.y
self.bullets.add(bullet)
# Enemy spirit
class Enemy(MySprite):
def __init__(self):
super().__init__('./img/enemy.png')
# The secret of separation , Set the speed and position
self.speed = random.randint(2, 3)
self.rect.bottom = 0
x = WINDOW.width - self.rect.width
self.rect.x = random.randint(0, x)
def update(self):
super().update()
if self.rect.y >= WINDOW.height:
self.kill()
# Explosion effect Wizard
class Boom(MySprite):
def __init__(self, x, y):
super().__init__('./img/boom.png')
# Set the position of the explosion effect
self.rect.centerx = x
self.rect.centery = y
Four 、 Effect display
1) Different backgrounds

2) The impact is over
The rules of the game : Direction keys can be moved around ,R Play again .

summary
News of the game going online within three seconds of the countdown , That's true. 🤭 Chestnuts know 🤭 Kiko knows 🤭 Pear knows 🤭
Gu Muzi knows 🤭 You are waiting for all the above personnel to enter the site , Did you know you just entered ?
【 Meta universe interstellar universe battle Games officially opened 】………… Ten thousand times set sail ( Xuan )
Zhixing I Ching coincides with Tao , What you say is true . To be honest, I don't understand , That is, no self enters the Tao by mistake .
Come to me and try the source code of the material ! I'm waiting for you in a hurry
Complete free source code collection office : Find me ! Public at the end of the article hao You can get it by yourself , Didi, I can also !
I recommend previous articles ——
project 1.0 Super Marie
project 1.1 Mine clearance
project 1.3 Space mecha game
project 1.4 Fruit ninja
project 2.0 Connected to the Internet 、 Man machine Gobang game
A summary of the article ——
project 1.0 Python—2021 | Summary of existing articles | Continuous updating , Just read this article directly
( More + The source code is summarized in the article !! Welcome to ~)

边栏推荐
猜你喜欢

如何实现多个传感器与西门子PLC之间485无线通讯?

工业物联网中的时序数据

力扣-单调栈

Monotonous stack!!!

多线程一定能优化程序性能吗?

Matlab simulation of solving multi-objective optimal value based on PSO optimization

颜值爆表 Redis官方可视化工具来啦,针不戳

Cloud native observability tracking technology in the eyes of Baidu engineers

【7.16】代码源 -【数组划分】【拆拆】【选数2】【最大公约数】
![[machine learning basics] unsupervised learning (5) -- generation model](/img/a3/8b72d5472ceacdc094880be6efcbe4.png)
[machine learning basics] unsupervised learning (5) -- generation model
随机推荐
ESP三相SVPWM控制器的simulink仿真
VMware虚拟机下载安装使用教程
Simulation of voltage source PWM rectifier with double closed loop vector control based on Simulink
String与Integer互相转换
什么是服务器托管及和虚拟主机的区别
[CTFHub]JWT 的头部和有效载荷这两部分的数据是以明文形式传输的,如果其中包含了敏感信息的话,就会发生敏感信息泄露。试着找出FLAG。格式为 flag{}
Matlab simulation of Turbo code error rate performance
postgresql没有nvl的解决办法,postgresql查询所有的表
idea一次启动多个项目
CBOC signal modulation and demodulation simulation based on MATLAB, output its correlation, power spectrum and frequency offset tracking
BGP basic configuration
基于matlab的BOC调制信号捕获仿真
多项式承诺Polynomial commitment方案汇总
Activity的启动流程
颜值爆表 Redis官方可视化工具来啦,针不戳
【Pygame实战】打扑克牌嘛?赢了输了?这款打牌游戏,竟让我废寝忘食。
Smart headline: smart clothing forum will be held on August 4, and the whole house smart sales will exceed 10billion in 2022
基於matlab的CBOC信號調制解調仿真,輸出其相關性,功率譜以及頻偏跟踪
centos7 中彻底卸载mysql
day18