Skip to content

Instantly share code, notes, and snippets.

@peterthorsteinson
Created October 30, 2019 16:47
Show Gist options
  • Save peterthorsteinson/1e16bc8d0a2fb7715ba62065fd2914a5 to your computer and use it in GitHub Desktop.
Save peterthorsteinson/1e16bc8d0a2fb7715ba62065fd2914a5 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Timers;
class Program
{
static List<Bot> bots = new List<Bot>();
static void Main()
{
Console.CursorVisible = false;
Bot bot1 = new Bot(10, 20, ConsoleColor.Yellow);
bot1.Moved += HandleBotMoved;
bots.Add(bot1);
Bot bot2 = new Bot(20, 10, ConsoleColor.Red);
bot2.Moved += HandleBotMoved;
bots.Add(bot2);
bot1.Start();
bot2.Start();
Console.ReadLine();
foreach (var bot in bots) bot.Stop();
}
static void HandleBotMoved(Bot bot)
{
Console.ForegroundColor = bot.color;
Console.SetCursorPosition(bot.x_prev, bot.y_prev);
Console.Write(' ');
Console.SetCursorPosition(bot.x, bot.y);
Console.Write('*');
}
}
class Bot
{
public int x_prev = 0;
public int y_prev = 0;
public int x = 0;
public int y = 0;
public ConsoleColor color = ConsoleColor.White;
Timer timer;
public event Action<Bot> Moved;
static Random random = new Random();
static object syncObj = new object { };
public Bot(int x, int y, ConsoleColor color)
{
this.x = x;
this.y = y;
this.color = color;
timer = new Timer(100);
timer.Elapsed += OnTimerEvent;
}
~Bot()
{
timer.Dispose();
}
public void Start()
{
timer.AutoReset = true;
timer.Enabled = true;
timer.Start();
}
public void Pause()
{
timer.Enabled = false;
}
public void Stop()
{
timer.Stop();
}
void OnTimerEvent(Object source, ElapsedEventArgs e)
{
lock (syncObj)
{
x_prev = x;
y_prev = y;
x += random.Next(-1, +2);
if (x < 0) x += 1; if (x > 20) x -= 1;
y += random.Next(-1, +2);
if (y < 0) y += 1; if (y > 20) y -= 1;
Moved?.Invoke(this);
}
}
}
@peterthorsteinson
Copy link
Author

BrownianBotsWithTimerEvent

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment