Skip to content

Instantly share code, notes, and snippets.

@niihelium
Last active January 8, 2023 11:43
Show Gist options
  • Save niihelium/2fb537d4e7e6815bf9bbba978426c913 to your computer and use it in GitHub Desktop.
Save niihelium/2fb537d4e7e6815bf9bbba978426c913 to your computer and use it in GitHub Desktop.
Example Effects Manager in C#
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