Skip to content

Instantly share code, notes, and snippets.

@eastmad
Last active August 31, 2022 21:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eastmad/b76b7f7e6862f683eb556fc4bb76f011 to your computer and use it in GitHub Desktop.
Save eastmad/b76b7f7e6862f683eb556fc4bb76f011 to your computer and use it in GitHub Desktop.
State Machine with Transitions
using TheNewStack;
namespace TheNewStack
{
public enum TVState { OFF, STANDBY, CHANNEL1, CHANNEL2}
public enum TVCommand { TURN_ON, TURN_OFF, SWITCH_TO_CHANNEL1, SWITCH_TO_CHANNEL2, SWITCH_OFF}
public struct Transition
{
public TVState FromState;
public TVState ToState;
public TVCommand Command;
public Transition(TVState fromState, TVState toState, TVCommand command)
{
FromState = fromState;
ToState = toState;
Command = command;
}
}
public class StateMachineWithTransitions
{
private List<Transition> permittedTransitions;
public TVState CurrentState;
public StateMachineWithTransitions()
{
permittedTransitions = new List<Transition>()
{
new Transition(TVState.OFF, TVState.STANDBY, TVCommand.TURN_ON),
new Transition(TVState.STANDBY, TVState.OFF, TVCommand.TURN_OFF),
new Transition(TVState.STANDBY, TVState.CHANNEL1, TVCommand.SWITCH_TO_CHANNEL1),
new Transition(TVState.CHANNEL2, TVState.CHANNEL1, TVCommand.SWITCH_TO_CHANNEL1),
new Transition(TVState.CHANNEL2, TVState.STANDBY, TVCommand.SWITCH_OFF),
new Transition(TVState.STANDBY, TVState.CHANNEL2, TVCommand.SWITCH_TO_CHANNEL2),
new Transition(TVState.CHANNEL1, TVState.CHANNEL2, TVCommand.SWITCH_TO_CHANNEL2),
new Transition(TVState.CHANNEL1, TVState.STANDBY, TVCommand.SWITCH_OFF),
};
CurrentState = TVState.OFF;
}
public Transition FindTransition(TVState fromState, TVCommand command)
{
Transition foundTransition = permittedTransitions.Find(transition => transition.FromState == fromState && transition.Command == command);
return foundTransition;
}
public bool DoCommand(TVCommand command)
{
bool result = false;
Transition transition = FindTransition(CurrentState, command);
if (transition.FromState == CurrentState)
{
CurrentState = transition.ToState;
Console.WriteLine(command + ": Now " + CurrentState);
result = true;
}
return result;
}
}
}
public class Program
{
static void Main(String[] args)
{
StateMachineWithTransitions s = new StateMachineWithTransitions();
s.DoCommand(TVCommand.TURN_ON);
s.DoCommand(TVCommand.SWITCH_TO_CHANNEL1);
s.DoCommand(TVCommand.SWITCH_TO_CHANNEL2);
s.DoCommand(TVCommand.SWITCH_TO_CHANNEL2);
s.DoCommand(TVCommand.TURN_ON);
s.DoCommand(TVCommand.SWITCH_OFF);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment