Skip to content

Session 1: Introductions, Games, Architecture, Engine

:material-circle-edit-outline: 约 263 个字 :fontawesome-solid-code: 20 行代码 :material-clock-time-two-outline: 预计阅读时间 1 分钟

S01_GameArchPygame.pdf

game loop

Each time around the loop:

  1. Check for inputs (from user, network, ...)
  2. Update game state, based on those inputs
  3. Draw the next frame, based on that state
Normal structure of a game 
initialize_game() 
while not done: 
    *user_inputs, done = get_inputs() 
    game_state = update_game_state(user_inputs) 
    render_game(game_state)

Frame

One picture is rendered (calculated and shown to user) each time around the loop

This is a frame

"FPS" -- frames per second

Event Queue

Pygame manages user inputs (and a few other features) with an event queue

Queue: a list. First-in-First-Out

Event: an object representing something happening in the system

Each time around the game loop, you must handle all the events in the queue

Example event processing 
def get_inputs(): 
    done = left = right = False 
    for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            done = True 
        elif event.type == pygame.KEYDOWN: 
            if event.key == pygame.K_ESCAPE: 
                done = True 
            elif event.key == pygame.K_RIGHT: 
                right = True 
            elif event.key == pygame.K_LEFT: 
                left = True 
    return (left, right, done)

game architecture

MVC: model-view-controller

MVC is a common architectural style for GUI, web applications and games

Model

Manages the data and operations on the data

Provides a well-defined interface to the data

In web and many GUI apps, the model is a database

View

Provides a way to visualize the data

Draw the frame, make the music, rumble, etc

Controller

Handles input

Maps input actions to model or view actions

Graphics

Engine

An engine provides some level of graphic algorithms to be embedded in your code

Image

Alpha Channels: An extra 8-bits specifies the amount of transparency

0 = transparent, 255 = opaque

The Surface

In Pygame, a surface is a place to draw

a canvas on which an artist places paint

Or, as a bank of memory where all those pixels are stored

Special surface: the display surface -- will be visible to the user in the game window

image-20241124104201997

image-20241124104315601

Colorkey 设置后,During a blit, any Colorkey pixel will not be copied