78 lines
1.9 KiB
TypeScript
78 lines
1.9 KiB
TypeScript
// title: game of life
|
|
// author: Simon Cambier
|
|
// desc: short description
|
|
// script: js
|
|
|
|
const width = 240;
|
|
const height = 136;
|
|
|
|
let state: boolean[][] = [];
|
|
let next: boolean[][] = [];
|
|
let generation = 0;
|
|
|
|
function BOOT() {
|
|
for (let i = 0; i < width; i++) {
|
|
state[i] = [];
|
|
next[i] = [];
|
|
for (let j = 0; j < height; j++) {
|
|
state[i][j] = Math.random() > 0.5;
|
|
next[i][j] = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
function TIC() {
|
|
cls(13);
|
|
|
|
for (let i = 0; i < width; i++) {
|
|
for (let j = 0; j < height; j++) {
|
|
let count = 0;
|
|
|
|
// Use modulo to wrap around the edges
|
|
if (state[(i - 1 + width) % width][(j - 1 + height) % height]) count++; // top left
|
|
if (state[(i - 1 + width) % width][j]) count++; // top
|
|
if (state[(i - 1 + width) % width][(j + 1) % height]) count++; // top right
|
|
if (state[i][(j - 1 + height) % height]) count++; // left
|
|
if (state[i][(j + 1) % height]) count++; // right
|
|
if (state[(i + 1) % width][(j - 1 + height) % height]) count++; // bottom left
|
|
if (state[(i + 1) % width][j]) count++; // bottom
|
|
if (state[(i + 1) % width][(j + 1) % height]) count++; // bottom right
|
|
|
|
// Currently alive
|
|
if (state[i][j]) {
|
|
if (count < 2) {
|
|
next[i][j] = false;
|
|
} else if (count > 3) {
|
|
next[i][j] = false;
|
|
} else {
|
|
next[i][j] = true;
|
|
}
|
|
}
|
|
// Currently dead
|
|
else {
|
|
if (count === 3) {
|
|
next[i][j] = true;
|
|
} else {
|
|
next[i][j] = false;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Swap state and next
|
|
// Use a temp var, otherwise state and next will be the same object
|
|
let temp = state;
|
|
state = next;
|
|
next = temp;
|
|
|
|
for (let i = 0; i < width; i++) {
|
|
for (let j = 0; j < height; j++) {
|
|
if (state[i][j]) {
|
|
pix(i, j, 7);
|
|
}
|
|
}
|
|
}
|
|
|
|
print(`Generation: ${++generation}`, 1, 1, 0);
|
|
}
|