簡體   English   中英

為什么我的 p5 javascript 生命游戲無法運行?

[英]Why is my p5 javascript game of life not working?

我看了一段關於生命游戲的編碼訓練視頻,我嘗試制作一個程序,但它不起作用。 它只是在屏幕上生成隨機方塊作為第一張圖像(起始位置),然后生成另一幀,正方塊(白色)消失,僅此而已。 只有2幀。 而且它沒有顯示錯誤。 有人可以解釋為什么嗎?

 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; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>

您不小心在這里使用了相等 ( == ) 而不是賦值 ( = )

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM