LabeledMap and Map equal each other - javascript

When I run this in Webstorm, labeledMap and map equal each other and that breaks my paintCanvas(); This is a long shot, and my code is messy, because I've been debugging for hours, and need help. Here is the code:
I am trying to create a pathfinding algorithm. The array "map" represents the array that contains only integers that represent whether each spot of the array represents a wall/start/end/path, and labeledMap converts the wall/start/end to strings, so the paths can be labeled with the number of steps it takes to get there from the start. That way, I can use labeledMap to find the shortest route to get to the end. This may not be the most efficient method, but this is just my way of experimenting with algorithms. But when I ran the program, both labeledMap converted to strings, and that confuses me because I never mentioned it to do that.
Javascript:
const ctx = canvas.getContext('2d');
const cellSize = 10;
const wallPercent = 35;
const colors = ["#FFFFFF", "#283747", "#1ABC9C", "#E74C3C", "#3498DB", "#F7DC6F"]
var map = [];
var labeledMap = []
var start = [];
var end = [];
function setupArray(){
var table = []
var row = []
for(i = 0; i < canvas.height/cellSize; i++){
for(j = 0; j < canvas.width/cellSize; j++){
if(Math.trunc(Math.random()*100) < wallPercent){
row.push(1);
} else{
row.push(0);
}
}
table.push(row);
row = []
}
return table;
}
function selectPoints(){
let startX = Math.floor(Math.random()*map.length);
let startY = Math.floor(Math.random()*map[0].length);
let endX = Math.floor(Math.random()*map.length);
let endY = Math.floor(Math.random()*map[0].length);
if(map[startX][startY] === 0 && map[endX][endY] === 0){
map[startX][startY] = 2;
map[endX][endY] = 3;
} else {
selectPoints();
}
}
function paintCanvas(){
ctx.beginPath();
for(let i = 0; i < map.length; i++){
for(let j = 0; j < map[0].length; j++){
ctx.fillStyle = colors[map[i][j]]
ctx.fillRect(j*cellSize, i*cellSize, cellSize, cellSize);
ctx.fill();
}
}
}
function dijkstraAlgorithm(){
var parsedLocations = [];
var iterationCount = 0;
labeledMap = map;
for(let i = 0; i < map.length; i++){
for(let j = 0; j < map[0].length; j++){
if(map[i][j] === 1){
labeledMap[i][j] = "wall"
} else if(map[i][j] === 2){
labeledMap[i][j] = "start"
start.push(i);
start.push(j)
} else if(map[i][j] === 3){
labeledMap[i][j] = "end"
end.push(i);
end.push(j);
} else {
labeledMap[i][j] = 0;
}
}
}
console.log(map, labeledMap)
parsedLocations.push([0, start[0], start[1]]);
setInterval(function(){
iterationCount += 1;
for(let i = 0; i < parsedLocations.length; i++){
if(parsedLocations[i][0] === iterationCount - 1){
map[parsedLocations[i][1] + 1][parsedLocations[i][2]] = 4;
map[parsedLocations[i][1] - 1][parsedLocations[i][2]] = 4;
map[parsedLocations[i][1]][parsedLocations[i][2] + 1] = 4;
map[parsedLocations[i][1]][parsedLocations[i][2] - 1] = 4;
console.log(map, labeledMap)
}
paintCanvas();
}
}, 250)
}
function initialize(){
map = setupArray();
selectPoints();
paintCanvas();
dijkstraAlgorithm();
}
initialize()
HTML:
<html>
<head>
<title>Pathfinding</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/style.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
</head>
<body>
<!--<div id="navbar">
<div id="algorithms-navbar">
<button id="algorithms-header">Pathfinding <span><img src="https://www.flaticon.com/svg/vstatic/svg/25/25243.svg?token=exp=1619464904~hmac=16f5273099cf29e2ef39d65ee1bdf395" alt="Dropdown" class="algorithm-dropdown"></span></button>
<div id="algorithms-body" class="inactive">
<button id="astar-algorithm" class="pathfinding-active">A* Algorithm</button>
</div>
</div>
</div>-->
<canvas id="canvas"></canvas>
<button onclick="initialize()" id="rerunBtn">Rerun</button>
<script src="js/SetupCanvas.js"></script>
</body>
</html>

Related

js chrome graphics problem: data is correct, render is wrong

I am a beginner at JS so I hope this problem is not too ridiculous. I want to render a white square 6x6 with a blue square 2x2 in the centre, using Canvas. When I print out the data I generate, it seems ok. But when it renders, all I get is a blue square 6x6. This is part of a larger file but I have simplified it to concentrate on this one problem. Using chrome devtools. Thanks.
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>obstacleTest</title>
</head>
<body>
<script>
let _data;
let gridLength = 6;
let grid = [];
let tempGrid = [];
function drawGrid (data) {
let width = 600;
let height = 600;
let gridLength = data.length;
let widthCell = width / gridLength;
let heightCell = height / gridLength;
let canvas = document.getElementById("grid");
if (canvas == null) {
canvas = document.createElement("canvas");
canvas.id = "grid";
canvas.width = width;
canvas.height = height;
document.getElementsByTagName("body")[0].appendChild(canvas);
}
let context = canvas.getContext("2d");
function drawCells () {
for (let i = 0; i < gridLength; i++) {
for (let j = 0; j < gridLength; j++) {
if (_data && _data[i][j] === cellColor(data[i][j])) {
continue;
}
context.clearRect(
i * widthCell,
j * heightCell,
widthCell,
heightCell
);
context.fillStyle = cellColor(data[i][j]);
context.fillRect(
i * widthCell,
j * heightCell,
widthCell,
heightCell
);
}
}
}
drawCells();
if (!_data) {
_data = [];
}
for (let i = 0; i < gridLength; i++) {
_data[i] = [];
for (let j = 0; j < gridLength; j++) {
_data[i][j] = cellColor(data[i][j]);
}
}
}
function updateGrid (data) {
drawGrid(data);
}
let cellColor = function (cell) {
return cell.obstacle = true ? "rgb(0,0,250)" : "rgb(125, 125, 125)"; //blue or grey
};
function Cell (i, j) {
this.i = i;
this.j = j;
this.obstacle = false;
}
function initGrids () {
for (let i = 0; i < gridLength; i = i + 1) {
grid[i] = [];
tempGrid[i] = [];
for (let j = 0; j < gridLength; j = j + 1) {
grid[i][j] = new Cell(i, j);
tempGrid[i][j] = new Cell(i, j);
}
}
}
function setObstacle () {
let xmin = 2;
let xmax = 3;
let ymin = 2;
let ymax = 3;
console.log("xmin, xmax, ymin, ymax ; " + xmin, xmax, ymin, ymax);
for (let i = xmin; i <= xmax; i++) {
for (let j = ymin; j <= ymax; j++) {
grid[i][j].obstacle = true; // implies blue
console.log(i, j, grid[i][j].obstacle);
}
console.log("________________");
}
}
//___________________________________________________________________________
initGrids();
for (let i = 0; i < gridLength; i++) {
for (let j = 0; j < gridLength; j++) {
grid[i][j].obstacle = false;
console.log(i, j, grid[i][j].obstacle);
}
console.log("_______");
}
setObstacle();
drawGrid(
grid.map(function (row) {
return row.map(function (cell) {
return cell;
});
})
);
//____________________________________________________________________________
</script>
</body>
</html>
There is a really tiny error in your code which causes your issue.
Let's have a look at the function returning the appropriate color based on the obstacle property:
let cellColor = function (cell) {
return cell.obstacle = true ? "rgb(0,0,250)" : "rgb(125, 125, 125)"; //blue or grey
};
If obstacle is true it should return blue and if not gray. The problem is that
return cell.obstacle = true
is not a comparison it's an assignment. So as you always assign true to obstacle, all you get is the blue color.
Try changing it to this:
return cell.obstacle === true

Paint bucket getting "Maximum Call Stack Size Exceeded" error

