JSFiddle - React, Tailwind, and code Playground

by darthdeus

HTML

<canvas id="canvas" height="200" width="200" tabindex="1"></canvas>

JavaScript

var lastFrame = performance.now();
var requestAnimationFrameId;
var FPS = 1;
var alpha = 0.1;

function stopGameLoop() {
    window.cancelAnimationFrame(requestAnimationFrameId);
}

function gameLoop(timestamp) {
    requestAnimationFrameId = window.requestAnimationFrame(gameLoop);

    if (timestamp < lastFrame + (1000 / 60)) {
        return;
    }

    var dt = (timestamp - lastFrame) / 1000;
    lastFrame = timestamp;
    FPS = FPS + (1 - alpha) * (1/dt - FPS);

    updatePlayer(dt);

    drawMap();
    drawPlayer();
}

requestAnimationFrameId = window.requestAnimationFrame(gameLoop);

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var BOX_SIZE = 20;
var MAP_W = 10;
var MAP_H = 6;

function drawBox(color, x, y, w, h) {
  ctx.fillStyle = color;
  ctx.fillRect(x, y, w || BOX_SIZE, h || BOX_SIZE);
}

var map = [
  0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,
  1,0,0,0,0,0,0,0,0,0,
  1,1,0,0,0,1,0,0,0,0,
  1,1,1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1,1,1,  
];

function drawMap() {
  for (var i = 0; i < MAP_H; i++) {
    for (var j = 0; j < MAP_W; j++) {
      var color = map[i * MAP_W + j] ? "#5d995d" : "lightblue";
      drawBox(color, BOX_SIZE * j, BOX_SIZE * i);
    }
  }
}

var keys = {};
window.onkeyup = function(e) { delete keys[e.keyCode] }
window.onkeydown = function(e) { keys[e.keyCode] = true; }

var player = { x: 60, y: 60 };

function drawPlayer() {
		drawBox("#612b2e", player.x, player.y);
}

function updatePlayer(dt) {
		// Key codes for player hotkeys.
    var A = 65;
    var W = 87;
    var D = 68;
    
    // The player moves at 80px per second.
    var SPEED = 80;
    
    // We calculate the tile where the player is.
    var tileX = Math.floor(player.x / BOX_SIZE);
    var tileY = Math.floor(player.y / BOX_SIZE);

    // Player collides on the left either with the leftmost edge of the screen,
    // or with a tile which is adjacent to the left.
    var possibleCollisionLeft = tileX == 0 || map[tileY * MAP_W +...