Prerequisite installation of pygame in cmd pip install pygame can be
I. Window Construction
import sys import pygame def run_game(): # Initialize and create a screen object pygame.init() screen = pygame.display.set_mode((1200,800)) pygame.display.set_caption("Alien Invasion") # The main cycle of the game while True: # Monitor keyboard and mouse events for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() # Make the recently drawn screen visible pygame.display.flip() run_game()
II. Game Settings
import pygame class Ship(): def __init__(self,screen): """Initialize the Starting Position of the Spacecraft""" self.screen = screen #Loading the spacecraft image and obtaining its outer rectangle self.image = pygame.image.load('images/ship.bmp') self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() #Place each new spacecraft in the central starting position of the screen self.rect.centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom def blitme(self): """Drawing a spacecraft at a specified position""" self.screen.blit(self.image,self.rect)
Modify alien_invasion.py
--snip-- import pygame from settings import Settings def run_game(): # Initialize pygame, settings, and screen objects pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # Start the main game cycle while True: --snip-- # Redraw the screen every time you loop screen.fill(ai_settings.bg_color) # Make the recently drawn screen visible pygame.display.flip() run_game()
3. Adding Spacecraft Images
In http://www.ituring.com.cn/book/1861, the right download source code file is decompressed and the image of the spaceship is found in the chapter12 folder.
Why is it a bmp picture?
Almost any type of image file can be used in the game, but bitmap (.bmp) files are the simplest because Pygame loads bitmaps by default.
import pygame class Ship(): def __init__(self,screen): """Initialize the Starting Position of the Spacecraft""" self.screen = screen #Loading the spacecraft image and obtaining its outer rectangle self.image = pygame.image.load('images/ship.bmp') self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() #Place each new spacecraft in the central starting position of the screen self.rect.centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom def blitme(self): """Drawing a spacecraft at a specified position""" self.screen.blit(self.image,self.rect)
The results are as follows: