JSFiddle - React, Tailwind, and code Playground

by Scott Kaye

CSS

body {
    margin: 0;
    overflow: hidden;
	display: flex;
	align-items: center;
	justify-content: center;
	height: 100vh;
	background: #000;
}

canvas {
	border: 5px solid #fff;
}

JavaScript

const game = {
    board: {
        tiles: [
            [1, 0, 0, 0, 0, 0, 0, 0],
            [1, 1, 0, 0, 0, 1, 1, 0],
            [1, 1, 0, 1, 0, 1, 1, 1],
            [0, 1, 0, 1, 0, 0, 0, 1],
            [0, 0, 0, 0, 0, 1, 0, 1],
            [0, 0, 0, 1, 0, 1, 0, 1],
            [1, 0, 0, 1, 0, 0, 0, 1],
            [1, 1, 0, 1, 0, 1, 1, 1],
        ]
    },
	player: {
		size: 20,
		speed: 2,
		color: "#fa1",
		startTile: {
			x: 1,
			y: 4,
		},
		x: 0,
		y: 0,
		vx: 0,
		vy: 0,
		movesX: [],
		movesY: []
	}
};

const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");

canvas.width = 500;
canvas.height = 500;

document.body.appendChild(canvas);

function getTileSize() {
	return {
		width: canvas.width / game.board.tiles[0].length,
		height: canvas.height / game.board.tiles.length
	};
}

function drawBoard() {
    ctx.fillStyle = "#000";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    ctx.fillStyle = "#fff";
	let tileSize = getTileSize();
	
    for (let y = 0; y < game.board.tiles.length; ++y) {
	    for (let x = 0; x < game.board.tiles[y].length; ++x) {
            let isTileSet = game.board.tiles[y][x];
			
            if (isTileSet) {
                ctx.fillRect(x * tileSize.width, y * tileSize.height, tileSize.width, tileSize.height);
            }
        }
    }
}

function drawPlayer() {
    requestAnimationFrame(drawPlayer);
	
	const fillPlayer = (padding = 0) => ctx.fillRect(
		game.player.x - game.player.size / 2 - padding | 0,
		game.player.y - game.player.size / 2 - padding | 0,
		game.player.size + padding * 2,
		game.player.size + padding * 2
	);
	
	ctx.fillStyle = "#000";
	fillPlayer(0);
	
	let v = handleCollisions();
	
	game.player.x += v.x;
	game.player.y += v.y;
	
	ctx.fillStyle = game.player.color;
	fillPlayer(0);
}

function handleCollisions() {
	let v = {
		x: game.player.vx,
		y: game.player.vy
	};
	
	// Player
	let x = game.player.x;
	let y = game.player.y;

	let tileSize = getTileSize();
	let...