JSFiddle - React, Tailwind, and code Playground

by alexb

HTML

<canvas id="game-canvas"></canvas>

JavaScript

const canvas = document.getElementById("game-canvas");
const ctx = canvas.getContext("2d");

// Set the size of the canvas
canvas.width = 400;
canvas.height = 400;

// Create the grid
const gridSize = 20;
const grid = new Array(gridSize);
for (let i = 0; i < gridSize; i++) {
grid[i] = new Array(gridSize);
}

// Create the pirate ship
const pirateShip = {
x: 0,
y: 0,
width: 20,
height: 20,
color: "red"
};

// Draw the pirate ship on the grid
function drawPirateShip() {
ctx.fillStyle = pirateShip.color;
ctx.fillRect(
pirateShip.x * gridSize,
pirate.y * gridSize,
pirateShip.width,
pirateShip.height
);
}

// Draw the grid lines
function drawGrid() {
ctx.strokeStyle = "black";
ctx.lineWidth = 1;
for (let i = 0; i <= gridSize; i++) {
ctx.beginPath();
ctx.moveTo(i * gridSize, 0);
ctx.lineTo(i * gridSize, canvas.height);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0, i * gridSize);
ctx.lineTo(canvas.width, i * gridSize);
ctx.stroke();
}
}

// Handle key presses
document.addEventListener("keydown", e => {
switch (e.keyCode) {
// Left arrow
case 37:
if (pirateShip.x > 0) pirateShip.x -= 1;
break;
// Up arrow
case 38:
if (pirateShip.y > 0) pirateShip.y -= 1;
break;
// Right arrow
case 39:
if (pirateShip.x < gridSize - 1) pirateShip.x += 1;
break;
// Down arrow
case 40:
if (pirateShip.y < gridSize - 1) pirateShip.y += 1;
break;
}
});

// Update and draw the game
function update() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);

// Draw the grid
drawGrid();

// Draw the pirate ship
drawPirateShip();

// Request another animation frame
requestAnimationFrame(update);
}

// Start the game
requestAnimationFrame(update);