Last active
January 8, 2023 11:43
-
-
Save niihelium/2fb537d4e7e6815bf9bbba978426c913 to your computer and use it in GitHub Desktop.
Example Effects Manager in C#
This file contains 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; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Timers; | |
namespace EffectsManager | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
EffectManager em = new EffectManager((change, effect) => | |
{ | |
Console.WriteLine("Effect: " + effect.ToString() + " is " + change.ToString()); | |
}); | |
em.AddEffect(Effect.Type.Slow, 0.05f, 5000L); | |
em.AddEffect(Effect.Type.SpeedIncrease, 0.15f, 3000L); | |
while (true) { | |
} | |
} | |
} | |
} | |
public class Effect | |
{ | |
public enum Type | |
{ | |
Slow, | |
SpeedIncrease, | |
SpeedDecrease, | |
} | |
public Type type; | |
public long until; | |
public float strength; | |
public Effect(Type type, float strength, long until) | |
{ | |
this.type = type; | |
this.strength = strength; | |
this.until = until; | |
} | |
} | |
class EffectManager | |
{ | |
public enum EffectChange | |
{ | |
Added, Ended | |
} | |
Action<EffectChange, Effect.Type> onEffectChange; | |
SortedList<long, Effect> queue = new SortedList<long, Effect>(); | |
public EffectManager(Action<EffectChange, Effect.Type> effectChangeListener) | |
{ | |
onEffectChange = effectChangeListener; | |
} | |
internal void AddEffect(Effect.Type effect, float strength, long duration) | |
{ | |
long until = DateTimeOffset.Now.ToUnixTimeMilliseconds() + duration; | |
queue.Add(until, new Effect(effect, strength, DateTimeOffset.Now.ToUnixTimeMilliseconds() + duration)); | |
onEffectChange(EffectChange.Added, effect); | |
UpdateTimer(); | |
} | |
private void UpdateTimer() | |
{ | |
if (queue.Count == 0) | |
return; | |
Effect next = queue.First().Value; | |
if (next != null) | |
{ | |
long interval = next.until - DateTimeOffset.Now.ToUnixTimeMilliseconds(); | |
System.Timers.Timer timer = new System.Timers.Timer(interval); | |
timer.Elapsed += RemoveEffect; | |
timer.Enabled = true; | |
} | |
} | |
private void RemoveEffect(Object source, ElapsedEventArgs e) | |
{ | |
if (queue.Count == 0) | |
return; | |
Effect ended = queue.First().Value; | |
queue.RemoveAt(0); | |
onEffectChange(EffectChange.Ended, ended.type); | |
UpdateTimer(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment