Skip to content

Instantly share code, notes, and snippets.

@tswaters
Created December 13, 2020 00:05
Show Gist options
  • Save tswaters/e3b38b18cc2330ae99210ddad66a0823 to your computer and use it in GitHub Desktop.
Save tswaters/e3b38b18cc2330ae99210ddad66a0823 to your computer and use it in GitHub Desktop.
Terminal game of life
import readline from 'readline'
const w = process.stdout.columns
const h = process.stdout.rows
const init = () => Array.from({ length: w * h }).map(() => Math.round(Math.random()))
let state = init()
const deindex = (i) => [i % w, Math.floor(i / w)]
// toroidal array - this returns index from arbitrary x/y coordinates
// coordinates can exceeds bounds of width/height, making it toroidal
const index = (dx, dy) => {
const xmod = dx % w
const ymod = dy % h
const x = xmod === 0 ? 0 : (dx < 0 ? w : 0) + xmod
const y = ymod === 0 ? 0 : (dy < 0 ? h : 0) + ymod
return x + y * w
}
process.stdout.write('\x1b[2J') // clear screen
process.stdout.write('\x1b[?25l') // hide cursor
process.stdin.setRawMode(true)
readline.emitKeypressEvents(process.stdin)
process.stdin.on('keypress', function (ch, key) {
if (key && key.ctrl && key.name === 'c') {
process.stdout.write('\x1b[1;1H') // cursor 0,0
process.stdout.write('\x1b[2J') // clear screen
process.stdout.write('\x1b[?25h') // show cursor
process.stdin.unref()
clearInterval(tid)
} else {
process.stdout.write('\x1b[2J') // clear screen
state = init()
}
})
const tid = setInterval(
() =>
(state = state.map((cur, i) => {
const [x, y] = deindex(i)
const sum = [
state[index(x - 1, y - 1)],
state[index(x - 1, y)],
state[index(x - 1, y + 1)],
state[index(x, y - 1)],
state[index(x, y)],
state[index(x, y + 1)],
state[index(x + 1, y - 1)],
state[index(x + 1, y)],
state[index(x + 1, y + 1)],
].reduce((acc, nval) => acc + nval)
let r = 0
if (sum === 3) r = 1
if (sum === 4) r = cur
if (r !== cur) {
process.stdout.write(`\x1b[${y + 1};${x + 1}H`) // move cursor
process.stdout.write(r ? `\u2588` : ' ') // block or space
}
return r
})),
0
)
@tswaters
Copy link
Author

Game of life? In MY terminal? It's more likely than you think!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment