Code viewer for World: intersection (clone by Zoro)

// Cloned by Zoro on 9 Nov 2024 from World "intersection " by Zoro 
// Please leave this clone trail here.
 
let cols = 19;
let rows = 13;
let w, h;
let grid = [];
let intersections = [];
let whiteGrids = []; // List to store white path cells
let roadGrids = []; // List to store road cells including intersections

function setup() {
  createCanvas(900, 600);
  w = width / cols;
  h = height / rows;
  frameRate(4);

  // Initialize the grid and set walls
  for (let i = 0; i < cols; i++) {
    grid[i] = [];
    for (let j = 0; j < rows; j++) {
      grid[i][j] = new Spot(i, j);
      grid[i][j].wall = !(i % 3 === 0 || j % 3 === 0); // Set wall for cells not on paths

      // If it's not a wall, add it to the whiteGrids list
      if (!grid[i][j].wall) {
        whiteGrids.push({ i, j }); // Save white path cell coordinates
        roadGrids.push({ i, j });  // Add to roadGrids list as well
      }
    }
  }

  // Set corner cells as walls for layout consistency
  grid[0][0].wall = true;
  grid[0][rows - 1].wall = true;
  grid[cols - 1][0].wall = true;
  grid[cols - 1][rows - 1].wall = true;

  // Identify and save all intersections
  for (let i = 0; i < cols; i++) {
    for (let j = 0; j < rows; j++) {
      if (!grid[i][j].wall && isIntersection(i, j)) {
        intersections.push({ i, j }); // Save intersection coordinates
      }
    }
  }

  // Log the white path cells and intersections for debugging
  console.log("White Grids (Path):", whiteGrids);
  console.log("Road Grids (Paths and Intersections):", roadGrids);
  console.log("Intersections:", intersections); // Log intersections for debugging
}

function draw() {
  background(255);

  // Draw grid
  for (let i = 0; i < cols; i++) {
    for (let j = 0; j < rows; j++) {
      let spot = grid[i][j];
      spot.show();
    }
  }
}

// Define the Spot object to represent each cell in the grid
function Spot(i, j) {
  this.i = i;
  this.j = j;
  this.wall = false; // Default is path (white)

  // Show the grid cell with different colors
  this.show = function() {
    if (this.wall) {
      fill(0); // Wall - Black
    } else if (isIntersection(this.i, this.j)) {
      fill(150); // Intersection - Gray
    } else {
      fill(255); // Path - White
    }
    stroke(200);
    rect(this.i * w, this.j * h, w, h);
  };
}

// Check if a cell is an intersection by counting adjacent white cells
function isIntersection(i, j) {
  let whiteNeighbors = 0;

  // Check above
  if (j > 0 && !grid[i][j - 1].wall) whiteNeighbors++;
  // Check below
  if (j < rows - 1 && !grid[i][j + 1].wall) whiteNeighbors++;
  // Check left
  if (i > 0 && !grid[i - 1][j].wall) whiteNeighbors++;
  // Check right
  if (i < cols - 1 && !grid[i + 1][j].wall) whiteNeighbors++;

  // If more than two white neighbors, it's an intersection
  return whiteNeighbors > 2;
}