<< Back

Infection simulation

I wanted to make this thing for so long, and yet I've never actually sat down and given it any thought. Well, yesterday I didn't feel particularly sleepy, so I decided to just try to write it.

And it only took 30 minutes or so - most of it was spent trying to figure out why I couldn't stop infinite endless recursion. Turns out, I forgot that you can't compare arrays in Javascript via a simple equation.

After I got that figured out, everything went butter smooth. Now, I won't go step by step here like in a normal tutorial, but I will show you the entire thing and explain some of it. I also made you a demo here. Go ahead and click anywhere on the canvas and see the infection spread. Just like a real infection, it takes a little bit of time to spread, so have patience!

Also I have just realized its kinda spooky-themed so hey, look at me, I'm participating in Halloween!

Anyway, here is the code:

It looks long, but really its actually quite a lot shorter than most the code I write. I was surprised.

I borrowed some functions from StackOverflow, no shame in that. Why reinvent the wheel? Otherwise, everything else is my own code. I'm using recursion to enable the "infection" to spread continuously.

Once you click on a spot, it gets it's own little process attached and it repeats until its infected (10 in 1000 chance of that happening), then once it has successfully been infected, it colors itself red, and constructs a grid of 3x3 around itself. Then it starts randomly picking spots out of that grid, and if the spot isn't infected yet, it attaches the infection process to it and everything repeats!

Recursion is tricky to get right, but boy is it fun when you do. I should show you how to make minesweeper in JS using recursion sometime.

Anyway, sorry I am a day late to the Halloween stuff. Hope this article was spooky enough! (I mean there's recursion, thats spooky, right? Right?)