Как объект корабля узнает, что он отображается в центре нижней части главного экрана? - PullRequest
0 голосов
/ 15 апреля 2020

Это соответствующие исходные файлы:

1. ship.py

#!/usr/bin/python3

import pygame

class Ship(object):
    """A class to manage the ship."""

    def __init__(self, ai_game):
        """Initialize the ship and set its starting position."""
        self.screen = ai_game.screen
        self.screen_rect = ai_game.screen.get_rect()

        # Load the ship image and get its rect.
        self.image = pygame.image.load('images/ship.bmp')
        self.rect = self.image.get_rect()

        # Start each new ship at the bottom center of the screen.
        self.rect.midbottom = self.screen_rect.midbottom

    def blitme(self):
        """Draw the ship at its current location."""
        self.screen.blit(self.image, self.rect)

2. alien_invasion.py

#!/usr/bin/python3

import pygame
from sys import exit
from settings import Settings
from ship import Ship

class AlienInvasion(object):
    """Overall class to manage game assets and behavior."""

    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Alien Invasion")

        self.ship = Ship(self)

    def run_game(self):
        """Start the main loop for the game"""
        while True:
            # Watch for keyboard and mouse events. ** The Event Loop **
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()

            # Redraw the screen during each pass through the loop
            self.screen.fill(self.settings.bg_color)
            self.ship.blitme()

            # Make the most recently drawn screen visible.
            pygame.display.flip()

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

Запуск alien_invasion.py дает следующий вывод ... enter image description here ... который является желаемым выводом. Я просто не понимаю, как корабль rect расположен (правильно) по центру снизу, когда метод Ship.blitme() принимает параметры image и rect (а не rect.midbottom). Насколько я понимаю, атрибут self.rect.midbottom нигде не используется для рисования изображения на экране после его определения.

TIA!

1 Ответ

1 голос
/ 15 апреля 2020

Когда вы создаете экземпляр класса корабля, вы перемещаете его прямоугольник в нижнюю середину экрана с помощью self.rect.midbottom = self.screen_rect.midbottom. Это также перемещает rect.x и rect.y, поэтому, когда вы моргаете кораблем с помощью прямоугольника, он уже расположен вправо

...