This is the code of the paint bucket tool in my drawing app using the p5.js library. The function self.floodFill always get "Maximum Call Stack Size Exceeded" because of recursion and I want to know the way to fix it. I am thinking if changing the function to a no recursion function would help or not. Any help would be appreciated.
function BucketTool(){
var self = this;
//set an icon and a name for the object
self.icon = "assets/bucket.jpg";
self.name = "Bucket";
var d = pixelDensity();
var oldColor;
var searchDirections = [[1,0],[-1,0],[0,1],[0,-1]];
var pixelsToFill = [];
var positionArray = new Array(2);
self.checkBoundary = function(currentX, currentY, localOldColor) {
if (self.getPixelAtXYPosition(currentX,currentY).toString() != localOldColor.toString() || currentX < 0 || currentY < 0 || currentX > width || currentY > height || pixelsToFill.indexOf(currentX+" "+currentY) != -1) {
return false;
}
return true;
};
self.floodFill = function(currentX, currentY, localOldColor, localSearchDirections) {
if (self.checkBoundary(currentX, currentY, localOldColor)){
pixelsToFill.push(currentX+" "+currentY);
} else {
return;
}
for (var i = 0; i < searchDirections.length; i++){
self.floodFill(currentX + searchDirections[i][0], currentY + searchDirections[i][1], localOldColor, localSearchDirections);
}
};
self.getPixelAtXYPosition = function(x, y) {
var colour = [];
for (var i = 0; i < d; i++) {
for (var j = 0; j < d; j++) {
// loop over
index = 4 * ((y * d + j) * width * d + (x * d + i));
colour[0] = pixels[index];
colour[1] = pixels[index+1];
colour[2] = pixels[index+2];
colour[3] = pixels[index+3];
}
}
return colour;
}
self.drawTheNeededPixels = function(){
for(var i = 0; i < pixelsToFill.length; i++){
positionArray = pixelsToFill[i].split(" ");
point(positionArray[0],positionArray[1]);
}
}
self.draw = function () {
if(mouseIsPressed){
pixelsToFill = [];
loadPixels();
oldColor = self.getPixelAtXYPosition(mouseX, mouseY);
self.floodFill(mouseX, mouseY, oldColor, searchDirections);
self.drawTheNeededPixels();
}
};
}
This problem is well documented on the wikipedia page and the shortfalls of the different types of algorithms to perform flood filling. You've gone for the stack-based recursive implementation.
To prevent a stackoverflow — Maximum Call Stack Exceeded — the first step would be to use a data structure. Using queues/stacks rather than having the function call itself.
The code below creates an empty stack where we put a new object containing the x and y where the user has chosen to fill. This is then added to the pixelsToFill array. We then loop the stack until it's completely empty, at which point we are ready to display the filled pixels.
In the while loop we pop an element off the stack and then find its children — the directions up, down, left, right denoted by the searchDirections array you created. If we've not seen the child before and it's within the boundary we add it to the pixelsToFill array and add it to the stack to repeat the process:
self.floodFill = function (currentX, currentY, localOldColor, localSearchDirections) {
let stack = [];
stack.push({ x: currentX, y: currentY });
pixelsToFill.push(currentX + " " + currentY);
while (stack.length > 0) {
let current = stack.pop();
for (var i = 0; i < searchDirections.length; i++) {
let child = {
x: current.x + searchDirections[i][0],
y: current.y + searchDirections[i][1],
localOldColor,
};
if (self.checkBoundary(child.x, child.y, localOldColor)) {
pixelsToFill.push(child.x + " " + child.y);
stack.push(child);
}
}
}
};
This code may stop the stackoverflow but there are still a lot of optimisations that can be made. Once again, it's worth checking out the Wikipedia page and potentially take a look at Span filling.
let bucketTool;
function setup() {
createCanvas(400, 400);
bucketTool = new BucketTool();
}
function draw() {
background(220);
strokeWeight(5);
circle(width / 2, height / 2, 100);
frameRate(1);
bucketTool.draw();
}
function BucketTool() {
var self = this;
//set an icon and a name for the object
// self.icon = "assets/bucket.jpg";
// self.name = "Bucket";
var d = pixelDensity();
var oldColor;
var searchDirections = [
[1, 0],
[-1, 0],
[0, 1],
[0, -1],
];
var pixelsToFill = [];
var positionArray = new Array(2);
self.checkBoundary = function (currentX, currentY, localOldColor) {
if (
self.getPixelAtXYPosition(currentX, currentY).toString() !=
localOldColor.toString() ||
currentX < 0 ||
currentY < 0 ||
currentX > width ||
currentY > height ||
pixelsToFill.indexOf(currentX+" "+currentY) != -1
) {
return false;
}
return true;
};
self.floodFill = function (currentX, currentY, localOldColor, localSearchDirections) {
let stack = [];
stack.push({ x: currentX, y: currentY });
pixelsToFill.push(currentX + " " + currentY);
while (stack.length > 0) {
let current = stack.pop();
for (var i = 0; i < searchDirections.length; i++) {
let child = {
x: current.x + searchDirections[i][0],
y: current.y + searchDirections[i][1],
localOldColor,
};
if (self.checkBoundary(child.x, child.y, localOldColor)) {
pixelsToFill.push(child.x + " " + child.y);
stack.push(child);
}
}
}
};
self.getPixelAtXYPosition = function (x, y) {
var colour = [];
for (var i = 0; i < d; i++) {
for (var j = 0; j < d; j++) {
// loop over
index = 4 * ((y * d + j) * width * d + (x * d + i));
colour[0] = pixels[index];
colour[1] = pixels[index + 1];
colour[2] = pixels[index + 2];
colour[3] = pixels[index + 3];
}
}
return colour;
};
self.drawTheNeededPixels = function () {
for (var i = 0; i < pixelsToFill.length; i++) {
positionArray = pixelsToFill[i].split(" ");
point(positionArray[0], positionArray[1]);
}
};
self.draw = function () {
if (mouseIsPressed) {
pixelsToFill = [];
loadPixels();
oldColor = self.getPixelAtXYPosition(mouseX, mouseY);
self.floodFill(mouseX, mouseY, oldColor, searchDirections);
console.log(pixelsToFill.length);
self.drawTheNeededPixels();
}
};
}
html, body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<main>
</main>
<script src="sketch.js"></script>
</body>
</html>
Shameless plug, but relevant: I've created a blog comparing the different flood fill algorithms using p5.js.

