commit 3a0e32066f35de2ede833f820d4906faa42f6b6c
parent dc4abee56e21a9f91a9b6d14d18308170ea6abda
Author: dwrz <dwrz@dwrz.net>
Date:   Mon, 26 Dec 2022 17:13:55 +0000
Refactor minotaur automatic size
Diffstat:
2 files changed, 36 insertions(+), 4 deletions(-)
diff --git a/cmd/minotaur/main.go b/cmd/minotaur/main.go
@@ -15,8 +15,8 @@ import (
 )
 
 var (
-	height = flag.Int("h", 2, "height")
-	width  = flag.Int("w", 2, "width")
+	height = flag.Int("h", 0, "height")
+	width  = flag.Int("w", 0, "width")
 	tick   = flag.Int("t", 250, "ms between minotaur movement")
 )
 
@@ -25,10 +25,10 @@ func main() {
 
 	// Parse flags.
 	flag.Parse()
-	if *height <= 0 {
+	if *height < 0 {
 		l.Error.Fatalf("invalid height: %d", *height)
 	}
-	if *width <= 0 {
+	if *width < 0 {
 		l.Error.Fatalf("invalid width: %d", *width)
 	}
 	if *tick <= 0 {
@@ -62,6 +62,19 @@ func main() {
 	if err != nil {
 		l.Error.Fatalf("failed to get terminal attributes: %v", err)
 	}
+	size, err := t.Size()
+	if err != nil {
+		l.Error.Fatalf("failed to get terminal size: %v", err)
+	}
+	// If no dimensions were provided, use the terminal size.
+	if *height == 0 {
+		rows := int(size.Rows)
+		height = &rows
+	}
+	if *width == 0 {
+		cols := int(size.Columns)
+		width = &cols
+	}
 
 	// TODO: refactor; handle sigwinch.
 	go func() {
diff --git a/pkg/minotaur/minotaur.go b/pkg/minotaur/minotaur.go
@@ -58,6 +58,25 @@ type Parameters struct {
 }
 
 func New(p Parameters) (*Game, error) {
+	// Account for two spaces per cell; horizontal passages and walls.
+	// Account an extra row for the right wall.
+	if p.Width%4 == 0 {
+		p.Width -= 1
+	}
+	p.Width /= 4
+
+	// Account extra rows for vertical passages and walls.
+	if p.Height%2 == 0 {
+		p.Height -= 1
+	}
+	p.Height /= 2
+
+	// If either the terminal width or height are zero,
+	// then the terminal is too small to render the maze.
+	if p.Height == 0 || p.Width == 0 {
+		return nil, fmt.Errorf("terminal too small")
+	}
+
 	var g = &Game{
 		errs:     make(chan error),
 		events:   make(chan *input.Event),