JSFiddle - React, Tailwind, and code Playground
by schrodingers
HTML
<div>
<canvas id="gameCanvas"></canvas>
</div>
<div class="create">
<input type='button' onClick='createWorld()' value='New World'>
</div>
CSS
body {
display: flex;
flex-flow: column;
justify-content: center;
align-items: center;
padding: 0;
margin: 1em auto;
}
.create {
font-size: 1em;
// position: absolute;
bottom: 5em;
text-align: center;
}
JavaScript
// A* Pathfinding for HTML5 Canvas
// Based on Edsger Dijkstra's 1959 algorithm
// the world grid: a 2d array of tiles
var world = [
[]
];
// size in the world in sprite tiles
var worldWidth = 15;
var worldHeight = 15;
// size of a tile in pixels
var tileWidth = 32;
var tileHeight = 32;
// start and end of path
var pathStart = [worldWidth, worldHeight];
var pathEnd = [0, 0];
var currentPath = [];
// the html page is ready
var canvas = document.getElementById('gameCanvas');
var canvas.width = worldWidth * tileWidth;
var canvas.height = worldHeight * tileHeight;
var ctx = canvas.getContext("2d");
var spritesheet = ctx.fillRect();
// fill the world with walls
function createWorld() {
// create emptiness
for (var x = 0; x < worldWidth; x++) {
world[x] = [];
for (var y = 0; y < worldHeight; y++) {
world[x][y] = 0;
}
}
// scatter some walls
for (var x = 0; x < worldWidth; x++) {
for (var y = 0; y < worldHeight; y++) {
if (Math.random() > 0.75)
world[x][y] = 1;
}
}
// calculate initial possible path
// note: unlikely but possible to never find one...
currentPath = [];
while (currentPath.length == 0) {
pathStart = [Math.floor(Math.random() * worldWidth), Math.floor(Math.random() * worldHeight)];
pathEnd = [Math.floor(Math.random() * worldWidth), Math.floor(Math.random() * worldHeight)];
if (world[pathStart[0]][pathStart[1]] == 0)
currentPath = findPath(world, pathStart, pathEnd);
}
redraw();
}
function redraw() {
var spriteNum = 0;
// clear the screen
ctx.fillStyle = '#000000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (var x = 0; x < worldWidth; x++) {
for (var y = 0; y < worldHeight; y++) {
// choose a sprite to draw
switch (world[x][y]) {
case 1:
spriteNum = 1;
break;
default:
spriteNum = 0;
break;
}
// draw it
//...