Skip to content

Instantly share code, notes, and snippets.

@t-tutiya
Created January 10, 2020 13:41
Show Gist options
  • Save t-tutiya/f78399201e818a5ec7fc3aa74d5f0833 to your computer and use it in GitHub Desktop.
Save t-tutiya/f78399201e818a5ec7fc3aa74d5f0833 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Tsukasa
{
abstract class PushDownStateMachine<StateType>
{
protected Stack<StateType> StateStack;
public PushDownStateMachine()
{
StateStack = new Stack<StateType>();
}
public void PushState(StateType command)
{
StateStack.Push(command);
}
public void PushStateList(IEnumerable<StateType> commandList)
{
foreach (var command in commandList.Reverse())
{
StateStack.Push(command);
}
}
public void EvalState()
{
while (true)
{
if (StateStack.Count == 0) return;
if (DispatchState(StateStack.Pop())) return;
}
}
protected abstract bool DispatchState(StateType state);
}
enum TacticalMethod { Attack, Guard, DubleAttackAndGurad, Wait };
class Knight : PushDownStateMachine<TacticalMethod>
{
protected override bool DispatchState(TacticalMethod command)
{
return command switch
{
TacticalMethod.Attack => Attack(),
TacticalMethod.Guard => Guard(),
TacticalMethod.DubleAttackAndGurad => DubleAttackAndGurad(),
TacticalMethod.Wait => Wait(),
_ => false,
};
}
private bool Attack()
{
Console.WriteLine("Attack!");
return false;
}
private bool Guard()
{
Console.WriteLine("Guard!");
return false;
}
private bool DubleAttackAndGurad()
{
PushStateList(new List<TacticalMethod>()
{
TacticalMethod.Attack,
TacticalMethod.Attack,
TacticalMethod.Guard
}
);
return false;
}
private bool Wait()
{
Console.WriteLine("Wait(Halt)");
return true;
}
}
class Program
{
static void Main()
{
var knight = new Knight();
knight.PushStateList(new List<TacticalMethod>()
{
TacticalMethod.Attack,
TacticalMethod.Guard,
TacticalMethod.Wait,
TacticalMethod.DubleAttackAndGurad,
});
knight.EvalState();
Console.WriteLine("====");
knight.EvalState();
Console.WriteLine("end");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment