summaryrefslogtreecommitdiffstats
path: root/life.go
blob: 078e72c9d2e8a690a1d5e8fb9b04b5137aca0ac6 (plain) (blame)
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package main

import (
	"bufio"
	"fmt"
	"math/rand/v2"
	"os"
	"runtime"
	"sync"
	"time"

	"golang.org/x/term"
)

var stdout = bufio.NewWriter(os.Stdout)

const (
	left = -(1 + iota)
	right
)

func readKeys(out chan<- rune) {
	defer close(out)
	stdin := bufio.NewReader(os.Stdin)
	for {
		b, err := stdin.ReadByte()
		if err != nil {
			break
		}
		if b == '\x1b' {
			buf := make([]byte, 2)
			n, err := stdin.Read(buf)
			switch string(buf[:n]) {
			case "[D":
				out <- left
			case "[C":
				out <- right
			}
			if err != nil {
				break
			}
		} else {
			out <- rune(b)
		}
	}
}

type board struct {
	buf  []bool
	rows int
	cols int
}

func newBoard(rows, cols int) board {
	return board{
		buf:  make([]bool, rows*cols),
		rows: rows,
		cols: cols,
	}
}

func (b board) row(i int) []bool {
	start := i * b.cols
	return b.buf[start : start+b.cols]
}

func (b board) neighborCount(i, j int) int {
	count := 0
	for di := -1; di <= 1; di++ {
		for dj := -1; dj <= 1; dj++ {
			if di == 0 && dj == 0 {
				continue
			}
			ii := i + di
			jj := j + dj
			if ii < 0 {
				ii = b.rows - 1
			} else if ii == b.rows {
				ii = 0
			}
			if jj < 0 {
				jj = b.cols - 1
			} else if jj == b.cols {
				jj = 0
			}
			if b.row(ii)[jj] {
				count++
			}
		}
	}
	return count
}

var numCPU = runtime.NumCPU()

func step(nextBoard, activeBoard board) {
	chunkSize := (activeBoard.rows + numCPU - 1) / numCPU
	wg := new(sync.WaitGroup)
	for start := 0; start < activeBoard.rows; start += chunkSize {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for i := start; i < min(start+chunkSize, activeBoard.rows); i++ {
				for j := range activeBoard.cols {
					count := activeBoard.neighborCount(i, j)
					nextBoard.row(i)[j] = count == 3 || count == 2 && activeBoard.row(i)[j]
				}
			}
		}()
	}
	wg.Wait()
}

func life() error {
	cols, rows, err := term.GetSize(int(os.Stdout.Fd()))
	if err != nil {
		return err
	}
	oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
	if err != nil {
		return err
	}
	defer term.Restore(int(os.Stdin.Fd()), oldState)

	board1 := newBoard(rows, cols)
	for i := range board1.rows {
		for j := range board1.cols {
			board1.row(i)[j] = rand.IntN(2) != 0
		}
	}
	board2 := newBoard(rows, cols)
	activeBoard := board1
	nextBoard := board2

	const minDelay = time.Second / 300

	delay := 250 * time.Millisecond
	running := true
	oneTick := false

	frameTimer := time.NewTicker(minDelay)
	defer frameTimer.Stop()
	lastFrameTime := time.Now()
	accumulator := time.Duration(0)

	keyCh := make(chan rune, 1024)
	go readKeys(keyCh)

	for now := range frameTimer.C {
	Read:
		for {
			var key rune
			select {
			case key = <-keyCh:
			default:
				break Read
			}
			switch key {
			case 'q':
				return nil
			case ' ':
				running = !running
			case '.':
				if !running {
					oneTick = true
				}
			case left:
				delay += delay / 3
			case right:
				delay = max(delay-delay/3, minDelay)
			}
		}

		accumulator += now.Sub(lastFrameTime)
		lastFrameTime = now
		if oneTick || accumulator >= delay {
			if accumulator >= delay {
				accumulator -= delay
			}
			if running || oneTick {
				oneTick = false
				step(nextBoard, activeBoard)
				activeBoard, nextBoard = nextBoard, activeBoard
			}
		}
		// Prevent falling behind.
		if accumulator > delay {
			accumulator = delay
		}

		stdout.WriteString("\x1b[H")
		for i := range activeBoard.rows {
			if i > 0 {
				stdout.WriteString("\r\n")
			}
			for j := range activeBoard.cols {
				if activeBoard.row(i)[j] {
					stdout.WriteByte('#')
				} else {
					stdout.WriteByte(' ')
				}
			}
		}
		stdout.Flush()
	}
	panic("unreachable")
}

func main() {
	if err := life(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}