When I wrote a thunder fighter in python for my cousin

Hits: 0

Everyone has played Thunder Fighter, that's all

My cousin, who is only in elementary school, bothers me to get grades on weekends. Others are simulating the college entrance examination for three years and five years. I am different. I wrote a game for him and played it by myself, but I couldn’t teach him to [crawl] . Well, it’s not suitable for a young age~

1. Preparation

Software version used:

  • Python3.6
  • pycharm2019 Professional Edition

You can also use other ones. If there is no software, I will put it at the end.

Install these two modules

  • pygame
  • random

win+r to open the run box, enter cmd, press Enter to open the command prompt window, enter pip install space plus the module you want to install, if the download is slow, change the domestic mirror source, because it downloads from abroad by default, so will be slower.

we’re going to prepare these things

  1. Font file

  2. Background music file

  3. Background image

You can design it yourself, prepare it yourself, and change the name to the same.

Of course, you can also change to other names, but you also have to change the name in the code

Second, the code display

Forget it, let me put the code directly, it’s a bit long, you will definitely not be able to read it, I will put it in the comments to talk about it, so that you can read it.

#import module
import pygame, os
import time
import random
from pygame.sprite import Sprite
from pygame.sprite import Group

def fire\_music():
    pass
    # Set fire music 
    # effect = pygame.mixer.Sound('sounds/fire.wav') 
    # pygame.mixer.Sound.play(effect)

class  Boss ( Sprite ): 
    def \ _ \ _init \ _ \ _ ( self ,boss\_img\_name) :
         super ().\ _ \_init\ _ \ _ ()
         # Load BOSS image 
        self .image = pygame.image .load( 'image/' +boss\_img\_name+ '.png' ).convert\_alpha()
         # Convert BOSS size 
        # self.image = pygame.transform.scale(self.image, (1, 12)) 
        # Generate BOSS rectangle frame 
        self .rect = self .image.get\_rect()
         self.blood \= 1000 
        # The speed of the boss moving left and right 
        self .speed = 3.5

    def move(self):
        if self.rect.centerx>=512:
            self.speed \=-self.speed
        if self.rect.centerx<=0:
            self.speed \= -self.speed
        self.rect.centerx +=self.speed

class Enemy(Sprite):
    def \_\_init\_\_(self,screen):

super ().\ _ \_init\ _ \ _ ()
         # Get the screen object 
        self .screen = screen
         # Randomly generate 5 numbers 
        alien\_num = random. randint( 1 , 5 )
         # Randomly load one of the five planes 
        self .image = pygame.image.load( 'picture/alien\_' + str(alien\_num) + '.png' )
         # picture = pygame.transform.scale(picture, (1280, 720)) 
        self . image = pygame.transform.scale( self .image,( 62 , 62 ))
         # Get the rect of the plane 
        self .rect = self.image.get\_rect()
         # The score obtained by shooting down the machine 
        self .score = 10 
        # Load the bullet image 
        self .bullet\_img = pygame.image.load( "image/alien\_bullet.png" ).convert\ _alpha()
         self .bullet\_img \= pygame.transform.scale( self .bullet\_img, ( 12 , 12 ))
         # The following is the code that can adjust the size of the bullet 
        # picture = pygame.transform.scale(picture, (1280 , 720)) #The 
        movement speed of the plane 
        self .speed = random.randint( 3 , 5 )

        #Generate bullet sprite combination 
        self .bullets = Group()
         # Enemy shooting frequency 
        self .shoot\_frequency = 0

    # The plane appears 
    def  move ( self ) :
         self .rect.top += 5 #No 
        need to shoot for 
        now # self.shoot() 
        # self.moveBullet( ) # Shoot 
    bullets 
    def  shoot ( self ) :
         if  self .shoot\_frequency % 200 == 0 :
            bullet \= Enemy\_Bullet(self.bullet\_img, self.rect.midbottom)
            self.bullets.add(bullet)
        self.shoot\_frequency += 1
        if self.shoot\_frequency > 200:
            self.shoot\_frequency \= 1
    def moveBullet(self):
        for bullet in self.bullets:
            bullet.move()
            if bullet.rect.bottom < 0:
                self.bullets.remove(bullet)
    def drawBullets(self, scr):
        self.bullets.draw(scr)

