ライフゲーム
https://gyazo.com/81a7d805f9ef4308862d2e3652494a28 https://www.amazon.co.jp/dp/4535783837
買ったのだけどどっか行ってしまった... 増井俊之.icon
と思ったら本棚で発見!
と思ったがまた行方不明! 増井俊之.icon 2022/4/24
マスをクリック → スタート
https://youtu.be/PNK_a0cl9W0
p5-sketch-button.icon p5.js によるライフゲーム code:sketch.js
const sketch = p => {
let w;
let columns;
let rows;
let board;
let next;
p.setup = () => {
p.createCanvas(300, 480);
w = 10;
// Calculate columns and rows
columns = p.floor(p.width / w);
rows = p.floor(p.height / w);
// Wacky way to make a 2D array is JS
board = new Array(columns);
for (let i = 0; i < columns; i++) {
boardi = new Array(rows); }
// Going to use multiple 2D arrays and swap them
next = new Array(columns);
for (i = 0; i < columns; i++) {
}
init();
}
p.draw = () => {
p.background(255);
generate();
for ( let i = 0; i < columns;i++) {
for ( let j = 0; j < rows;j++) {
if ((boardij == 1)) p.fill(0,0,255); else p.fill(255);
p.stroke(0);
p.rect(i * w, j * w, w-1, w-1);
}
}
}
// reset board when mouse is pressed
p.mousePressed = () => {
init();
}
// Fill board randomly
function init() {
for (let i = 0; i < columns; i++) {
for (let j = 0; j < rows; j++) {
// Lining the edges with 0s
if (i == 0 || j == 0 || i == columns-1 || j == rows-1) boardij = 0; // Filling the rest randomly
else boardij = p.floor(p.random(2)); }
}
}
// The process of creating the new generation
function generate() {
// Loop through every spot in our 2D array and check spots neighbors
for (let x = 1; x < columns - 1; x++) {
for (let y = 1; y < rows - 1; y++) {
// Add up all the states in a 3x3 surrounding grid
let neighbors = 0;
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
}
}
// A little trick to subtract the current cell's state since
// we added it in the above loop
// Rules of Life
if ((boardxy == 1) && (neighbors < 2)) nextxy = 0; // Loneliness else if ((boardxy == 1) && (neighbors > 3)) nextxy = 0; // Overpopulation else if ((boardxy == 0) && (neighbors == 3)) nextxy = 1; // Reproduction else nextxy = boardxy; // Stasis }
}
// Swap!
let temp = board;
board = next;
next = temp;
}
}
new p5(sketch, 'editor');
p5-sketch-button.icon 実行
ライフゲームは下記の紹介動画がおすすめですyanma.icon
適度にストーリー性があってとても良い
これはすごい 増井俊之.icon
https://youtu.be/6js8RfUmOuQ