Class Instance: Aircraft Wars

1. Bullet module

import pygame
WINDOW_WIDTH = 512 # Adjust the window size according to actual needs
WINDOW_HEIGHT = 768

class Bullet(object):
    def __init__(self):
        # image, rectangle object, speed
        self.bullet_img = pygame.image.load('res/bullet_11.png') # Choose the resource file by yourself
        self.enemy_bullet_img = pygame.image.load('res/bullet_4.png')
        self.bullet_rect = self.bullet_img.get_rect()
        self.enemy_bullet_rect = self.enemy_bullet_img.get_rect()
        self.speed = 5
        self.enemy_speed = 3
        # switch
        #On: Indicates that you can move, draw and kill enemies
        # Close: When the bullet moves outside the window, return: It means that it does not move, draw or kill the enemy
        # The default state of the switch: off: the switch is only turned on when the user fires a bullet
        self.is_shot = False
        self.enemy_is_shot = False
    def move(self):
        self.bullet_rect.move_ip(0, -self.speed)
        self.enemy_bullet_rect.move_ip(0, self.enemy_speed)
        # When the bullet moves outside above the window, the switch closes
        if self.bullet_rect[1] < 0:
            self.is_shot = False
        if self.enemy_bullet_rect[1] > 600:
            self.enemy_is_shot = False

  

The enemy module

import pygame
import random
import bullet

WINDOW_WIDTH = 512 # Here, because of the problem of my computer resolution, I made the interface smaller. .
WINDOW_HEIGHT = 600
class Enemy(object):
    def __init__(self):
        # Picture, rectangle object (set the default position of the enemy plane), speed img-plane_1.png
        num = str (random.randint (1, 7))
        self.enemy_img = pygame.image.load('res/img-plane_'+ num +'.png')
        self.enemy_rect = self.enemy_img.get_rect()
        # The default position is random horizontally, outside the vertical window
        self.enemy_rect[0] = random.randint(0, WINDOW_WIDTH-self.enemy_rect[2])
        self.enemy_rect[1] = -self.enemy_rect[3] # 0, 0, width, height
        self.speed = random.randint(2, 4)
        self.enemy_bullet_list = [bullet.Bullet() for _ in range(10)]


    def move(self):
        # move the rectangle object move_ip (0, +speed)
        self.enemy_rect.move_ip(0, self.speed)
        # Because the enemy plane needs to be recycled, judge if it moves outside the window, put the enemy plane in the initial position
        if self.enemy_rect[1] > WINDOW_HEIGHT:
            self.reset()

    def reset(self):
        self.enemy_rect[0] = random.randint(0, WINDOW_WIDTH - self.enemy_rect[2])
        self.enemy_rect[1] = -self.enemy_rect[3] # 0, 0, width, height
        self.speed = random.randint(2, 3)

    def shot(self):
        # Swing bullet position -- 10 list
        for bullet in self.enemy_bullet_list:
            # If the bullet is in the firing state, the position is only placed -- switch false
            # if bullet.is_shot == False
            if not bullet.enemy_is_shot:
                #level
                bullet.enemy_bullet_rect[0] = self.enemy_rect[0] + self.enemy_rect[2]/2 - bullet.enemy_bullet_rect[2]/2
                bullet.enemy_bullet_rect[1] = self.enemy_rect[1] + self.enemy_rect[3]
                # The reason for the position is because it is about to launch
                bullet.enemy_is_shot = True
                break # Just take one bullet, and call this shot function the next time the user presses j or space

  

3. Game map module

import pygame
import random

WINDOW_WIDTH = 512
WINDOW_HEIGHT = 768

class GameMap(object):
    def __init__(self):
        # Load two pictures, set the initial position and speed of the picture
        self.num = str(random.randint(1,5)) # Make sure the random is the same number
        self.bg_img1 = pygame.image.load('res/img_bg_level_' + self.num + '.jpg')
        self.bg_img2 = pygame.image.load('res/img_bg_level_' + self.num + '.jpg')
        self.bg_img1_y = -WINDOW_HEIGHT
        self.bg_img2_y = 0
        self.speed = 1

    def map_scroll(self):
        if self.bg_img1_y >= 0:
            self.bg_img1_y = -WINDOW_HEIGHT
        if self.bg_img2_y >= WINDOW_HEIGHT:
            self.bg_img2_y = 0
        self.bg_img1_y += self.speed
        self.bg_img2_y += self.speed

 

4. Our hero fighter module

import pygame
import bullet
WINDOW_WIDTH = 512
WINDOW_HEIGHT = 600

class Hero(object):
    def __init__(self):
        # figure, rectangle object, speed, set the initial position of the aircraft
        self.hero_img = pygame.image.load('res/hero.png')
        self.hero_rect = self.hero_img.get_rect()  # (0, 0, 120, 78)
        self.hero_rect.move_ip(WINDOW_WIDTH/2-self.hero_rect[2]/2, WINDOW_HEIGHT-self.hero_rect[3])
        # (horizontal middle, vertical bottom, 120 ,78)
        self.speed = 2
        # Because it is the plane that fires the bullet, create the bullet object: 10 -- create a bullet list
        # self.bullet = bullet.Bullet()
        self.bullet_list = [bullet.Bullet() for _ in range(1000)]


    def move_up(self):
        # move up -- y -speed -- >0
        if self.hero_rect[1] > 0:
            self.hero_rect.move_ip(0, -self.speed)

    def move_down(self): # y +speed < lowest coordinate
        if self.hero_rect[1] < WINDOW_HEIGHT-self.hero_rect[3]:
            self.hero_rect.move_ip(0, self.speed)
    def move_left(self):
        if self.hero_rect[0] > 0:
            self.hero_rect.move_ip(-self.speed, 0)
    def move_right(self):
        if self.hero_rect[0] < WINDOW_WIDTH- self.hero_rect[2]:
            self.hero_rect.move_ip(self.speed, 0)

    def shot(self):
        # Swing bullet position -- 10 list
        for bullet in self.bullet_list:
            # If the bullet is in the firing state, the position is only placed -- switch false
            # if bullet.is_shot == False
            if not bullet.is_shot:
                #level
                bullet.bullet_rect[0] = self.hero_rect[0] + self.hero_rect[2]/2 - bullet.bullet_rect[2]/2
                bullet.bullet_rect[1] = self.hero_rect[1] - bullet.bullet_rect[3]
                # The reason for the position is because it is about to launch
                bullet.is_shot = True
                break # Just take one bullet, and call this shot function the next time the user presses j or space

  

5. The main module of aircraft war

# Create a window object, display
import pygame
import sys # To close the game window
import game_map
import hero
import bullet
import enemy
# import time


# Experience: As long as the variable names are all capitalized, the data will not be modified in the later stage.
WINDOW_WIDTH = 512
WINDOW_HEIGHT = 600


