Compare commits

..

3 Commits

Author SHA1 Message Date
84e9e8fdea feat: add step counter.
Based on discussions on bubbletea github for when I got into issues with
view.

https://github.com/charmbracelet/bubbletea/discussions/1343#discussioncomment-12376381
2025-03-03 22:28:42 +01:00
118a8da1c2 feat: return correct model. 2025-03-03 22:23:08 +01:00
b6c347965c feat: fix logic. 2025-03-03 22:22:29 +01:00

14
main.go
View File

@ -18,6 +18,7 @@ const (
type gol struct { type gol struct {
grid [ROW][COL]int grid [ROW][COL]int
buffer [ROW][COL]int buffer [ROW][COL]int
step int
} }
// Create array that holds field's to check for neighbours // Create array that holds field's to check for neighbours
@ -47,11 +48,11 @@ func (g gol) Init() tea.Cmd {
return nil return nil
} }
// Check neighobours // Check neighbours
func (g gol) countNeighbours(x int, y int) int { func (g gol) countNeighbours(x int, y int) int {
n := 0 n := 0
for i := 0; i < 8; i++ { for i := 0; i < 8; i++ {
if g.buffer[x+CHECK_ARRAY[i][0]][y+CHECK_ARRAY[i][1]] == 1 { if g.grid[x+CHECK_ARRAY[i][0]][y+CHECK_ARRAY[i][1]] == 1 {
n += 1 n += 1
} }
} }
@ -63,7 +64,7 @@ func (g gol) Life() tea.Model {
for i := 1; i < ROW-1; i++ { for i := 1; i < ROW-1; i++ {
for j := 1; j < COL-1; j++ { for j := 1; j < COL-1; j++ {
n := g.countNeighbours(i, j) n := g.countNeighbours(i, j)
if g.buffer[i][j] == 1 { if g.grid[i][j] == 1 {
if n < 2 || n > 3 { if n < 2 || n > 3 {
g.buffer[i][j] = 0 g.buffer[i][j] = 0
} }
@ -74,6 +75,8 @@ func (g gol) Life() tea.Model {
} }
} }
} }
g.grid = g.buffer
g.step++
return g return g
} }
@ -86,8 +89,7 @@ func (g gol) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
case "ctrl+c", "q": case "ctrl+c", "q":
return g, tea.Quit return g, tea.Quit
case " ": case " ":
g.Life() return g.Life(), nil
return g, nil
} }
} }
return g, nil return g, nil
@ -95,7 +97,7 @@ func (g gol) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
// Let's draw this all simply // Let's draw this all simply
func (g gol) View() string { func (g gol) View() string {
var s string s := fmt.Sprintf("Step: %d\n", g.step)
// Making sure to not draw the empty field around the array // Making sure to not draw the empty field around the array
for i := 1; i < ROW-1; i++ { for i := 1; i < ROW-1; i++ {
for j := 1; j < COL-1; j++ { for j := 1; j < COL-1; j++ {