1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
const pr = t => process.stdout.write(t)
class GameOfLife {
constructor(){
this.width = process.stdout.columns - 2
this.height = process.stdout.rows - 4
this.cells = Array.from({length: this.width * this.height}, () => Math.round(Math.random()))
}
printBoard() {
console.clear()
pr('╔' + '═'.repeat(this.width) + '╗')
pr('║' + ' '.repeat(Math.floor((this.width - 12) / 2)) + 'GAME OF LIFE' + ' '.repeat(Math.ceil((this.width - 12) / 2)) + '║')
pr('╠' + '═'.repeat(this.width) + '╣')
for (let l=0; l<this.height; l++) {
pr('║' + this.cells.slice(l*this.width, (l+1)*this.width).map((c, i) => (
c === 1
? this.prevCells && this.prevCells[l*this.width+i] === 1
? '#'
: '\x1b[32m#\x1b[0m'
: this.prevCells && this.prevCells[l*this.width+i] === 1
? '\x1b[31m#\x1b[0m'
: ' '
)).join('') + '║')
}
pr('╚' + '═'.repeat(this.width) + '╝')
}
findCell(x, y) {
return this.cells[x + y * this.width]
}
computeCellNextState(x, y){
const st = (x, y) => {
if (x >= 0 && x < this.width && y >= 0 && y < this.height) {
return this.findCell(x, y)
} else {
return 0;
}
}
const total = st(x-1, y-1) + st(x, y-1) + st(x+1, y-1) + st(x-1, y) + st(x+1, y) + st(x-1, y+1) + st(x, y+1) + st(x+1, y+1)
if (st(x, y) === 1) {
if (total < 2) {
return 0
} else if (total >= 2 && total <= 3) {
return 1
} else {
return 0
}
} else if (total === 3) {
return 1
} else {
return 0
}
}
printNextGeneration(){
const nextState = []
for (let y = 0; y < this.height; y++) {
for (let x = 0; x < this.width; x++) {
nextState.push(this.computeCellNextState(x, y))
}
}
this.prevCells = this.cells
this.cells = nextState
this.printBoard()
}
}
let game = new GameOfLife()
pr('\u001B[?25l')
let animation = setInterval(() => game.printNextGeneration(), 250)
process.on('SIGINT', function() {
clearInterval(animation)
pr('\u001B[?25h')
console.clear()
process.exit()
});
process.stdout.on('resize', () => {
clearInterval(animation)
game = new GameOfLife()
animation = setInterval(() => game.printNextGeneration(), 250)
})
|