This article mainly introduces the complete implementation idea of Python alien invasion game programming in detail. The example code introduced in this article is very detailed and has certain reference value. Interested friends can refer to the complete implementation idea of Python alien invasion game programming

The preparatory work

Download Python, such as Anaconda3 (64-bit), and import the PyGame package

! [](https://p6-tt-ipv6.byteimg.com/large/pgc-image/44abc61fcc784ddbbc8ccedf910bd999)
! [](https://p3-tt-ipv6.byteimg.com/large/pgc-image/1a750042cea844d684c70748f4305d15)
! [](https://p6-tt-ipv6.byteimg.com/large/pgc-image/803f39852b104117aed19918eda99fdc)
! [](https://p6-tt-ipv6.byteimg.com/large/pgc-image/d05aa958614f48c992d4e9931816dfe0)
! [](https://p9-tt-ipv6.byteimg.com/large/pgc-image/bb3cc7ee53394fdfbc9f55e85175ccfd)

1. Alien Settings, alien. Py, code:

(PS: the following is the source code, the need for source code and material children’s shoes can be downloaded to download

import pygame from pygame.sprite import Sprite class Alien(Sprite): Def __init__(self,ai_settings,screen): """ super(Alien,self).__init__() self.screen = screen self.ai_settings = ai_settings # load Alien image, And set its rect property self.image = Pygame.image.load ('images/alien. BMP ') self.rect = self.image.get_rect() # Each alien is initially near the top left corner of the screen X = float(self.rect.x) def blitme(self): self.rect.x = float(self.rect.x) def blitme(self): Self.screen. blit(self.image,self.rect) def check_edges(self): """ 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): X += (self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction) self.rect.x = self.xCopy the code

2. The main program of the game, alien_invasion. Py, code:

import pygame from settings import Settings from game_stats import GameStats from button import Button from ship import Ship from pygame.sprite import Group import game_functions as gf from scoreboard import Scoreboard def run_game(): Pygame.init () # initialize background Settings ai_settings = Settings() # global Settings screen = pygame.display.set_mode(# create screen window (ai_settings.screen_width,ai_settings.screen_height) pyGame.display. Set_caption ('Alien Invasion') # Play_button = Button(ai_settings,screen,"Play") # Create stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, Bullets = Group() # Create aliens = Group() # Create aliens = Group() # Create aliens Gf. Create_fleet (ai_settings, screen, ship, aliens) # start playing the main loop while True: # monitor keyboard and mouse events gf. Check_events (ai_settings, screen, stats, sb, play_button, ship, aliens, bullets) if stats. Game_active: # # mobile spacecraft gf. Update_ship (ship) to update the bullet position gf. Update_bullets (ai_settings, screen, stats, sb, ship, aliens, bullets) # update aliens Gf. Update_aliens (ai_settings, stats, screen, sb, ship, aliens, bullets) # update screen gf.update_screen(ai_settings,screen,stats,sb,ship,aliens,bullets,play_button) run_game()Copy the code

3. Set bullet, bullet. Py, code:

import pygame from pygame.sprite import Sprite import time class Bullet(Sprite): Def __init__(self,ai_settings,screen,ship): Super (Bullet,self).__init__() self.screen = screen # create the initial position of the Bullet rectangle (0,0,3,15) corresponding to lef, top, width, Rect = pygame. rect (0,0, ai_settings.bullet_width, Ai_settings.bullet_height) self.rect.centerx = ship.rect.centerx # Set the center point x coordinates to be the same as the ship self.rect.top = ship.rect.top # Top = float(self.rect.top) self.color = ai_settings.bullet_color self.speed_factor = ai_settings.bullet_speed_factor def update(self): self.top -=self.speed_factor self.rect.top = self.top print(self.rect.top) def draw_bullet(self): pygame.draw.rect(self.screen,self.color,self.rect)Copy the code

4. Set Play button, button.py, code:

import pygame.font class Button(): def __init__(self,ai_settings,screen,msg): Self.screen = screen self.screen_rect = screen.get_rect() # set the size of the button and other attributes self.width,self.height = 200,50 Self.button_color = (0,255,0) self.text_color = (255,255,255) self.font = pygame.font.SysFont(None,48) Centered and make it self. The rect = pygame. The rect (0, 0, the self. The width, the self. Height) self. The rect. Center = self. Screen_rect. Center # just create a button on the tag self.prep_msg(msg) def prep_msg(self,msg): """ Render MSG as an image, "" 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): Self.screen. fill(self.button_color,self.rect) self.screen.blit(self.msg_image,self.msg_image_rect)Copy the code

5. Set the game function, game_functions.py, code:

import sys
import pygame
from bullet import Bullet
from alien import Alien
from time import sleep

def check_events(ai_settings,screen,stats,sb,play_button,ship,aliens,bullets):
 # 监视键盘和鼠标事件
 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):
 """在玩家单击Play按钮时开始游戏"""
 button_clicked = play_button.rect.collidepoint(mouse_x,mouse_y)
 if button_clicked and not stats.game_active:
 #重置游戏设置
 ai_settings.initialize_dynamic_settings()

 #隐藏光标
 pygame.mouse.set_visible(False)
 #重置游戏统计信息
 stats.reset_stats()
 stats.game_active = True

 #重置计分牌图像
 sb.prep_score()
 sb.prep_high_score()
 sb.prep_level()
 sb.prep_ships()

 #清空外星人列表和子弹列表
 aliens.empty()
 bullets.empty()

 #创建一群新的外星人,并让飞船居中
 create_fleet(ai_settings,screen,ship,aliens)
 ship.center_ship()

def update_screen(ai_settings,screen,stats,sb,ship,aliens,bullets,play_button):
 '''更新屏幕上的图片,并切换到新屏幕'''
 screen.fill(ai_settings.bg_color) # 设置背景颜色
 ship.blitme() # 绘制飞船
 aliens.draw(screen)
 # 循环子弹组里面的元素,进行绘制 为空时不执行
 for bullet in bullets.sprites():
 bullet.draw_bullet() # 绘制子弹
 #显示得分
 sb.show_score()
 #如果游戏处于非活跃状态,就显示Play按钮
 if not stats.game_active:
 play_button.draw_button()
 # 显示最新屏幕,擦拭旧屏幕
 pygame.display.flip()
 # print('1')

def check_keydown_events(event,ai_settings,screen,ship,bullets):
 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_bullet(ai_settings,screen,ship,bullets)
 elif event.key == pygame.K_q:
 sys.exit()

def check_keyup_events(event,ship):
 if event.key == pygame.K_RIGHT:
 ship.moving_right = False
 elif event.key == pygame.K_LEFT:
 ship.moving_left = False

def update_bullets(ai_settings,screen,stats,sb,ship,aliens,bullets):
 '''更新子弹位置,删除子弹'''
 bullets.update() # 子弹组每个成员执行self.update()操作
 for bullet in bullets.sprites():
 if bullet.rect.bottom <= 0: # 子弹出界 删除
  bullets.remove(bullet)
 check_bullet_alien_collisions(ai_settings,screen,stats,sb,ship,aliens,bullets)

def check_bullet_alien_collisions(ai_settings,screen,stats,sb,ship,aliens,bullets): 
 """响应外星人和子弹的碰撞"""
 #删除发生碰撞的子弹和外星人
 collisions = pygame.sprite.groupcollide(bullets,aliens,True,True)

 if collisions:
 for aliens in collisions.values(): 
  stats.score += ai_settings.alien_points * len(aliens)
  sb.prep_score()
 check_high_score(stats,sb)

 if len(aliens)==0:
 #删除现有的子弹并新建一群外星人,加快游戏进度节奏
 bullets.empty()
 ai_settings.increase_speed()

 #提高等级
 stats.level += 1
 sb.prep_level()

 create_fleet(ai_settings,screen,ship,aliens)

def update_ship(ship):
 ship.update()

def fire_bullet(ai_settings,screen,ship,bullets):
 # 创建一个子弹对象 加入到子弹组
 if len(bullets) < ai_settings.bullets_allowed: # 子弹少于允许值时再生成
 new_bullet = Bullet(ai_settings, screen, ship)
 bullets.add(new_bullet)

def get_number_aliens_x(ai_settings,alien_width):
 """计算每行可容纳多少个外星人"""
 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):
 """计算屏幕可容纳多少行外星人"""
 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_aliens(ai_settings,screen,aliens,alien_number,row_number):
 """创建一个外星人并将其放在当期行"""
 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):
 """创建外星人群"""
 #创建一个外星人,并计算一行可以容纳多少个外星人
 #外星人间距为外星人宽度
 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)

 #创建第一行外星人
 for row_number in range(number_rows):
 for alien_number in range(number_aliens_x):
  #创建一个外星人并将其加入当前行
  create_aliens(ai_settings,screen,aliens,alien_number,row_number)

def check_fleet_edges(ai_settings,aliens):
 """有外星人到达边缘时采取相应措施"""
 for alien in aliens.sprites():
 if alien.check_edges():
  change_fleet_direction(ai_settings,aliens)
  break

def change_fleet_direction(ai_settings,aliens):
 """将整群外星人下移,并改变他们的运动方向"""
 for alien in aliens.sprites():
 alien.rect.y += ai_settings.fleet_drop_speed
 ai_settings.fleet_direction *= -1

def ship_hit(ai_settings,stats,screen,sb,ship,aliens,bullets):
 """响应被外星人撞到的飞船"""
 if stats.ships_left > 0:
 #将ship_left减1
 stats.ships_left -= 1

 #更新记分牌
 sb.prep_ships()

 #清空外星人列表和子弹列表
 aliens.empty()
 bullets.empty()
 #创建一群新的外星人,并将飞船放到屏幕低端中央
 create_fleet(ai_settings,screen,ship,aliens)
 ship.center_ship()
 #暂停
 sleep(0.5)
 else:
 stats.game_active = False
 pygame.mouse.set_visible(True)

def check_aliens_bottom(ai_settings,stats,screen,sb,ship,aliens,bullets):
 """检查是否有外星人到达屏幕低端"""
 screen_rect = screen.get_rect()
 for alien in aliens.sprites():
 if alien.rect.bottom >= screen_rect.bottom:
  #像飞船被撞到一样进行处理
  ship_hit(ai_settings,stats,screen,sb,ship,aliens,bullets)
  break

def update_aliens(ai_settings,stats,screen,sb,ship,aliens,bullets):
 """更新外星人群中所有外星人的位置"""
 check_fleet_edges(ai_settings,aliens)
 aliens.update()
 #检测外星人和飞船之间的碰撞
 if pygame.sprite.spritecollideany(ship,aliens):
 ship_hit(ai_settings,stats,screen,sb,ship,aliens,bullets)
 #检查是否有外星人到达屏幕低端
 check_aliens_bottom(ai_settings,stats,screen,sb,ship,aliens,bullets)

def check_high_score(stats,sb):
 """检查是否诞生了新的最高纪录"""
 if stats.score > stats.high_score:
 stats.high_score = stats.score
 sb.prep_high_score() 
Copy the code

6. Game_stats. Py

Class GameStats(): """ """ def __init__(self,ai_settings): """ "Initialize statistics """ self.ai_settings = ai_settings self.reset_stats() # The game is inactive when it starts self.game_active = False # The highest score should not be reset under any circumstances self.high_score = 0 self.level = 1 def reset_stats(self): """ Initializes statistics that may change while the game is running. """ self.ships_left = self.ai_settings.ship_limit self.score = 0Copy the code

7. Score setting, scoreboard.py:

import pygame.font from pygame.sprite import Group from ship import Ship class Scoreboard(): Def __init__(self, ai_settings, screen, stats): """ Initializes the attributes involved in displaying the score """ self.screen =screen self.screen_rect = screen.get_rect() self.ai_settings = ai_settings self.stats = Self. text_color = (30, 30, 30) self.font = pygame.font.SysFont(None, Self.prep_score () self.prep_high_score() self.prep_level() self.prep_ships() def prep_score(self): 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 self.score_rect = self.score_image.get_rect() self.score_rect.right = self.screen_rect.right - 20 self.score_rect.top = 5 def prep_high_score(self): 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) # place 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 = 5 def prep_level(self): Self. level_image = self.font. Render (STR (self.stats.level), True, self.text_color, Self.ai_settings.bg_color) # put the score in the upper right corner self.level_rect = self.score_image.get_rect() self.level_rect.right = self.screen_rect.right self.level_rect.top = self.score_rect.bottom def prep_ships(self): """ displays how many ships are left """ self.ships = Group() for ship_number in range(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): Self.screen. blit(self.score_image, self.score_rect) self.screen.blit(self.high_score_image, High_score_rect) self.screen.blit(self.level_image, self.level_rect) # draw the ship self.ships. Draw (self.screen)Copy the code

8. Settings, settings.py:

Class Settings(): "save all Settings for alien invasion" def __init__(self): Self.screen_width = 1200 self.screen_height = 600 self.bg_color = (230,230,230 Self.ship_limit = 3 self.ship_image_path = 'images/ship.bmp' # ship image path # bullet set self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = 60,60,60 self.bullets_allowed = 3 # number of bullets allowed on screen # aliens set self.fleet_drop_speed = 10 # speed up the game at what speed Self.speedup_scale = 1.1 # alien points increase speed self.score_scale = 1.5 self.initialize_dynamic_settings() def initialize_dynamic_settings(self): """ Initializes Settings that change as the game progresses """ self.ship_speed_factor = 1.5 self.bullet_speed_factor = 3 self.alien_speed_factor = 1 Self. fleet_direction = 1 # score self.alien_points = 50 def increase_speed(self): """ Increase speed Settings, 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) print(self.alien_points)Copy the code

9. Ship setup, ship.py, code:

Import pygame from pygame. Sprite import Sprite class Ship(Sprite): def __init__(self,ai_settings,screen): """ Initialize the ship, "" super(Ship,self).__init__() self.screen=screen self.ai_settings = ai_settings # Pygame. Image. The load (self) ai_settings) ship_image_path) # loading picture self. The image = pygame. Transform. Smoothscale (self image, (40, 60)) Self.screen_rect = screen.get_rect() # Get the screen.get_rect() # Get the screen.rect () # Put each new spaceship in the center of the bottom of the screen Self.rect. centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom # set to float self.center = Float (self.moving_right = False self.moving_left = self False def blitme(self): self.screen.blit(self.image,self.rect) def update(self): 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 > self.screen_rect.left: self.center -= self.ai_settings.ship_speed_factor self.rect.centerx = self.center def center_ship(self): """ Center the ship on the screen """ self.center = self.screen_rect.centerxCopy the code

Effect display:

! [](https://p26-tt.byteimg.com/large/pgc-image/927d95774c3e49278c224e85c46e4689)

Game resources: Image resources

! [](https://p9-tt-ipv6.byteimg.com/large/pgc-image/0e9300c5cabd4c71ae62ce732a7634d3)
! [](https://p3-tt-ipv6.byteimg.com/large/pgc-image/8a3c4769b59b4f079b2c2661540882e9)

(PS: the following is the source code, the need for source code and material children’s shoes can be downloaded to download