class Enemy\_Bullet(pygame.sprite.Sprite):
    def \_\_init\_\_(self, init\_pos):
        pygame.sprite.Sprite.\_\_init\_\_(self)

        self .image \= pygame.image.load( "image/alien\_bullet.png" ).convert\_alpha()
         self .image \= pygame.transform.scale( self .image, ( 12 , 12 ))
         self . rect \= self .image.get\_rect()
         # Set the initial position of enemy bullets 
        self .rect.midbottom = init\_pos
         self .rect.centery += 36 
        self .speed \= 8

    def  move ( self ) :
         self .rect.top += self .speed
 class  MyHero ( Sprite ): 
    \_rate \= 100  # milliseconds per frame 
    def \ _ \ _init \ _ \ _ ( self ,screen,size = 1 ) :
         super ().\ _ \_init\ _ \ _ ()
         # Get the screen object 
        self .screen = screen
         # Get the whole picture 
        self.image\_big = pygame.image.load( 'image/hero.png' ).convert\_alpha()
         # subsurface forms the subsurface frame of the big image 
        # Get the front image of the plane 
        self .image = self .image\_big.subsurface (pygame.Rect( 120 , 0 , 318 - 240 , 87 ))
         # Get the frame size of the plane's front rectangle 
        self .rect = self .image.get\_rect()
         # Get the screen object rectangle 
        self .screen\_rect = screen.get \_rect()
         # Get the x-coordinate of the center of the screen 
        self .rect.centerx = self .screen\_rect.centerx
         # Get the y-coordinate of the bottom of the screen 
        self .rect.centery =self .screen\_rect.bottom - self .rect.height
         # Set the initial position of the aircraft 
        self .centerX = float( self .rect.centerx)
         self .centerY \= float( self .rect.centery)
         # Aircraft tail flame 
        self .air = None
         # Set the aircraft tail flame position 
        self .air\_rect = pygame.Rect( self .centerX - 20 , self .centerY+int(( self .rect.height+ 72 )/ 2 )- 10 - 36 , 40 , 72 )

        #A collection of all bullets fired by the player 
        self .bullets = Group()
         self .bullet\_image \= pygame.image.load( 'image/bullet\_1.png' ).convert\_alpha()

    # Bullet shooting 
    def  shoot ( self ) :
         # Generate a bullet instance 
        bullet = Bullet( self .bullet\_image, self .rect.midtop)
         # Add bullets to the group bullet sprite collection 
        self .bullets.add(bullet)
     # Bullet delete 
    def  moveBullet ( self ) :
         # Check the bullet sprites set to the top of the screen one by one delete 
        for bullet in  self . bullets:
            bullet.move()
            if bullet.rect.bottom < 0 :
                 self .bullets.remove(bullet)
     # bullet display 
    def  drawBullets ( self , scr) :
         # draw the bullets in the sprite collection to the screen 
        self .bullets.draw(scr)



    # When flying up, add jet flame 
    def  set \ _air ( self , case ) :
         if  case == 'up' :
            air \= pygame.image.load( 'image/air.png' ).convert\_alpha()
            img \= air.subsurface(pygame.Rect(80, 0, 50, 87))
            self.air \= img
        elif case == 'remove':
            self.air \= None

    # Get the picture of the plane's moving state according to the moving direction 
    def  set \ _image ( self , case ) :
         if  case == 'left' :
            rect \= pygame.Rect(195,0,318-248,87)
            image \= self.image\_big.subsurface(rect)
        elif case =='right':
            rect \= pygame.Rect(195,0,318-248,87)
            image \= pygame.transform.flip(self.image\_big.subsurface(rect), True, False)
        elif case == 'up' or case == 'down':
            rect \= pygame.Rect(120, 0, 318 - 240, 87)
            image \= self.image\_big.subsurface(rect)
        self.image \= image

class Bullet(pygame.sprite.Sprite):
    def \_\_init\_\_(self, bullet\_img, init\_pos):
        pygame.sprite.Sprite.\_\_init\_\_(self)
        self.image \= bullet\_img
        self.rect \= bullet\_img.get\_rect()
        self.rect.midbottom \= init\_pos
        self.speed \= 25

    def move(self):
        self.rect.top \-= self.speed

# Initialize pygame
pygame.init()
# pygame.mixer.init() 
# pygame.mixer\_music.load('sounds/enviro.mp3') # Load and play music 
# pygame.mixer.music.play(-1) #-1 for loop playback 
# Set up the game Theme 
pygame.display.set\_caption( 'Thunderplane' )
 # Initialize screen size 
screen = pygame.display.set\_mode(( 512 , 768 ))

# Set the game background image
 # The background image 
bg\_img at the beginning of the game 0 = pygame.image.load( 'image/start\_bg.jpg' ).convert()
 # Load the game start icon 
start\_img = pygame.image .load( 'image/start.png' ).convert\_alpha()
start\_rect \= start\_img.get\_rect()
start\_rect.centerx \= 262 
start\_rect.centery \= 455 
# Background image 
bg\_img1 = pygame.image.load( 'image/map1.jpg' ).convert()
bg\_img2 \= bg\_img1.copy()
# The background image at the end of the game 
bg\_img3 = pygame.image.load( 'image/map3.jpg' ).convert()
 # Load the game over icon 
gameover\_img = pygame.image.load( 'image/gameover.png ' ).convert\_alpha()
 # Load the game success icon 
gamesuccess = pygame.image.load( 'image/success.png' ).convert\_alpha()

# Load the replay icon 
restart\_img = pygame.image.load( 'image/restart.png' ).convert\_alpha()
restart\_rect \= restart\_img.get\_rect()
restart\_rect.centerx \= 249 
restart\_rect.centery \= 420 
# initial position of background image 
pos\_y1 = - 768 
pos\_y2 \= 0

# Instantiate BOSS 
boss = Boss( 'boss\_1' )
bosses \= Group()
bosses.add(boss)
# Test the main character image 
# air = pygame.image.load('image/air.png').convert\_alpha() 
# img = air.subsurface(pygame.Rect(80, 0, 50, 87)) 
# image\ _big = pygame.image.load('image/hero.png').convert\_alpha() 
# image = image\_big.subsurface(pygame.Rect(195,0,318-248,87))

# Generate our plane
student\_plane = MyHero(screen)

# Generate enemy aircraft 
# Generate enemy aircraft group
enemies = Group()
# Generate enemy bullets
enemy\_bullets = Group()
max\_enemies \= 9   # Set the total number of enemy planes to 9 
# The randint parameter below the random appearance of enemy planes is 43,55 
ran1,ran2 = 30 , 40

# Generate timing frequency variable 
sec = 0 
# Generate score 
score = 0 
# Set system font 
my\_font = pygame.font.Font( 'fonts/msyh.ttf' , 18 )

# Game main loop 
# Set the game state to start and end 
game = 'wait'

while  True: 
    # The game is in a waiting state 
    if game == 'wait' :
         # The minimum game framework cannot be omitted 
        for event in pygame.event.get():
             if event.type == pygame.QUIT :
                pygame.quit()

        # Detect if the mouse is pressing the restart button 
            if event.type == pygame. MOUSEBUTTONDOWN: 
                # Detect if the mouse click position overlaps the restart rect 
                if start\_rect.collidepoint(event.pos):
                    student\_plane.\_\_init\_\_(screen)
                    game \= 'ing' 
        # game screen pause 
        screen.blit(bg\_img 0 , ( 0 , 0 ))
        screen.blit(start\_img, start\_rect)
        # Test tail flame position
        pygame.display.flip()
        time.sleep(0.05)

    # The game is in progress 
    elif game == 'ing' :
         # Set these 3 lines to monitor events and set a delay internally to prevent the game from freezing 
        # Screen scrolling------------------- ----------------------------------- 
        screen.blit(bg\_img1, ( 0 , pos\_y1) )
        screen.blit(bg\_img2, ( 0 , pos\_y2))
         # test tail flame position 
        # screen.blit(img, (100, 100)) 
        pos\_y1 += 1 
        pos\_y2 += 1 
        # screen background scroll Reset the position after completion 
        if pos\_y1 >= 0 :
            pos\_y1 \= -768
        if pos\_y2 >= 768:
            pos\_y2 \= 0


        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            # Monitor keyboard events 
            # Press the button to cancel the upward tail flame to correct the aircraft posture 
            if event.type == pygame. KEYUP: 
                student\_plane.set\_image( 'down' )
                student\_plane.air \= None
            # Fire bullets 
            if event.type == pygame. KEYDOWN: 
                if event.key == pygame.K\_SPACE and len(student\_plane.bullets) < 6 : # Check the number of bullet sets to limit the maximum number of bullets
                    fire\_music()
                    # Generate a bullet instance 
                    # Add bullets to the group bullet sprite collection
                    student\_plane.shoot()
        # Draw the bullets in the sprite collection to the screen
        student\_plane.drawBullets(screen)
        # Check one by one to delete the bullets that the bullet sprite collection reaches the top of the screen
        student\_plane.moveBullet()

        keys \= pygame.key.get\_pressed()
        if keys\[pygame.K\_a\]:
             # Set the plane status image 
            student\_plane.set\_image( 'left' )
             if student\_plane.rect.centerx>= 40 :
                student\_plane.rect.centerx \-=8.5

        elif keys\[pygame.K\_d\]:
            # Set the plane status image 
            student\_plane.set\_image( 'right' )
             if student\_plane.rect.centerx <= 478 :
                student\_plane.rect.centerx +=8.5

        elif keys \ [pygame.K \ _w \]:
            #Set the plane status image 
            student\_plane.set\_image( 'up' )
            student\_plane.set\_air('up')

            if student\_plane.rect.centery >= 45:
                student\_plane.rect.centery \-=8.5

        elif keys\[pygame.K\_s\]:
            # Set the plane status image 
            student\_plane.set\_image( 'down' )
             if student\_plane.rect.centery <= 727 :
                student\_plane.rect.centery +=8.5

        # show plane
        screen.blit(student\_plane.image,student\_plane.rect)
        if student\_plane.air != None:
            screen.blit(student\_plane.air, (student\_plane.rect.centerx\-30, student\_plane.rect.centery+33))

        # Enemy ----------------------------------------------- ----------------------------------------

        # Enemy movement 
        # Control time rhythm sec variable 
        sec += 1 
        # Randomly control the rhythm of generating enemy planes
        rhy = random.randint(ran1,ran2)
        # Maximum number of enemy planes

        if sec%rhy == 0  and len(enemies) < max\_enemies or sec == 1 : # Set the total number of enemy planes to 9 
            # Generate an enemy plane
            enemy = Enemy(screen)
            enemy.rect.centerx\=random.randint( 0 , 512 )
             # Generate bullets for the above enemy plane
            enemy\_bullet = Enemy\_Bullet((enemy.rect.centerx,enemy.rect.centery))
            # Enemy aircraft group and enemy aircraft bullet group load enemy aircraft and bullets
            enemies.add(enemy)
            enemy\_bullets.add(enemy\_bullet)
        # Enemy Appearance and Enemy Bullet Appearance
        enemies.draw(screen)
        enemy\_bullets.draw(screen)
        # Iterate over the set of enemies 
        for enemy in  enemies: 
            # Make each object move
            enemy.move()
            # Automatically delete the enemy plane when it exceeds the screen boundary
            collision\_over1 = pygame.sprite.collide\_rect(student\_plane, enemy)

            if collision\ _over1: 
                # To prevent old bullets and planes from existing when restarting the game
                enemies.remove(enemy)
                game \= 'over'
            if enemy.rect.bottom >768:
                enemies.remove(enemy)
        for enemy\_bullet in enemy\ _bullets: 
            # make each object move
            enemy\_bullet.move()

            collision\_over2 \= pygame.sprite.collide\_rect(student\_plane, enemy\_bullet)
            if collision\ _over2: 
                # To prevent old bullets and planes from existing when restarting the game
                enemy\_bullets.remove(enemy\_bullet)
                game \= 'over' 
            # Automatically delete the enemy when the enemy's bullet goes beyond the screen border 
            if enemy\_bullet.rect.bottom > 768 :
                enemy\_bullets.remove(enemy\_bullet)


        # -------------Boss ------------------------- - 
        if score >= 140 :
             # The rhythm of small enemy planes appearing 
            ran1,ran2 = 15 , 25 
            max\_enemies \= 17
            screen.blit(boss.image,boss.rect)
            boss.move()
            for my\_bullet in student\_plane.bullets:
                hit\_boss \= pygame.sprite.collide\_rect(boss,my\_bullet)
                if hit\_boss:
                    boss.blood \-=1.2
                    score+=1
                if boss.blood <=0:
                    game \= 'success'

        # Handling collisions -----------------------------Collision detection---------------------- -------------------------------- 
        # Parameters: 
        # group1: sprite group 1. 
        # group2: sprite group 2. 
        # dokill1: Whether to destroy the colliding sprites in sprite group 1 when a collision occurs. 
        # dokill2: Whether to destroy the colliding sprites in sprite group 2 when a collision occurs.
        collisions = pygame.sprite.groupcollide(student\_plane.bullets, enemies, True, True)
        if collisions:
            score+=10

        # -----------game over------------

        # Display of scores and rewards -------------------------------------------- ----------------------------- 
        surface1 = my\_font.render(u "Current score: %s" %(score) , True,\[ 255 , 0 , 0 \])
        screen.blit(surface1,\[20,20\])

        # update screen
        pygame.display.flip()
        # set framerate and delay 
        time.sleep( 0 . 05 )

    #Game over state 
    elif game == 'over' :
        score \= 0 
        # The minimum game framework cannot be omitted 
        for event in pygame.event.get():
             if event.type == pygame.QUIT :
                pygame.quit()

        # Detect if the mouse is pressing the restart button 
            if event.type == pygame. MOUSEBUTTONDOWN: 
                # Detect if the mouse click position overlaps the restart rect 
                if restart\_rect.collidepoint(event.pos):
                    student\_plane.\_\_init\_\_(screen)
                    game \= 'ing'

        # Game end game screen pause 
        screen.blit(bg\_img1, ( 0 , pos\_y1))
        screen.blit(bg\_img2, (0, pos\_y2))

        screen.blit(gameover\_img, (163, 310))
        screen.blit(restart\_img, restart\_rect)
        # Test tail flame position 
        # screen.blit(img, (100, 100)) 
        pos\_y1 += 0 
        pos\_y2 += 0
        pygame.display.flip()
        time.sleep(0.05)
        # surface2 = my\_font.render("Game Over" , True, \[255, 0, 0\])
        # screen.blit(surface1, \[250, 350\])
    elif game == 'success':
        score \= 0 
        boss.blood \= 1000 
        # The minimum game framework cannot be omitted 
        for event in pygame.event.get():
             if event.type == pygame.QUIT :
                pygame.quit()

        # Detect if the mouse is pressing the restart button 
            if event.type == pygame. MOUSEBUTTONDOWN: 
                # Detect if the mouse click position overlaps the restart rect 
                if restart\_rect.collidepoint(event.pos):
                    student\_plane.\_\_init\_\_(screen)
                    game \= 'ing'

        # Game end game screen pause 
        screen.blit(bg\_img1, ( 0 , pos\_y1))
        screen.blit(bg\_img2, (0, pos\_y2))

        screen.blit(gamesuccess, (170, 220))
        screen.blit(restart\_img, restart\_rect)
        # Test tail flame position 
        # screen.blit(img, (100, 100)) 
        pos\_y1 += 0 
        pos\_y2 += 0
        pygame.display.flip()
        time.sleep(0.05)

