aboutsummaryrefslogtreecommitdiff
path: root/internal/game/render_predictions.go
blob: 851aa671f6f916860521fd93e53b7a13dc273c4f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
package game

import (
	"fmt"
	"math"
	"strconv"
	"strings"
	"unicode/utf8"

	"thehouseoficarus/internal/casino"
	"thehouseoficarus/internal/color"
	"thehouseoficarus/internal/net"
	"thehouseoficarus/internal/prediction"
	"thehouseoficarus/internal/ui"
)

// Fixed fields keep the outcome labels, percentages and bars on the same
// columns from one market row to the next.
const (
	predictionNameWidth = 6
	predictionPctWidth  = 5
)

func predictionWidth(s *net.Session) int {
	width := 80
	if w := s.Player.OptionInt("wrap_width"); w > 0 {
		width = min(width, w)
	}
	return max(12, width)
}
func (g *Game) predictionGlyph(s *net.Session, unicode, ascii string) string {
	if s.Player.OptionBool("unicode") {
		return unicode
	}
	return ascii
}
func (g *Game) predictionSep(s *net.Session) string {
	if s.Player.OptionBool("unicode") {
		return " · "
	}
	return " | "
}
func padRightRunes(s string, n int) string {
	if d := n - utf8.RuneCountInString(s); d > 0 {
		return s + strings.Repeat(" ", d)
	}
	return s
}
func padLeftRunes(s string, n int) string {
	if d := n - utf8.RuneCountInString(s); d > 0 {
		return strings.Repeat(" ", d) + s
	}
	return s
}

func (g *Game) predictionFrame(s *net.Session, title string, lines []string) {
	width := predictionWidth(s)
	inner := width - 4
	tl, tr, bl, br, h, v := "+", "+", "+", "+", "-", "|"
	if s.Player.OptionBool("unicode") {
		tl, tr, bl, br, h, v = "╔", "╗", "╚", "╝", "═", "║"
	}
	border := func(text string) string { return g.colorize(s, "casino_menu", text) }
	title = color.TruncateVisible(" "+title+" ", width-4, s.Player.OptionBool("unicode"))
	top := tl + h + title + strings.Repeat(h, max(0, width-3-color.VisibleLen(title))) + tr
	out := []string{border(top)}
	for _, text := range lines {
		for _, line := range predictionFrameLines(text, inner) {
			out = append(out, border(v)+" "+line+strings.Repeat(" ", max(0, inner-color.VisibleLen(line)))+" "+border(v))
		}
	}
	out = append(out, border(bl+strings.Repeat(h, width-2)+br))
	s.WriteLine(strings.Join(out, "\n"))
}

// WrapANSI emits CRLF. Strip those separators before padding framed rows;
// an embedded CR would return the Telnet cursor to column zero mid-row.
func predictionFrameLines(text string, width int) []string {
	var out []string
	for _, line := range strings.Split(color.WrapANSI(text, width), "\n") {
		line = strings.TrimSuffix(line, "\r")
		if color.VisibleLen(line) <= width {
			out = append(out, line)
			continue
		}
		// WrapANSI word-wraps but does not split long URLs/identifiers. Split those
		// without cutting an ANSI sequence or losing any of the resolution text.
		var b strings.Builder
		runes := []rune(line)
		visible := 0
		for i := 0; i < len(runes); i++ {
			if runes[i] == '\x1b' && i+1 < len(runes) && runes[i+1] == '[' {
				b.WriteRune(runes[i])
				i++
				b.WriteRune(runes[i])
				for i+1 < len(runes) {
					i++
					b.WriteRune(runes[i])
					if runes[i] >= 0x40 && runes[i] <= 0x7e {
						break
					}
				}
				continue
			}
			if visible == width {
				out = append(out, b.String())
				b.Reset()
				visible = 0
			}
			b.WriteRune(runes[i])
			visible++
		}
		if b.Len() > 0 {
			out = append(out, b.String())
		}
	}
	return out
}

func (g *Game) predictionDirection(s *net.Session, delta float64) string {
	if delta > 0 {
		return g.predictionGlyph(s, "↑", "^")
	}
	if delta < 0 {
		return g.predictionGlyph(s, "↓", "v")
	}
	return g.predictionGlyph(s, "→", "=")
}
func (g *Game) predictionDelta(s *net.Session, delta float64, unit string) string {
	category := "casino_result_push"
	if delta > 0 {
		category = "casino_result_win"
	} else if delta < 0 {
		category = "casino_result_loss"
	}
	format := "%s %+.1f %s"
	if unit == "cr" {
		format = "%s %+.0f %s"
	}
	return g.colorize(s, category, fmt.Sprintf(format, g.predictionDirection(s, delta), delta, unit))
}

