commit efe2c8a9c859e34a3c6c169222042416c96611cd Author: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Fri Nov 27 19:04:23 2026 +0330 init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..26b029b --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/.idea/ +/.thermal-snake/ +/thermal-snake diff --git a/README.md b/README.md new file mode 100644 index 0000000..6727d7e --- /dev/null +++ b/README.md @@ -0,0 +1,54 @@ +# Thermal Snake + +An infrared arcade for your terminal. Chase heat through a 22 × 13 chamber as your snake grows and the pace climbs. Thermal Snake runs entirely on the server and opens directly over SSH. + +## Start the server + +Install Go 1.26 or later, then run this from the project directory. + +```sh +go run ./cmd/thermal-snake +``` + +The server listens on `127.0.0.1:2222` by default. To make it reachable by other machines, choose a listen address and optionally set a dedicated data directory. + +```sh +go run ./cmd/thermal-snake -addr 0.0.0.0:2222 -data ./snake-data +``` + +The data directory defaults to `.thermal-snake/`. Keep `scores.db` and `host_ed25519` there across restarts to retain score history and the server's SSH identity. The server prints its host key fingerprint at startup so players can verify the connection. + +## Connect and play + +Use a Unicode terminal with at least **50 columns × 23 rows**. At **76 columns** the chamber gains a side panel. The server accepts SSH public-key authentication. Use an existing key or create a dedicated one once. + +```sh +ssh-keygen -t ed25519 -f ~/.ssh/thermal_snake +ssh -t -o IdentitiesOnly=yes -i ~/.ssh/thermal_snake -p 2222 arcade@127.0.0.1 +``` + +Use the same key on later connections to keep your callsign and scores. The server assigns each authenticated key a unique callsign. The SSH username has no effect on your identity. + +| Keys | Action | +| --- | --- | +| **Enter** | Launch, resume a paused run, or replay from the debrief | +| **Arrows** or **W A S D** | Steer | +| **P**, **Space**, or **Esc** | Pause or resume during a run | +| **L** / **H** | Open the shared rankings / your run history from the lobby or debrief | +| **Tab**, **← / →**, **R**, **Esc** | Switch record tabs, page through results, refresh, or go back | +| **Q** or **Ctrl+C** | Exit | + +Each **◆** is worth **100 points** and grows the coil by one cell. Collect three to raise the heat level and speed up. The first pickup is straight ahead. The pointed head shows your direction, and **×** marks an impact. Shrinking the terminal below the minimum pauses the run until you resize and resume. + +A wall strike, a collision with your own coil, or filling the chamber ends a run. Every completed run goes into your history, including zero scores and scores below your best. Exiting mid-run leaves it unfinished. The shared rankings show each pilot's best score. If scores tie, the pilot whose best was recorded first ranks higher. + +## Code and tests + +- `internal/game` owns movement, collision, pickups, scoring, and pace. It has no terminal, network, or storage dependencies. +- `internal/arcade` owns the Bubble Tea session, countdown and pause states, terminal layout, and records screens. +- `internal/scores` stores pilots, runs, and bests in bbolt. Each completed run is recorded in one transaction. +- `cmd/thermal-snake` wires together Wish, public-key authentication, and the server lifecycle. + +```sh +go test -race ./... +``` diff --git a/cmd/thermal-snake/main.go b/cmd/thermal-snake/main.go new file mode 100644 index 0000000..d1dfbf7 --- /dev/null +++ b/cmd/thermal-snake/main.go @@ -0,0 +1,137 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "log/slog" + "net" + "os" + "os/signal" + "path/filepath" + "syscall" + "time" + + tea "charm.land/bubbletea/v2" + "charm.land/ssh" + "charm.land/wish/v2" + wishtea "charm.land/wish/v2/bubbletea" + gossh "golang.org/x/crypto/ssh" + + "thermal-snake/internal/arcade" + "thermal-snake/internal/scores" +) + +func main() { + addr := flag.String("addr", "127.0.0.1:2222", "SSH listen address") + data := flag.String("data", ".thermal-snake", "directory for the score database and SSH host key") + flag.Parse() + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if err := serve(ctx, *addr, *data); err != nil { + slog.Error("thermal snake", "error", err) + os.Exit(1) + } +} + +func serve(ctx context.Context, addr, data string) error { + if err := os.MkdirAll(data, 0700); err != nil { + return fmt.Errorf("open data directory: %w", err) + } + store, err := scores.Open(filepath.Join(data, "scores.db")) + if err != nil { + return fmt.Errorf("open score database: %w", err) + } + defer store.Close() + + sessions := make(chan struct{}, 32) + server, err := wish.NewServer( + wish.WithAddress(addr), + wish.WithHostKeyPath(filepath.Join(data, "host_ed25519")), + wish.WithPublicKeyAuth(func(_ ssh.Context, key ssh.PublicKey) bool { + _, certificate := key.(*gossh.Certificate) + return key != nil && !certificate + }), + wish.WithIdleTimeout(30*time.Minute), + wish.WithMiddleware(wishtea.MiddlewareWithProgramHandler(func(session ssh.Session) *tea.Program { + pty, _, ok := session.Pty() + if !ok { + wish.Fatalln(session, "Thermal Snake needs a terminal. Reconnect with ssh -t.") + return nil + } + key := session.PublicKey() + if key == nil { + wish.Fatalln(session, "Thermal Snake needs an SSH public key.") + return nil + } + fingerprint := gossh.FingerprintSHA256(key) + pilot, err := store.Register(fingerprint) + if err != nil { + slog.Error("open pilot profile", "error", err) + wish.Fatalln(session, "The score database is unavailable. Try reconnecting.") + return nil + } + size := limitTerminalSize(tea.WindowSizeMsg{Width: pty.Window.Width, Height: pty.Window.Height}) + model := arcade.New(store, fingerprint, pilot, size.Width, size.Height) + options := append(wishtea.MakeOptions(session), + tea.WithWindowSize(size.Width, size.Height), + tea.WithContext(session.Context()), + tea.WithFilter(func(_ tea.Model, msg tea.Msg) tea.Msg { + switch msg := msg.(type) { + case tea.WindowSizeMsg: + return limitTerminalSize(msg) + case tea.SuspendMsg: + return tea.ResumeMsg{} + default: + return msg + } + }), + ) + return tea.NewProgram(model, options...) + }), func(next ssh.Handler) ssh.Handler { + return func(session ssh.Session) { + select { + case sessions <- struct{}{}: + defer func() { <-sessions }() + next(session) + default: + wish.Fatalln(session, "The arcade is full. Try again in a moment.") + } + } + }), + ) + if err != nil { + return fmt.Errorf("configure SSH: %w", err) + } + server.HandshakeTimeout = 10 * time.Second + server.SessionRequestCallback = func(_ ssh.Session, request string) bool { return request == "shell" } + + listener, err := net.Listen("tcp", server.Addr) + if err != nil { + return fmt.Errorf("listen for SSH: %w", err) + } + slog.Info("Thermal Snake listening", "address", listener.Addr(), "host_key", gossh.FingerprintSHA256(server.HostSigners[0].PublicKey())) + stopClosing := context.AfterFunc(ctx, func() { _ = listener.Close() }) + defer stopClosing() + err = server.Serve(listener) + if ctx.Err() != nil { + shutdown, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + if err := server.Shutdown(shutdown); err != nil { + _ = server.Close() + } + return nil + } + _ = server.Close() + if !errors.Is(err, ssh.ErrServerClosed) { + return err + } + return nil +} + +// Bound rendering and terminal buffers to a size larger than a typical terminal. +func limitTerminalSize(size tea.WindowSizeMsg) tea.WindowSizeMsg { + return tea.WindowSizeMsg{Width: min(size.Width, 300), Height: min(size.Height, 150)} +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..aa10d87 --- /dev/null +++ b/go.mod @@ -0,0 +1,39 @@ +module thermal-snake + +go 1.26.0 + +require ( + charm.land/bubbletea/v2 v2.1.3 + charm.land/lipgloss/v2 v2.0.6 + charm.land/ssh v0.4.3 + charm.land/wish/v2 v2.0.6 + github.com/charmbracelet/x/ansi v0.11.10 + go.etcd.io/bbolt v1.4.3 + golang.org/x/crypto v0.57.0 +) + +require ( + charm.land/log/v2 v2.0.1 // indirect + github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be // indirect + github.com/charmbracelet/colorprofile v0.4.3 // indirect + github.com/charmbracelet/keygen v0.5.4 // indirect + github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 // indirect + github.com/charmbracelet/x/conpty v0.2.0 // indirect + github.com/charmbracelet/x/term v0.2.2 // indirect + github.com/charmbracelet/x/termios v0.1.1 // indirect + github.com/charmbracelet/x/windows v0.2.2 // indirect + github.com/charmbracelet/x/xpty v0.1.4 // indirect + github.com/clipperhouse/displaywidth v0.11.0 // indirect + github.com/clipperhouse/uax29/v2 v2.7.0 // indirect + github.com/creack/pty v1.1.24 // indirect + github.com/go-logfmt/logfmt v0.6.1 // indirect + github.com/lucasb-eyer/go-colorful v1.4.1 // indirect + github.com/mattn/go-runewidth v0.0.30 // indirect + github.com/muesli/cancelreader v0.2.2 // indirect + github.com/pires/go-proxyproto v0.15.0 // indirect + github.com/rivo/uniseg v0.4.7 // indirect + github.com/xo/terminfo v1.2.0 // indirect + golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba // indirect + golang.org/x/sync v0.23.0 // indirect + golang.org/x/sys v0.48.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..691a46e --- /dev/null +++ b/go.sum @@ -0,0 +1,76 @@ +charm.land/bubbletea/v2 v2.1.3 h1:UasShJ8x3xVS5RfnHRJ8eRBKeXQOf+ulC+W3R3kQO/k= +charm.land/bubbletea/v2 v2.1.3/go.mod h1:prmZH2MRzgJvolhYyC8JLNa7Whju9O5/nmrVhoXJizw= +charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ= +charm.land/lipgloss/v2 v2.0.6/go.mod h1:ipDDJNSGa1hlwDtSfW1s2/xR8Vdhbut4PXh2zEKZd0Q= +charm.land/log/v2 v2.0.1 h1:uMk+t1hM/fomIqt7vn/Ub0AKo7IHvnDu6NK17nbOVx0= +charm.land/log/v2 v2.0.1/go.mod h1:VXZNB8zoPPEIcvd7bRi2fpQpGCWweCSfWOwczA9dibs= +charm.land/ssh v0.4.3 h1:hr5cYmlUYsP+KxyG/ug7ZMzKKN9f6VOD9yPpcGqdzzM= +charm.land/ssh v0.4.3/go.mod h1:so/3IECPNlYZSnE7JKn7NFmcUyyxJqIAeM4TJy35qPk= +charm.land/wish/v2 v2.0.6 h1:VZkQQyaplBSQ8ZWOJGwbOJmhP4ju/pcEJAachDxaPzs= +charm.land/wish/v2 v2.0.6/go.mod h1:IY4eAZ2wsEixBhsbBIj0JEG4Nrz0uzjx8oGXG15i12M= +github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8= +github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4= +github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ12Gv5o= +github.com/aymanbagabas/go-udiff v0.4.1/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w= +github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q= +github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q= +github.com/charmbracelet/keygen v0.5.4 h1:XQYgf6UEaTGgQSSmiPpIQ78WfseNQp4Pz8N/c1OsrdA= +github.com/charmbracelet/keygen v0.5.4/go.mod h1:t4oBRr41bvK7FaJsAaAQhhkUuHslzFXVjOBwA55CZNM= +github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 h1:hISLzUbwcvJbGoNR6A3L/TpguRRnACBmZOee8LcHLJw= +github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4/go.mod h1:aJDVk+WOVM1K04rdc/71PMPoUGfjxjhvXfP3Pjz1Zio= +github.com/charmbracelet/x/ansi v0.11.10 h1:GjcX3+rAk+8wDX/jY0XwrZstxkjRcLkYU3TvwzZWiRA= +github.com/charmbracelet/x/ansi v0.11.10/go.mod h1:DG/hpOnaI2QJ/KMMqLL2h0KVhluuJLazf8973P+Vy5w= +github.com/charmbracelet/x/conpty v0.2.0 h1:eKtA2hm34qNfgJCDp/M6Dc0gLy7e07YEK4qAdNGOvVY= +github.com/charmbracelet/x/conpty v0.2.0/go.mod h1:fexgUnVrZgw8scD49f6VSi0Ggj9GWYIrpedRthAwW/8= +github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f h1:pk6gmGpCE7F3FcjaOEKYriCvpmIN4+6OS/RD0vm4uIA= +github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f/go.mod h1:IfZAMTHB6XkZSeXUqriemErjAWCCzT0LwjKFYCZyw0I= +github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk= +github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI= +github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY= +github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo= +github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM= +github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k= +github.com/charmbracelet/x/xpty v0.1.4 h1:4jaW7u+8AHQMxesiVc+zUMsspu7GyDwtJO+gy/tFtW4= +github.com/charmbracelet/x/xpty v0.1.4/go.mod h1:7t8P7BpPiolHJ1pLzz7/4ujDbD+sUxI9yA3CBOLOIcU= +github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8= +github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0= +github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= +github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= +github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= +github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-logfmt/logfmt v0.6.1 h1:4hvbpePJKnIzH1B+8OR/JPbTx37NktoI9LE2QZBBkvE= +github.com/go-logfmt/logfmt v0.6.1/go.mod h1:EV2pOAQoZaT1ZXZbqDl5hrymndi4SY9ED9/z6CO0XAk= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss= +github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-runewidth v0.0.30 h1:+KUuiDA4fF0R1p5FeueHefjDm+GIM+kWfFnDjybOPgk= +github.com/mattn/go-runewidth v0.0.30/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8= +github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= +github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/pires/go-proxyproto v0.15.0 h1:dTshmNbFm/D+0+sbrxUuddPOZ5Y0B7c5NhtsBkm6LqI= +github.com/pires/go-proxyproto v0.15.0/go.mod h1:OXsCrKwrK2tXS9YrI5tkHx5xaQlO8FH3lFW76orFh24= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/xo/terminfo v1.2.0 h1:d0ZTOCpuGE0lwSAOs0zcJjwz3jWQyqcRt9XbGJpCOl4= +github.com/xo/terminfo v1.2.0/go.mod h1:lGzkSo8Fe7IRh/w+Gqz7n5mDog4FVXCj3gy/DYTBqio= +go.etcd.io/bbolt v1.4.3 h1:dEadXpI6G79deX5prL3QRNP6JB8UxVkqo4UPnHaNXJo= +go.etcd.io/bbolt v1.4.3/go.mod h1:tKQlpPaYCVFctUIgFKFnAlvbmB3tpy1vkTnDWohtc0E= +golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= +golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba h1:Ck8QetSgk912qxWLMCKxd0in+aiyBQyDSMae6e/xmpU= +golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba/go.mod h1:50RgIsmK7OwqzTTeqcSXQW8SswW0o8fRcDxmqGluJ8E= +golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= +golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= +golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/arcade/field.go b/internal/arcade/field.go new file mode 100644 index 0000000..cf83d4f --- /dev/null +++ b/internal/arcade/field.go @@ -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) + "╯") +} diff --git a/internal/arcade/model.go b/internal/arcade/model.go new file mode 100644 index 0000000..5c46056 --- /dev/null +++ b/internal/arcade/model.go @@ -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) + } +} diff --git a/internal/arcade/records.go b/internal/arcade/records.go new file mode 100644 index 0000000..23fde4c --- /dev/null +++ b/internal/arcade/records.go @@ -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) +} diff --git a/internal/arcade/view.go b/internal/arcade/view.go new file mode 100644 index 0000000..ef78bcb --- /dev/null +++ b/internal/arcade/view.go @@ -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) +} diff --git a/internal/game/game.go b/internal/game/game.go new file mode 100644 index 0000000..5444d04 --- /dev/null +++ b/internal/game/game.go @@ -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-- + } + } +} diff --git a/internal/game/game_test.go b/internal/game/game_test.go new file mode 100644 index 0000000..4b2cabf --- /dev/null +++ b/internal/game/game_test.go @@ -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") + } +} diff --git a/internal/scores/store.go b/internal/scores/store.go new file mode 100644 index 0000000..5b97835 --- /dev/null +++ b/internal/scores/store.go @@ -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) +} diff --git a/internal/scores/store_test.go b/internal/scores/store_test.go new file mode 100644 index 0000000..832fa80 --- /dev/null +++ b/internal/scores/store_test.go @@ -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) + } +}