首页 > 解决方案 > GofL 数组框架

问题描述

我在使用countNeighbors生活游戏中的一个类时遇到了麻烦实际上,我正在使用 p5.js,它是一个使用 java 的在线编辑器,到目前为止代码是:

let grid;
let cols;
let rows;
let resolution = 50;

function setup() {
    createCanvas(800, 600); 

    cols = round(width / resolution);
    rows = round(height / resolution);

    grid = make2DArray(cols, rows);

    for(let i = 0; i < cols; i++){
        for(let j = 0; j < rows; j++){
            grid[i][j] = floor(random(2));
        }
    }
    //Print the grid in the console:
    console.table(grid);
}

function make2DArray(cols, rows){
    //Crear el array de arrays:
    let arr = new Array(cols);

    for(let i = 0; i < arr.length; i++){
        arr[i] = new Array(rows);
    }

    return arr;
}

function draw() {
    background(0);

    //Paint the initial world:
    for(let i=0; i<cols; i++){
        for(let j=0; j<rows; j++){

          let x = i * resolution;
          let y = j * resolution;

          if(grid[i][j] == 1){
              fill(255);
              rect(x, y, resolution, resolution);
          }
        }
    }

    let next = make2DArray(cols, rows);

    //Fill the 'next' world based on grid state:
    for(let i = 0; i < cols; i++){
        for(let j = 0; j < rows; j++){
          //Check the state of current cell:
          let state = grid[i][j];

          //Count number of neighbors:
          let neighbors = countNeighbors(grid, i, j);

          if ( state == 1 && (neighbors < 2 || neighbors > 3)){
              next[i][j] = 0; 
          }
          else if ( state == 0 && neighbors == 3){
              next[i][j] = 1; 
          }
          else{
              next[i][j] = state;
          }
        }
    }

    grid = next;
}

function countNeighbors(world, x, y){

    tot = 0;

//S.O.S!!!!

    return tot;
}

目标是使用数组计算 neihgbors,例如:

000000000
0xxxxxxx0
0xxxxxxx0
0xxxxxxx0
000000000 etc... 

X=cell alive or empty 
0=framework outside the visible array to avoid problems with edges

标签: javascriptarraysprocessingcyclep5.js

解决方案


推荐阅读