javascript - 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
解决方案
推荐阅读
- wordpress - 如何在我自己的插件上修复“此插件尚未使用 WordPress 的最新 3 个主要版本进行测试。它...”
- arrays - Google表格中一行中的数字范围
- gradle - Gradle 仅在 CI 工作期间抱怨缺少 jar
- arrays - 迅速。随机化从一组图像中选择的索引
- google-apps-script - Google Sheet 脚本:使用 getActiveSheet() 重置活动单元格
- python - 在 HPC 上运行并行 python 程序
- reactjs - Formik with Yup - 使用 test() 函数时抛出异常
- oracle - PL/SQL:在选择范围内选择声明变量以获取百分比
- machine-learning - 上置信界算法的感觉
- javascript - 在 Mocha/Chai 测试中测试时可能允许 SyntaxErrors 吗?