First of all, I'm sorry , I haven't updated it for too long . Mid Autumn Festival went out to play, there is no update , Then another week of new employee training , therefore , I didn't have time to update , I went home to accompany my parents during the National Day , Today is a day off , Seize the time to update . If there are no special circumstances , Try to use the weekend time to update articles for everyone . therefore , For the recent delay, let's say sorry again ! The previous two articles introduced the creation of aliens , This includes The creation of the first alien as well as The creation of a group of aliens . In fact, it is not difficult for us to find and compare with the front in creating the implementation of Alien Creation Creation of spacecraft The principle is the same , It's just that some small details are different . This article introduces the alien group we created to move !
Next, let's move the alien crowd to the right on the screen , Hit the edge of the screen and move down a certain distance , Then move in the opposite direction . We will continue to move all aliens , Until all aliens are eliminated , An alien hit a spaceship , Or aliens arrive at the bottom of the screen . Next , We first realize that aliens move to the right .
For mobile aliens , We will use alien.py
The method in update()
, And call it for every alien in the alien population . First , We are settings.py
Add a setting to control alien speed at the end :
class Settings(): """ Storage 《 Alien invasion 》 All settings classes for """ def __init__(self): """ Initialize game settings """ # Screen settings self.screen_width = 1400 self.screen_height = 700 self.bg_color = (230, 230, 230) # Spacecraft setup self.ship_speed_factor = 1.5 # Bullet settings self.bullet_speed_factor = 3.6 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = 60, 60, 60 self.bullets_allowed = 6 # Alien settings self.alien_speed_factor = 1
then , We are alien.py
Setting implementation in update()
:
import pygame from pygame.sprite import Sprite class Alien(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 # Loading alien images , And set its rect attribute self.image = pygame.image.load("images/alien.bmp") self.rect = self.image.get_rect() # Each alien was initially near the top left corner of the screen self.rect.x = self.rect.width self.rect.y = self.rect.height # Store the exact location of Aliens self.x = float(self.rect.x) def blitme(self): """ Draw aliens in designated locations """ self.screen.blit(self.image, self.rect) def update(self): """ Moving aliens to the right """ self.x += self.ai_settings.alien_speed_factor self.rect.x = self.x
Every time you update the alien's location , Move it to the right , The amount of movement is alien_speed_factor
Value , We use properties self.x
Track the exact location of each Alien , This property can store small values . then , We use self.x
To update the alien's rect
Location . In the main while The method to update the ship and bullets has been called in the loop , But now we need to alien_invasion.py
Update the location of each Alien :
import sys import pygame from settings import Settings from ship import Ship import game_functions as gf from pygame.sprite import Group from alien import Alien 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("Alian Invasion") # Create a spaceship 、 A bullet train and an alien train ship = Ship(ai_settings, screen) # Create a group for storing bullets bullets = Group() aliens = Group() # Creating alien groups # alien = Alien(ai_settings, screen) gf.create_fleet(ai_settings, screen, ship, aliens) # Start the main cycle of the game while True: # Monitor keyboard and mouse events gf.check_events(ai_settings, screen, ship, bullets) ship.update() gf.update_bullets(bullets) gf.update_aliens(aliens) gf.update_screen(ai_settings, screen, ship, aliens, bullets) run_game()
We'll update the location of the aliens after updating the bullets , Because we'll check later to see if any bullets hit aliens . Finally, in the document game_funcation.py
Add function at the end update_aliens()
:
import sys import pygame from bullet import Bullet from alien import Alien def check_keydown_events(event, ai_settings, screen, ship, bullets): """ Response 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: # Create a bullet , And add it to the group bullets in fire_bullet(ai_settings, screen, ship, bullets) elif event.key == pygame.K_q: sys.exit() def fire_bullet(ai_settings, screen, ship, bullets): """ If the limit has not been reached , Just fire a bullet """ if len(bullets) < ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet) def check_keyup_events(event, ship): """ Response loosening """ 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, ship, bullets): """ Respond to key 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) def update_screen(ai_settings, screen, ship, aliens, bullets): """ Update image on screen , And switch to the new screen """ # Redraw the screen every time you cycle screen.fill(ai_settings.bg_color) # Redraw all the bullets behind the spaceship and the alien for bullet in bullets.sprites(): bullet.draw_bullet() ship.blitme() aliens.draw(screen) # Make the most recently drawn screen visible pygame.display.flip() def update_bullets(bullets): """ Update bullet position , And delete the missing bullets """ # Update bullet position bullets.update() # Delete bullets that have disappeared for bullet in bullets.copy(): if bullet.rect.bottom <= 0: bullets.remove(bullet) def get_number_aliens_x(ai_settings, alien_width): avaliable_space_x = ai_settings.screen_width - 2 * alien_width number_aliens_x = int(avaliable_space_x / (2 * alien_width)) return number_aliens_x def create_alien(ai_settings, screen, aliens, alien_number, row_number): # Create an alien , And calculate how many aliens a row can hold 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): """ Creating alien groups """ 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 the first line of Aliens for row_number in range(number_rows): for alien_number in range(number_aliens_x): # Create an alien and add it to the current line create_alien(ai_settings, screen, aliens, alien_number, row_number) def get_number_rows(ai_settings, ship_height, alien_height): """ How many lines of aliens can the screen hold """ 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 update_aliens(aliens): """ Update the location of all aliens in the alien crowd """ aliens.update()
We're right aliens
Calling method update()
, This will automatically call the method... For each alien update()
. If we run this game now , You'll see the aliens moving to the right , And gradually disappear on the right edge of the screen , The specific effect is as follows :
Now let's create an alien to hit the right edge of the screen and move down 、 Move the setting to the left again , We started with settings.py
Make the following settings in :
class Settings(): """ Storage 《 Alien invasion 》 All settings classes for """ def __init__(self): """ Initialize game settings """ # Screen settings self.screen_width = 1400 self.screen_height = 700 self.bg_color = (230, 230, 230) # Spacecraft setup self.ship_speed_factor = 1.5 # Bullet settings self.bullet_speed_factor = 3.6 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = 60, 60, 60 self.bullets_allowed = 6 # Alien settings self.alien_speed_factor = 1 self.fleet_drop_speed = 10 # fleet_direction by 1 To the right , by -1 Move left self.fleet_direction = 1
Set up fleet_drop_speed
Specifies when an alien hits the edge of the screen , The speed at which the aliens move down . It's good to separate this speed from horizontal speed , So we can adjust the two speeds separately . To achieve fleet_direction
Set up , You can set it to a text value , Such as left
or right
, But then you have to write if-elif
Statement to check the moving direction of the alien crowd . Since only these two directions are possible , We use value 1 and -1 To represent them , And switch between these two values when the alien crowd changes direction . in addition , In view of the need to increase the size of each alien when moving to the right x coordinate , Moving to the left requires reducing each Alien x Coordinates of , It's more reasonable to use numbers to indicate direction .
Now you need to write a method to check whether aliens hit the edge of the screen , Need modification alien.py
Medium update()
, So that every alien moves in the right direction :
import pygame from pygame.sprite import Sprite class Alien(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 # Loading alien images , And set its rect attribute self.image = pygame.image.load("images/alien.bmp") self.rect = self.image.get_rect() # Each alien was initially near the top left corner of the screen self.rect.x = self.rect.width self.rect.y = self.rect.height # Store the exact location of Aliens self.x = float(self.rect.x) def blitme(self): """ Draw aliens in designated locations """ self.screen.blit(self.image, self.rect) def check_edges(self): """ If aliens are on the edge of the screen , Just go back to 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
We can call new methods on any alien check_edges()
, See if it's on the left or right edge of the screen . If alien rect
Of right
Property greater than or equal to the screen's rect
Of right
attribute , That means aliens are on the right edge of the screen . If alien rect
Of left
Property less than or equal to 0, That means aliens are on the left edge of the screen . We modified the method update()
, Set the amount of movement to alien speed and fleet_direction
The product of the , Let aliens move left or right . If fleet _direction
by 1, The alien's current x The coordinates increase to alien_speed_factor
, To move the aliens to the right ; If fleet_direction
by -1, The alien's current x Coordinate subtraction alien_speed_factor
, To move the aliens to the left .
When an alien reaches the edge of the screen , We need to move the whole group of aliens down , And change the direction they move . We need to be right about game_function.py
Make major changes , because , We're going to check here whether aliens have reached the left edge or the right edge . So , We write functions check_fleet_edges() and change_fleet_direction()
, Also on update_aliens()
It's been modified :
import sys import pygame from bullet import Bullet from alien import Alien def check_keydown_events(event, ai_settings, screen, ship, bullets): """ Response 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: # Create a bullet , And add it to the group bullets in fire_bullet(ai_settings, screen, ship, bullets) elif event.key == pygame.K_q: sys.exit() def fire_bullet(ai_settings, screen, ship, bullets): """ If the limit has not been reached , Just fire a bullet """ if len(bullets) < ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet) def check_keyup_events(event, ship): """ Response loosening """ 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, ship, bullets): """ Respond to key 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) def update_screen(ai_settings, screen, ship, aliens, bullets): """ Update image on screen , And switch to the new screen """ # Redraw the screen every time you cycle screen.fill(ai_settings.bg_color) # Redraw all the bullets behind the spaceship and the alien for bullet in bullets.sprites(): bullet.draw_bullet() ship.blitme() aliens.draw(screen) # Make the most recently drawn screen visible pygame.display.flip() def update_bullets(bullets): """ Update bullet position , And delete the missing bullets """ # Update bullet position bullets.update() # Delete bullets that have disappeared for bullet in bullets.copy(): if bullet.rect.bottom <= 0: bullets.remove(bullet) def get_number_aliens_x(ai_settings, alien_width): avaliable_space_x = ai_settings.screen_width - 2 * alien_width number_aliens_x = int(avaliable_space_x / (2 * alien_width)) return number_aliens_x def create_alien(ai_settings, screen, aliens, alien_number, row_number): # Create an alien , And calculate how many aliens a row can hold 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): """ Creating alien groups """ 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 the first line of Aliens for row_number in range(number_rows): for alien_number in range(number_aliens_x): # Create an alien and add it to the current line create_alien(ai_settings, screen, aliens, alien_number, row_number) def get_number_rows(ai_settings, ship_height, alien_height): """ How many lines of aliens can the screen hold """ 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 check_fleet_edges(ai_settings, aliens): """ When aliens reach the edge, take corresponding measures """ for alien in aliens.sprites(): 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 aliens.sprites(): alien.rect.y += ai_settings.fleet_drop_speed ai_settings.fleet_direction = -1 def update_aliens(ai_settings, aliens): """ Check for aliens on the edge of the screen , And update the location of the entire group of aliens """ check_fleet_edges(ai_settings, aliens) aliens.update()
stay check_fleet_edges()
in , We traverse the Alien Swarm , And call... For each of them check_edges()
. If check_edges()
return True, We know that the corresponding alien is at the edge of the screen , We need to change the direction of the alien population , therefore , We call change_fleet_direction()
And exit the loop . stay change_fleet_direction()
in , We traverse all aliens , Move each alien down fleet_drop_speed
Set the value of the ; then , take fleet_direction
The value of is changed to its current value and -1 The product of the . We modified the function update_aliens()
, In which you call check_fleet_edges()
To determine if there are aliens at the edge of the screen . Now? , function update_aliens()
Contains formal parameters ai_settings
, therefore , When we call it, we specify the and ai_settings
The corresponding argument :
import sys import pygame from settings import Settings from ship import Ship import game_functions as gf from pygame.sprite import Group from alien import Alien 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("Alian Invasion") # Create a spaceship 、 A bullet train and an alien train ship = Ship(ai_settings, screen) # Create a group for storing bullets bullets = Group() aliens = Group() # Creating alien groups # alien = Alien(ai_settings, screen) gf.create_fleet(ai_settings, screen, ship, aliens) # Start the main cycle of the game while True: # Monitor keyboard and mouse events gf.check_events(ai_settings, screen, ship, bullets) ship.update() gf.update_bullets(bullets) gf.update_aliens(ai_settings, aliens) gf.update_screen(ai_settings, screen, ship, aliens, bullets) run_game()
If we run this game now , The Alien Swarm will move back and forth on the screen , And move down after reaching the edge of the screen , The specific effect is as follows :
The previous two articles introduced the creation of aliens , This includes The creation of the first alien as well as The creation of a group of aliens . In fact, it is not difficult for us to find and compare with the front in creating the implementation of Alien Creation Creation of spacecraft The principle is the same , It's just that some small details are different . This paper introduces how to make our alien group move , We first let the aliens move to the right , Then set the alien's moving direction and check whether the alien can hit the edge of the screen and further operate : I.e. move down . Next , We can introduce the realization of the alien elimination function . In order to let everyone better absorb the knowledge points used in the project , Each of our articles is only for you to realize 《 Alien invasion 》 A function of , therefore , I hope you can read it carefully , Write the code carefully , Understand the deep meaning , Let's maximize the value of this project . In fact, this project is already very typical , The code is everywhere , however , If you just paste and copy , There is no value in learning your knowledge , You still have to follow , Then you should know the meaning of each line of code or which knowledge point we introduced earlier , That's the only way , This project will play a different value , I hope you will study hard , Lay a solid foundation of basic knowledge .Python It's a practical language , It is the simplest of many programming languages , It's also the best way to get started . When you learn the language , Go to study again java、go as well as C The language is relatively simple . Of course ,Python It's also a popular language , It is very helpful for the realization of artificial intelligence , therefore , It's worth your time to learn . Life is endless , Struggle is more than , We work hard every day , study hard , Constantly improve your ability , I believe I will learn something . come on. !!!
Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .