Last active
August 2, 2023 04:06
-
-
Save hk0i/d59c324520669db1057d878530cc398d to your computer and use it in GitHub Desktop.
testing generics, interfaces and state machines
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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