class GameWindow(object):
    def __init__(self):
        pygame.init()
        # size, title. logo
        self.window = pygame.display.set_mode([WINDOW_WIDTH, WINDOW_HEIGHT])
        pygame.display.set_caption('Airplane Wars V1.1')
        self.ico = pygame.image.load('res/app.ico')
        pygame.display.set_icon(self.ico)
        # create map object
        self.map = game_map.GameMap()
        # Animation or drawing first --
        # create the airplane object
        self.hero = hero.Hero()
        # Create enemy aircraft object
        self.enemy_list = [enemy.Enemy() for _ in range(5)]
        # load background music
        pygame.mixer.music.load("./res/bg2.ogg")
        # Loop background music
        pygame.mixer.music.play(-1)


    def run(self):
        while True:
            self.action()
            self.draw()
            self.event()
            self.bullet_hit_enemy()
            if self.enemy_hit_hero():
                break
            self.update()

    # function -- do animation
    def action(self):
        # Map animation is called in
        self.map.map_scroll()
        # Call the bullet movement animation
        for bullet in self.hero.bullet_list:
            if bullet.is_shot:
                bullet.move()
        for enemy in self.enemy_list:
            for bullet in enemy.enemy_bullet_list:
                if bullet.enemy_is_shot:
                    bullet.move()
        for enemy in self.enemy_list:
            enemy.move()

    # function -- draw image
    def draw(self):
        self.window.blit(self.map.bg_img1, (0,self.map.bg_img1_y))
        self.window.blit(self.map.bg_img2, (0,self.map.bg_img2_y))
        # draw the plane
        self.window.blit(self.hero.hero_img, (self.hero.hero_rect[0], self.hero.hero_rect[1]))
        # draw bullet: switch is true
        for bullet in self.hero.bullet_list:
            if bullet.is_shot is True:
                self.window.blit(bullet.bullet_img, (bullet.bullet_rect[0], bullet.bullet_rect[1]))
        for enemy in self.enemy_list:
            for bullet in enemy.enemy_bullet_list:
                if bullet.enemy_is_shot is True:
                    self.window.blit(bullet.enemy_bullet_img, (bullet.bullet_rect[0], bullet.bullet_rect[1]))
        # draw enemy plane
        for enemy in self.enemy_list:
            self.window.blit(enemy.enemy_img, (enemy.enemy_rect[0], enemy.enemy_rect[1]))

    # Collision detection -- bullet collides with enemy plane
    def bullet_hit_enemy(self):
        # Take each bullet, look at all enemy planes, and see which bullet (must be the firing status switch is True) collided with which enemy plane
        for bullet in self.hero.bullet_list:
            if bullet.is_shot == True:
                for enemy in self.enemy_list:
                    if pygame.Rect.colliderect(bullet.bullet_rect, enemy.enemy_rect):
                        # load sound
                        boom_sound = pygame.mixer.Sound("./res/baozha.ogg")
                        # play sound
                        boom_sound.play()
                        # The enemy plane disappears -- put it on the top and wait for the next move down to reset
                        enemy.reset()
                        # bullet disappears -- false
                        bullet.is_shot = False
                        break

    # collision detection -- enemy plane collides with hero plane
    def enemy_hit_hero(self):
        for enemy in self.enemy_list:
            if pygame.Rect.colliderect(enemy.enemy_rect, self.hero.hero_rect):
                # exit the main loop
                return True
        return False



    # The hero plane is artificially controlled to move, and an event function is added
    def event(self):
        # Single event -- returns a list
        self.event_list = pygame.event.get()
        for event in self.event_list:
            # Cross
            if event.type == pygame.QUIT:
                # close the game window
                # sys.exit()
                # # Exit pygame
                # pygame.quit()
                self.gameOver()
            # Determine the type of keyboard press
            if event.type == pygame.KEYDOWN:
                # Determine which key was pressed
                if event.key == pygame.K_ESCAPE:
                    self.gameOver()
                if event.key == pygame.K_r:
                    for enemy in self.enemy_list:
                        enemy.shot()

        # Consecutive, multiple event continuous keypress -- determine which key is pressed
        # time.sleep(3)
        self.pressed = pygame.key.get_pressed()
        if self.pressed[pygame.K_SPACE] or self.pressed[pygame.K_j]:
            self.hero.shot()
        # print(self.pressed)  (0,0,0,1,0,0)
        if self.pressed[pygame.K_UP]:
            self.hero.move_up()
        if self.pressed[pygame.K_DOWN]:
            self.hero.move_down()
        if self.pressed[pygame.K_LEFT]:
            self.hero.move_left()
        if self.pressed[pygame.K_RIGHT]:
            self.hero.move_right()

    def gameOver(self):
        pygame.quit()
        sys.exit()
    # function update
    def update(self):
        pygame.display.update()

if __name__ == '__main__':
    game = GameWindow()
    game.run()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325858789&siteId=291194637