Efficient Table Seating Function

I'm creating a table seating function in javascript, directly below, for a scenario where there is a population of P participants, in this case tested with 80, and S seats per table, in this case tested by 8, each participant may only visit each table once with a total of ten tables and each participant may not meet another participant more than once for a minimum of 10 rotations.
How can I make 10 unique sets of P/S, 10 times?
To explain my naming, arrayArray is the array for each of the tables and the outer arrays inner array elements are the table seating, arrayArrayPrevious is the list of everyone whose already been to a table, and the participantArray is an array of all possible participants.
The trouble seems to be when finding two participants have already met and moving the second one to the end of the participantArray to be tried again later results in only one participant ever being placed.
I'm placing the entire code below the function snippet in the event someone can help solve it and its useful for others in the future.
function notMetAlready(w, arrayArray, participantAlreadyMet){
if(arrayArray.includes(participantAlreadyMet)){
var moveToEnd = arrayArray[w][0];
console.log(moveToEnd);
participantArray.push(moveToEnd);
console.log(participantArray);
return true;
//console.log(index);
}
if(!arrayArray.includes(participantAlreadyMet)){
return true;
}
else{
return false;
}
}
Full Code
<html>
<head>
<script type="text/javascript">
var tables = 10;
var participants = 80;
var participantPool = [];
var seatingPerTable = participants/tables;
var arrayArray = new Array(tables);
for(var i = 1; i <= participants; i++){
participantPool.push(i);
}
var count = 1;
var participantArray = new Array(participants);
var participantAlreadyMet = new Array(participants);
var arrayArrayPrevious = new Array(tables);
for (var i = 0; i <= tables; i++) {
arrayArrayPrevious[i] = [];
arrayArray[i] = [];
}
for (var i = i; i < participantAlreadyMet.length; i++) {
participantAlreadyMet[i] = [i];
}
function MatchingPairs() {
for (var i = 0; i < tables; i++) {
arrayArray[i] = [];
}
for(var h = 0; h < participants; h++){
participantArray[i] = i+1;
}
for(var w = 0; w < arrayArray.length; w++){
if(tablesHaveNotIncluded(w,0)){
// for(var n = 1; n < participants; n++){
do{
if(tablesDoNotInclude(0) && notMetAlready(w, arrayArray[w], participantAlreadyMet[0])){
arrayArray[w].push(participantArray[0]);
arrayArrayPrevious[w].push(participantArray[0]);
participantArray.shift();
}
}while(participantArray >= 0);
}
}
function notMetAlready(w, arrayArray, participantAlreadyMet){
if(arrayArray.includes(participantAlreadyMet)){
var moveToEnd = arrayArray[w][0];
console.log(moveToEnd);
participantArray.push(moveToEnd);
console.log(participantArray);
return true;
}
if(!arrayArray.includes(participantAlreadyMet)){
return true;
}
else{
return false;
}
}
for(var z = 0; z < tables; z++){
var plus = z + 1;
console.log("Table " + plus + " " + arrayArray[z] );
}
console.log("Rotation " + count);
count++;
function tablesHaveNotIncluded(w,n){
var outerArray = arrayArrayPrevious[w];
if(!outerArray.includes(n)){
return true;
}
return false;
}
function tablesDoNotInclude(n){
for(var w = 0; w < tables; w++){
if(!arrayArray[w].includes(n)){
return true;
}
}
return false;
}
}
</script>
</head>
<body>
<button onclick="MatchingPairs()">Combinations</button>
</body>
</html>

