From 4e3ed9cf2a92e0b310672e8955e3c6e430dcfb25 Mon Sep 17 00:00:00 2001 From: Crony Akatsuki Date: Mon, 3 Mar 2025 11:48:02 +0100 Subject: [PATCH] feat: got logic to run. --- main.go | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/main.go b/main.go index 9fadcc6..4bb3ac6 100644 --- a/main.go +++ b/main.go @@ -20,6 +20,9 @@ type gol struct { buffer [ROW][COL]int } +// Create array that holds field's to check for neighbours +var CHECK_ARRAY = [8][2]int{{-1, -1}, {-1, 0}, {-1, +1}, {0, -1}, {0, +1}, {+1, -1}, {+1, 0}, {+1, +1}} + // Initialize empty game of life func initGol() gol { start := [ROW][COL]int{} @@ -44,6 +47,36 @@ func (g gol) Init() tea.Cmd { return nil } +// Check neighobours +func (g gol) countNeighbours(x int, y int) int { + n := 0 + for i := 0; i < 8; i++ { + if g.buffer[x+CHECK_ARRAY[i][0]][y+CHECK_ARRAY[i][1]] == 1 { + n += 1 + } + } + return n +} + +// Life logic +func (g gol) Life() tea.Model { + for i := 1; i < ROW-1; i++ { + for j := 1; j < COL-1; j++ { + n := g.countNeighbours(i, j) + if g.buffer[i][j] == 1 { + if n < 2 || n > 3 { + g.buffer[i][j] = 0 + } + } else { + if n == 3 { + g.buffer[i][j] = 1 + } + } + } + } + return g +} + // Simple update func (g gol) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { @@ -52,6 +85,9 @@ func (g gol) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg.String() { case "ctrl+c", "q": return g, tea.Quit + case " ": + g.Life() + return g, nil } } return g, nil