3. Effect display

Let’s take a look at the running effect, play a little bit

Brothers, I will give you the code directly, please like and forward it after reading it~

Here I have prepared a zero-based Python learning material for everyone. Interested students can take a look.

“Python Experience Sharing”

===============================

Learning Python well is a good way to make money , whether it’s a job or a side business , but to learn Python, you still have to have a study plan. Finally , I will share with you a complete set of Python learning materials for free , and give some help to those who want to learn Python!

1. Learning routes in all directions of Python

All directions of Python are to organize the technical points commonly used in Python to form a summary of knowledge points in various fields. Its usefulness is that you can find corresponding learning resources according to the above knowledge points to ensure that you can learn more comprehensively.

2. Learning software

If a worker wants to do a good job, he must first sharpen his tools. The commonly used development software for learning Python is here, which saves everyone a lot of time.

Three, introductory learning video

When we watch videos to learn, we can’t move our eyes and brains without hands. The more scientific way of learning is to use them after understanding. At this time, the hands-on project is very suitable.

4. Practical cases

Optical theory is useless. You have to learn to follow along, and you have to do practical exercises before you can apply what you have learned to practice. At this time, you can learn from actual combat cases.

5. Interview information

We must learn Python in order to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Ali, Tencent, and Byte, and some Ali bosses have given authoritative answers. After finishing this set The interview materials believe that everyone can find a satisfactory job.

This full version of Python’s full set of learning materials has been uploaded
to CSDN. If you need it, you can scan the CSDN official certification QR code below on WeChat to get it for free [guaranteed 100% free].

You may also like...

Leave a Reply

Your email address will not be published.