main program
import pygame from import Group from settings import Settings from game_stats import gameStats from ship import Ship from button import Button import game_functions as gf def run_game(): # Initialize background settings () # Create an instance of Settings and store it in the variable ai_settings ai_settings = Settings() # Create a display window named screen in which all graphical elements of the game are drawn screen = .set_mode((ai_settings.screen_heigth, ai_settings.screen_width)) .set_caption("Aline invasion") #Create play button play_button = Button(ai_settings,screen,"play") # Create an instance for storing game statistics stats = gameStats(ai_settings) #Create a ship, a bullet team, and a team of aliens # ship =Ship(ai_settings,screen) bullets = Group() aliens = Group() #Create an alien swarm gf.create_fleet(ai_settings, screen, ship, aliens) #Start the main game loop while True: # Monitor mouse and keyboard events gf.check_events(ai_settings,screen,ship,bullets) if stats.game_active: # Spaceships move () # Bullet movement gf.update_bullets(ai_settings, screen, ship, aliens,bullets) gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets) #Redraw the screen gf.update_screen(ai_settings, screen, stats, ship, bullets, aliens, play_button) run_game()
game_functions.py
import sys import pygame from bullet import Bullet from alien import Alien from time import sleep def check_keydown_events(event,ai_settings,screen, ship, bullets): '''Response pressed''' if == pygame.K_RIGHT: ship.moving_right = True elif == pygame.K_LEFT: ship.moving_left = True elif == pygame.K_UP: ship.moving_up = True elif == pygame.K_DOWN: ship.moving_down = True elif == pygame.K_q: () # Can fire bullets even when the ship is moving if == pygame.K_SPACE: fire_bullet(ai_settings, screen, ship, bullets) def check_keyup_events(event, ship): if == pygame.K_RIGHT: ship.moving_right = False elif == pygame.K_LEFT: ship.moving_left = False elif == pygame.K_UP: ship.moving_up = False elif == pygame.K_DOWN: ship.moving_down = False def check_events(ai_settings,screen,ship, bullets): '''Respond to mouse and keyboard events''' for event in (): if == : () elif == : check_keydown_events(event, ai_settings, screen, ship, bullets) elif == : check_keyup_events(event,ship) def update_screen(ai_settings, screen, stats, ship, bullets, aliens, play_button): # Redraw the screen on every loop # Call the method screen_fill() - fill the screen with the background color (ai_settings.screen_bg_color) # Repaint all the bullets behind the spaceships and aliens # for bullet in (): bullet.draw_bullet() () (screen) #() # 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 () def update_bullets(ai_settings, screen, ship, aliens, bullets): () # Delete disappeared bullets for bullet in (): if <= 0: (bullet) #print(len(bullets)) # Displays how many bullets are currently on the screen, thus verifying that the bullets have indeed been removed check_bullet_alien_collide(ai_settings, screen, ship, aliens, bullets) def fire_bullet(ai_settings, screen, ship, bullets): if len(bullets) < ai_settings.bullet_num: # Create a bullet and add it to the grouping bullets new_bullet = Bullet(ai_settings, screen, ship) (new_bullet) def check_bullet_alien_collide(ai_settings, screen, ship, aliens, bullets): '''Check if any bullets have hit the aliens If so, delete the corresponding aliens and bullets Iterate over all bullets in the grouping bullets, then over each alien in the grouping aliens. Whenever a bullet overlaps an alien, groupcllid() adds a key-value pair to the dictionary it returns. The two real parameters True tell pygame to remove bullets and aliens that collide ''' collisions = (bullets, aliens, True, True) if len(aliens) == 0: # Delete all existing bullets () # A new swarm will appear as soon as the current swarm is wiped out # create_fleet(ai_settings, screen, ship, aliens) def get_number_aliens_x(ai_settings, alien_width): available_space_x = ai_settings.screen_heigth - 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 the screen can hold''' # Keep the length in terms of the height of the aliens, subtract the height of the ship and the empty distance between the aliens and the ship. available_space_y = (ai_settings.screen_heigth - (10*alien_height) - ship_height) number_rows = int(available_space_y/(2*alien_height)) #number_rows is the number of rows for aliens. return number_rows def crate_aline(ai_settings, screen, aliens, alien_number, rows_number): # Create an alien and add it to the current line alien = Alien(ai_settings, screen) alien_width = = alien_width + 2 * alien_width * alien_number = = + 2**rows_number (alien) def create_fleet(ai_settings, screen, ship, aliens): '''Create a swarm of aliens''' #Create an alien and calculate how many aliens can fit in a row.''' #The spacing of the aliens is the width of the aliens.''' alien = Alien(ai_settings, screen) number_aliens_x = get_number_aliens_x(ai_settings, ) number_rows = get_number_rows(ai_settings, , ) # Wear an alien suit for row_number in range(number_rows): # Create an alien for alien_number in range(number_aliens_x): crate_aline(ai_settings, screen, aliens, alien_number, row_number) def check_fleet_edges(ai_settings, aliens): '''Response when aliens reach the edge of the screen''' for alien in (): if alien.check_edges(): change_fleet_direction(ai_settings, aliens) break def change_fleet_direction(ai_settings, aliens): '''Move the whole group of aliens down and change their direction''' for alien in (): +=ai_settings.fleet_drop_speed ai_settings.fleet_direction *= -1 def ship_hit(ai_settings, stats, screen, ship, aliens, bullets): '''Responding to a ship hit by aliens''' if stats.ships_left > 0: # Subtract ship_left by 1 stats.ships_left -= 1 # Empty the alien list and the bullet list () () # Create a new group of aliens and place the ship in the center of the screen floor create_fleet(ai_settings, screen, ship, aliens) ship.center_ship() #Pause sleep(0.5) else: stats.game_active = False def check_aliens_bottom(ai_setting, stats, screen, ship, aliens, bullets): '''Check if any aliens have reached the bottom of the screen''' screen_rect = screen.get_rect() for alien in (): if >= screen_rect.bottom: # Handle it like a spaceship that's been hit ship_hit(ai_setting, stats, screen, ship, aliens, bullets) break def update_aliens(ai_settings, stats, screen, ship, aliens, bullets): '''Check if any aliens are located at the edge of the screen and update the aliens' position''' check_fleet_edges(ai_settings, aliens) #Update the location of all aliens in the alien swarm''' () # Detecting collisions between aliens and spaceships if (ship,aliens): ship_hit(ai_settings, stats, screen, ship, aliens, bullets) #Check to see if aliens reach the bottom of the screen check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets)
import pygame class Ship(object): def __init__(self,ai_settings,screen): The # parameter screen specifies where to draw the ship to. = screen self.ai_settings = ai_settings #Load the spaceship image and get its outer rectangle = (r'E:\pycharm project\Airplane Wars\images\') #Load an image, this function returns a surface representing the spaceship to be stored in the = .get_rect() # Use get_rect() to get the attribute rect of the corresponding surface. self.screen_rect = screen.get_rect() # Put each new ship at the bottom center of the screen # = self.screen_rect.centerx # Set (the x-coordinate of the ship's center) to the rectangular attribute centerx that represents the screen = self.screen_rect.bottom # Set (the y-coordinate of the lower edge of the ship) to the attribute bottom representing the rectangle of the screen # Store small values in the ship's attribute center = float() #Moving Signs self.moving_right = False #Add attribute: moving_right self.moving_left = False self.moving_up = False self.moving_down = False def update(self): '''Adjust the position of the ship according to the movement flag''' if self.moving_right and <self.screen_rect.right: #:Returns the x-coordinate of the right end of the ship's outer rectangle. += self.ai_settings.ship_speed_factor #self.screen_rect.right: return the coordinates of the right side of the screen if self.moving_left and >0: # Same as above -= self.ai_settings.ship_speed_factor if self.moving_up and >self.screen_rect.top: -= self.ai_settings.ship_speed_factor if self.moving_down and <self.screen_rect.bottom: += self.ai_settings.ship_speed_factor def blitme(self): '''Draw the ship at the specified location''' (,) # Draws the image to the screen according to the specified position def center_ship(self): '''Center the ship on the screen''' = self.screen_rect.centerx
import pygame from import Sprite import os class Alien(Sprite): '''Represents a single alien class''' def __init__(self, ai_settings, screen): '''Initialize the alien and set its initial position''' super(Alien,self).__init__() self.ai_settings = ai_settings = screen #Load the alien image and set the seven-rect property = (r'E:\pycharm project\Airplane Wars\images\') = .get_rect() # Use get_rect() to get the attribute rect of the corresponding surface. #Set the initial position of the alien ship = = # Store the exact location of the aliens = float() def check_edges(self): '''Return True if the alien is at the edge of the screen''' screen_rect = .get_rect() if > screen_rect.right: return True elif < screen_rect.left: return True def update(self): '''Move the aliens to the right''' += (self.ai_settings.alien_speed_factor*self.ai_settings.fleet_direction) = def blitme(self): '''Draw aliens at the specified location''' (,)
import class Button(): def __init__(self,ai_settings, screen, msg): '''Initialize the properties of the button''' = screen self.screen_rect = screen.get_rect() # Set the size and other properties of the button , = 200,50 self.button_color = (0,255,255) self.text_color = (255,255,255) = (None,48) # Create the rect object of the button and center it = (0,0,,) = self.screen_rect.center Labels for #buttons need to be created only once self.prep_msg(msg) def prep_msg(self,msg): '''Render the msg as an image and center it on the button''' self.msg_image = (msg,True,self.text_color,self.button_color) self.msg_image_rect = self.msg_image.get_rect() self.msg_image_rect.center = def draw_button(self): '''Draw a button filled with a color, in draw text''' (self.button_color,) (self.msg_image,self.msg_image_rect)
import pygame from import Sprite class Bullet(Sprite): The #Bullet class inherits the Sprite class imported from the module '''One manages the bullets fired by the ship''' #By using sprites, you can group related elements in the game and manipulate all the elements in the group at the same time. def __init__(self,ai_settings, screen, ship): '''Create a bullet object at the location of the ship''' super(Bullet,self).__init__() # Call super() to inherit Sprite. = screen # Create a rectangle at (0, 0) where the table is a bullet, in the correct position to set the = (0, 0, ai_settings.bullet_width,ai_settings.bullet_height) #Bullets are not image based, then you must create a rectangle from blank using () = = #Store bullet positions in decimals = float() # Store the y-coordinate of the bullet as a decimal value #Set bullet color and velocity = ai_settings.bullet_color self.speed_factor = ai_settings.bullet_speed_factor def update(self): '''Update the decimal value indicating the position of the bullet''' -= self.speed_factor # Update the position of the rect that represents the bullet = def draw_bullet(self): '''Drawing bullets on the screen''' (,,) The #function() uses a function stored in the # The color fill of the bullet indicates therectScreen occupied
game_stats.py
'''Tracking game statistics''' class gameStats(): def __init__(self, ai_settings): self.ai_settings = ai_settings self.reset_stats() # Games are inactive when they first start self.game_active = False def reset_stats(self): '''Initialize statistics that may change during the run of the game''' self.ships_left = self.ai_settings.ship_limit
class Settings(): def __init__(self): #Screen Settings self.screen_heigth = 1000 self.screen_width = 700 self.screen_bg_color = (230,230,230) #Set background color self.ship_speed_factor = 1.5 self.ship_limit = 3 self.bullet_speed_factor = 1 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = 60,60,60 self.bullet_num = 6 # Alien setup self.alien_speed_factor = 1 #fleet_drop_speed is the speed of the drop when an alien hits the edge of the screen self.fleet_drop_speed = 10 # Right when fleet_direction is 1, left when -1 self.fleet_direction = 1
summarize
The above is a small introduction to the python implementation of the war aliens mini-game, I hope to help you, if you have any questions please leave me a message, I will reply to you in time. Here also thank you very much for your support of my website!
If you find this article helpful, please feel free to reprint it, and please note the source, thank you!