Start a game with pygame

The following code sets up an empty game window, and starts an event loop and a loop that continually refreshes the screen.

An empty game window

import sys
import pygame as pg
def run_game():
    # Initialize and set up screen.
    pg.init()
    screen = pg.display.set_mode((1200, 800))
    pg.display.set_caption("Alien Invasion")

    # Start main loop.
    while True:
        # Start event loop.
        for event in pg.event.get():
            if event.type == pg.QUIT:
                sys.exit()

        # Refresh screen.
        pg.display.flip()

run_game()

Setting a custom window size

The display.set_mode() function accepts a tuple that defines the
screen size.

screen_dim = (1200, 800)
screen = pg.display.set_mode(screen_dim)

Setting a custom background-color

Colors are defined as a tuple of red, green, and blue values. Each value ranges from 0-255.

bg_color = (230, 230, 230)
screen.fill(bg_color)

Leave a Reply

Your email address will not be published. Required fields are marked *