JSFiddle - React, Tailwind, and code Playground
by EastJesus
HTML
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="ball">
</div>
<div id="apple">
</div>
CSS
#ball{
width: 10px;
height: 10px;
background: blue;
position: absolute;
top: 100px;
left: 100px;
transition: all 0.3s;
border-radius: 50%;
z-index: 2;
}
#apple{
width: 10px;
height: 10px;
background: green;
position: absolute;
transition: top 1s, left 1s, opacity 0.1s;
border-radius: 50%;
}
Babel + JSX
var ball = $("#ball");
var apple = $("#apple");
var leftDistance = Math.abs(parseInt(ball.css("left"), 10) - parseInt(apple.css("left"), 10));
var topDistance = Math.abs(parseInt(ball.css("top"), 10) - parseInt(apple.css("top"), 10));
var appleLeft = 0;
var appleTop = 0;
var eatDistance = 10;
class Ball{
constructor(top, left){
this.top = top;
this.left = left;
}
refreshDistance(){
leftDistance = Math.abs(parseInt(ball.css("left"), 10) - parseInt(apple.css("left"), 10));
topDistance = Math.abs(parseInt(ball.css("top"), 10) - parseInt(apple.css("top"), 10));
}
increase(){
ball.css("width", "+=10");
ball.css("height", "+=10");
}
}
var ballCoords = new Ball(100, 100);
class Apple{
constructor(top, left){
this.top = top;
this.left = left;
}
toHide(){
apple.css("opacity", "0");
apple.css("top", "-1000px");
}
getRandom(){
appleLeft = Math.floor(50 + Math.random() * 200);
appleTop = Math.floor(50 + Math.random() * 200);
apple.css({
'left' : appleLeft,
'top' : appleTop
})
}
begin(){
appleLeft = Math.floor(50 + Math.random() * 200);
appleTop = Math.floor(50 + Math.random() * 200);
apple.css({
'left' : appleLeft,
'top' : appleTop,
'opacity' : '1'
})
}
}
var appleCoords = new Apple(150, 150);
appleCoords.begin();
setInterval(function(){
appleCoords.getRandom();
}, 1000)
$(document).keydown(function(e){
var event = e.which;
switch(event){
case 37:
ball.css("left", "-=10");
break;
case 38:
ball.css("top", "-=10");
break;
case 39:
ball.css("left", "+=10");
break;
case 40:
ball.css("top", "+=10");
break;
}
ballCoords.refreshDistance();
if(leftDistance <= eatDistance && topDistance <= eatDistance){
appleCoords.toHide();
ballCoords.refreshDistance();
ballCoords.increase();
eatDistance += 3;
appleCoords = new Apple(150, 150);
...