func predictionPct(p float64) string {
	v := p * 100
	if math.Abs(v-math.Round(v)) < 0.05 {
		return fmt.Sprintf("%.0f%%", math.Round(v))
	}
	return fmt.Sprintf("%.1f%%", v)
}

// predictionTable renders a shared, single-frame table with the same column
// layout across every counter screen. The flex column absorbs overflow so live
// numbers (shares, cost, P/L) are never truncated to make room for prose.
func (g *Game) predictionTable(s *net.Session, title string, headers []string, rows [][]string, flex int) {
	unicode := s.Player.OptionBool("unicode")
	width := predictionWidth(s)
	budget := width - (3*len(headers) + 1)
	widths := make([]int, len(headers))
	for i, h := range headers {
		widths[i] = color.VisibleLen(h)
	}
	for _, row := range rows {
		for i, cell := range row {
			if i < len(widths) && color.VisibleLen(cell) > widths[i] {
				widths[i] = color.VisibleLen(cell)
			}
		}
	}
	total := 0
	for _, w := range widths {
		total += w
	}
	if total > budget {
		excess := total - budget
		if flex >= 0 && flex < len(widths) && widths[flex] > 4 {
			shrink := min(excess, widths[flex]-4)
			widths[flex] -= shrink
			excess -= shrink
		}
		for excess > 0 {
			progress := false
			for i := range widths {
				if i == flex {
					continue
				}
				if widths[i] > 1 {
					widths[i]--
					excess--
					progress = true
					if excess == 0 {
						break
					}
				}
			}
			if !progress {
				break
			}
		}
		for r := range rows {
			for i := range rows[r] {
				if i < len(widths) {
					rows[r][i] = color.TruncateVisible(rows[r][i], widths[i], unicode)
				}
			}
		}
	}
	table := ui.Table{Title: title, Columns: headers, Rows: rows}
	s.WriteLine(strings.Join(table.Render(unicode, width), "\n"))
}

// predictionOddsCell draws one complementary bar per market. Every row shares
// the same left/right field widths, so outcome labels, percentages and bars
// line up down the column. Multi-outcome markets list their actual labels.
func (g *Game) predictionOddsCell(s *net.Session, m prediction.Market, target int) string {
	names, _, prices, err := m.Values()
	if err != nil || target < 8 {
		return ""
	}
	unicode := s.Player.OptionBool("unicode")
	if len(names) != 2 {
		parts := make([]string, 0, len(names))
		for i, name := range names {
			parts = append(parts, prediction.Clean(name, 12)+" "+predictionPct(prices[i]))
		}
		return color.TruncateVisible(strings.Join(parts, g.predictionSep(s)), target, unicode)
	}
	leftPct, rightPct := predictionPct(prices[0]), predictionPct(prices[1])
	left := padRightRunes(strings.ToUpper(prediction.Clean(names[0], predictionNameWidth)), predictionNameWidth) +
		" " + padLeftRunes(leftPct, predictionPctWidth)
	right := padRightRunes(rightPct, predictionPctWidth)
	rightName := padRightRunes(strings.ToUpper(prediction.Clean(names[1], predictionNameWidth)), predictionNameWidth)
	bar := target - color.VisibleLen(left) - color.VisibleLen(right) - color.VisibleLen(rightName) - 3
	if bar < 3 {
		// Narrow screens: keep the aligned percentages, drop the names.
		left = padLeftRunes(leftPct, predictionPctWidth)
		right = padRightRunes(rightPct, predictionPctWidth)
		rightName = ""
		bar = target - 2*predictionPctWidth - 3
	}
	if bar < 3 {
		bar = 3
	}
	split := int(math.Round(prices[0] * float64(bar)))
	split = max(0, min(bar, split))
	fill, empty := g.predictionGlyph(s, "█", "#"), g.predictionGlyph(s, "░", ".")
	barText := g.colorize(s, "casino_result_win", strings.Repeat(fill, split)) +
		g.colorize(s, "casino_result_loss", strings.Repeat(empty, bar-split))
	cell := g.colorize(s, "casino_result_win", left) + " " + barText + " " + g.colorize(s, "casino_result_loss", right)
	if rightName != "" {
		cell += " " + g.colorize(s, "casino_action", rightName)
	}
	return color.TruncateVisible(cell, target, unicode)
}

