State Machine


This is part of a series on how this game was implemented technically, as part of the Game Jam it was developed for. It is recommended to read them roughly in-order as later blog entries may refer to earlier ones.

Technical:

  1. State Machine
  2. Pathfinding/Movement
  3. Isometric Rendering
  4. API
  5. Control Sources
  6. AI
  7. Networking
  8. Fog of War
  9. Bit Packing
  10. Palette Shifting

Other:

----

State Machine

Unlike many games, which use many objects with collisions, physics, etc. Turn-based games can be modelled differently. 

This game is stored as a grid, which holds the terrain, characters, movement, attack, etc. Which actions a player can take depend on the "state" of the grid. Essentially each state is a single mode with well-defined transitions to the other states: 

  • Idle
  • Move
  • Target

Idle

If the user clicks on a unit, fill the movement and attack grids and the state becomes "display movement"

Display Movement

If the user clicks on a blue square that's free, move the unit to that location and the fill the attack grid for just that new location, then set the state to "select target".

If the user clicks on a red square that has an enemy unit, find a corresponding blue square that matches it, then do movement as before

Select Target

If the user clicks on a red square with an enemy unit, do the battle calculation then set the unit to wait, and set the state to "idle"

If the user clicks on the unit itself, just set to wait without doing an attack and progress back to "idle"

-----

By handling just these transitions (and the ability to cancel back to idle) the entire game logic can be captured in just a handful of functions. These are functions like "getUnitAtPosition", "fillMovement", "fillAttack", etc.

The only information that needs to persist between states is the unit's idle position and their post-movement position, in case the user wants to cancel an action. All other game information can be regenerated just by calling the right functions in response to use actions (clicks)  

Files

index.zip Play in browser
Jul 07, 2022

Leave a comment

Log in with itch.io to leave a comment.