首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么我的p5 javascript生活游戏不起作用?

为什么我的p5 javascript生活游戏不起作用?
EN

Stack Overflow用户
提问于 2022-08-09 18:24:41
回答 1查看 45关注 0票数 1

我看了一个关于生活游戏的编码训练视频,我试着制作一个程序,但它不起作用。它只是在屏幕上生成随机方格作为第一张图像(起始位置),然后生成另一帧,正方格(白色)消失,仅此而已。只有2帧。而且它没有显示出一个错误。谁能解释一下原因吗?

代码语言:javascript
运行
复制
function make2D(x, y) {
  let arr = new Array(x);
  for (let i = 0; i < x; i++) {
    arr[i] = new Array(y);
  }
  return arr;
}

let grid;
let col;
let row;
let resolution = 20;

function setup() {
  createCanvas(500, 500);
  col = width / resolution;
  row = height / resolution;
  grid = make2D(col, row);
  for (let i = 0; i < col; i++) {
    for (let j = 0; j < row; j++) {
      grid[i][j] = floor(random(2));
    }
  }
}

function draw() {
  frameRate(1);
  background(0);
  //drawing
  for (let i = 0; i < col; i++) {
    for (let j = 0; j < row; j++) {
      let x = i * resolution;
      let y = j * resolution;
      if (grid[i][j]) {
        fill(255);
      } else {
        fill(0);
      }
      rect(x, y, resolution, resolution);
    }
  }
  //processing
  let next = make2D(col, row);
  for (let i = 0; i < col; i++) {
    for (let j = 0; j < row; j++) {
      let nb = calculatePosition(grid, i, j);
      //fill(255,0,0);
      //text(grid[i][j],i*resolution+6,j*resolution+15);
      if (grid[i][j] == 0 && nb == 3) {
        next[i][j] == 1;
      } else if (grid[i][j] == 1 && (nb > 3 || nb < 2)) {
        next[i][j] == 0;
      } else {
        next[i][j] = grid[i][j];
      }
    }
  }
  grid = next;
}

function calculatePosition(grid, x, y) {
  let sum = 0;
  for (let i = -1; i < 2; i++) {
    for (let j = -1; j < 2; j++) {
      let cols = (x + i + col) % col;
      let rows = (y + j + row) % row;
      sum += grid[cols][rows];
    }
  }
  sum -= grid[x][y];
  console.log(sum);
  return sum;
}
代码语言:javascript
运行
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>

EN

回答 1

Stack Overflow用户

发布于 2022-08-09 19:13:22

您不小心在这里使用相等(==)而不是赋值(=)。

代码语言:javascript
运行
复制
if (grid[i][j] == 0 && nb == 3) {
  next[i][j] == 1;
} else if (grid[i][j] == 1 && (nb > 3 || nb < 2)) {
  next[i][j] == 0;
} else {
  next[i][j] = grid[i][j];
}

您还应该将frameRate调用移动到setup()

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73296522

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档