JSFiddle - React, Tailwind, and code Playground

by wirey00

HTML

<div class="container">
    <div id="snake">
        <div class="head snake"></div>
        <div class="body snake"></div>
        <div class="body snake"></div>
        <div class="body snake last"></div>
       
    </div>
    <div class="food"></div>
</div>

CSS

.container {
    height:400px;
    width:400px;
    margin:0 auto;
    background-color:#FFC;    
    position:relative;
}

.snake {
    height:10px;
    width:10px;
    position:absolute;
    /*left:20px;
    bottom:170px;*/
    background-color:#999;
    border-radius:5px;    
}

.food {
    height:10px;
    width:10px;
    position:absolute;
    background-color:#0F9;    
    border-radius:5px;
 
    left:60px;
    bottom:90px;
}

JavaScript

$(document).ready(function() {

    var positionx = ['50px', '40px', '30px', '20px'];
    var positiony = ['170px', '170px', '170px', '170px'];
    var direction = 'x+';
    var gameover = false;
    var score = 0;
    //setup
    $('.snake').each(function(index, element) {
        $(this).css({
            'left': positionx[index],
            'bottom': positiony[index]
        });
    });
    //movement 
    $(document).keydown(function(e) {
        if (e.keyCode == 37 && direction !== 'x+') {

            direction = 'x-'
        }
        else if (e.keyCode == 38 && direction !== 'y-') {

            direction = 'y+'
        }
        else if (e.keyCode == 39 && direction !== 'x-') {

            direction = 'x+'
        }
        else if (e.keyCode == 40 && direction !== 'y+') {

            direction = 'y-'
        }
    });

    function movement() {
        //check for self collisions
        $('.body').each(function(index, element) {
            if ($(this).css('bottom') < $('.head').css('bottom') + '10' && $('.head').css('bottom') < $(this).css('bottom') + '10' && $(this).css('left') < $('.head').css('left') + '10' && $('.head').css('left') < $(this).css('left') + '10') {

                gameover = true;
            }
        });
        if (gameover == false) {
            //set position array            
            $('.snake').each(function(index, element) {
                positionx[index] = $(this).css('left');
                positiony[index] = $(this).css('bottom');
            });
            //check direction and animate head/first circle
            if (direction == 'x+') {
                $('.head').css({
                    'left': '+=10px'
                })
            }
            else if (direction == 'x-') {
                $('.head').css({
                    'left': '-=10px'
                })
            }
            else if (direction == 'y+') {
                $('.head').css({
                    'bottom': '+=10px'
             ...