gol/cmd/gol/gol.go
2025-02-11 22:30:21 +01:00

86 lines
1.6 KiB
Go

package main
import (
"flag"
"gol/gol"
"gol/term"
"log"
"os"
"os/signal"
"runtime/pprof"
"syscall"
"time"
)
func main() {
cpuprofile := flag.String("cpuprofile", "", "write cpu profile to file")
flag.Parse()
// Jeśli podano flagę cpuprofile, rozpocznij profilowanie
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal("could not create CPU profile: ", err)
}
defer f.Close()
if err := pprof.StartCPUProfile(f); err != nil {
log.Fatal("could not start CPU profile: ", err)
}
defer pprof.StopCPUProfile()
}
game()
}
func game() {
// arenas - front one is printent, then new state is calculated into back one
// next front and back are switched
front := gol.New(20, 40)
back := gol.New(20, 40)
// draw initial objects
// glider
front[0][3] = true
front[1][4] = true
front[2][2] = true
front[2][3] = true
front[2][4] = true
// cross
front[16][21] = true
front[17][21] = true
front[18][21] = true
// catch interrupt signals
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
// initialize screen
term.StartFullscreen()
term.TurnCursor(term.CursorOff)
defer restoreScreen()
// setup timer
ticker := time.NewTicker(250 * time.Millisecond)
defer ticker.Stop()
mainLoop:
for {
term.GoHome()
front.PrintMe()
front.NextGen(back)
front, back = back, front // switch arenas
select {
case <-sigs: // interrupt (Ctrl-C etc)
break mainLoop
case <-ticker.C: // wait for next tick
}
}
}
// restoreScreen switch back terminal to normal mode.
func restoreScreen() {
term.FinishFullscreen()
term.TurnCursor(term.CursorOn)
}