aboutsummaryrefslogtreecommitdiff
path: root/internal
diff options
context:
space:
mode:
Diffstat (limited to 'internal')
-rw-r--r--internal/game/render_help.go91
-rw-r--r--internal/game/render_help_test.go81
-rw-r--r--internal/ui/table.go107
-rw-r--r--internal/ui/table_test.go91
4 files changed, 343 insertions, 27 deletions
diff --git a/internal/game/render_help.go b/internal/game/render_help.go
index e2893b5..2d3a304 100644
--- a/internal/game/render_help.go
+++ b/internal/game/render_help.go
@@ -13,9 +13,11 @@ import (
)
type HelpDef struct {
- Name string `yaml:"name"`
- Category string `yaml:"category"`
- Content string `yaml:"description"`
+ Name string `yaml:"name"`
+ Aliases []string `yaml:"aliases"`
+ Related []string `yaml:"related"`
+ Category string `yaml:"category"`
+ Content string `yaml:"description"`
}
type cmdEntry struct {
@@ -63,7 +65,7 @@ var commandList = []cmdEntry{
{"mine", "Active", "Mine rocks (Mining)"},
{"mix", "Active", "Mix potions (Pharmacy)"},
{"mods / modlist", "Instant", "List available science modules"},
- {"north / south / east / west / ne / nw / se / sw / up / down", "Active", "Move in a direction"},
+ {"north / south / east / west / up / down", "Active", "Move in a direction"},
{"option / options", "Instant", "View or change settings"},
{"prompt", "Instant", "Set custom command prompt"},
{"pull / push", "Active", "Interact with objects"},
@@ -94,16 +96,56 @@ func LoadHelp(dataDir string) ([]HelpDef, error) {
dir := filepath.Join(dataDir, "help")
var helps []HelpDef
behavior.WalkYAMLDir(dir, func(path, id string, data []byte) error {
- var h HelpDef
- if err := yaml.Unmarshal(data, &h); err != nil {
+ h := parseHelpDef(data)
+ if h == nil {
return nil
}
- helps = append(helps, h)
+ helps = append(helps, *h)
return nil
})
return helps, nil
}
+// helpRaw accepts both the canonical schema (name/description) and the
+// legacy variant (title/body) used by a few help files.
+type helpRaw struct {
+ Name string `yaml:"name"`
+ Title string `yaml:"title"`
+ Aliases []string `yaml:"aliases"`
+ Related []string `yaml:"related"`
+ Category string `yaml:"category"`
+ Description string `yaml:"description"`
+ Body string `yaml:"body"`
+}
+
+// parseHelpDef unmarshals a help definition, normalizing legacy title/body
+// files onto the canonical HelpDef. Returns nil for files that are not help
+// topics (no name at all).
+func parseHelpDef(data []byte) *HelpDef {
+ var raw helpRaw
+ if err := yaml.Unmarshal(data, &raw); err != nil {
+ return nil
+ }
+ name := raw.Name
+ if name == "" {
+ name = raw.Title
+ }
+ if name == "" {
+ return nil
+ }
+ content := raw.Description
+ if content == "" {
+ content = raw.Body
+ }
+ return &HelpDef{
+ Name: name,
+ Aliases: raw.Aliases,
+ Related: raw.Related,
+ Category: raw.Category,
+ Content: content,
+ }
+}
+
func (g *Game) doHelp(sess *net.Session, topic string) {
if topic == "" {
unicode := true
@@ -141,16 +183,47 @@ func (g *Game) doHelp(sess *net.Session, topic string) {
return
}
- topic = strings.ToLower(topic)
+ topic = strings.ToLower(strings.TrimSpace(topic))
for _, h := range helps {
- if strings.ToLower(h.Name) == topic {
+ if matchesHelpTopic(h, topic) {
sess.WriteLine(fmt.Sprintf(" %s", h.Content))
+ if len(h.Related) > 0 {
+ sess.WriteLine("")
+ sess.WriteLine(fmt.Sprintf(" Related topics: %s", strings.Join(h.Related, ", ")))
+ }
return
}
}
+
+ // No dedicated help page. If it's a known command, at least show its
+ // summary from the command table instead of a dead end.
+ for _, c := range commandList {
+ for _, name := range strings.Split(c.Name, " / ") {
+ if strings.ToLower(strings.TrimSpace(name)) == topic {
+ sess.WriteLine(fmt.Sprintf(" %s - %s", c.Name, c.Desc))
+ sess.WriteLine("")
+ sess.WriteLine(" (No detailed help page for this command yet.)")
+ return
+ }
+ }
+ }
sess.WriteLine(fmt.Sprintf("No help found for '%s'.", topic))
}
+// matchesHelpTopic reports whether the help entry answers the given topic,
+// matching its name or any declared alias (case-insensitive).
+func matchesHelpTopic(h HelpDef, topic string) bool {
+ if strings.EqualFold(h.Name, topic) {
+ return true
+ }
+ for _, a := range h.Aliases {
+ if strings.EqualFold(strings.TrimSpace(a), topic) {
+ return true
+ }
+ }
+ return false
+}
+
func firstLine(s string) string {
if idx := strings.Index(s, "\n"); idx >= 0 {
return s[:idx]
diff --git a/internal/game/render_help_test.go b/internal/game/render_help_test.go
new file mode 100644
index 0000000..b8ad614
--- /dev/null
+++ b/internal/game/render_help_test.go
@@ -0,0 +1,81 @@
+package game
+
+import (
+ "strings"
+ "testing"
+)
+
+func loadHelpOrSkip(t *testing.T) []HelpDef {
+ t.Helper()
+ helps, err := LoadHelp("../../data")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(helps) == 0 {
+ t.Fatal("no help topics loaded")
+ }
+ return helps
+}
+
+func TestLoadHelpAllFilesParse(t *testing.T) {
+ helps := loadHelpOrSkip(t)
+ seen := map[string]bool{}
+ for _, h := range helps {
+ if strings.TrimSpace(h.Name) == "" {
+ t.Errorf("help entry with empty name: %q", h.Content)
+ }
+ if seen[h.Name] {
+ t.Errorf("duplicate help topic %q", h.Name)
+ }
+ seen[h.Name] = true
+ }
+}
+
+func TestNewPlayerHelpExists(t *testing.T) {
+ helps := loadHelpOrSkip(t)
+ found := false
+ for _, h := range helps {
+ if h.Name == "newplayer" {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatal("help topic 'newplayer' missing (referenced by intro room)")
+ }
+}
+
+func TestHelpAliasesResolveWithoutCollision(t *testing.T) {
+ helps := loadHelpOrSkip(t)
+ owner := map[string]string{}
+ for _, h := range helps {
+ for _, a := range h.Aliases {
+ a = strings.ToLower(strings.TrimSpace(a))
+ if a == "" {
+ continue
+ }
+ if prev, dup := owner[a]; dup {
+ t.Errorf("alias %q claimed by both %q and %q", a, prev, h.Name)
+ }
+ owner[a] = h.Name
+ }
+ }
+ for topic, want := range map[string]string{
+ "mine": "mining",
+ "chop": "woodcutting",
+ "fish": "fishing",
+ "fletch": "fletch",
+ "newplayer": "newplayer",
+ "new player": "newplayer",
+ } {
+ resolved := ""
+ for _, h := range helps {
+ if matchesHelpTopic(h, topic) {
+ resolved = h.Name
+ break
+ }
+ }
+ if resolved != want {
+ t.Errorf("help %q resolved to %q, want %q", topic, resolved, want)
+ }
+ }
+}
diff --git a/internal/ui/table.go b/internal/ui/table.go
index 5ef2c99..e85e505 100644
--- a/internal/ui/table.go
+++ b/internal/ui/table.go
@@ -38,6 +38,68 @@ type Table struct {
Rows [][]string
}
+// rebalanceWidths shrinks column widths in place so their sum fits budget.
+// Rather than crushing only the last column, every column wider than the
+// fair share (budget/nCols) is capped first, then columns are trimmed one
+// rune at a time from the widest until the table fits. Leftover slack is
+// handed back round-robin to columns that lost width so wide layouts still
+// use the full line.
+func rebalanceWidths(colWidths []int, budget int) {
+ original := make([]int, len(colWidths))
+ copy(original, colWidths)
+
+ fair := budget / len(colWidths)
+ if fair < 1 {
+ fair = 1
+ }
+ for i, w := range colWidths {
+ if w > fair {
+ colWidths[i] = fair
+ }
+ }
+
+ sum := func() int {
+ t := 0
+ for _, w := range colWidths {
+ t += w
+ }
+ return t
+ }
+
+ // Tight tables: trim the widest column until we fit (or hit 1).
+ for sum() > budget {
+ widest := 0
+ for i, w := range colWidths {
+ if w > colWidths[widest] {
+ widest = i
+ }
+ }
+ if colWidths[widest] <= 1 {
+ break
+ }
+ colWidths[widest]--
+ }
+
+ // Give unused width back to the columns that were reduced.
+ for {
+ extra := budget - sum()
+ if extra <= 0 {
+ break
+ }
+ progress := false
+ for i := 0; i < len(colWidths) && extra > 0; i++ {
+ if colWidths[i] < original[i] {
+ colWidths[i]++
+ extra--
+ progress = true
+ }
+ }
+ if !progress {
+ break
+ }
+ }
+}
+
func (t *Table) Render(unicode bool, maxWidth int) []string {
g := tableGlyphSet(unicode)
@@ -65,29 +127,38 @@ func (t *Table) Render(unicode bool, maxWidth int) []string {
}
}
+ headerCells := t.Columns
+ bodyRows := t.Rows
+
if maxWidth > 0 {
+ // Cell padding: one space on each side of every cell, plus one
+ // separator between columns.
overhead := 3*nCols + 1
- total := overhead
+ budget := maxWidth - overhead
+ if budget < nCols {
+ budget = nCols
+ }
+
+ total := 0
for _, w := range colWidths {
total += w
}
- if total > maxWidth {
- last := nCols - 1
- budget := maxWidth - overhead
- for i := 0; i < last; i++ {
- budget -= colWidths[i]
- }
- if budget < 5 {
- budget = 5
- }
- colWidths[last] = budget
-
- if len(t.Columns) > last {
- t.Columns[last] = color.TruncateVisible(t.Columns[last], budget, unicode)
+ if total > budget {
+ rebalanceWidths(colWidths, budget)
+
+ // Truncate every cell to its (possibly reduced) column width.
+ // Work on copies so rendering never mutates the table.
+ headerCells = make([]string, len(t.Columns))
+ copy(headerCells, t.Columns)
+ for i := range headerCells {
+ headerCells[i] = color.TruncateVisible(headerCells[i], colWidths[i], unicode)
}
+ bodyRows = make([][]string, len(t.Rows))
for i := range t.Rows {
- if len(t.Rows[i]) > last {
- t.Rows[i][last] = color.TruncateVisible(t.Rows[i][last], budget, unicode)
+ bodyRows[i] = make([]string, len(t.Rows[i]))
+ copy(bodyRows[i], t.Rows[i])
+ for j := 0; j < len(bodyRows[i]) && j < nCols; j++ {
+ bodyRows[i][j] = color.TruncateVisible(bodyRows[i][j], colWidths[j], unicode)
}
}
}
@@ -164,11 +235,11 @@ func (t *Table) Render(unicode bool, maxWidth int) []string {
}
if hasCols {
- out = append(out, makeRow(t.Columns))
+ out = append(out, makeRow(headerCells))
out = append(out, makeSep(g.sepLeft, g.sepCross, g.sepRight, g.fillHSep))
}
- for _, row := range t.Rows {
+ for _, row := range bodyRows {
out = append(out, makeRow(row))
}
diff --git a/internal/ui/table_test.go b/internal/ui/table_test.go
new file mode 100644
index 0000000..68b6d32
--- /dev/null
+++ b/internal/ui/table_test.go
@@ -0,0 +1,91 @@
+package ui
+
+import (
+ "strings"
+ "testing"
+
+ "thehouseoficarus/internal/color"
+)
+
+func renderWidths(t *testing.T, tt *Table, unicode bool, maxWidth int) []string {
+ t.Helper()
+ lines := tt.Render(unicode, maxWidth)
+ for _, l := range lines {
+ if vl := color.VisibleLen(l); maxWidth > 0 && vl > maxWidth+1 {
+ t.Errorf("line exceeds maxWidth %d: %d (%q)", maxWidth, vl, l)
+ }
+ }
+ // All border/content lines must be the same visible width so the box
+ // lines up.
+ widths := map[int]bool{}
+ for _, l := range lines {
+ widths[color.VisibleLen(l)] = true
+ }
+ if len(widths) > 1 {
+ var ws []string
+ for w := range widths {
+ ws = append(ws, string(rune('0'+w)))
+ }
+ t.Errorf("inconsistent line widths: %v", strings.Join(ws, ","))
+ }
+ return lines
+}
+
+func TestTableFitsWithinWidth(t *testing.T) {
+ tt := &Table{
+ Title: "Commands",
+ Columns: []string{"Command", "Type", "Description"},
+ Rows: [][]string{
+ {"north / south / east / west / ne / nw / se / sw / up / down", "Active", "Move in a direction"},
+ {"bet", "Active", "Place a casino wager (e.g. bet 100 on banker)"},
+ {"attack / kill", "Active", "Attack a mob"},
+ },
+ }
+ for _, w := range []int{0, 40, 80, 100} {
+ lines := renderWidths(t, tt, true, w)
+ // Description column must never be crushed: with three columns the
+ // description always keeps at least a fair share of the budget.
+ if w == 80 {
+ // lines: border, title, sep, header, sep, rows...
+ if !strings.Contains(lines[5], "Move i") {
+ t.Errorf("description column crushed at width 80: %q", lines[5])
+ }
+ }
+ }
+}
+
+func TestTableNoMutation(t *testing.T) {
+ tt := &Table{
+ Title: "T",
+ Columns: []string{"A", "B"},
+ Rows: [][]string{{"very long cell content here", "x"}},
+ }
+ before := tt.Columns[0]
+ _ = tt.Render(true, 20)
+ if tt.Columns[0] != before {
+ t.Errorf("Render mutated table columns: %q", tt.Columns[0])
+ }
+}
+
+func TestTableASCIIFallback(t *testing.T) {
+ tt := &Table{Title: "T", Columns: []string{"A", "B"}, Rows: [][]string{{"1", "2"}}}
+ lines := renderWidths(t, tt, false, 0)
+ if !strings.Contains(lines[0], "+") {
+ t.Errorf("expected ASCII border, got %q", lines[0])
+ }
+}
+
+func TestTableColoredCellWidth(t *testing.T) {
+ // ANSI-colored cells must be measured and padded by visible length.
+ red := "\x1b[31m"
+ reset := "\x1b[0m"
+ tt := &Table{Columns: []string{"A", "B"}, Rows: [][]string{{red + "hi" + reset, "x"}}}
+ lines := renderWidths(t, tt, true, 0)
+ // lines: top border, header, sep, data row, bottom border
+ if len(lines) < 5 {
+ t.Fatalf("expected 5 lines, got %d: %q", len(lines), lines)
+ }
+ if !strings.Contains(lines[3], "hi") || !strings.Contains(lines[3], "x") {
+ t.Errorf("unexpected row: %q", lines[3])
+ }
+}