JSFiddle - React, Tailwind, and code Playground

by Minko Gechev

HTML

<div class="box">
    <div class="ball"></div>
</div>
<button>Start</button>

CSS

html, body {
    height: 100%;
}

.ball {
    width: 40px;
    height: 40px;
    border-radius: 20px;
    background-color: #7CDE84;
    position: absolute;
    cursor: pointer;
}

.box {
    width: 300px;
    height: 300px;
    border-style: dashed;
    border-width: 10px;
    border-color: red;
    position: relative;
}

JavaScript

;(function () {
    function Ball(el, box, stepCallback) {
        this.el = el;
        this.width = el.width();
        this.height = el.height()
        this.box = box;
        this.stepCallback = stepCallback;
    }
    
    Ball.prototype.moveRand = function () {
        var rand = Math.random() * Math.PI;
        this.el.animate({
            left: Math.cos(rand) * this.box.el.width(),
            top: Math.sin(rand) * this.box.el.height()
        }, {
            step: this.stepCallback,
            duration: 3000
        });
    };
    
    Ball.prototype.stop = function () {
        this.el.stop();
    };
    
    function Box(el) {
        this.el = el;
        this.width = el.width();
        this.height = el.height();
    }
    
    function Game(box, ballContainer) {
        this.box = box;
        this.running = false;
        this.ball = new Ball(ballContainer, box, jQuery.proxy(function () {
            if (this.outsideBox()) {
                this.endGame();
            }
        }, this));
        this.result = 0;
    }
    
    Game.prototype.start = function () {
        var self = this;
        this.running = true;
        this.ball.el.css({
            left: (this.box.el.width() - this.ball.el.width()) / 2,
            top: (this.box.el.height() - this.ball.el.height()) / 2
        });
        this.ball.moveRand();
        this.ball.el.on('click', function () {
            self.ball.stop();
            self.ball.moveRand();
        });
        this._interval = setInterval(function () {
            self.result += 1;
        }, 1000);
    };
    
    Game.prototype.outsideBox = function () {
        var pos = this.ball.el.position();
        return pos.left < 0 || pos.top < 0 || pos.left + this.ball.width > this.box.width || pos.top + this.ball.height > this.box.height;
    };
    
    Game.prototype.endGame = function () {
        if (!this.running) return;
        this.running = false;
        this.ball.stop();
       ...