The examples in this article share the specific code of python code to realize the aircraft war for your reference. The specific content is as follows
import pygame
import sys
from pygame.sprite import Sprite
from pygame.sprite import Group
from time import sleep
import pygame.font
# Modify some new settings of the game
classSettings():"""Store all settings of "Alien Invasion""""
def __init__(self):"""Initialize the game settings"""
# Screen settings
self.screen_width =1200
self.screen_height =800
self.bg_color =(230,230,230) #light grey
# Spaceship setup, move 1.5 pixels
self.ship_limit =3
# Bullet settings---Create a dark gray bullet with a width of 3 pixels and a height of 15 pixels
self.bullet_speed_factor =3
self.bullet_width =3
self.bullet_height =15
self.bullet_color =60,60,60
self.bullets_allowed =3
# Alien settings
self.fleet_drop_speed =10
# At what speed to speed up the pace of the game
self.speedup_scale =1.1
# Increase speed of alien points
self.score_scale =1.5
self.initialize_dynamic_settings()
def initialize_dynamic_settings(self):"""Initialize settings that change as the game progresses"""
self.ship_speed_factor =1.5
self.bullet_speed_factor =3
self.alien_speed_factor =1
# fleet_direcction is 1 means to the right, which is-1 means left
self.fleet_direction =1
# Scoring
self.alien_points =50
def increase_speed(self):"""Improve speed settings and alien points"""
self.ship_speed_factor *= self.speedup_scale
self.bullet_speed_factor *= self.speedup_scale
self.alien_speed_factor *= self.speedup_scale
self.alien_points =int(self.alien_points * self.score_scale)
# Create a ship class
classShip(Sprite):
def __init__(self, ai_settings, screen):"""Initialize the spacecraft and set its starting position"""super(Ship, self).__init__()
self.screen = screen
self.ai_settings = ai_settings
# Load the spaceship image and get its bounding rectangle
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect() #Obtain the corresponding surface properties in rectangular form
self.screen_rect = screen.get_rect()
# Place each new ship in the bottom center of the screen
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
# Store decimal values in the spaceship's attribute center----Control the speed of the spacecraft in more detail when speeding up the game rhythm later
self.center =float(self.rect.centerx)
# Move sign
self.moving_right = False
self.moving_left = False
def update(self):"""Adjust the position of the spacecraft according to the moving signs"""
# Update the center value of the spaceship instead of rect
if self.moving_right and self.rect.right < self.screen_rect.right:
self.center += self.ai_settings.ship_speed_factor
if self.moving_left and self.rect.left 0:
self.center -= self.ai_settings.ship_speed_factor
# According to self.center updates the rect object
self.rect.centerx = self.center
def center_ship(self):"""Center the spaceship on the screen"""
self.center = self.screen_rect.centerx
def blitme(self):"""Draw the spaceship at the specified location"""
self.screen.blit(self.image, self.rect)
# Create an Alien class
classAlien(Sprite):"""Class representing a single alien"""
def __init__(self, ai_settings, screen):"""Initialize the alien and set its starting position"""super(Alien, self).__init__()
self.screen = screen
self.ai_settings = ai_settings
# Load the alien image and set its rect attribute
self.image = pygame.image.load('images/alien.bmp')
self.rect = self.image.get_rect()
# Every alien is initially near the upper left corner of the screen
self.rect.x = self.rect.width
self.rect.y = self.rect.height
# Store the exact location of the alien
self.x =float(self.rect.x)
def check_edges(self):"""If the alien is at the edge of the screen, return True"""
screen_rect = self.screen.get_rect()if self.rect.right = screen_rect.right:return True
elif self.rect.left <=0:return True
def update(self):"""Move aliens left or right"""
self.x +=(self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction)
self.rect.x = self.x
def blitme(self):"""Draw aliens at designated locations"""
self.screen.blit(self.image, self.rect)
def get_number_aliens_x(ai_settings, alien_width):"""Calculate how many aliens can fit in each row"""
available_space_x = ai_settings.screen_width -2* alien_width
number_aliens_x =int(available_space_x /(2* alien_width))return number_aliens_x
def get_number_rows(ai_settings, ship_height, alien_height):"""Calculate how many lines of aliens can fit on the screen"""
available_space_y =(ai_settings.screen_height -(3* alien_height)- ship_height)
number_rows =int(available_space_y /(2* alien_height))return number_rows
def create_alien(ai_settings, screen, aliens, alien_number, row_number):"""Create an alien and place it in the current row"""
alien =Alien(ai_settings, screen)
alien_width = alien.rect.width
alien.x = alien_width +2* alien_width * alien_number
alien.rect.x = alien.x
alien.rect.y = alien.rect.height +2* alien.rect.height * row_number
aliens.add(alien)
def create_fleet(ai_settings, screen, ship, aliens):"""Create alien crowd"""
# Create an alien and calculate how many aliens can fit in a row
# The distance between aliens is the width of aliens
alien =Alien(ai_settings, screen)
number_aliens_x =get_number_aliens_x(ai_settings, alien.rect.width)
number_rows =get_number_rows(ai_settings, ship.rect.height, alien.rect.height)
# Create alien crowd
for row_number inrange(number_rows):for alien_number inrange(number_aliens_x):
# Create an alien and add it to the current line
create_alien(ai_settings, screen, aliens, alien_number, row_number)classBullet(Sprite):"""A class that manages the bullets fired by the spacecraft"""
def __init__(self, ai_settings, screen, ship):"""Create a bullet object where the spaceship is"""super(Bullet, self).__init__()
self.screen = screen
# in(0,0)Create a rectangle representing the bullet and set the correct position
self.rect = pygame.Rect(0,0, ai_settings.bullet_width, ai_settings.bullet_height)
self.rect.centerx = ship.rect.centerx
self.rect.top = ship.rect.top
# Store the bullet position expressed as a decimal
self.y =float(self.rect.y)
# Set the color and speed of bullets
self.color = ai_settings.bullet_color
self.speed_factor = ai_settings.bullet_speed_factor
def update(self):"""Move bullet up"""
# Update the decimal value indicating the position of the bullet
self.y -= self.speed_factor
# Update the rect position representing the bullet
self.rect.y = self.y
def draw_bullet(self):"""Draw bullets on the screen"""
pygame.draw.rect(self.screen, self.color, self.rect)
# Manage events, set up two functions, one to handle KEYDOWN events, and one to handle KEYUP events
def check_keydown_events(event, ai_settings, screen, ship, bullets):"""Respond to the button"""if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.key == pygame.K_SPACE:fire_bullets(ai_settings, screen, ship, bullets)
elif event.key == pygame.K_q:
sys.exit()
def check_keyup_events(event, ship):"""Response release"""if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False
def check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets):"""Responding to key press and mouse events"""for event in pygame.event.get():if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:check_keydown_events(event, ai_settings, screen, ship, bullets)
elif event.type == pygame.KEYUP:check_keyup_events(event, ship)
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_x, mouse_y = pygame.mouse.get_pos()check_play_button(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, mouse_x, mouse_y)
def check_play_button(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, mouse_x, mouse_y):"""Start a new game when the player clicks the Play button"""
button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)if button_clicked and not stats.game_active:
# Reset game settings
ai_settings.initialize_dynamic_settings()
# Hide cursor
pygame.mouse.set_visible(False)
# Reset game statistics
stats.reset_stats()
stats.game_active = True
# Reset the scoreboard image
sb.prep_score()
sb.prep_high_score()
sb.prep_level()
sb.prep_ships()
# Clear the list of aliens and bullets
aliens.empty()
bullets.empty()
# Create a new group of aliens and center the spaceship
create_fleet(ai_settings, screen, ship, aliens)
ship.center_ship()
def fire_bullets(ai_settings, screen, ship, bullets):"""If the limit is not reached yet, fire a bullet"""
# Create a bullet and add it to the group bullets
iflen(bullets)< ai_settings.bullets_allowed:
new_bullet =Bullet(ai_settings, screen, ship)
bullets.add(new_bullet)
def check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, aliens, bullets):"""Respond to the collision of bullets and aliens"""
# If so, delete the corresponding bullets and aliens
collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)iflen(aliens)==0:
# Eliminate existing bullets, speed up the pace of the game, and create a new group of aliens
# If the whole group of aliens are wiped out, increase one level
bullets.empty()
ai_settings.increase_speed()
# Level up
stats.level +=1
sb.prep_level()create_fleet(ai_settings, screen, ship, aliens)if collisions:for aliens in collisions.values():
stats.score += ai_settings.alien_points *len(aliens)
sb.prep_score()check_high_score(stats, sb)
def update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets):"""Update the bullet position and delete the disappeared bullet"""
# Update bullet position
bullets.update()
# Delete the disappeared bullet
for bullet in bullets.copy():if bullet.rect.bottom <=0:
bullets.remove(bullet)check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, aliens, bullets)
def change_fleet_direction(ai_settings, aliens):"""Move the whole group of aliens down and change their direction"""for alien in aliens.sprites():
alien.rect.y += ai_settings.fleet_drop_speed
ai_settings.fleet_direction *=-1
def check_fleet_edges(ai_settings, aliens):"""Measures to respond when an alien reaches the edge"""for alien in aliens.sprites():if alien.check_edges():change_fleet_direction(ai_settings, aliens)break
def ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets):"""Responding to a spacecraft hit by an alien"""if stats.ships_left 0:
# Will ships_left minus 1
stats.ships_left -=1
# Update the scoreboard
sb.prep_ships()
# Clear the list of aliens and bullets
aliens.empty()
bullets.empty()
# Create a new group of aliens and place the spaceship at the bottom center of the screen
create_fleet(ai_settings, screen, ship, aliens)
ship.center_ship()
# time out
sleep(0.5)else:
stats.game_active = False
pygame.mouse.set_visible(True)
def check_aliens_bottom(ai_settings, screen, stats, sb, ship, aliens, bullets):"""Check if any aliens have reached the bottom of the screen"""
screen_rect = screen.get_rect()for alien in aliens.sprites():if alien.rect.bottom = screen_rect.bottom:
# Treat as if a spaceship is hit
ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets)break
def update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets):"""Check if there are aliens at the edge of the screen and update the position of the entire group of aliens"""check_fleet_edges(ai_settings, aliens)
aliens.update()
# Detect collisions between aliens and spacecraft
if pygame.sprite.spritecollideany(ship, aliens):ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets)
# Check if any aliens reach the bottom of the screen
check_aliens_bottom(ai_settings, screen, stats, sb, ship, aliens, bullets)classGameStats():"""Track game statistics"""
def __init__(self, ai_settings):"""Initialize statistics"""
self.ai_settings = ai_settings
self.reset_stats()
# The game is in an inactive state when it first starts, in order to add a Play button
self.game_active = False
# The maximum score should not be reset under any circumstances
self.high_score =0
def reset_stats(self):"""Initialize statistics that may change during the game"""
self.ships_left = self.ai_settings.ship_limit
self.score =0
self.level =1classScoreboard():"""Class showing score information"""
def __init__(self, ai_settings, screen, stats):"""Initialize the attributes involved in the display score"""
self.screen = screen
self.screen_rect = screen.get_rect()
self.ai_settings = ai_settings
self.stats = stats
# Font setting used when displaying score information
self.text_color =(30,30,30)
self.font = pygame.font.SysFont(None,48)
# Prepare an image containing the highest score and current score
self.prep_score()
self.prep_high_score()
self.prep_level()
self.prep_ships()
def prep_score(self):"""Convert the score into a rendered image"""
rounded_score =int(round(self.stats.score,-1))
score_str ="{:,}".format(rounded_score)
self.score_image = self.font.render(score_str, True, self.text_color, self.ai_settings.bg_color)
# Put the score in the upper right corner of the screen
self.score_rect = self.score_image.get_rect()
self.score_rect.right = self.screen_rect.right -20
self.score_rect.top =20
def prep_high_score(self):"""Convert the highest score into a rendered image"""
high_score =int(round(self.stats.high_score,-1))
high_score_str ="{:,}".format(high_score)
self.high_score_image = self.font.render(high_score_str, True, self.text_color, self.ai_settings.bg_color)
# Put the highest score in the center of the screen
self.high_score_rect = self.high_score_image.get_rect()
self.high_score_rect.centerx = self.screen_rect.centerx
self.high_score_rect.top = self.score_rect.top
def prep_level(self):"""Convert grade to rendered image"""
self.level_image = self.font.render(str(self.stats.level), True, self.text_color, self.ai_settings.bg_color)
# Put the grade below the score
self.level_rect = self.level_image.get_rect()
self.level_rect.right = self.score_rect.right
self.level_rect.top = self.score_rect.bottom +10
def prep_ships(self):"""Shows how many ships are left"""
self.ships =Group()for ship_number inrange(self.stats.ships_left):
ship =Ship(self.ai_settings, self.screen)
ship.rect.x =10+ ship_number * ship.rect.width
ship.rect.y =10
self.ships.add(ship)
def show_score(self):"""Show score and spaceship on screen"""
self.screen.blit(self.score_image, self.score_rect)
self.screen.blit(self.high_score_image, self.high_score_rect)
self.screen.blit(self.level_image, self.level_rect)
# Draw spaceship
self.ships.draw(self.screen)
def check_high_score(stats, sb):"""Check if a new highest score is born"""if stats.score stats.high_score:
stats.high_score = stats.score
sb.prep_high_score()classButton():
def __init__(self, ai_settings, screen, msg):"""Initialize button properties"""
self.screen = screen
self.screen_rect = screen.get_rect()
# Set the size and other properties of the button
self.width, self.height =200,50
self.button_color =(0,255,0) #bright green
self.text_color =(255,255,255) #white
self.font = pygame.font.SysFont(None,48) #Use default, 48-point font
# Create the rect object of the button and center it
self.rect = pygame.Rect(0,0, self.width, self.height)
self.rect.center = self.screen_rect.center
# The button label only needs to be created once
self.prep_msg(msg)
def prep_msg(self, msg):"""Render msg as an image and center it on the button"""
self.msg_image = self.font.render(msg, True, self.text_color, self.button_color)
self.msg_image_rect = self.msg_image.get_rect()
self.msg_image_rect.center = self.rect.center
def draw_button(self):
# Draw a button filled with color, then draw text
self.screen.fill(self.button_color, self.rect)
self.screen.blit(self.msg_image, self.msg_image_rect)
# Update the image on the screen and switch to the new screen
def update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button):"""Update the image on the screen and switch to the new screen"""
# Redraw the screen every time you loop
screen.fill(ai_settings.bg_color)
# Repaint all the bullets behind the spaceship and aliens
for bullet in bullets.sprites():
bullet.draw_bullet()
ship.blitme()
aliens.draw(screen)
# Show score
sb.show_score()
# If the game is inactive, draw the Play button
if not stats.game_active:
play_button.draw_button()
# Make the most recently drawn screen visible
pygame.display.flip()
def run_game():
# Initialize the game and create a screen object
pygame.init()
ai_settings =Settings()
screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("Alien Invation")
# Create a spaceship
ship =Ship(ai_settings, screen)
# Create an alien
alien =Alien(ai_settings, screen)
# Create a group for storing bullets
bullets =Group()
# Create an alien group
aliens =Group()
# Create an alien crowd
create_fleet(ai_settings, screen, ship, aliens)
# Create an instance to store game statistics and create a scoreboard
stats =GameStats(ai_settings)
sb =Scoreboard(ai_settings, screen, stats)
# Create the Play button
play_button =Button(ai_settings, screen,"Play")
# Start the main loop of the game
while True:check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets)if stats.game_active:
ship.update()update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets)update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets)update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)run_game()
The result is shown below:
More interesting classic mini game implementation topics, share with you:
C++ classic games summary
Python classic games summary
python tetris game collection
JavaScript classic games are constantly playing
Summary of classic java games
JavaScript classic games summary
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts