JSFiddle - React, Tailwind, and code Playground
CSS
body {
padding: 0;
margin: 0;
background-color: #000;
}
.shoo {
width: 50px;
height:50px;
background-color:#555;
color: white;
text-align: center;
position:fixed;
cursor: pointer;
}
JavaScript
var i = 0;
var x = 0;
$(document).ready(function(){
spawnFly();
});
function spawn() {
var clone = document.createElement('div');
clone.className = "shoo";
var buzz = document.createElement('p');
buzz.innerHTML = "BUZZ";
clone.appendChild(buzz);
clone.onclick = swat;
document.body.appendChild(clone);
animateDiv($(clone)); // animate the spawned fly
}
function swat() {
var id = $(this).remove();
x--; // removes a fly from the swarm
}
function spawnFly() {
if(x >= 15){
alert("YOU LOST\n15 Flys have infested your screen!");
}
else if(x < 15) {
x++; // adds another fly to the counter
setTimeout(spawnFly, 2000); // spawns a new fly after a few secs
spawn(); // called recursively until fly count is met
}
}
function makeNewPosition(){
var h = $(window).innerHeight() - 50;
var w = $(window).innerWidth() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
function animateDiv($e){
var newq = makeNewPosition();
var oldq = $e.offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$e.animate({ top: newq[0], left: newq[1] }, speed, function(){
animateDiv($e);
});
};
function calcSpeed(prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = 0.1;
var speed = Math.ceil(greatest/speedModifier);
return speed;
}