Структура массива GofL - PullRequest
       47

Структура массива GofL

1 голос
/ 26 октября 2019

У меня проблемы с работой с классом 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

1 Ответ

0 голосов
/ 26 октября 2019

4 соседа (x, y): (x-1, y), (x+1, y), (x, y-1) и (x, y+1).

Оценить, находится ли сосед по сетке (не выходит за пределы) и занята ли ячейка (например, grid[x-1][y] == 1). Если это условие выполнено, увеличьте счетчик (tot). Например:

function countNeighbors(world, x, y) {

    let tot = 0; 

    if (x > 0 && grid[x-1][y] == 1) {
        tot ++;
    }
    if (y > 0 && grid[x][y-1] == 1) {
        tot ++;
    }
    if (x < cols-1 && grid[x+1][y] == 1) {
        tot ++;
    }
    if (y < cols-1 && grid[x][y+1] == 1) {
        tot ++;
    }

    return tot;
}

или то же самое с циклом:

function countNeighbors(world, x, y) {

    let nb = [[x-1, y], [x+1, y], [x, y-1], [x, y+1]];

    let tot = 0; 
    nb.forEach(function(n) {
        if (n[0] >= 0 && n[0] < cols && n[1] >= 0 && n[1] < rows && grid[n[0]][n[1]]) {
            tot++;
        }
    });
    return tot;
}

См. пример, в котором я регулировал частоту кадров (frameRate(5);):

let grid, cols, rows;
let resolution = 20;

function setup() {
    createCanvas(400, 200); 

    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);

    frameRate(5);
}

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) {

    let nb = [[x-1, y], [x+1, y], [x, y-1], [x, y+1]];

    let tot = 0; 
    nb.forEach(function(n) {
        if (n[0] >= 0 && n[0] < cols && n[1] >= 0 && n[1] < rows && grid[n[0]][n[1]]) {
            tot++;
        }
    });
    return tot;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
...