Processes for optimizing canvas animations

I've got a small web app in development to simulate the Ising model of magnetism. I've found that the animation slows down considerably after a few seconds of running, and it also doesn't loop after 5 seconds like I want it to with the command:
setInteval(main, 500)
I've added start and stop buttons. When I stop the animation, and then restart it, it begins fresh at the usual speed, but again slows down.
My question is: what steps can I take to troubleshoot and optimize the performance of my canvas animation? I hope to reduce or mitigate this slowing effect.
JS code:
window.onload = function() {
var canvas = document.getElementById("theCanvas");
var context = canvas.getContext("2d");
var clength = 100;
var temperature = 2.1;
var playAnim = true;
canvas.width = clength;
canvas.height = clength;
var imageData = context.createImageData(clength, clength);
document.getElementById("stop").addEventListener("click",function(){playAnim=false;});
document.getElementById("start").addEventListener("click",function(){playAnim=true;});
function init2DArray(xlen, ylen, factoryFn) {
//generates a 2D array of xlen X ylen, filling each element with values defined by factoryFn, if called.
var ret = []
for (var x = 0; x < xlen; x++) {
ret[x] = []
for (var y = 0; y < ylen; y++) {
ret[x][y] = factoryFn(x, y)
}
}
return ret;
}
function createImage(array, ilen, jlen) {
for (var i = 0; i < ilen; i++) {
for (var j = 0; j < jlen; j++) {
var pixelIndex = (j * ilen + i) * 4;
if (array[i][j] == 1) {
imageData.data[pixelIndex] = 0; //r
imageData.data[pixelIndex+1] = 0; //g
imageData.data[pixelIndex+2] = 0; //b
imageData.data[pixelIndex+3] = 255; //alpha (255 is fully visible)
//black
} else if (array[i][j] == -1) {
imageData.data[pixelIndex] = 255; //r
imageData.data[pixelIndex+1] = 255; //g
imageData.data[pixelIndex+2] = 255; //b
imageData.data[pixelIndex+3] = 255; //alpha (255 is fully visible)
//white
}
}
}
}
function dU(i, j, array, length) {
var m = length-1;
//periodic boundary conditions
if (i == 0) { //top row
var top = array[m][j];
} else {
var top = array[i-1][j];
}
if (i == m) { //bottom row
var bottom = array[0][j];
} else {
var bottom = array[i+1][j];
}
if (j == 0) { //first in row (left)
var left = array[i][m];
} else {
var left = array[i][j-1];
}
if (j == m) { //last in row (right)
var right = array[i][0];
} else {
var right = array[i][j+1]
}
return 2.0*array[i][j]*(top+bottom+left+right); //local magnetization
}
function randInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
var myArray = init2DArray(clength, clength, function() {var c=[-1,1]; return c[Math.floor(Math.random()*2)]}); //creates a 2D square array populated with -1 and 1
function main(frame) {
if (!playAnim){return;} // stops
window.requestAnimationFrame(main);
createImage(myArray, clength, clength);
context.clearRect(0,0,clength,clength);
context.beginPath();
context.putImageData(imageData,0,0);
for (var z = 0; z < 10*Math.pow(clength,2); z++) {
i = randInt(clength-1);
j = randInt(clength-1);
var deltaU = dU(i, j, myArray, clength);
if (deltaU <= 0) {
myArray[i][j] = -myArray[i][j];
} else {
if (Math.random() < Math.exp(-deltaU/temperature)) {
myArray[i][j] = -myArray[i][j];
}
}
}
}
var timer = setInterval(main, 500);
}

Javascript game of life array gets reset

