Skip to content

Instantly share code, notes, and snippets.

@adammyhre
Created October 26, 2024 16:50
Show Gist options
  • Save adammyhre/9cc8154d2c79c3b9154dc1c70d4d56cd to your computer and use it in GitHub Desktop.
Save adammyhre/9cc8154d2c79c3b9154dc1c70d4d56cd to your computer and use it in GitHub Desktop.
Stack-Based Finite State Machine (Push Down Automata)
using System.Collections.Generic;
namespace Automata {
public abstract class State {
protected readonly PushDownAutomata pda;
protected State(PushDownAutomata pda) {
this.pda = pda;
}
public abstract void Enter();
public abstract void Update();
public abstract void Exit();
}
public struct Context {}
public class PushDownAutomata {
readonly Stack<State> stateStack = new();
public State CurrentState => stateStack.Count > 0 ? stateStack.Peek() : null;
public Context context;
public PushDownAutomata(Context context) {
this.context = context;
}
public void PushState(State newState) {
stateStack.Push(newState);
newState.Enter();
}
public void PopState() {
if (stateStack.Count == 0) return;
CurrentState.Exit();
stateStack.Pop();
}
public void Update() => CurrentState?.Update();
public void SetContext(Context context) => this.context = context;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment