JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://cdn.crafty-modules.com/crafty-DEBUG.js"></script>
JavaScript
Crafty.init(256, 286);
Crafty.background('rgb(0,0,0)');
//We are going to create a gamegrid with game cells that allow for path finding, collision detection, etc...
var cellDivisions = 32; //this is the number of cells across and down, a square //every 8 pixels
//this factory will create our gamecells, a factory is essentially a function that returns properties/methods
var gameCell = function()
{
return{
xCell: 0,
yCell: 0,
solid: false,
occupiedBy: undefined, //the gamecell could be occupied by a player, enemy, item, etc...
neighbors: new Array(4), //the north, south, east, west neighbors
}
}
//build the gameGrid using our gamecell factory
var gameGrid = new Array(cellDivisions); //this is an array of rows (it's index = Y position)
for(var r = 0;r < cellDivisions;r++){
gameGrid[r] = new Array(cellDivisions);
//populate the row
for(var c = 0;c < cellDivisions;c++) { //it's index = X position
gameGrid[r][c] = gameCell()
//set the x, y,
gameGrid[r][c].xCell = c
gameGrid[r][c].yCell = r
//define a crafty entity to represent the gameCell object
var cell = Crafty.e("2D, Canvas, Color")
//maybe this cell is solid?
if (Math.floor(Math.random()*20) > 18) { gameGrid[r][c].solid = true; cell.color('rgb(50,50,50)')
} else { cell.color('rgb(130,130,130)') } //else the cell is not solid, and is a lighter color grey
//Finally we place the gameCell in the correct position in the viewport
cell.attr({w:7, h:7, x:gameGrid[r][c].xCell*(8) , y:gameGrid[r][c].yCell*(8) })
}
}
//assign neighbors to each gameCell
for(var r = 0;r < cellDivisions;r++)
{
for(var c = 0;c < cellDivisions;c++)
{
//calculate & assign the neighbors for each cell on the gamegrid
//we do this once when the grid is being built, essentially 'caching' the neighbors into the gameGrid object
//the tradeoff is that...