For a fun little project I decided to program conway's game of life in javascript. My logic seems to make sense and each individual function does its job however I still dont get my intended result. I have an array called grid, which stores the value of all the cells, and if they are alive or dead. I check each individual cell, then check all 8 surrounding cells to count neighbors, repeat for every other cell. At some point my grid no longer stores the correct value and resets. At this point I'm starting to think it's a javascript problem.
<body>
<style>
* {
padding: 0;
margin: 0;
}
body {
overflow: hidden;
}
canvas {
background: #FFFFFF;
display: block;
margin: 0 auto;
}
</style>
<canvas id="canvas" style="border:1px solid #000000;"></canvas>
</body>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var Game = {};
var nextGrid, emptyGrid, grid;
Game.horCells = 30;
Game.cellSize = canvas.width / Game.horCells;
Game.verCells = Math.floor(canvas.height / Game.cellSize);
Game.startLives = 80;
config();
//setInterval(run, 1000);
function config() {
console.log("in config");
emptyGrid = newGrid(Game.horCells, Game.verCells);
grid = emptyGrid;
nextGrid = emptyGrid;
//Manual Setup
for (var i = 0; i < Game.startLives; i++) {
//grid[getRandomInt(0, Game.horCells - 1)][getRandomInt(0, Game.verCells - 1)] = true;
}
grid[0][3] = true;
grid[1][3] = true;
grid[2][3] = true;
}
function run() {
console.log("gread" + grid[3][3]);
draw();
update();
}
function draw() {
console.log("Draw");
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < Game.horCells; i++) {
for (var j = 0; j < Game.verCells; j++) {
if (grid[i][j] === false) {
ctx.fillStyle = "#FFFFFF";
} else if (grid[i][j] === true) {
console.log("drawing live");
ctx.fillStyle = "#000000";
}
ctx.fillRect(i * Game.cellSize, j * Game.cellSize, Game.cellSize, Game.cellSize);
}
}
}
function update() {
for (var p = 0; p < Game.horCells; p++) {
for (var k = 0; k < Game.verCells; k++) {
nextGrid[p][k] = survival(p, k);
}
}
}
function survival(x, y) {
var neighbours = 0;
for (var l = 0; l < 3; l++) {
for (var m = 0; m < 3; m++) {
var sx = (x - 1) + l;
var sy = (y - 1) + m;
//Check bounds
if (inBounds(sx, sy) === true && grid[sx][sy]) {
neighbours++;
}
}
}
if (grid[x][y]) {
neighbours--;
if (neighbours === 2 || neighbours === 3) {
return true;
} else if (neighbours < 2 || neighbours > 3) {
console.log("DIED");
return false;
}
} else if (grid[x][y] === false && neighbours === 3) {
return true;
} else {
console.log("DIED");
return false;
}
}
function inBounds(x, y) {
return (x >= 0 && x < Game.horCells && y >= 0 && y < Game.horCells);
}
function newGrid(xCells, yCells) {
var gridd = new Array(xCells);
for (var i = 0; i < xCells; i++) {
gridd[i] = new Array(yCells);
}
for (var j = 0; j < xCells; j++) {
for (var k = 0; k < yCells; k++) {
gridd[j][k] = false;
}
}
return gridd;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>
emptyGrid = newGrid(Game.horCells, Game.verCells);
grid = emptyGrid;
nextGrid = emptyGrid
Creates 1 grid, then assigns grid and nextGrid to the same object. Again, grid and nextGrid are the same object. Any changes you make to 1 will happen to the other.
Create 2 separate grids so they can be changed independently:
grid = newGrid(Game.horCells, Game.verCells);
nextGrid = newGrid(Game.horCells, Game.verCells);
Or, to neaten it up slightly:
var g = () => newGrid(Game.horCells, Game.verCells);
grid = g();
nextGrid = g();
Just to clear up the question in the comments:
var g = () => newGrid(Game.horCells, Game.verCells);
Is (basically) the same thing as:
var g = function() {
return newGrid(Game.horCells, Game.verCells);
}
It's known as a "fat-arrow" function.
Both bits do the same thing though: they create a function that returns a new grid. This has the benefit of not needing to write newGrid(Game.horCells, Game.verCells); twice.
I used an arrow function instead of the function keyword because the latter is giant and ugly, which takes away from the goal of cleaning up the code.

Categories