Session 1: Introductions, Games, Architecture, Engine
game loop
Each time around the loop:
- Check for inputs (from user, network, ...)
- Update game state, based on those inputs
- 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
Colorkey 设置后,During a blit, any Colorkey pixel will not be copied