State Machine

At the highest level inside the main loop, the game program uses a state machine to behave the correct way at any given time, based on what the player has done so far. If you don't know what a state machine is, or just want a refresher there is a nice guide here: https://learn.adafruit.com/circuitpython-101-state-machines

GAME_STATE Object

The state machine in this game uses numbers to track the state and we give each number a descriptive variable name to use in the code.

The current state that the state machine is in gets stored in GAME_STATE["STATE"]. All of the possible states are in tilegame_assets\states.py:

# State machine constants

# playing the game: draw the map, listen for D-pad buttons to move player
STATE_PLAYING = 0

# player beat this map level
STATE_MAPWIN = 1

# waiting for player to press A button to continue
STATE_WAITING = 2

# player lost by touching sparky
STATE_LOST_SPARKY = 3

# minerva shows a fun fact
STATE_MINERVA = 4

The "STATE" item within the GAME_STATE dictionary is the only one that refers to the state machine logic. 

The rest of the items in the GAME_STATE dictionary store information about the current game and map. 

Here are the starting values:

Download: file
GAME_STATE = {
    # hold the map state as it came out of the csv. Only holds non-entities.
    "ORIGINAL_MAP": {},
    # hold the current map state as it changes. Only holds non-entities.
    "CURRENT_MAP": {},
    # Dictionary with touple keys that map to lists of entity objects.
    # Each one has the index of the sprite in the ENTITY_SPRITES list
    # and the tile type string
    "ENTITY_SPRITES_DICT": {},
    # hold the location of the player in tile coordinates
    "PLAYER_LOC": (0, 0),
    # list of items the player has in inventory
    "INVENTORY": [],
    # how many hearts there are in this map level
    "TOTAL_HEARTS": 0,
    # sprite object to draw for the player
    "PLAYER_SPRITE": None,
    # size of the map
    "MAP_WIDTH": 0,
    "MAP_HEIGHT": 0,
    # which map level within MAPS we are currently playing
    "MAP_INDEX": 0,
    # current state of the state machine 
    "STATE": STATE_PLAYING,
}

Their values will change as the map gets loaded and the player moves around and does things within the game. 

This guide was first published on Jun 10, 2020. It was last updated on Jun 10, 2020.

This page (Game Code Structure) was last updated on Apr 02, 2021.

Text editor powered by tinymce.