Python编程-外星人入侵:第12章-武装飞船

们来开发一个名为《外星人入侵》的游戏吧!为此将使用Pygame,这是一组功能强大而有趣的模块,可用于管理图形、动画乃至声音,让你能够更轻松地开发复杂的游戏。通过使用Pygame来处理在屏幕上绘制图像等任务,可将重点放在程序的高级逻辑上。

开始游戏项目

创建Pygame 窗口以及响应用户输入

alien_invasion.py

import sys
import pygame
from setting import Setting


class AlienInvasion:
    """Classes for managing game resources and behaviors"""

    def __init__(self):
        """Initialize the game and create game assets. """
        pygame.init()
        self.settings = Setting()
        self.screen = pygame.display.set_mode((self.settings.screen_with, self.settings.screen_heith))
        pygame.display.set_caption("Alien Invasion")

    def run_game(self):
        """Start the main loop 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 most recently drawn screen visible.
            # The screen is redrawn each time through the loop.
            self.screen.fill(self.settings.bg_color)
            pygame.display.flip()


if __name__ == '__main__':
    # Create a game instance and run the game.
    ai = AlienInvasion()
    ai.run_game()

setting.py

class Setting:
    """A class that stores all settings in the game Alien Invasion. """
    def __init__(self):
        """Initialize the game's settings. """
        # screen settings.
        self.screen_with = 800
        self.screen_heith = 500
        self.bg_color=(230, 230, 230)

添加飞船图像

ship.py

import pygame
from _class.setting import Setting


class Ship:
    """管理飞船的类"""

    def __init__(self, ai_game):
        pygame.init()
        """初始化飞船并设置其初始位置"""
        self.screen = ai_game.screen
        self.settings = Setting()
        self.screen_rect = ai_game.screen.get_rect()
        # Load the spaceship image and get its bounding rectangle.
        self.image = pygame.image.load('images/ship.bmp')
        self.rect = self.image.get_rect()
        # For each new ship, center it at the bottom of the screen.
        self.rect.midbottom = self.screen_rect.midbottom
        self.x = float(self.rect.x)
        self.y = float(self.rect.y)
        # Mobile sign.

        self.moving_up = False
        self.moving_down = False
        self.moving_right = False
        self.moving_left = False

    def update(self):
        """Adjust the position of the ship according to the moving flag. """
        if self.moving_right and self.rect.right < self.screen_rect.right:
            self.x += self.settings.ship_speed
        if self.moving_left and self.rect.left > 0:
            self.x -= self.settings.ship_speed
        self.rect.x = self.x

        if self.moving_up and self.rect.top > 0:
            self.y -= self.settings.ship_speed
        if self.moving_down and self.rect.bottom < self.screen_rect.bottom:
            self.y += self.settings.ship_speed
        self.rect.y = self.y

    def blitme(self):
        """在指定位置绘制飞船"""
        self.screen.blit(self.image, self.rect)

setting.py

class Setting:
    """A class that stores all settings in the game Alien Invasion. """
    def __init__(self):
        """Initialize the game's settings. """
        # screen settings.
        self.screen_with = 800
        self.screen_heith = 500
        self.bg_color=(137, 214, 255)
        self.ship_speed = 1.5

alien_invasion.py

import sys
import pygame
from _class.setting import Setting
from _class.ship import Ship


class AlienInvasion:
    """Classes for managing game resources and behaviors"""

    def __init__(self):
        """Initialize the game and create game assets. """
        pygame.init()
        self.settings = Setting()
        # self.screen = pygame.display.set_mode((self.settings.screen_with, self.settings.screen_heith))
        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height
        pygame.display.set_caption("Alien Invasion")
        self.ship = Ship(self)

    def _update_screen(self):
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()

    def _check_event(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)

    def _check_keydown_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_UP:
            self.ship.moving_up = True
        elif event.key == pygame.K_DOWN:
            self.ship.moving_down = True
        elif event.key == pygame.K_q:
            sys.exit()

    def _check_keyup_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        if event.key == pygame.K_LEFT:
            self.ship.moving_left = False
        if event.key == pygame.K_UP:
            self.ship.moving_up = False
        if event.key == pygame.K_DOWN:
            self.ship.moving_down = False

    def run_game(self):
        """Start the main loop of the game. """
        while True:
            self._check_event()
            self.ship.update()
            self._update_screen()
            pygame.display.flip()

images
ship.png

调用

main.py

from _class.alien_invasion import AlienInvasion
ai = AlienInvasion()
ai.run_game()

添加射击功能

让外星人群移动