This post shows how the behaviour of a rabbit can be coded using a finite state machine, by breaking down the rabbit’s behaviour into different states. The rabbit’s goal is to wander around and eat carrots, whilst avoiding the deadly mouse cursor!
The previous tutorial showed you how to code a bouncing ball using a finite state machine. This tutorial will take the concept further.
The tutorial uses Processing and the Java programming language. Visit my Processing page if you want to learn more about what you can achieve with coding.
Introduction
The rabbit is controlled using four states:
enum RabbitState
{
WANDER, SEEK, EAT, FLEE
};
The rabbit’s behaviour is coded inside a class called ‘Rabbit’. The rabbit has one function for each state it can be in. The switch case decides which state to execute.
void Update()
{
switch(state)
{
case WANDER:
WanderUpdate();
break;
case SEEK:
SeekUpdate();
break;
case EAT:
EatUpdate();
break;
case FLEE:
FleeUpdate();
break;
}
WrapAroundScreen();
}
Notice if the rabbit moves off the screen, then it’s position will be wrapped to the other side of the screen.
Wander
In the wander state, the rabbit will move in a random direction, until it gets close to a carrot. When a carrot is near, the rabbit will change to the seek state.

Seek
In the seek state the rabbit will move towards the nearest carrot. If the rabbit reaches the carrot, then it will enter the eat state. However if the carrot is eaten by another rabbit, then the rabbit will return to the wander state.

Eat
In the eat state, the rabbit will eat the carrot until the carrot has been completely eaten, then return to the wander state.

Flee
The last state is the flee state, which can be triggered in any of the other states. The rabbit will flee if the blue circle of doom overlaps the rabbit’s bounding circle. The blue circle of doom’s position is controlled by the mouse cursor, and can be used to protect the carrots!
When a rabbit is fleeing, it will move away from the mouse position until it has reached a safe distance, then it will return to the wander state.

Diagram
This diagram below shows all the states the rabbit can be in, and which states the rabbit can change to, based on it’s current state. For example if the rabbit is in the wander state, then it can only change to the seek or the flee state, depending on the condition.

Conclusion
Thanks for reading this post, I hope you found it interesting and learned how useful finite state machines can be!
For more finite state machine tutorials, check out:

