2

I am doing Python Crash Course Alien invasion and when I test this code, the image of the ship doesn't appear. It is just a black background.

I've been trying for so long to find out why.

The game code (alien_invasion.py):

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


def run_game():
    # Initialize pygame, settings, and screen object.
    pygame.init()
    ai_settings = Settings()
    
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    
    screen.fill(ai_settings.bg_color)
    # Make a ship.
    ship = Ship(screen)

    # Background color
    bg_color = (230, 230, 230)

    # Start the main loop for the game
    while True:

        ship.blitme()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
                self.screen.fill(self.settings.bg_color)
                pygame.display.flip()
run_game()

Settings code (settings.py):

class Settings():
   """Initialize the game's settings."""
   # Screen settings
  def __init__(self):
    self.screen_width = 1200
    self.screen_height = 800
    self.bg_color = (230, 230, 230)

Ship code (ship.py):

import pygame

class Ship():
    def __init__(self, screen):
        self.screen = screen
        # Load the ship image and get its rect.
        self.image = pygame.image.load(r'C:\Users\user\Desktop\alien invasion\ship.bmp')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()
        # Start each new ship at the bottom center of the screen.
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

    def blitme(self):
        self.screen.blit(self.image, self.rect)

No error comes up, but when I run this code nothing happens. Just a black screen.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Allen Chen
  • 31
  • 1
  • 5
  • for `.blit()` arguments are `surface` and `position` (position as a tuple) like this: `.blit(surface, (x, y))` where surface would be your image in this case and `x` and `y` the according positions – Matiiss Nov 02 '20 at 19:00

1 Answers1

2

It is a matter of Indentation. You have to update the display in the main application loop.
Furthermore you need to draw the ship after drawing the background:

def run_game():
    # [...]

    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
    
        #<--| INDENTATION

        # draw background        
        screen.fill(ai_settings.bg_color)

        # draw scene (ship)
        ship.blitme()

        # update disaply
        pygame.display.flip()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174