Configuration class
import pygame
# Constant of screen background image
SCREEN_RECT = pygame.Rect(0,0,480,700)
# Create timer constant for enemy aircraft
CREATE_ENEMY_EVENT = pygame.USEREVENT
# The hero fired bullets
HERO_FIRE_EVENT = pygame.USEREVENT +1
class Settings():
""" Store all the settings classes """
def __init__(self):
self.caption = " Aircraft battle "
Main program class :
import pygame
from plane_sprites import *
import Settings
import sys
from hero import Hero
class PlaneGame():
""" Aircraft war main program """
def __init__(self):
self.screen = pygame.display.set_mode(Settings.SCREEN_RECT.size)
self.clock = pygame.time.Clock()
# Set the timer
pygame.time.set_timer(Settings.CREATE_ENEMY_EVENT,1000)
pygame.time.set_timer(Settings.HERO_FIRE_EVENT, 500)
def __create_sprits(self):
# Create spirit and spirit group of enemy aircraft
self.plane_group = pygame.sprite.Group()
# Create a hero's spirit and spirit group
self.hero = Hero()
self.hero_group = pygame.sprite.Group(self.hero)
def start_game(self):
pygame.init()
pygame.display.set_caption(Settings.Settings().caption)
bg = pygame.image.load("./images/background.png")
bg_rect1 = pygame.Rect(0, 0, 480, 700)
bg_rect2 = pygame.Rect(0, -700, 480, 700)
self.screen.blit(bg, bg_rect1) # Display the loaded image on the screen , The second parameter specifies the location
self.screen.blit(bg, bg_rect2)
# Create elves
self.__create_sprits()
# Draw player plane
# The main cycle of the game
while True:
self.clock.tick(60)
# The movement of the background picture
# Draw the background image first to avoid residual shadows
self.__background_scrool(bg, bg_rect1, bg_rect2)
# Monitor keyboard and mouse events
self.__event_handler()
# collision detection
self.__check_collide()
# Call the sprite group
self.__update_sprites()
# Make the most recently drawn screen visible
pygame.display.flip()
def __background_scrool(self, bg, bg_rect1, bg_rect2):
""" Background image movement """
bg_rect1.y += 1
bg_rect2.y += 1
if bg_rect1.y >= 700:
bg_rect1.y = -700
elif bg_rect2.y >= 700:
bg_rect2.y = -700
self.screen.blit(bg, bg_rect1)
self.screen.blit(bg, bg_rect2)
def __event_handler(self):
""" Monitor keyboard and mouse events """
for event in pygame.event.get():
if event:
print(event)
# Determine whether the event type is an exit event
if event.type == pygame.QUIT:
PlaneGame.__game_over()
elif event.type == Settings.CREATE_ENEMY_EVENT:
print(" Enemy planes flying in and out ---")
plane_path = "./images/enemy1.png"
plane = [GameSprites(plane_path) for i in range(10)]
self.plane_group.add(plane)
elif event.type == Settings.HERO_FIRE_EVENT:
self.hero.fire()
# elif event.type ==pygame.KEYDOWN and event.key == pygame.K_RIGHT:
# self.hero.speed = 2
# elif event.type ==pygame.KEYDOWN and event.key == pygame.K_LEFT:
# self.hero.speed = -2
# Use what the keyboard provides to get key tuples ( It can continuously move to the right )( recommend )
keys_press = pygame.key.get_pressed()
# Determine the index value of the corresponding key in the tuple
if keys_press[pygame.K_RIGHT] :
self.hero.speed = 2
elif keys_press[pygame.K_LEFT]:
self.hero.speed = -2
else:
self.hero.speed =0
def __check_collide(self):
""" collision detection """
pygame.sprite.groupcollide(self.hero.bullets,self.plane_group,True,True)
enemies = pygame.sprite.spritecollide(self.hero, self.plane_group, True)
# Determine whether there is content in the list
if enemies:
# Let the hero die
self.hero.kill()
self.__game_over()
def __update_sprites(self, ):
""" Modify the sprite group """
self.plane_group.update()
self.plane_group.draw(self.screen)
self.hero_group.update()
self.hero_group.draw(self.screen)
self.hero.bullets.update()
self.hero.bullets.draw(self.screen)
@staticmethod
def __game_over():
""" How to end the game """
pygame.quit()
sys.exit()
# Test module
if __name__ == '__main__':
PlaneGame().start_game()
# print(map(lambda x:x+1,[1,2,3]))
Enemy aircraft elves
import pygame
import random
class GameSprites(pygame.sprite.Sprite):
""" Aircraft war game wizard """
def __init__(self, image_path, speed=1):
""" Initialization method :param image_path: Picture path :param speed: Movement speed """
super().__init__()
self.speed = random.randint(1,3)
self.image = pygame.image.load(image_path)
# x,y Will be set to 0,size Is the size of the image
self.rect = self.image.get_rect()
self.rect.x = random.randint(0,400)
self.rect.y = random.randint(-500,-self.rect.height)
# Destroy enemy aircraft objects
def __del__(self):
print(" The enemy plane hung up ")
# You can remove sprites from all sprite groups
self.kill()
def update(self):
""" rewrite update Method """
self.rect.y += self.speed
if self.rect.y >= 700:
print("del enemy")
self.__del__()
Heroes
import pygame
import random
from bullet import Bullet
class Hero(pygame.sprite.Sprite):
""" Aircraft war heroes """
def __init__(self, speed=0):
""" Initialization method :param speed: Movement speed """
super().__init__()
self.speed = speed
self.image = pygame.image.load("./images/me1.png")
# x,y Will be set to 0,size Is the size of the image
self.rect = self.image.get_rect()
self.rect.centerx = 480 * 0.5
self.rect.bottom = 700 - 120
# Create the sprite group of bullets
self.bullets = pygame.sprite.Group()
# Destroy enemy aircraft objects
def __del__(self):
print(" The hero is dead ")
# You can remove sprites from all sprite groups
self.kill()
def update(self):
""" rewrite update Method """
self.rect.x += self.speed
if self.rect.x >= 380:
self.rect.x = 380
elif self.rect.x <= 0:
self.rect.x = 0
# bullets
def fire(self):
print(" bullets ...")
for i in range(3):
# Create bullet wizard
bullet = Bullet()
# Set the wizard position
bullet.rect.bottom = self.rect.y -i*20
bullet.rect.centerx = self.rect.centerx
self.bullets.add(bullet)
Bullets
import pygame
class Bullet(pygame.sprite.Sprite):
""" Aircraft vs bullets """
def __init__(self, speed=-2):
""" Initialization method :param speed: Movement speed """
super().__init__()
self.speed = speed
self.image = pygame.image.load("./images/bullet2.png")
# x,y Will be set to 0,size Is the size of the image
self.rect = self.image.get_rect()
def update(self):
""" rewrite update Method """
self.rect.y += self.speed
# Determine whether the bullet flew off the screen
if self.rect.bottom <0:
self.__del__()
def __del__(self):
print(" The bullet was destroyed ")
self.kill()
The operation effect is as follows :
Understanding of key points :