ehmatthes / pcc

Resources for Python Crash Course, from No Starch Press.
2.96k stars 1.85k forks source link

Chapter 13 - The Aliens cannot move in the X axis #104

Closed STEFANOVIVAS closed 3 years ago

STEFANOVIVAS commented 3 years ago

My code is exactly the same as the book but I can't get the aliens to move laterally, just on the vertical axis.

alien.py

` class Alien(Sprite):

    def __init__(self, ai):
    super().__init__()
    self.screen = ai.screen
    self.settings = ai.settings
    # load alien image
    self.image = pygame.image.load('images/alien.bmp')
    self.rect = self.image.get_rect()
    # start each new alien near the top left of the screen
    self.rect.x = self.rect.width
    self.rect.y = self.rect.height

    # Store the alien's position as a decimal value.
    self.x = float(self.rect.x)

def update(self):
    """Move the alien right or left."""
    self.x += (self.settings.alien_speed * self.settings.fleet_direction)
    self.rect.x = self.x

def check_edges(self):
    """Return true if alien is at edge of screen"""
    screen_rect = self.screen.get_rect()
    if self.rect.right >= screen_rect.right or self.rect.left <= 0:
        return True`

alien_invasion.py

` class AlienInvasion:

    def __init__(self):
    pygame.init()
    self.settings = Settings()
    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
    # Surface: Part of the screen where a game element can be displayed.
    pygame.display.set_caption("Alien invasion")
    self.ship = Ship(self)
    self.bullets = pygame.sprite.Group()
    self.aliens = pygame.sprite.Group()

    self._create_fleet()

def run_game(self):
    # """Inicia o loop principal para o jogo."""
    while True:
        self._check_events()
        self.ship.update()
        self._update_bullets()
        self._update_aliens()
        self._update_screen()

def _check_events(self):
    """ aguarda por eventos gerados pelo mouse ou teclado"""
    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_q:
        sys.exit()
    elif event.key == pygame.K_SPACE:
        self.fire_bullet()

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

def _update_bullets(self):
    self.bullets.update()
    for bullet in self.bullets.copy():
        if bullet.rect.bottom <= 0:
            self.bullets.remove(bullet)
    pygame.sprite.groupcollide(
        self.bullets, self.aliens, True, True
    )

def fire_bullet(self):
    if len(self.bullets) < self.settings.bullets_allowed:
        new_bullet = Bullet(self)
        self.bullets.add(new_bullet)

def _create_fleet(self):
    alien = Alien(self)
    alien_width, alien_height = alien.rect.size
    available_space_x = self.settings.screen_width - (2 * alien_width)
    number_aliens_x = available_space_x // (2 * alien_width)

    # Determine the number of rows of aliens that fit on the screen.
    ship_height = self.ship.rect.height
    available_space_y = (self.settings.screen_height -
                         (3 * alien_height) - ship_height)
    number_rows = available_space_y // (2 * alien_height)
    for row_number in range(number_rows):
        for alien_number in range(number_aliens_x):
            self._create_alien(alien_number, row_number)

def _create_alien(self, alien_number, row_number):
    alien = Alien(self)
    alien_width, alien_height = alien.rect.size
    alien.x = alien_width + 2 * alien_width * alien_number
    alien.rect.x = alien.x
    alien.y = alien_height + 2 * alien_height * row_number
    alien.rect.y = alien.y
    self.aliens.add(alien)

def _check_fleet_edges(self):
    for alien in self.aliens.sprites():
        if alien.check_edges:
            self._change_fleet_direction()
            break

def _change_fleet_direction(self):
    for alien in self.aliens.sprites():
        alien.rect.y += self.settings.fleet_drop_speed
    self.settings.fleet_direction *= -1

def _update_aliens(self):
    self.aliens.update()
    self._check_fleet_edges()

def _update_screen(self):
    """Update images on the screen, and flip to the new screen."""
    self.screen.fill(self.settings.bg_color)
    self.ship.blitme()
    for bullet in self.bullets.sprites():
        bullet.draw_bullet()
    self.aliens.draw(self.screen)
    pygame.display.flip()

if name == 'main': ai = AlienInvasion() ai.run_game() ` settings.py

` class Settings: def init(self):

Screen setings

    self.screen_width = 1366
    self.screen_height = 768
    self.bg_color = (230, 230, 230)
    self.ship_speed = 1.5

    # Bullet settings
    self.bullet_speed = 1.0
    self.bullet_width = 3
    self.bullet_height = 15
    self.bullet_color = (60, 60, 60)
    self.bullets_allowed = 3

    # alien settings
    self.alien_speed = 1.0
    self.fleet_drop_speed = 10
    self.fleet_direction = 1

`

ehmatthes commented 3 years ago

In order to test this I would have to copy all of this code into separate files, fix some indentation, and then try to run it. And it probably wouldn't be the exact same code you're running, because of the indentation issues.

Can you either post your code to a separate GitHub repo and link to it, or email me a zip file of your project? I'm ehmatthes at gmail.

Also, this looks like code from the second edition, but you're in the online resources for the first edition. If it helps in any way, the second edition resources are here: https://ehmatthes.github.io/pcc_2e/regular_index/

STEFANOVIVAS commented 3 years ago

Yeah..you are right. I'm in the wrong edition. Anyway..i just found the error..a missing pair of brackets in the alien.check_edges funcition. Rsrsrs Sorry