Alien invasion project in Python application -- Aliens (Part 2)

One meter long 2021-10-29 05:12:08
alien invasion project python application

Preface

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 !

Let the alien crowd 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 .

1、 Moving aliens 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 :

2、 Create settings that represent the direction of alien movement

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 .

3、 Check if aliens hit the edge of the screen

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 .

4、 Move the Alien Swarm down and change its direction

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 :

summary

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 .

版权声明
本文为[One meter long]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/10/20211013170537893e.html

  1. OpenCV - Python Real play (14) - face detection details (six lignes de code seulement pour apprendre 4 méthodes de détection de visage)
  2. 你好,python开发mes系统,能分享下吗,我最近也想搞这方面的
  3. 你好,python開發mes系統,能分享下嗎,我最近也想搞這方面的
  4. Bonjour, Python a développé mon système, pouvez - vous le partager?
  5. Introduction to tuples in Python
  6. Introduction to strings in python (Part 2)
  7. Introduction to strings in python (Part 1)
  8. python关于 if 的简单操作时,输出结果不是预期所要的结果 的问题
  9. python關於 if 的簡單操作時,輸出結果不是預期所要的結果 的問題
  10. Lorsque Python fonctionne simplement sur if, la sortie n'est pas le résultat attendu
  11. Python中字典问题请求解惑
  12. Python中字典問題請求解惑
  13. Demande de résolution de problèmes de dictionnaire en python
  14. Python中字典问题请求解惑
  15. Python technique 2: advanced usage of function parameters
  16. Demande de résolution de problèmes de dictionnaire en python
  17. Preliminary Knowledge - Python Core use Common Data Analysis Library (ⅱ)
  18. 关于python的代码问题,终端打印为什么会起飞
  19. En ce qui concerne les problèmes de code Python, pourquoi l'impression du terminal décolle - t - elle?
  20. Python中种子seed的运用问题
  21. L'application de Seed en python
  22. Python functional programming series 008: Testability
  23. [must see for getting started with Python] the difference and connection between cookie and session in Python!
  24. Python Xiaobai from scratch pyqt5 project actual combat (4) basic controls
  25. Python Xiaobai starts the pyqt5 project from scratch (3) connection between signal and slot
  26. Echarts ne peut pas afficher le HTML en PDF en utilisant le pdfkit de Python
  27. 一只Python 小white 的日常提问(づ ●─● )づ
  28. 2021 tutoriel complet d'automatisation des tests d'interface python [matériel d'apprentissage joint]
  29. Décrivez ce que les connaissances pertinentes jouent dans votre travail en utilisant arduino ou Python, y compris les bibliothèques pertinentes, en conjonction avec votre travail quotidien.
  30. Une question quotidienne d'un petit morceau de Python (づ● - ●)
  31. Python中字典问题请求解惑
  32. 一只Python 小white 的日常提問(づ ●─● )づ
  33. 在python中的问题,请问如何解决
  34. Only 10 questions are needed to easily master Matplotlib graphics processing | Python skill tree
  35. 在python中的問題,請問如何解决
  36. Comment résoudre le problème en python
  37. Demande de résolution de problèmes de dictionnaire en python
  38. 使用python,在一个命名为.txt文本文档写入n m乘法表。
  39. En utilisant Python, écrivez une table de multiplication n m dans un document texte nommé.txt.
  40. 使用python,在一個命名為.txt文本文檔寫入n m乘法錶。
  41. Python,前缀后缀相同时合并
  42. 关于#python#的问题:python
  43. 關於#python#的問題:python
  44. Python,前綴後綴相同時合並
  45. Questions sur # # Python #: Python
  46. Python, préfixe et suffixe combinés en même temps
  47. python manage.py shell无法运行,
  48. python manage.py shell無法運行,
  49. Le shell Python manage.py ne fonctionne pas,
  50. python中使用vscode Import 'matplotlib.pyplot' could not be resolved from source 问题
  51. [Chapter 11 of the full version] Python advanced crawler practice - system master Po anti climbing skills challenge high salary
  52. L'utilisation de vscode Import 'matplotlib.pyplot' en python ne peut pas être résolue à partir du problème source
  53. Python fusionne les deux listes et supprime les éléments dupliqués lors de la fusion
  54. [JS Reverse AES Reverse Encryption] python crawler combat, les jours sont de plus en plus décisifs
  55. 30 jeux Python. Je peux jouer à la pêche au travail pendant une journée.
  56. J'a i collecté un nouveau hit de liste en python, donc c'est un secret que quelqu'un d'autre peut devenir un magnat des médias!
  57. J'a i utilisé Python pour ramper à travers 5000 belles photos de papier peint, un jour oublié Premier amour!
  58. [Python planting system] the best green plant for your girlfriend. Girls love it when they see it! Attachment: should be able to feed - right??!
  59. [Python love guide] two small programs for sweetness burst table are released! Afraid you can't find someone?
  60. J'ai utilisé Python pour me connecter à la plus grande plate - forme de jeu au monde, et à quel point le cryptage steam est intelligent [code source inclus]