Sunday, January 12, 2014

Why Party Animals is using a Finite State Machine



We finally decided on a game flow for Party Animals. This time we have something more complex than just answering multiple choice questions every turn.

Note: Answering the same multiple choice question every turn is bad game design.

Now that we have a rough idea on how the game is going to work each turn, the next step in the game dev process is for me, the programmer, to design how it is going to be implemented.

The game is a turn based 2-player game so I came up with a classic solution:

Finite State Machines (FSM)


"State machines" is a useful world modeling concept from computer science. Here's what Wikipedia says about it. The key concepts here are 1) a machine has a finite set of states 2) the machine is in one of those states at any given time 3) the machine changes to another state through a transition.

In games, screen management is a common example. One screen shows you the Main Menu screen, then depending on the user input in that state you can either transition to a Settings screen or a New Game screen, New Game screen transitions to a High Score screen or a Game Over screen and so on. It's a neat way to structure your code; everything a state does is contained inside one code block and interaction with other screens are done through transitions.

So how does that apply to the game?


I write my codes on paper like a hipster do


In the game, the player turn cycle is an FSM. A player starts in the My Turn state -- in it, his avatar is shown and his UI is reactivated. If the player selects to move his avatar to a district, the game transitions into the Move state -- the avatar is shown moving to the desired location. Since the Move state doesn't rely on user input, it can immediately transition into the End Turn state once the animations are done. In the End Turn state, we can decide to show more effects, animate the avatar to "sit" etc. (This is just an example, I ended up with plenty of states for the game.)

What's important is that these states are contained in one block of code -- a class, or a function. You want to have draw confetti when a turn is done? Fine, let's add that in the End Turn state. You want to have a minigame that determines if a player can move to the location or not? Write a MiniGame state that transitions to the Move or Stay state depending on the result. We can even assign a "controller" into each state for it to differentiate between a human or a computer AI taking a turn.

Am I over-engineering this? That's what I thought at first when I was sketching down the design on paper. But after I coded it and was amazed at how easily the pieces seem to snap together with the entire game, I imaginarily thanked my professor for not being boring back in Computer Science school.

0 comments:

Post a Comment

 

Party Animals Copyright © 2011 -- Template created by O Pregador -- Powered by Blogger