gameoflife-go/main.go
2024-01-26 18:28:36 +01:00

110 lines
2.2 KiB
Go

package main
import (
"math"
"math/rand"
"os"
"github.com/tfriedel6/canvas/sdlcanvas"
"strconv"
)
var (
squareSize int
sizeX int
sizeY int
gameWidth int
gameHeight int
)
func initTable(sizeX, sizeY int) map[int]map[int]int {
table := make(map[int]map[int]int)
for x := 0; x < sizeX; x++ {
table[x] = make(map[int]int)
for y := 0; y < sizeY; y++ {
table[x][y] = rand.Intn(2)
}
}
return table
}
func updateTable(table map[int]map[int]int) map[int]map[int]int {
sum := 0
newTable := make(map[int]map[int]int)
for x := 0; x < sizeX; x++ {
newTable[x] = make(map[int]int)
for y := 0; y < sizeY; y++ {
sum = getSum(table, x, y)
if sum == 3 {
newTable[x][y] = 1
} else if sum > 3 || sum < 2 {
newTable[x][y] = 0
} else {
newTable[x][y] = table[x][y]
}
}
}
return newTable
}
func getSum(table map[int]map[int]int, x, y int) int {
sum := 0
sum += table[(sizeX+x-1)%sizeX][(sizeY+y-1)%sizeY]
sum += table[x][(sizeY+y-1)%sizeY]
sum += table[(sizeX+x+1)%sizeX][(sizeY+y-1)%sizeY]
sum += table[(sizeX+x-1)%sizeX][y]
sum += table[(sizeX+x+1)%sizeX][y]
sum += table[(sizeX+x-1)%sizeX][(sizeY+y+1)%sizeY]
sum += table[x][(sizeY+y+1)%sizeY]
sum += table[(sizeX+x+1)%sizeX][(sizeY+y+1)%sizeY]
return sum
}
func main() {
squareSize, _ = strconv.Atoi(os.Args[1])
sizeX, _ = strconv.Atoi(os.Args[2])
sizeY, _ = strconv.Atoi(os.Args[3])
gameWidth = squareSize * sizeX
gameHeight = squareSize * sizeY
table := initTable(sizeX, sizeY)
wnd, cv, err := sdlcanvas.CreateWindow(gameWidth, gameHeight, "Game of life")
if err != nil {
panic(err)
}
defer wnd.Destroy()
w, h := float64(cv.Width()), float64(cv.Height())
wnd.MainLoop(func() {
cv.SetFillStyle("#3f4b7e")
cv.FillRect(0, 0, w, h)
for x := 0; x < sizeX; x++ {
for y := 0; y < sizeY; y++ {
if table[x][y] == 1 {
cv.SetFillStyle(255, 255, 255)
cv.BeginPath()
// cv.Rect(float64(x*squareSize), float64(y*squareSize), float64(squareSize), float64(squareSize))
cv.Arc(float64(x*squareSize), float64(y*squareSize), float64(squareSize)/2, 0, math.Pi*2, false)
cv.ClosePath()
cv.Fill()
}
}
}
table = updateTable(table)
})
}