Skip to content

Instantly share code, notes, and snippets.

@hk0i
Last active August 2, 2023 04:06
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 hk0i/d59c324520669db1057d878530cc398d to your computer and use it in GitHub Desktop.
Save hk0i/d59c324520669db1057d878530cc398d to your computer and use it in GitHub Desktop.
testing generics, interfaces and state machines
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
public class TestMaps
{
[Test]
public void CyclicDependency()
{
var machine = new FakeMachine<FakeStates, IFakeState>();
machine.Register(FakeStates.Attack, new FakeAttackState(machine));
machine.Register(FakeStates.Jump, new FakeJumpState(machine));
machine.Switch(FakeStates.Attack);
}
}
public class FakeJumpState: IFakeState
{
readonly FakeMachine<FakeStates,IFakeState> _machine;
public FakeJumpState(FakeMachine<FakeStates,IFakeState> machine)
{
_machine = machine;
}
public void OnStart()
{
Debug.Log("Jumped!");
}
~FakeJumpState()
{
Debug.Log("Cleaned fake jump");
}
}
public class FakeAttackState: IFakeState
{
readonly FakeMachine<FakeStates, IFakeState> _machine;
public FakeAttackState(FakeMachine<FakeStates, IFakeState> machine)
{
_machine = machine;
}
public void OnStart()
{
Debug.Log("Attacked!");
_machine.Switch(FakeStates.Jump);
}
~FakeAttackState()
{
Debug.Log("Cleaned fake attack");
}
}
public interface IFakeState
{
void OnStart();
}
public class FakeMachine<TStateKey, TStateValue> where TStateValue: IFakeState
{
Dictionary<TStateKey, TStateValue> _stateMap = new();
TStateValue CurrentState => _currentState;
TStateValue _currentState;
public void Register(TStateKey key, TStateValue value)
{
_stateMap.Add(key, value);
}
public void Switch(TStateKey stateKey)
{
Assert.True(_stateMap.ContainsKey(stateKey));
var state = _stateMap[stateKey];
state.OnStart();
}
~FakeMachine()
{
Debug.Log("Cleaned fake machine");
}
}
public enum FakeStates
{
Jump,
Attack,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment