JSFiddle - React, Tailwind, and code Playground

by Marc Malignan

HTML

<div id="board">
    <div id="player"></div>
</div>

CSS

#board {
    position: relative;
    background: lightgray;
}

#player {
    position: absolute;
    bottom: 0; left: 0;
    background: silver;
    border-radius: 50% 50% 0 0;
}

JavaScript

var board = {
    width: 400,
    height: 200
}

var player = {
    size: 32,
    speed: {
        walk: 4,
        sprint: 8,
        jump: 4
    },
    state: {
        jumping: false,
        falling: false
    },
    jump: {
        jumpStart: 0,
        jumpHeight: 0
    }
}

var keys = {
    shift: false,
    up: false,
    right: false,
    down: false,
    left: false
}

function init() {
    $('#board')
        .css('width', board.width+'px')
        .css('height', board.height+'px');
    $('#player')
        .css('width', player.size+'px')
        .css('height', player.size+'px');
}

function move() {
    var el = $('#player');
    var currentH = el.css('left');
    currentH = parseInt(currentH.substring(0, currentH.length-2));
    
    var newH = currentH;
    var speed= keys.shift ? player.speed.sprint : player.speed.walk;
    
    if(keys.left) newH -= speed;
    if(keys.right) newH += speed;
    
    if(newH<0) newH = 0;
    else if(newH>board.width-player.size) newH = board.width-player.size;
    
    el.css('left', newH);
}

function jump() {
    var el = $('#player');
    var currentV = el.css('bottom');
    currentV = parseInt(currentV.substring(0, currentV.length-2));
    
    var newV = currentV;
    el.css('bottom', '+='+player.speed.jump);
}

function fall() {
    var el = $('#player');
    el.animate({ bottom: player.jump.jumpStart }, 1000 );
}

function check() {
    if(keys.left || keys.right) move();
    if(keys.space) jump();
}

$(window).on('keydown', function(e) {
    e.preventDefault();
    var key = e.keyCode;
    if(key==16) keys.shift = true;
    else if(key==37) keys.left = true;
    else if(key==38) keys.up = true;
    else if(key==39) keys.right = true;
    else if(key==40) keys.down = true;
    else if(key==32) {
        player.
        keys.space = true;
    }
});
$(window).on('keyup', function(e) {
    e.preventDefault();
    var key = e.keyCode;
    if(key==16) keys.shift = false;
    else if(key==37) keys.left = false;
   ...