odin-gol/main.odin

70 lines
1.4 KiB
Odin
Raw Normal View History

2024-05-02 11:28:03 +02:00
package main
import "core:fmt"
import "core:math/rand"
2024-05-02 11:28:03 +02:00
import "core:strings"
2024-05-02 13:09:40 +02:00
import "core:time"
2024-05-02 11:28:03 +02:00
2024-05-02 13:27:53 +02:00
WIDTH :: 64
HEIGHT :: 64
2024-05-02 11:28:03 +02:00
AREA :: WIDTH * HEIGHT
state: [AREA]bool
2024-05-02 11:28:03 +02:00
main :: proc() {
2024-05-02 13:09:40 +02:00
fmt.print("\e[2J") // clear screen
for i in 0 ..< AREA do state[i] = bool(rand.uint32() & 1)
2024-05-02 11:28:03 +02:00
for {
print_board()
update_board()
2024-05-02 13:09:40 +02:00
time.sleep(time.Millisecond * 50)
2024-05-02 11:28:03 +02:00
}
}
print_board :: proc() {
2024-05-02 13:27:53 +02:00
fmt.print("\e[u") // reset cursor
for y := 0; y < HEIGHT; y += 2 {
2024-05-02 13:09:40 +02:00
line := strings.builder_make()
2024-05-02 13:25:01 +02:00
defer strings.builder_destroy(&line)
for x in 0 ..< WIDTH {
2024-05-02 11:28:03 +02:00
top := state[x + y * WIDTH]
bot := state[x + (y + 1) * WIDTH]
c: rune
2024-05-02 13:09:40 +02:00
switch {
case top && bot:
c = '█'
case top && !bot:
c = '▀'
case !top && bot:
c = '▄'
case:
c = ' '
2024-05-02 11:28:03 +02:00
}
2024-05-02 13:09:40 +02:00
strings.write_rune(&line, c)
2024-05-02 11:28:03 +02:00
}
2024-05-02 13:09:40 +02:00
fmt.println(strings.to_string(line))
2024-05-02 11:28:03 +02:00
}
}
update_board :: proc() {
new_state: [AREA]bool = ---
for x in 0 ..< WIDTH {
for y in 0 ..< HEIGHT {
2024-05-02 11:28:03 +02:00
count := 0
for dx in -1 ..= 1 {
2024-05-02 11:28:03 +02:00
px := (x + dx + WIDTH) % WIDTH
for dy in -1 ..= 1 {
2024-05-02 11:28:03 +02:00
py := (y + dy + HEIGHT) % HEIGHT
2024-05-02 13:27:53 +02:00
if state[px + py * WIDTH] do count += 1
2024-05-02 11:28:03 +02:00
}
2024-05-02 13:27:53 +02:00
}
cell := state[x + y * WIDTH]
new_cell := (count == 3 && !cell) || (cell && count < 5 && count > 2)
new_state[x + y * WIDTH] = new_cell
2024-05-02 11:28:03 +02:00
}
}
for i in 0 ..< AREA {
2024-05-02 11:28:03 +02:00
state[i] = new_state[i]
}
}