// predictionHeat maps a probability to an RGB color: red at 0%, green at 100%.
func predictionHeat(p float64) (int, int, int) {
	if p < 0.5 {
		t := p / 0.5
		return 230, int(80 + 120*t), 60
	}
	t := (p - 0.5) / 0.5
	return int(230 - 170*t), 200, 80
}

// predictionGraph colors the odds history: the trace is shaded by price while
// the axes and labels stay dim, so the line reads clearly at a glance.
func (g *Game) predictionGraph(s *net.Session, points []prediction.Point, width int) []string {
	raw := prediction.GraphMode(points, s.Player.OptionBool("unicode"), width)
	lines := strings.Split(raw, "\n")
	vert := "|"
	if s.Player.OptionBool("unicode") {
		vert = "│"
	}
	mode := g.colorMode(s)
	out := make([]string, 0, len(lines))
	for _, line := range lines {
		i := strings.Index(line, vert)
		j := strings.LastIndex(line, vert)
		if i < 0 || j <= i {
			out = append(out, g.colorize(s, "casino_action", line))
			continue
		}
		pct := 0.0
		if len(line) >= 4 && line[3] == '%' {
			if n, err := strconv.Atoi(strings.TrimSpace(line[:3])); err == nil {
				pct = float64(n) / 100
			}
		}
		r, gc, b := predictionHeat(pct)
		spec := color.ColorSpec{Fg: color.NearestXterm256(r, gc, b)}
		out = append(out, g.colorize(s, "casino_action", line[:i+len(vert)])+
			color.Render(mode, spec, line[i+len(vert):j])+
			g.colorize(s, "casino_action", line[j:]))
	}
	return out
}

// predictionCommands returns the context-sensitive verb hints. The counter
// uses the same menu hooks as every casino game, so look/what and the
// casino_hints option behave identically.
func (g *Game) predictionCommands(s *net.Session) []casino.MenuCommand {
	if s.PredictionBusy {
		return []casino.MenuCommand{{Command: "stop", Desc: "Leave the counter and cancel the pending request"}}
	}
	commands := []casino.MenuCommand{}
	if !s.PredictionUnavailable {
		switch s.PredictionScreen {
		case "view":
			commands = append(commands, casino.MenuCommand{Command: "buy SHARES OUTCOME", Desc: "Buy outcome shares, e.g. buy 10 yes"}, casino.MenuCommand{Command: "back", Desc: "Return to your place in the market list"})
		case "active":
			commands = append(commands, casino.MenuCommand{Command: "holding N", Desc: "Open contract N's market (or type its number)"}, casino.MenuCommand{Command: "sell N", Desc: "Sell all shares of contract N to the house"})
		case "closed":
			commands = append(commands, casino.MenuCommand{Command: "holding N", Desc: "Open contract N's market (or type its number)"})
		default:
			commands = append(commands, casino.MenuCommand{Command: "view N", Desc: "Open market N (or type its number)"}, casino.MenuCommand{Command: "find WORDS", Desc: "Search the popular-market selection"})
		}
		if s.PredictionScreen == "list" || s.PredictionScreen == "closed" {
			commands = append(commands, casino.MenuCommand{Command: "next", Desc: "Next page"}, casino.MenuCommand{Command: "prev", Desc: "Previous page"})
		}
		rules := "How to play prediction markets"
		if s.PredictionScreen == "view" {
			rules = "Resolution rules for the selected market"
		}
		commands = append(commands, casino.MenuCommand{Command: "markets", Desc: "Browse the market selection"}, casino.MenuCommand{Command: "active", Desc: "Your open contracts"}, casino.MenuCommand{Command: "closed", Desc: "Your sold and resolved contracts"}, casino.MenuCommand{Command: "rules", Desc: rules})
	}
	return append(commands, casino.MenuCommand{Command: "collect", Desc: "Withdraw winnings from resolved contracts"}, casino.MenuCommand{Command: "refresh", Desc: "Update this screen with live data"}, casino.MenuCommand{Command: "stop", Desc: "Leave the counter"})
}

// predictionHints uses the exact same visibility policy, balance line and
// command-column renderer as the other casino games.
func (g *Game) predictionHints(s *net.Session, force ...bool) {
	forced := len(force) > 0 && force[0]
	show := g.casinoHintsVisible(s, &casino.MenuView{ShowHints: s.PredictionShowHints})
	s.PredictionShowHints = false
	if !forced && !show {
		return
	}
	balance := fmt.Sprintf("Available %s credits", g.colorize(s, "casino_credits", fmt.Sprint(s.Player.Credits)))
	s.WriteLine("")
	s.WriteLine(g.renderCasinoCommands(s, balance, "", g.predictionCommands(s)))
}