I’m fairly new to coding and working on the Alien Invasion project in the book Python Crash Course. However, I’ve run into an issue after creating the alien fleet wherein the game runs very, very slowly. This shouldn’t be an issue with my computer as it’s pretty new and can run far more complex tasks without any issues. Here’s the relevant code:
In the file alien_invasion.py (the main game file):
def run_game():
#start the game. init initializes the background.
#screen draws the screen with its size.
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("Alien Invasion")
#colors in RGB
bg_color = (230, 230, 230)
#Makes a ship, bullets, and aliens
ship = Ship(ai_settings, screen)
bullets = Group()
alien = Alien(ai_settings, screen)
aliens = Group()
#Make an alien fleet
gf.create_fleet(ai_settings, screen, ship, aliens)
#start the main loop
while True:
gf.check_events(ai_settings, screen, ship, bullets)
ship.update()
bullets.update()
gf.update_bullets(aliens, bullets)
gf.update_aliens(ai_settings, aliens)
gf.update_screen(ai_settings, screen, ship, aliens, bullets)
run_game()
And in the game_functions file:
def get_number_aliens_x(ai_settings, alien_width):
#Determines how many aliens fit in a row
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):
#Determines how many rows of aliens to make
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_alien(ai_settings, screen, aliens, alien_number, row_number):
#Creates an alien and places it in the row
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):
#Creates a fleet of 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)
#Creates the first row of aliens and places them
for row_number in range(number_rows):
for alien_number in range(number_aliens_x):
create_alien(ai_settings, screen, aliens, alien_number, row_number)
Can anyone spot why it might be running so slowly?