Pygame actual combat: the front is burning high, and the alien base is once again "airborne".

  Introduction

"The universe is much larger than anyone can imagine. Wouldn't it be a waste of space if it were just us?"

I forgot where I got it. It may be borrowed by the next class or bought by relatives and friends.

In short, hiding in the quilt with a flashlight and seeing 12 o'clock, the more afraid I am, the more I want to see it~

Bermuda Triangle, UFO s, planes that have disappeared for many years, dissecting aliens, crystal skulls, Bigfoot monsters, crop circles, Egyptian pyramids

Today's article is an alien topic that everyone is interested in! Xiaobian's brain capacity is limited, but he can't imagine what aliens look like.

But I can cartoon this alien game for you! Absolutely not scary, even a little cute~

text

Writing games? Or we are familiar with the pygame module, which is mainly divided into three py source files.

Rules of the game: we control the fort to shoot down aliens invading the earth 🌏, You can regenerate three times each time, destroy aliens once, add points accordingly, enter the next level, and complete all levels.

First, define our battery class: there are corresponding comments to see.

'''Our class'''
class aircraftSprite(pygame.sprite.Sprite):
    def __init__(self, color, bullet_color, **kwargs):
        pygame.sprite.Sprite.__init__(self)
        # Life value
        self.num_life = 3
        self.max_num_life = 5
        # Minimum unit
        self.cell = [3, 3]
        self.num_cols = 15
        self.num_rows = 8
        # For collision detection
        self.rect = pygame.Rect(0, 550, self.cell[0] * self.num_cols, self.cell[0] * self.num_rows)
        # Fill color area
        self.filled_cells = [7,21,22,23,36,37,38,46,47,48,49,50,51,52,53,54,55,56,57,58,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119]
        # Ship color
        self.color = color
        # Ship bullet color
        self.bullet_color = bullet_color
        # Is the bullet cooling
        self.is_cooling = False
        self.init_count = 35
        self.cooling_count = self.init_count
        # score
        self.score = 0
        # Avoid repeatedly increasing health
        self.old_score = -1
        self.resetBoom()
    '''Shooting'''
    def shot(self):
        if self.is_cooling:
            return None
        self.is_cooling = True
        self.cooling_count = self.init_count
        return myBulletSprite(self.rect.x + self.rect.width // 2, self.rect.y, self.bullet_color)
    '''Draw it on the screen'''
    def draw(self, screen):
        for i in range(0, len(self.filled_cells)):
            y = self.filled_cells[i] // self.num_cols
            x = self.filled_cells[i] % self.num_cols
            rect = [x * self.cell[0] + self.rect[0], y * self.cell[1] + self.rect[1], self.cell[0], self.cell[1]]
            pygame.draw.rect(screen, self.color, rect)
    '''Update ship location and other information'''
    def update(self, WIDTH):
        # position information
        x = pygame.mouse.get_pos()[0] - (self.rect.width // 2)
        if x < 0:
            x = pygame.mouse.get_pos()[0]
        elif x > WIDTH - self.rect.width:
            x = WIDTH - self.rect.width
        self.rect.x = x
        # Bullet information
        if self.is_cooling:
            self.cooling_count -= 1
            if self.cooling_count == 0:
                self.is_cooling = False
    '''Explosion after being hit'''
    def boom(self, screen):
        self.boomed_rect.x = self.rect.x
        self.boomed_rect.y = self.rect.y
        self.boomed_count += 1
        if self.boomed_count % 1 == 0:
            self.boomed_frame += 1
            for i in range(0, len(self.boomed_filled_cells)):
                y = self.boomed_filled_cells[i] // self.boomed_num_cols
                x = self.boomed_filled_cells[i] % self.boomed_num_cols
                rect = [x * self.boomed_cell[0] + self.boomed_rect[0], y * self.boomed_cell[1] + self.boomed_rect[1], self.boomed_cell[0], self.boomed_cell[1]]
                pygame.draw.rect(screen, self.color, rect)
        if self.boomed_frame > 4:
            return True
        else:
            return False
    '''Reset the data used for the explosion'''
    def resetBoom(self):
        # Used when hit and exploded
        self.one_dead = False
        self.boomed_filled_cells = [3,7,12,15,17,20,24,30,36,40,44,45,53,54,58,62,68,74,78,81,83,86,91,95]
        self.boomed_cell = [3, 3]
        self.boomed_num_cols = 11
        self.boomed_num_rows = 9
        self.boomed_rect = pygame.Rect(0, 0, self.boomed_num_cols*self.boomed_cell[0], self.boomed_num_rows*self.boomed_cell[1])
        # Controls the time of each frame
        self.boomed_count = 0
        # Current frame of explosion effect
        self.boomed_frame = 0

Then define the local ufo class:

class enemySprite(pygame.sprite.Sprite):
    def __init__(self, category, number, color, bullet_color, **kwargs):
        pygame.sprite.Sprite.__init__(self)
        self.cell = [3, 3]
        # number
        self.number = number
        # type
        self.category = category
        if category == 'small':
            self.reward = 20
            self.num_cols = 8
            self.num_rows = 8
            self.rect = pygame.Rect(0, 0, self.num_cols * self.cell[0], self.num_rows * self.cell[1])
            self.filled_cells = [[3,4,10,11,12,13,17,18,19,20,21,22,24,25,27,28,30,31,32,33,34,35,36,37,38,39,42,45,49,51,52,54,56,58,61,63], 
                                 [3,4,10,11,12,13,17,18,19,20,21,22,24,25,27,28,30,31,32,33,34,35,36,37,38,39,41,43,44,46,48,55,57,62]]
        elif category == 'medium':
            self.reward = 15
            self.num_cols = 11
            self.num_rows = 8
            self.rect = pygame.Rect(0, 0, self.num_cols * self.cell[0], self.num_rows * self.cell[1])
            self.filled_cells = [[2,8,11,14,18,21,22,24,25,26,27,28,29,30,32,33,34,35,37,38,39,41,42,43,44,45,46,47,48,49,50,51,52,53,54,56,57,58,59,60,61,62,63,64,68,74,78,86], 
                                 [2,8,14,18,24,25,26,27,28,29,30,34,35,37,38,39,41,42,44,45,46,47,48,49,50,51,52,53,54,55,57,58,59,60,61,62,63,65,66,68,74,76,80,81,83,84]]
        elif category == 'large':
            self.reward = 10
            self.num_cols = 12
            self.num_rows = 8
            self.rect = pygame.Rect(0, 0, self.num_cols * self.cell[0], self.num_rows * self.cell[1])
            self.filled_cells = [[4,5,6,7,13,14,15,16,17,18,19,20,21,22,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,41,42,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,62,63,64,67,68,69,73,74,77,78,81,82,86,87,92,93], 
                                 [4,5,6,7,13,14,15,16,17,18,19,20,21,22,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,41,42,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,63,64,67,68,74,75,77,78,80,81,84,85,94,95]]
        self.color = color
        self.bullet_color = bullet_color
        self.speed = [8, 20]
        self.change_count = 0
        self.change_flag = False
        # Used when hit and exploded
        self.boomed_filled_cells = [3,7,12,15,17,20,24,30,36,40,44,45,53,54,58,62,68,74,78,81,83,86,91,95]
        self.boomed_cell = [3, 3]
        self.boomed_num_cols = 11
        self.boomed_num_rows = 9
        self.boomed_rect = pygame.Rect(0, 0, self.boomed_num_cols * self.boomed_cell[0], self.boomed_num_rows * self.boomed_cell[1])
        self.boomed_count = 0
        self.boomed_frame = 0
    '''Shooting'''
    def shot(self):
        return enemyBulletSprite(self.rect.x + self.rect.width // 2, self.rect.y, self.bullet_color)
    '''Draw it on the screen'''
    def draw(self, screen):
        if self.change_count > 50:
            self.change_count = 0
            self.change_flag = not self.change_flag
        if self.change_flag:
            for i in range(0, len(self.filled_cells[0])):
                y = self.filled_cells[0][i] // self.num_cols
                x = self.filled_cells[0][i] % self.num_cols
                rect = [x * self.cell[0] + self.rect[0], y * self.cell[1] + self.rect[1], self.cell[0], self.cell[1]]
                pygame.draw.rect(screen, self.color, rect)
        else:
            for i in range(0, len(self.filled_cells[1])):
                y = self.filled_cells[1][i] // self.num_cols
                x = self.filled_cells[1][i] % self.num_cols
                rect = [x * self.cell[0] + self.rect[0], y * self.cell[1] + self.rect[1], self.cell[0], self.cell[1]]
                pygame.draw.rect(screen, self.color, rect)
    '''Update enemy location and other information'''
    def update(self, direction, HEIGHT):
        # Used to change shape
        self.change_count += 1
        # Update location information
        if direction == 'right':
            self.rect.x += self.speed[0]
        elif direction == 'left':
            self.rect.x -= self.speed[0]
        elif direction == 'down':
            self.rect.y += self.speed[1]
        if self.rect.y >= HEIGHT - self.rect.height:
            return True
        else:
            return False
    '''Explosion after being hit'''
    def boom(self, screen):
        self.boomed_rect.x = self.rect.x
        self.boomed_rect.y = self.rect.y
        self.boomed_count += 1
        if self.boomed_count % 1 == 0:
            self.boomed_frame += 1
            for i in range(0, len(self.boomed_filled_cells)):
                y = self.boomed_filled_cells[i] // self.boomed_num_cols
                x = self.boomed_filled_cells[i] % self.boomed_num_cols
                rect = [x * self.boomed_cell[0] + self.boomed_rect[0], y * self.boomed_cell[1] + self.boomed_rect[1], self.boomed_cell[0], self.boomed_cell[1]]
                pygame.draw.rect(screen, self.color, rect)
        if self.boomed_frame > 4:
            return True
        else:
            return False

The enemy negotiated with us and fired bullets:

class myBulletSprite(pygame.sprite.Sprite):
    def __init__(self, x, y, color, **kwargs):
        pygame.sprite.Sprite.__init__(self)
        self.cell = [2, 2]
        self.num_cols = 1
        self.num_rows = 4
        self.rect = pygame.Rect(x, y, self.num_cols * self.cell[0], self.num_rows * self.cell[1])
        self.filled_cells = [0,1,2,3]
        self.speed = 8
        self.color = color
    '''Draw it on the screen'''
    def draw(self, screen):
        for i in range(0, len(self.filled_cells)):
            y = self.filled_cells[i] // self.num_cols
            x = self.filled_cells[i] % self.num_cols
            rect = [x * self.cell[0] + self.rect[0], y * self.cell[1] + self.rect[1], self.cell[0], self.cell[1]]
            pygame.draw.rect(screen, self.color, rect)
    '''Update bullet location and other information'''
    def update(self):
        self.rect.y -= self.speed
        if self.rect.y + self.rect.height < 0:
            return True
        else:
            return False


'''Enemy bullet elves'''
class enemyBulletSprite(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        pygame.sprite.Sprite.__init__(self)
        self.cell = [3, 3]
        self.num_cols = 3
        self.num_rows = 7
        self.rect = pygame.Rect(x, y, self.num_cols * self.cell[0], self.num_rows * self.cell[1])
        self.filled_cells = [[0,4,8,10,12,16,20], 
                             [2,4,6,10,14,16,18]]
        self.change_count = 0
        self.change_flag = False
        self.speed = 4
        self.color = color
    '''Draw it on the screen'''
    def draw(self, screen):
        if self.change_count > 2:
            self.change_count = 0
            self.change_flag = not self.change_flag
        if self.change_flag:
            for i in range(0, len(self.filled_cells[0])):
                y = self.filled_cells[0][i] // self.num_cols
                x = self.filled_cells[0][i] % self.num_cols
                rect = [x * self.cell[0] + self.rect[0], y * self.cell[1] + self.rect[1], self.cell[0], self.cell[1]]
                pygame.draw.rect(screen, self.color, rect)
        else:
            for i in range(0, len(self.filled_cells[1])):
                y = self.filled_cells[1][i] // self.num_cols
                x = self.filled_cells[1][i] % self.num_cols
                rect = [x * self.cell[0] + self.rect[0], y * self.cell[1] + self.rect[1], self.cell[0], self.cell[1]]
                pygame.draw.rect(screen, self.color, rect)
    '''Update bullet location and other information'''
    def update(self, HEIGHT):
        # A count used to change the shape of a bullet
        self.change_count += 1
        # position information
        self.rect.y += self.speed
        if self.rect.y > HEIGHT:
            return True
        else:
            return False

There are many codes, and the main code files are attached:

import os
import sys
import cfg
import random
import pygame
from modules import *


'''Start the game'''
def startGame(screen):
    clock = pygame.time.Clock()
    # Load font
    font = pygame.font.SysFont('arial', 18)
    if not os.path.isfile('score'):
        f = open('score', 'w')
        f.write('0')
        f.close()
    with open('score', 'r') as f:
        highest_score = int(f.read().strip())
    # enemy
    enemies_group = pygame.sprite.Group()
    for i in range(55):
        if i < 11:
            enemy = enemySprite('small', i, cfg.WHITE, cfg.WHITE)
        elif i < 33:
            enemy = enemySprite('medium', i, cfg.WHITE, cfg.WHITE)
        else:
            enemy = enemySprite('large', i, cfg.WHITE, cfg.WHITE)
        enemy.rect.x = 85 + (i % 11) * 50
        enemy.rect.y = 120 + (i // 11) * 45
        enemies_group.add(enemy)
    boomed_enemies_group = pygame.sprite.Group()
    en_bullets_group = pygame.sprite.Group()
    ufo = ufoSprite(color=cfg.RED)
    # we
    myaircraft = aircraftSprite(color=cfg.GREEN, bullet_color=cfg.WHITE)
    my_bullets_group = pygame.sprite.Group()
    # Used to control enemy location updates
    # --Move one line
    enemy_move_count = 24
    enemy_move_interval = 24
    enemy_move_flag = False
    # --Change the moving direction (collective descent once while changing the direction)
    enemy_change_direction_count = 0
    enemy_change_direction_interval = 60
    enemy_need_down = False
    enemy_move_right = True
    enemy_need_move_row = 6
    enemy_max_row = 5
    # Used to control enemy bullets
    enemy_shot_interval = 100
    enemy_shot_count = 0
    enemy_shot_flag = False
    # Game in progress
    running = True
    is_win = False
    # Main cycle
    while running:
        screen.fill(cfg.BLACK)
        for event in pygame.event.get():
            # --Click the X in the upper right corner or press Esc to exit the game
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
            # --Shoot
            if event.type == pygame.MOUSEBUTTONDOWN:
                my_bullet = myaircraft.shot()
                if my_bullet:
                    my_bullets_group.add(my_bullet)
        # --Collision detection between our bullets and enemy / UFO
        for enemy in enemies_group:
            if pygame.sprite.spritecollide(enemy, my_bullets_group, True, None):
                boomed_enemies_group.add(enemy)
                enemies_group.remove(enemy)
                myaircraft.score += enemy.reward
        if pygame.sprite.spritecollide(ufo, my_bullets_group, True, None):
            ufo.is_dead = True
            myaircraft.score += ufo.reward
        # --Update and draw enemy
        # ----Enemy bullet
        enemy_shot_count += 1
        if enemy_shot_count > enemy_shot_interval:
            enemy_shot_flag = True
            enemies_survive_list = [enemy.number for enemy in enemies_group]
            shot_number = random.choice(enemies_survive_list)
            enemy_shot_count = 0
        # ----Enemy movement
        enemy_move_count += 1
        if enemy_move_count > enemy_move_interval:
            enemy_move_count = 0
            enemy_move_flag = True
            enemy_need_move_row -= 1
            if enemy_need_move_row == 0:
                enemy_need_move_row = enemy_max_row
            enemy_change_direction_count += 1
            if enemy_change_direction_count > enemy_change_direction_interval:
                enemy_change_direction_count = 1
                enemy_move_right = not enemy_move_right
                enemy_need_down = True
                # ----Each descent increases movement and firing speed
                enemy_move_interval = max(15, enemy_move_interval-3)
                enemy_shot_interval = max(50, enemy_move_interval-10)
        # ----Traversal update
        for enemy in enemies_group:
            if enemy_shot_flag:
                if enemy.number == shot_number:
                    en_bullet = enemy.shot()
                    en_bullets_group.add(en_bullet)
            if enemy_move_flag:
                if enemy.number in range((enemy_need_move_row-1)*11, enemy_need_move_row*11):
                    if enemy_move_right:
                        enemy.update('right', cfg.SCREENSIZE[1])
                    else:
                        enemy.update('left', cfg.SCREENSIZE[1])
            else:
                enemy.update(None, cfg.SCREENSIZE[1])
            if enemy_need_down:
                if enemy.update('down', cfg.SCREENSIZE[1]):
                    running = False
                    is_win = False
                enemy.change_count -= 1
            enemy.draw(screen)
        enemy_move_flag = False
        enemy_need_down = False
        enemy_shot_flag = False
        # ----Enemy explosion effects
        for boomed_enemy in boomed_enemies_group:
            if boomed_enemy.boom(screen):
                boomed_enemies_group.remove(boomed_enemy)
                del boomed_enemy
        # --Collision detection between enemy bullets and our spacecraft
        if not myaircraft.one_dead:
            if pygame.sprite.spritecollide(myaircraft, en_bullets_group, True, None):
                myaircraft.one_dead = True
        if myaircraft.one_dead:
            if myaircraft.boom(screen):
                myaircraft.resetBoom()
                myaircraft.num_life -= 1
                if myaircraft.num_life < 1:
                    running = False
                    is_win = False
        else:
            # ----Update ship
            myaircraft.update(cfg.SCREENSIZE[0])
            # ----Painting spacecraft
            myaircraft.draw(screen)
        if (not ufo.has_boomed) and (ufo.is_dead):
            if ufo.boom(screen):
                ufo.has_boomed = True
        else:
            # ----Update UFO
            ufo.update(cfg.SCREENSIZE[0])
            # ----Draw UFO
            ufo.draw(screen)
        # --Draw our ship bullets
        for bullet in my_bullets_group:
            if bullet.update():
                my_bullets_group.remove(bullet)
                del bullet
            else:
                bullet.draw(screen)
        # --Draw enemy bullets
        for bullet in en_bullets_group:
            if bullet.update(cfg.SCREENSIZE[1]):
                en_bullets_group.remove(bullet)
                del bullet
            else:
                bullet.draw(screen)
        if myaircraft.score > highest_score:
            highest_score = myaircraft.score
        # --Every 2000 points increase, our ship adds one life
        if (myaircraft.score % 2000 == 0) and (myaircraft.score > 0) and (myaircraft.score != myaircraft.old_score):
            myaircraft.old_score = myaircraft.score
            myaircraft.num_life = min(myaircraft.num_life + 1, myaircraft.max_num_life)
        # --If all the enemies are dead, we will win
        if len(enemies_group) < 1:
            is_win = True
            running = False
        # --Display text
        # ----Current score
        showText(screen, 'SCORE: ', cfg.WHITE, font, 200, 8)
        showText(screen, str(myaircraft.score), cfg.WHITE, font, 200, 24)
        # ----Number of enemies
        showText(screen, 'ENEMY: ', cfg.WHITE, font, 370, 8)
        showText(screen, str(len(enemies_group)), cfg.WHITE, font, 370, 24)
        # ----Highest score in history
        showText(screen, 'HIGHEST: ', cfg.WHITE, font, 540, 8)
        showText(screen, str(highest_score), cfg.WHITE, font, 540, 24)
        # ----FPS
        showText(screen, 'FPS: ' + str(int(clock.get_fps())), cfg.RED, font, 8, 8)
        # --Show remaining health
        showLife(screen, myaircraft.num_life, cfg.GREEN)
        pygame.display.update()
        clock.tick(cfg.FPS)
    with open('score', 'w') as f:
        f.write(str(highest_score))
    return is_win


'''Main function'''
def main():
    # initialization
    pygame.init()
    pygame.display.set_caption('Alien invasion ')
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.mixer.init()
    pygame.mixer.music.load(cfg.BGMPATH)
    pygame.mixer.music.set_volume(0.4)
    pygame.mixer.music.play(-1)
    while True:
        is_win = startGame(screen)
        endInterface(screen, cfg.BLACK, is_win)


'''run'''
if __name__ == '__main__':
    main()

The effects are as follows:

Summary

All right! This little game of alien war is finished ~ do you want this game?

💖 Pay attention to Xiaobian - get more wonderful content source code!

Your support is my biggest motivation!! Remember the third consecutive oh ~mua, welcome to read more game articles in the past~

  Source base:

Home page (pc side) the left source base to get free applet! Or private letter Xiaobian can also!



👑 Article summary——

1.1 python-2021 | summary of existing articles | continuously updated. It's enough to read this article directly~

Tags: Python Game Development source code pygame

Posted on Tue, 16 Nov 2021 21:18:35 -0500 by respecttheplayer