This commit is contained in:
Meghdad committed 2026-11-27 19:04:23 +03:30
commit efe2c8a9c8
13 files changed
+1700

No files matched your search

+170
View File
@@ -0,0 +1,170 @@
package arcade
import (
"fmt"
"strings"
lg "charm.land/lipgloss/v2"
"thermal-snake/internal/game"
)
const fieldWidth = 2 * game.Width
var (
cold = lg.NewStyle().Foreground(lg.Color("#6E405D")).Background(lg.Color("#211322"))
warm = lg.NewStyle().Foreground(lg.Color("#97536B")).Background(lg.Color("#30192B"))
hotspot = lg.NewStyle().Foreground(lg.Color("#B06978")).Background(lg.Color("#3F2236"))
foodStyles = [...]lg.Style{
lg.NewStyle().Bold(true).Foreground(lg.Color("#FFE7A5")).Background(lg.Color("#5F3243")),
lg.NewStyle().Bold(true).Foreground(lg.Color("#FFF5C4")).Background(lg.Color("#894B49")),
}
bodyStyles = [...]lg.Style{
lg.NewStyle().Foreground(lg.Color("#FFAD7C")).Background(lg.Color("#49233A")),
lg.NewStyle().Foreground(lg.Color("#FC7986")).Background(lg.Color("#49233A")),
lg.NewStyle().Foreground(lg.Color("#D95685")).Background(lg.Color("#49233A")),
lg.NewStyle().Foreground(lg.Color("#BB548C")).Background(lg.Color("#49233A")),
}
headStyle = lg.NewStyle().Bold(true).Foreground(lg.Color("#2C1727")).Background(lg.Color("#FFE7A5"))
impactStyle = lg.NewStyle().Bold(true).Foreground(lg.Color("#291423")).Background(lg.Color("#FF836D"))
overlayStyle = lg.NewStyle().Bold(true).Foreground(lg.Color("#FFE0A2")).Background(lg.Color("#522E46"))
headGlyphs = [...]string{"▴", "▸", "▾", "◂"}
)
// The lobby scan loops a single coil around the contours behind the live field.
var displayCoil = game.Frame{
Body: []game.Point{
{X: 16, Y: 4}, {X: 15, Y: 4}, {X: 14, Y: 4}, {X: 13, Y: 4}, {X: 12, Y: 4},
{X: 12, Y: 5}, {X: 12, Y: 6}, {X: 12, Y: 7}, {X: 11, Y: 7}, {X: 10, Y: 7},
{X: 9, Y: 7}, {X: 8, Y: 7}, {X: 8, Y: 6}, {X: 8, Y: 5}, {X: 8, Y: 4},
{X: 7, Y: 4}, {X: 6, Y: 4}, {X: 5, Y: 4}, {X: 4, Y: 4}, {X: 4, Y: 5},
{X: 4, Y: 6}, {X: 4, Y: 7}, {X: 4, Y: 8}, {X: 4, Y: 9}, {X: 5, Y: 9},
{X: 6, Y: 9}, {X: 7, Y: 9}, {X: 8, Y: 9}, {X: 9, Y: 9}, {X: 10, Y: 9},
{X: 11, Y: 9}, {X: 12, Y: 9}, {X: 13, Y: 9}, {X: 14, Y: 9}, {X: 15, Y: 9},
{X: 16, Y: 9}, {X: 17, Y: 9}, {X: 17, Y: 8}, {X: 17, Y: 7}, {X: 17, Y: 6},
{X: 16, Y: 6}, {X: 15, Y: 6},
},
Food: game.Point{X: 19, Y: 4}, Direction: game.Right,
}
func (m *Model) field() []string {
frame := displayCoil
label := fmt.Sprintf("FIELD / %d × %d", game.Width, game.Height)
art := m.screen == lobby
if art {
label = "CHAMBER SCAN"
} else {
frame = m.run.Frame()
}
cells := darkField
if art {
cells = scanField
row := m.phase % game.Height
cells[row] = scanLine[row]
}
if frame.Outcome != game.Clear {
cells[frame.Food.Y][frame.Food.X] = foodStyles[m.phase%2].Render("◆ ")
}
for i, p := range frame.Body {
shade := i * len(bodyStyles) / len(frame.Body)
glyph := [...]string{"██", "██", "▓▓", "▒▒"}[shade]
cells[p.Y][p.X] = bodyStyles[shade].Render(glyph)
}
head := frame.Body[0]
cells[head.Y][head.X] = headStyle.Render(headGlyphs[frame.Direction] + " ")
if frame.Outcome == game.Coil {
cells[frame.Impact.Y][frame.Impact.X] = impactStyle.Render("××")
}
switch m.screen {
case warmup:
box(&cells, 1, fmt.Sprintf("SEEK HEAT IN %02d", m.countdown))
case paused:
box(&cells, 5, "PAUSED")
}
top, bottom := -1, -1
if frame.Outcome == game.Wall {
switch frame.Impact.Y {
case -1:
top = frame.Impact.X
case game.Height:
bottom = frame.Impact.X
}
}
lines := []string{fieldEdge("╭", "╮", label, top)}
for y, row := range cells {
left, right := subtle.Render("│"), subtle.Render("│")
if frame.Outcome == game.Wall && frame.Impact.Y == y {
if frame.Impact.X < 0 {
left = impactStyle.Render("×")
} else {
right = impactStyle.Render("×")
}
}
lines = append(lines, left+strings.Join(row[:], "")+right)
}
return append(lines, fieldEdge("╰", "╯", "", bottom))
}
func fieldEdge(left, right, label string, impact int) string {
if impact >= 0 {
cells := 2 * impact
return subtle.Render(left+strings.Repeat("─", cells)) + impactStyle.Render("××") +
subtle.Render(strings.Repeat("─", fieldWidth-cells-2)+right)
}
if label == "" {
return subtle.Render(left + strings.Repeat("─", fieldWidth) + right)
}
prefix := subtle.Render(left + "─ ")
title := " " + label + " "
return prefix + accent.Render(title) + subtle.Render(" "+strings.Repeat("─", fieldWidth-3-lg.Width(title))+right)
}
var (
darkField = terrain(false, false)
scanField = terrain(true, false)
scanLine = terrain(true, true)
)
func terrain(gallery, scanning bool) [game.Height][game.Width]string {
var cells [game.Height][game.Width]string
for y := range game.Height {
for x := range game.Width {
style, glyph := cold, " "
if x%3 == 0 && y%2 == 0 {
glyph = "· "
}
if gallery {
dx, dy := x-10, y-6
radius := dx*dx + 3*dy*dy
switch {
case radius < 14:
style, glyph = hotspot, "░░"
case radius < 43:
style, glyph = warm, "░░"
case radius < 85:
style, glyph = warm, "··"
}
}
if scanning {
style = style.Background(lg.Color("#4A2B43"))
}
cells[y][x] = style.Render(glyph)
}
}
return cells
}
func box(cells *[game.Height][game.Width]string, y int, title string) {
const width = 24
left := (fieldWidth - width) / 4
// One box row takes the place of twelve two-column field cells.
for i := 0; i < 3; i++ {
clear(cells[y+i][left : left+width/2])
}
cells[y][left] = overlayStyle.Render("╭" + strings.Repeat("─", width-2) + "╮")
cells[y+1][left] = overlayStyle.Render("│" + center(title, width-2) + "│")
cells[y+2][left] = overlayStyle.Render("╰" + strings.Repeat("─", width-2) + "╯")
}
+270
View File
@@ -0,0 +1,270 @@
// Package arcade is the per-session terminal interface for Thermal Snake.
package arcade
import (
"crypto/rand"
"log/slog"
random "math/rand/v2"
"time"
tea "charm.land/bubbletea/v2"
"thermal-snake/internal/game"
"thermal-snake/internal/scores"
)
const (
minWidth = 50
minHeight = 23
wideWidth = 76
pageSize = 10
)
type screen uint8
const (
lobby screen = iota
warmup
playing
paused
debrief
records
)
type pulse struct{ generation uint64 }
type Model struct {
store *scores.Store
fingerprint string
pilot scores.Pilot
width, height int
screen screen
generation uint64
countdown int
phase int
run *game.Run
result scores.Run
saveFailed bool
personalBest bool
returnScreen screen
historyTab bool
page int
standings []scores.Standing
history []scores.Run
historyTotal int
readFailed bool
}
func New(store *scores.Store, fingerprint string, pilot scores.Pilot, width, height int) *Model {
return &Model{
store: store, fingerprint: fingerprint, pilot: pilot,
width: width, height: height,
}
}
func (m *Model) Init() tea.Cmd { return m.nextPulse(360 * time.Millisecond) }
func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width, m.height = msg.Width, msg.Height
if m.tooSmall() && (m.screen == playing || m.screen == warmup) {
m.screen = paused
m.generation++
}
case pulse:
if msg.generation == m.generation {
return m, m.onPulse()
}
case tea.KeyPressMsg:
return m, m.onKey(msg.String())
}
return m, nil
}
func (m *Model) tooSmall() bool { return m.width < minWidth || m.height < minHeight }
func (m *Model) nextPulse(delay time.Duration) tea.Cmd {
generation := m.generation
return tea.Tick(delay, func(time.Time) tea.Msg { return pulse{generation} })
}
func (m *Model) start() tea.Cmd {
if m.tooSmall() {
return nil
}
m.run = game.New(random.Uint64())
m.result = scores.Run{ID: rand.Text()}
m.countdown, m.phase = 3, 0
m.personalBest, m.saveFailed = false, false
m.screen = warmup
m.generation++
return m.nextPulse(450 * time.Millisecond)
}
func (m *Model) onPulse() tea.Cmd {
switch m.screen {
case lobby:
m.phase = (m.phase + 1) % (2 * game.Height)
return m.nextPulse(360 * time.Millisecond)
case warmup:
m.countdown--
if m.countdown > 0 {
return m.nextPulse(450 * time.Millisecond)
}
m.screen = playing
return m.nextPulse(m.run.Interval())
case playing:
m.phase = (m.phase + 1) % (2 * game.Height)
m.run.Step()
if m.run.Outcome() == "" {
return m.nextPulse(m.run.Interval())
}
m.screen = debrief
m.result.Score, m.result.Heat = m.run.Score(), m.run.Heat()
m.result.Outcome, m.result.Finished = m.run.Outcome(), time.Now().UTC()
// Commit before the debrief is rendered, even if the client disconnects now.
m.save()
}
return nil
}
func (m *Model) save() {
pilot, best, err := m.store.Record(m.fingerprint, m.result)
m.saveFailed = err != nil
if err != nil {
slog.Error("record run", "pilot", m.pilot.Callsign, "run", m.result.ID, "error", err)
return
}
m.pilot, m.personalBest = pilot, best
}
func (m *Model) onKey(key string) tea.Cmd {
switch key {
case "q", "ctrl+c":
return tea.Quit
}
if m.tooSmall() {
return nil
}
switch m.screen {
case lobby:
switch key {
case "enter":
return m.start()
case "l", "h":
m.openRecords(key == "h")
}
case warmup, playing:
switch key {
case "p", "space", "esc":
m.screen = paused
m.generation++
case "up", "w":
m.run.Steer(game.Up)
case "right", "d":
m.run.Steer(game.Right)
case "down", "s":
m.run.Steer(game.Down)
case "left", "a":
m.run.Steer(game.Left)
}
case paused:
switch key {
case "p", "space", "esc", "enter":
if m.countdown > 0 {
m.screen = warmup
return m.nextPulse(450 * time.Millisecond)
}
m.screen = playing
return m.nextPulse(m.run.Interval())
}
case debrief:
if m.saveFailed {
if key == "r" || key == "enter" {
m.save()
}
return nil
}
switch key {
case "enter":
return m.start()
case "esc":
return m.backToLobby()
case "l", "h":
m.openRecords(key == "h")
}
case records:
return m.recordsKey(key)
}
return nil
}
func (m *Model) backToLobby() tea.Cmd {
if pilot, err := m.store.Profile(m.fingerprint); err == nil {
m.pilot = pilot
} else {
slog.Error("read pilot profile", "pilot", m.pilot.Callsign, "error", err)
}
m.screen = lobby
m.run = nil
return m.nextPulse(360 * time.Millisecond)
}
func (m *Model) openRecords(history bool) {
m.returnScreen, m.screen = m.screen, records
m.generation++
m.historyTab, m.page = history, 0
m.loadRecords()
}
func (m *Model) recordsKey(key string) tea.Cmd {
switch key {
case "esc":
if m.returnScreen == lobby {
return m.backToLobby()
}
m.screen = m.returnScreen
case "tab", "l", "h":
m.historyTab = key == "h" || (key == "tab" && !m.historyTab)
m.page = 0
m.loadRecords()
case "left", "pgup":
if m.page > 0 {
m.page--
m.loadRecords()
}
case "right", "pgdown":
if m.page+1 < m.pages() {
m.page++
m.loadRecords()
}
case "r":
m.loadRecords()
}
return nil
}
func (m *Model) pages() int {
total := len(m.standings)
if m.historyTab {
total = m.historyTotal
}
return max(1, (total+pageSize-1)/pageSize)
}
func (m *Model) loadRecords() {
var err error
if m.historyTab {
m.history, m.historyTotal, err = m.store.History(m.fingerprint, m.page*pageSize, pageSize)
} else {
m.standings, err = m.store.Leaderboard()
m.page = min(m.page, m.pages()-1)
}
m.readFailed = err != nil
if err != nil {
slog.Error("load records", "pilot", m.pilot.Callsign, "error", err)
}
}
+98
View File
@@ -0,0 +1,98 @@
package arcade
import (
"fmt"
"strconv"
"strings"
"github.com/charmbracelet/x/ansi"
)
func (m *Model) recordsView(width int) []string {
border := subtle.Render("│")
inside := width - 4
row := func(s string) string {
return border + " " + s + strings.Repeat(" ", max(0, inside-ansi.StringWidth(s))) + " " + border
}
var title, tableHead string
if m.historyTab {
title = "FLIGHT LOG"
tableHead = historyLine(inside, "FINISHED UTC", "OUTCOME", "SCORE")
} else {
title = "SHARED RANKINGS"
tableHead = standingLine(inside, "RANK", "PILOT", "BEST", "RUNS", " ")
}
top := subtle.Render("╭─ ") + accent.Render(title) +
subtle.Render(" "+strings.Repeat("─", width-5-len(title))+"╮")
lines := []string{top, row(muted.Render(tableHead)), row(subtle.Render(strings.Repeat("─", inside)))}
entries, note := m.recordRows(inside)
for i := range pageSize {
var entry string
if i < len(entries) {
entry = entries[i]
}
lines = append(lines, row(entry))
}
page := fmt.Sprintf("PAGE %d / %d", m.page+1, m.pages())
lines = append(lines, row(pair(muted.Render(note), subtle.Render(page), inside)),
subtle.Render("╰"+strings.Repeat("─", width-2)+"╯"), "")
lines = append(lines, controls(control("TAB", "Switch"), control("←/→", "Page"), control("R", "Refresh"), control("ESC", "Back")))
if m.historyTab {
lines = append(lines, muted.Render("Newest completed runs first."))
} else {
lines = append(lines, muted.Render("Earliest best takes a score tie."))
}
return lines
}
func (m *Model) recordRows(width int) ([]string, string) {
if m.readFailed {
return []string{accent.Render(" Records unavailable. Press R to retry.")}, ""
}
if m.historyTab {
var rows []string
for _, run := range m.history {
line := historyLine(width, run.Finished.UTC().Format("2006-01-02 15:04:05"),
outcomeName(run.Outcome), prettyScore(run.Score))
rows = append(rows, rowStyle.Render(line))
}
if len(rows) == 0 {
rows = append(rows, muted.Render(" Finish a run to start your flight log."))
}
return rows, completionCount(m.historyTotal)
}
var rows []string
note := "Complete a run to rank"
for _, standing := range m.standings {
if standing.Callsign == m.pilot.Callsign {
note = fmt.Sprintf("YOUR RANK #%d", standing.Rank)
break
}
}
start := m.page * pageSize
end := min(start+pageSize, len(m.standings))
for _, standing := range m.standings[start:end] {
style, marker := rowStyle, " "
if standing.Callsign == m.pilot.Callsign {
style, marker = selfStyle, "›"
}
line := standingLine(width, fmt.Sprintf("#%d", standing.Rank), standing.Callsign,
prettyScore(standing.Best.Score), strconv.Itoa(standing.Total), marker)
rows = append(rows, style.Render(line))
}
if len(rows) == 0 {
rows = append(rows, muted.Render(" No completed runs yet."))
}
return rows, note
}
func standingLine(width int, rank, pilot, best, runs, marker string) string {
return fmt.Sprintf("%s %-6s %-*s %7s %6s ", marker, rank, width-25, pilot, best, runs)
}
func historyLine(width int, finished, outcome, score string) string {
return fmt.Sprintf(" %-19s %-*s %7s ", finished, width-32, outcome, score)
}
+277
View File
@@ -0,0 +1,277 @@
package arcade
import (
"fmt"
"strings"
tea "charm.land/bubbletea/v2"
lg "charm.land/lipgloss/v2"
"github.com/charmbracelet/x/ansi"
"thermal-snake/internal/game"
"thermal-snake/internal/scores"
)
var (
background = lg.Color("#160F18")
panel = lg.Color("#211322")
line = lg.Color("#805570")
text = lg.NewStyle().Foreground(lg.Color("#F8E8E1"))
muted = lg.NewStyle().Foreground(lg.Color("#C0A3B1"))
subtle = lg.NewStyle().Foreground(line)
accent = lg.NewStyle().Bold(true).Foreground(lg.Color("#FF9C72"))
bright = lg.NewStyle().Bold(true).Foreground(lg.Color("#FFE6A1"))
hot = lg.NewStyle().Bold(true).Foreground(lg.Color("#241322")).Background(lg.Color("#FFC177"))
keyStyle = lg.NewStyle().Bold(true).Foreground(lg.Color("#FFE1CC")).Background(lg.Color("#512D46"))
metric = lg.NewStyle().Bold(true).Foreground(lg.Color("#FFF3E7"))
rowStyle = text.Background(panel)
selfStyle = lg.NewStyle().Bold(true).Foreground(lg.Color("#FFE6A1")).Background(lg.Color("#4D2C44"))
)
func (m *Model) View() tea.View {
view := tea.NewView(m.render())
view.AltScreen = true
view.WindowTitle = "Thermal Snake"
view.BackgroundColor = background
view.ForegroundColor = lg.Color("#F8E8E1")
return view
}
func (m *Model) render() string {
if m.tooSmall() {
lines := []string{
accent.Render("◈ THERMAL SNAKE"),
"",
text.Render(fmt.Sprintf("Resize to %d × %d to play.", minWidth, minHeight)),
control("Q", "Exit"),
}
return position(lines, min(30, m.width), m.width, m.height)
}
width := minWidth
wide := m.width >= wideWidth
if wide {
width = wideWidth
}
wordmark := accent.Render("◈") + metric.Render(" T H E R M A L S N A K E")
lines := []string{
pair(wordmark, muted.Render(m.pilot.Callsign), width),
m.subtitle(),
subtle.Render(strings.Repeat("─", width)),
"",
}
if m.screen == records {
lines = append(lines, m.recordsView(width)...)
} else {
field := m.field()
stats := m.stats()
if wide {
rail := m.rail()
for i, row := range field {
if i < len(rail) {
row += " " + rail[i]
}
lines = append(lines, row)
}
lines = append(lines, "")
} else {
for _, row := range field {
lines = append(lines, " "+row)
}
lines = append(lines, stats)
}
lines = append(lines, m.controls(wide)...)
}
return position(lines, width, m.width, m.height)
}
func (m *Model) subtitle() string {
switch m.screen {
case lobby:
return muted.Render("INFRARED ARCADE / CLASSIC")
case records:
ranks, runs := muted, accent
if !m.historyTab {
ranks, runs = accent, muted
}
return ranks.Render("L RANKINGS") + subtle.Render(" / ") + runs.Render("H MY RUNS")
case debrief:
return accent.Render("RUN DEBRIEF")
default:
return muted.Render("CHAMBER") + subtle.Render(" / ") + accent.Render(m.phaseLabel())
}
}
func (m *Model) phaseLabel() string {
switch m.screen {
case warmup:
return "CALIBRATING"
case paused:
return "PAUSED"
default:
return "LIVE"
}
}
func (m *Model) rail() []string {
if m.screen == lobby {
return []string{
accent.Render("THE CHAMBER"),
"",
text.Render("Collect heat to grow."),
text.Render("Avoid the walls and coil."),
"",
bright.Render("◆") + muted.Render(" HEAT +100"),
text.Render("▸") + muted.Render(" SNAKE HEAD"),
"",
subtle.Render(strings.Repeat("─", 27)),
"",
muted.Render("PERSONAL BEST"),
metric.Render(prettyBest(m.pilot.Best)),
muted.Render(completionCount(m.pilot.Total)),
}
}
lines := []string{
muted.Render("SCORE"),
bright.Render(prettyScore(m.run.Score())),
"",
muted.Render("PERSONAL BEST"),
metric.Render(prettyBest(m.pilot.Best)),
"",
subtle.Render(strings.Repeat("─", 27)),
}
if m.screen == debrief {
status, style := "RUN LOGGED", muted
switch {
case m.saveFailed:
status, style = "SAVE FAILED", accent
case m.personalBest:
status, style = "NEW PERSONAL BEST", bright
}
return append(lines, "", accent.Render(outcomeName(m.run.Outcome())), style.Render(status),
muted.Render(fmt.Sprintf("HEAT COLLECTED %02d", m.run.Heat())))
}
return append(lines, "",
accent.Render(fmt.Sprintf("HEAT LEVEL %02d", m.run.Level())),
heatMeter(m.run.Heat(), m.run.Level()), "",
bright.Render("◆")+muted.Render(" HEAT +100"),
text.Render("▸")+muted.Render(" SNAKE HEAD"))
}
func (m *Model) stats() string {
switch m.screen {
case lobby:
return muted.Render("Collect ◆ for +100") + subtle.Render(" / ") +
muted.Render("BEST ") + metric.Render(prettyBest(m.pilot.Best))
case debrief:
status := outcomeName(m.run.Outcome())
switch {
case m.saveFailed:
status = "SAVE FAILED"
case m.personalBest:
status = "NEW BEST"
}
return accent.Render(status) + subtle.Render(" / ") + m.scoreAndBest()
default:
return m.scoreAndBest() + subtle.Render(" / ") + accent.Render(fmt.Sprintf("LVL %02d", m.run.Level()))
}
}
func (m *Model) scoreAndBest() string {
return muted.Render("SCORE ") + bright.Render(prettyScore(m.run.Score())) +
subtle.Render(" / ") + muted.Render("BEST ") + metric.Render(prettyBest(m.pilot.Best))
}
func (m *Model) controls(wide bool) []string {
switch m.screen {
case lobby:
return []string{"", controls(control("ENTER", "Launch"), control("L", "Ranks"), control("H", "Runs"), control("Q", "Exit"))}
case warmup, playing:
return []string{"", controls(control("↑↓←→ / WASD", "Steer"), control("P", "Pause"), control("Q", "Exit"))}
case paused:
return []string{"", controls(control("P / ENTER", "Resume"), control("Q", "Exit"))}
case debrief:
if m.saveFailed {
return []string{"", control("R", "Retry save")}
}
main := controls(control("ENTER", "Replay"), control("L", "Ranks"), control("H", "Runs"), control("ESC", "Lobby"))
if wide {
main = controls(main, control("Q", "Exit"))
}
return []string{"", main}
}
return nil
}
func controls(items ...string) string { return strings.Join(items, " ") }
func control(key, label string) string {
return keyStyle.Render(" "+key+" ") + " " + text.Render(label)
}
func outcomeName(outcome game.Outcome) string {
switch outcome {
case game.Wall:
return "WALL STRIKE"
case game.Coil:
return "COIL STRIKE"
case game.Clear:
return "CHAMBER CLEAR"
default:
return "—"
}
}
func completionCount(count int) string {
if count == 1 {
return "1 completed run"
}
return fmt.Sprintf("%d completed runs", count)
}
func prettyScore(n int) string { return fmt.Sprintf("%06d", n) }
func prettyBest(best *scores.Run) string {
if best == nil {
return "—"
}
return prettyScore(best.Score)
}
func heatMeter(heat, level int) string {
if level == game.MaxLevel {
return bright.Render("▰ ▰ ▰") + muted.Render(" MAX PACE")
}
lit := heat % game.HeatPerLevel
var marks []string
for i := range game.HeatPerLevel {
mark := subtle.Render("▱")
if i < lit {
mark = bright.Render("▰")
}
marks = append(marks, mark)
}
return strings.Join(marks, " ") + muted.Render(fmt.Sprintf(" %d TO NEXT", game.HeatPerLevel-lit))
}
func position(lines []string, width, cols, rows int) string {
width = max(0, width)
rows = max(0, rows)
lines = lines[:min(rows, len(lines))]
x, y := max(0, (cols-width)/2), (rows-len(lines))/2
for i, row := range lines {
lines[i] = strings.Repeat(" ", x) + ansi.Truncate(row, width, "")
}
return strings.Repeat("\n", y) + strings.Join(lines, "\n")
}
func pair(left, right string, width int) string {
left = ansi.Truncate(left, max(0, width-2-ansi.StringWidth(right)), "")
return left + strings.Repeat(" ", max(0, width-ansi.StringWidth(left)-ansi.StringWidth(right))) + right
}
func center(s string, width int) string {
s = ansi.Truncate(s, width, "")
pad := width - ansi.StringWidth(s)
return strings.Repeat(" ", pad/2) + s + strings.Repeat(" ", pad-pad/2)
}
+160
View File
@@ -0,0 +1,160 @@
// Package game contains the rules for a single Thermal Snake run.
package game
import (
"math/rand/v2"
"slices"
"time"
)
const (
Width = 22
Height = 13
PointsPerHeat = 100
HeatPerLevel = 3
MaxLevel = 8
)
type Point struct{ X, Y int }
type Direction uint8
const (
Up Direction = iota
Right
Down
Left
)
var offsets = [...]Point{{0, -1}, {1, 0}, {0, 1}, {-1, 0}}
type Outcome string
const (
Wall Outcome = "wall"
Coil Outcome = "coil"
Clear Outcome = "clear"
)
type Run struct {
body []Point // Head first.
food Point
direction Direction
turns [2]Direction
queued int
heat int
outcome Outcome
impact Point
random *rand.Rand
}
func New(seed uint64) *Run {
return &Run{
body: []Point{{6, 6}, {5, 6}, {4, 6}, {3, 6}},
food: Point{10, 6},
direction: Right,
random: rand.New(rand.NewPCG(seed, 0)),
}
}
func (r *Run) Score() int { return r.heat * PointsPerHeat }
func (r *Run) Heat() int { return r.heat }
func (r *Run) Level() int { return min(1+r.heat/HeatPerLevel, MaxLevel) }
func (r *Run) Outcome() Outcome { return r.outcome }
func (r *Run) Interval() time.Duration {
return time.Duration(175-15*(r.Level()-1)) * time.Millisecond
}
// Frame is an independent snapshot suitable for rendering a live or finished run.
type Frame struct {
Body []Point
Food Point
Direction Direction
Outcome Outcome
Impact Point
}
func (r *Run) Frame() Frame {
return Frame{slices.Clone(r.body), r.food, r.direction, r.outcome, r.impact}
}
// Steer buffers at most two perpendicular turns and applies one per step.
func (r *Run) Steer(direction Direction) {
if r.outcome != "" || direction > Left || r.queued == len(r.turns) {
return
}
previous := r.direction
if r.queued != 0 {
previous = r.turns[r.queued-1]
}
if direction%2 == previous%2 {
return
}
r.turns[r.queued] = direction
r.queued++
}
func (r *Run) Step() {
if r.outcome != "" {
return
}
if r.queued != 0 {
r.direction = r.turns[0]
r.turns[0] = r.turns[1]
r.queued--
}
head := r.body[0]
delta := offsets[r.direction]
next := Point{head.X + delta.X, head.Y + delta.Y}
if next.X < 0 || next.X >= Width || next.Y < 0 || next.Y >= Height {
r.outcome, r.impact = Wall, next
return
}
eating := next == r.food
occupied := r.body
if !eating {
occupied = occupied[:len(occupied)-1] // The tail moves away this step.
}
if slices.Contains(occupied, next) {
r.outcome, r.impact = Coil, next
return
}
if eating {
r.body = append(r.body, Point{})
}
copy(r.body[1:], r.body)
r.body[0] = next
if eating {
r.heat++
r.placeFood()
}
}
func (r *Run) placeFood() {
if len(r.body) == Width*Height {
r.outcome = Clear
return
}
var occupied [Height][Width]bool
for _, p := range r.body {
occupied[p.Y][p.X] = true
}
index := r.random.IntN(Width*Height - len(r.body))
for y := range Height {
for x := range Width {
if occupied[y][x] {
continue
}
if index == 0 {
r.food = Point{x, y}
return
}
index--
}
}
}
+86
View File
@@ -0,0 +1,86 @@
package game
import (
"slices"
"testing"
)
func TestHeatGrowthAndPace(t *testing.T) {
run := New(42)
for range 4 {
run.Step()
}
if run.Score() != 100 || len(run.body) != 5 || slices.Contains(run.body, run.food) {
t.Fatalf("after first heat got score %d, body %v and food %v", run.Score(), run.body, run.food)
}
firstInterval := run.Interval()
for range 2 {
head := run.body[0]
run.food = Point{head.X + 1, head.Y}
run.Step()
}
if run.Score() != 300 || run.Level() != 2 || run.Interval() >= firstInterval {
t.Fatalf("after three heat got score %d, level %d, interval %s", run.Score(), run.Level(), run.Interval())
}
}
func TestTurnsAreBufferedAndCannotReverse(t *testing.T) {
run := New(42)
run.Steer(Left) // Direct reversal is ignored.
run.Steer(Up)
run.Steer(Down) // Reverse of a queued turn is ignored too.
run.Steer(Left)
run.Step()
if head := run.body[0]; head != (Point{6, 5}) {
t.Fatalf("first turn reached %v", head)
}
run.Step()
if head := run.body[0]; head != (Point{5, 5}) {
t.Fatalf("second turn reached %v", head)
}
}
func TestCollisionRules(t *testing.T) {
run := New(42)
run.body = []Point{{3, 3}, {3, 2}, {2, 2}, {2, 3}}
run.direction = Left
run.Step()
if run.Outcome() != "" || run.body[0] != (Point{2, 3}) {
t.Fatal("moving into a vacating tail should be legal")
}
run.body = []Point{{3, 3}, {3, 2}, {2, 2}, {2, 3}, {2, 4}}
run.Step()
if run.Outcome() != Coil || run.impact != (Point{2, 3}) {
t.Fatalf("body collision got %q at %v", run.Outcome(), run.impact)
}
run = New(42)
run.Steer(Up)
for range Height {
run.Step()
}
if run.Outcome() != Wall || run.impact != (Point{6, -1}) || run.Score() != 0 {
t.Fatalf("wall collision got %q at %v with score %d", run.Outcome(), run.impact, run.Score())
}
}
func TestChamberClear(t *testing.T) {
run := New(42)
run.body = []Point{{0, 0}}
run.food = Point{1, 0}
for y := range Height {
for x := range Width {
if (Point{x, y}) != (Point{0, 0}) && (Point{x, y}) != run.food {
run.body = append(run.body, Point{x, y})
}
}
}
run.Step()
if run.Outcome() != Clear || len(run.body) != Width*Height {
t.Fatalf("last cell got outcome %q with length %d", run.Outcome(), len(run.body))
}
run.Step()
if run.Outcome() != Clear || run.Score() != 100 {
t.Fatal("finished runs should not advance")
}
}
+219
View File
@@ -0,0 +1,219 @@
// Package scores persists pilots, every completed run, and their personal bests.
package scores
import (
"encoding/binary"
"encoding/json"
"fmt"
"sort"
"time"
"go.etcd.io/bbolt"
"thermal-snake/internal/game"
)
var (
pilotsKey = []byte("pilots")
runsKey = []byte("runs")
recordedKey = []byte("recorded")
)
type Store struct{ db *bbolt.DB }
type Pilot struct {
Callsign string
Best *Run
Total int
}
type Run struct {
ID string
Score int
Heat int
Outcome game.Outcome
Finished time.Time
Order uint64
}
type Standing struct {
Rank int
Pilot
}
func Open(path string) (*Store, error) {
db, err := bbolt.Open(path, 0600, &bbolt.Options{Timeout: time.Second})
if err != nil {
return nil, err
}
err = db.Update(func(tx *bbolt.Tx) error {
for _, name := range [][]byte{pilotsKey, runsKey, recordedKey} {
if _, err := tx.CreateBucketIfNotExists(name); err != nil {
return err
}
}
return nil
})
if err != nil {
_ = db.Close()
return nil, err
}
return &Store{db: db}, nil
}
func (s *Store) Close() error { return s.db.Close() }
// Register assigns a unique display name to a verified public key fingerprint.
func (s *Store) Register(fingerprint string) (Pilot, error) {
var pilot Pilot
err := s.db.Update(func(tx *bbolt.Tx) error {
pilots := tx.Bucket(pilotsKey)
key := []byte(fingerprint)
if raw := pilots.Get(key); raw != nil {
return json.Unmarshal(raw, &pilot)
}
number, err := pilots.NextSequence()
if err != nil {
return err
}
pilot.Callsign = fmt.Sprintf("PILOT-%04d", number)
return put(pilots, key, pilot)
})
return pilot, err
}
func (s *Store) Profile(fingerprint string) (Pilot, error) {
var pilot Pilot
err := s.db.View(func(tx *bbolt.Tx) error {
var err error
pilot, err = readPilot(tx.Bucket(pilotsKey), []byte(fingerprint))
return err
})
return pilot, err
}
// Record writes the run, its history entry, and any new best in one transaction.
// Retrying the same ID is safe even when several sessions share a pilot.
func (s *Store) Record(fingerprint string, run Run) (Pilot, bool, error) {
var pilot Pilot
var personalBest bool
err := s.db.Update(func(tx *bbolt.Tx) error {
pilots := tx.Bucket(pilotsKey)
key := []byte(fingerprint)
var err error
pilot, err = readPilot(pilots, key)
if err != nil {
return err
}
allRuns := tx.Bucket(runsKey)
recorded := tx.Bucket(recordedKey)
id := []byte(fingerprint + "/" + run.ID)
if recorded.Get(id) != nil {
personalBest = pilot.Best != nil && pilot.Best.ID == run.ID
return nil
}
run.Order, err = allRuns.NextSequence()
if err != nil {
return err
}
history, err := allRuns.CreateBucketIfNotExists(key)
if err != nil {
return err
}
order := binary.BigEndian.AppendUint64(nil, run.Order)
if err := put(history, order, run); err != nil {
return err
}
if err := recorded.Put(id, order); err != nil {
return err
}
pilot.Total++
personalBest = pilot.Best == nil || run.Score > pilot.Best.Score
if personalBest {
pilot.Best = &run
}
return put(pilots, key, pilot)
})
return pilot, personalBest, err
}
func (s *Store) Leaderboard() ([]Standing, error) {
var standings []Standing
err := s.db.View(func(tx *bbolt.Tx) error {
return tx.Bucket(pilotsKey).ForEach(func(_, raw []byte) error {
var pilot Pilot
if err := json.Unmarshal(raw, &pilot); err != nil {
return err
}
if pilot.Best != nil {
standings = append(standings, Standing{Pilot: pilot})
}
return nil
})
})
if err != nil {
return nil, err
}
sort.Slice(standings, func(i, j int) bool {
left, right := standings[i].Best, standings[j].Best
if left.Score != right.Score {
return left.Score > right.Score
}
return left.Order < right.Order
})
for i := range standings {
standings[i].Rank = i + 1
}
return standings, nil
}
func (s *Store) History(fingerprint string, offset, limit int) ([]Run, int, error) {
var runs []Run
var total int
err := s.db.View(func(tx *bbolt.Tx) error {
key := []byte(fingerprint)
pilot, err := readPilot(tx.Bucket(pilotsKey), key)
if err != nil {
return err
}
total = pilot.Total
if offset >= total || limit <= 0 {
return nil
}
history := tx.Bucket(runsKey).Bucket(key)
cursor := history.Cursor()
k, v := cursor.Last()
for range offset {
k, v = cursor.Prev()
}
for k != nil && len(runs) < limit {
var run Run
if err := json.Unmarshal(v, &run); err != nil {
return err
}
runs = append(runs, run)
k, v = cursor.Prev()
}
return nil
})
return runs, total, err
}
func readPilot(bucket *bbolt.Bucket, key []byte) (Pilot, error) {
var pilot Pilot
raw := bucket.Get(key)
if raw == nil {
return pilot, fmt.Errorf("pilot is not registered")
}
err := json.Unmarshal(raw, &pilot)
return pilot, err
}
func put(bucket *bbolt.Bucket, key []byte, value any) error {
raw, err := json.Marshal(value)
if err != nil {
return err
}
return bucket.Put(key, raw)
}
+111
View File
@@ -0,0 +1,111 @@
package scores
import (
"fmt"
"path/filepath"
"sync"
"testing"
"thermal-snake/internal/game"
)
func TestRunHistoryAndRankingAcrossReopen(t *testing.T) {
path := filepath.Join(t.TempDir(), "scores.db")
store, err := Open(path)
if err != nil {
t.Fatal(err)
}
defer func() {
if store != nil {
_ = store.Close()
}
}()
alice, err := store.Register("key-A")
if err != nil {
t.Fatal(err)
}
bob, err := store.Register("key-B")
if err != nil {
t.Fatal(err)
}
if alice.Callsign == bob.Callsign {
t.Fatal("distinct keys share a callsign")
}
record := func(key, id string, score int, wantBest bool) {
t.Helper()
_, best, err := store.Record(key, Run{ID: id, Score: score, Outcome: game.Wall})
if err != nil || best != wantBest {
t.Fatalf("record %s got best=%v, err=%v", id, best, err)
}
}
record("key-B", "bob-first", 100, true)
record("key-A", "alice-first", 100, true)
record("key-A", "alice-low", 0, false)
record("key-A", "alice-equal", 100, false)
record("key-A", "alice-low", 0, false) // Retry with the same ID.
if err := store.Close(); err != nil {
t.Fatal(err)
}
store, err = Open(path)
if err != nil {
t.Fatal(err)
}
again, err := store.Register("key-A")
if err != nil || again.Callsign != alice.Callsign || again.Total != 3 || again.Best == nil || again.Best.ID != "alice-first" {
t.Fatalf("reopened profile: %+v, %v", again, err)
}
standings, err := store.Leaderboard()
if err != nil || len(standings) != 2 {
t.Fatalf("reopened standings: %+v, %v", standings, err)
}
if standings[0].Callsign != bob.Callsign || standings[0].Rank != 1 ||
standings[1].Callsign != alice.Callsign || standings[1].Rank != 2 {
t.Fatalf("equal scores ranked out of recording order: %+v", standings)
}
history, total, err := store.History("key-A", 1, 1)
if err != nil || total != 3 || len(history) != 1 || history[0].ID != "alice-low" || history[0].Score != 0 {
t.Fatalf("reopened history: %+v, total %d, %v", history, total, err)
}
record("key-A", "alice-high", 200, true)
standings, err = store.Leaderboard()
if err != nil || len(standings) != 2 || standings[0].Callsign != alice.Callsign {
t.Fatalf("new best should take first place: %+v, %v", standings, err)
}
}
func TestConcurrentSessionsShareAProfile(t *testing.T) {
store, err := Open(filepath.Join(t.TempDir(), "scores.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
const sessions = 18
var wg sync.WaitGroup
for i := range sessions {
wg.Go(func() {
if _, err := store.Register("same-key"); err != nil {
t.Errorf("register: %v", err)
return
}
if _, _, err := store.Record("same-key", Run{ID: fmt.Sprint(i), Score: i * 100}); err != nil {
t.Errorf("record: %v", err)
}
})
}
wg.Wait()
runs, total, err := store.History("same-key", 0, sessions)
if err != nil || len(runs) != sessions || total != sessions {
t.Fatalf("history has %d of %d runs: %v", len(runs), total, err)
}
pilot, err := store.Profile("same-key")
if err != nil || pilot.Best == nil || pilot.Best.Score != (sessions-1)*100 {
t.Fatalf("unexpected personal best: %+v, %v", pilot, err)
}
}