Pygame is installed, but when I try to run my program the window won't open

Question:

I am trying to do a project from an intro to Python book I found. I have pygame 2.1.2 and Python 3.10.5 installed, and my code runs without displaying any errors. The issue is that the pygame window does not open when I try to run my code. Here is my code:

import sys

import pygame

from settings import Settings
from ship import Ship

class AlienInvasion:
    """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_cpation("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.
            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()
Asked By: Rain

||

Answers:

The code should work after a few changes: pygame.display.set_caption() is misspelled, but more importantly the code doesn’t even run because of the space in __ main__. Lastly, you should call pygame.quit() before sys.exit() to avoid pygame from crashing.

Answered By: nonlinear
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.