Go · projectPacket catcher: a game with goroutines
Packet catcher is a small game for the SSH window. Packets fall from the top of the field, and you move a switch along the bottom with the arrow keys to catch them. The game counts the caught and the missed packets and ends after three misses.
╔══════════════════════════════════════════════════════════════════════════════╗ ║ PACKET CATCHER caught 0 missed 0 of 3 ║ ╠══════════════════════════════════════════════════════════════════════════════╣ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ╺━━━━━━━╸ ║ ║ ║ ╚══════════════════════════════════════════════════════════════════════════════╝ Enter starts the game, q quits.
╔══════════════════════════════════════════════════════════════════════════════╗ ║ PACKET CATCHER caught 0 missed 0 of 3 ║ ╠══════════════════════════════════════════════════════════════════════════════╣ ║ ║ ║ ║ ║ ║ ║ ▣ ║ ║ ║ ║ ║ ║ ║ ║ ▣ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ╺━━━━━━━╸ ║ ║ ║ ╚══════════════════════════════════════════════════════════════════════════════╝ ← → move the switch q quits
Download it on the NAS
curl -fsSLO https://kb.nasutils.net/projects/go/game.gogame.go Download game.go
// game.go: Packet catcher. Packets fall down the screen; move the switch with the arrow keys and catch them. Three
// missed packets end the game. One goroutine ticks, another reads keys, and main joins them with select.
// Build and run it: go build game.go && ./game (SEED fixes the packets, TICK_MS the speed; default 150 ms)
package main
import (
"fmt"
"math/rand/v2"
"os"
"os/exec"
"strconv"
"strings"
"time"
)
const (
left, right, top, bottom = 3, 78, 4, 21 // the playing field inside the frame
width = 9 // the switch that catches the packets
amber, green, red, dim = "\033[38;5;214m", "\033[1;32m", "\033[1;31m", "\033[2m"
bold, reset = "\033[1m", "\033[0m"
)
type packet struct{ x, y int }
type game struct {
x, caught, missed, ticks int
packets []packet
lost int // the column of the last missed packet, 0 for none
rnd *rand.Rand
}
func (g *game) step() { // one tick: every packet falls one line, a new one starts every fourth tick
g.ticks++
g.lost = 0
kept := g.packets[:0]
for _, p := range g.packets {
p.y++
switch {
case p.y < bottom:
kept = append(kept, p)
case p.x >= g.x && p.x < g.x+width:
g.caught++
default:
g.missed++
g.lost = p.x
}
}
g.packets = kept
if g.ticks%4 == 1 {
g.packets = append(g.packets, packet{left + g.rnd.IntN(right-left+1), top})
}
}
func (g *game) draw(message string) {
var b strings.Builder
fmt.Fprintf(&b, "\033[2;3H%sPACKET CATCHER%s caught %s%-3d%s missed %s%d%s of 3", bold+amber, reset,
green, g.caught, reset, red, g.missed, reset)
for y := top; y <= bottom; y++ {
fmt.Fprintf(&b, "\033[%d;%dH%s", y, left, strings.Repeat(" ", right-left+1))
}
for _, p := range g.packets {
fmt.Fprintf(&b, "\033[%d;%dH%s▣%s", p.y, p.x, green, reset)
}
if g.lost > 0 {
fmt.Fprintf(&b, "\033[%d;%dH%s✕%s", bottom, g.lost, red, reset)
}
fmt.Fprintf(&b, "\033[%d;%dH%s╺%s╸%s", bottom, g.x, amber, strings.Repeat("━", width-2), reset)
fmt.Fprintf(&b, "\033[24;1H\033[2K %s%s%s", dim, message, reset)
fmt.Print(b.String())
}
func frame() { // the frame around the field, drawn once
line := strings.Repeat("═", 78)
fmt.Printf("\033[2J\033[1;1H%s╔%s╗\033[2;1H║\033[2;80H║\033[3;1H╠%s╣", amber, line, line)
for y := top; y <= bottom+1; y++ {
fmt.Printf("\033[%d;1H║\033[%d;80H║", y, y)
}
fmt.Printf("\033[23;1H╚%s╝%s", line, reset)
}
func main() {
stty := func(args ...string) string { // stty works on the terminal it gets as its input
c := exec.Command("stty", args...)
c.Stdin = os.Stdin
out, _ := c.Output()
return strings.TrimSpace(string(out))
}
saved := stty("-g")
stty("raw", "-echo")
fmt.Print("\033[?1049h\033[?25l")
defer func() { fmt.Print("\033[0m\033[?25h\033[?1049l"); stty(saved) }()
seed, err := strconv.ParseUint(os.Getenv("SEED"), 10, 64)
if err != nil {
seed = uint64(time.Now().UnixNano())
}
tick := 150 * time.Millisecond
if ms, err := strconv.Atoi(os.Getenv("TICK_MS")); err == nil && ms > 0 {
tick = time.Duration(ms) * time.Millisecond
}
keys := make(chan string)
go func() { // the key reader: one read is one key or one whole arrow sequence
b := make([]byte, 8)
for {
n, err := os.Stdin.Read(b)
if err != nil {
close(keys)
return
}
keys <- string(b[:n])
}
}()
frame()
g := &game{x: (left + right - width) / 2, rnd: rand.New(rand.NewPCG(seed, 1))}
g.draw("Enter starts the game, q quits.")
for k := range keys { // wait for Enter
if k == "q" || k == "\003" {
return
}
if k == "\r" {
break
}
}
ticks := make(chan struct{})
go func() { // the clock goroutine: one signal for each tick
for range time.Tick(tick) {
ticks <- struct{}{}
}
}()
g.draw("← → move the switch q quits")
for {
select {
case <-ticks:
g.step()
if g.missed >= 3 {
g.draw(fmt.Sprintf("Game over. Packets caught: %d. Press any key.", g.caught))
<-keys
return
}
case k, ok := <-keys:
switch {
case !ok || k == "q" || k == "\003": // \003 is Ctrl+C in raw mode
return
case k == "\033[D" || k == "\033OD":
g.x = max(left, g.x-3)
case k == "\033[C" || k == "\033OC":
g.x = min(right-width+1, g.x+3)
}
}
g.draw("← → move the switch q quits")
}
}
What you learn
- A goroutine with
for range time.Tick(tick)sends one signal per tick on a channel. - A second goroutine reads the keys and sends each one on another channel.
selectwaits for whichever channel has something first, so the game reacts to a key between two ticks.rand.New(rand.NewPCG(seed, 1))gives the same packets for the sameSEED.- A
strings.Buildercollects a whole frame, and onePrintputs it on the screen without flicker.
How it works
The state of the game is one struct: the column of the switch, the counters, the falling packets and the tick count. step moves every packet one line down. A packet that reaches the bottom line is caught when it lands on the switch and missed otherwise. On ticks 1, 5, 9 and so on, a new packet starts at a random column.
main puts the terminal into raw mode, draws the frame once and waits for Enter. Then it starts the clock goroutine. The loop in main is the only place that changes the game, so the two goroutines never touch the state themselves; they only send on their channels. After each tick or key, draw paints the field again.
With TICK_MS=1000, as in the test, the packets fall one line a second, so the picture after a fixed time is the same in every run. Without it a tick is 150 ms.
Notes to the lines
- 16–21The field runs from column 3 to 78 and from line 4 to 21; the switch is 9 columns wide.
- 35–48
kept := g.packets[:0]reuses the slice and keeps only the packets still falling. - 41A packet is caught when its column lies under the switch.
- 49–51Every fourth tick, from the first, a new packet starts on line 4.
- 54–70
drawclears the field, draws the packets, the mark ✕ of a miss and the switch, then prints it all at once. - 93–100
SEEDandTICK_MSfrom the environment; without them the clock seeds the packets and a tick is 150 ms. - 102–113The key goroutine; when the input ends, it closes the channel, and the loop sees
ok == false. - 118–125
for k := range keyswaits for Enter before the first tick. - 126–131The clock goroutine.
- 134–151
selecttakes a tick or a key; ← and → move the switch 3 columns,maxandminkeep it in the field.
Run it
Build it in the terminal of Bucket & Code's editor, with its Go runtime:
eval "$(bvs use go-1.27-x86_64)"
go build game.go
./gameEnter starts the game, ← and → move the switch, q or Ctrl+C quits. The finished file runs on the NAS without Go and calls stty, which TurboShell has.
Try it yourself
Make the game faster as you play: after each caught packet, start a new clock goroutine with a shorter tick. Add a key p that pauses the game until you press it again.
More projects in Go
- A framed menu in Go with raw keysA Go program puts the terminal into raw mode, draws a framed menu with ANSI escapes and opens boxes with the NAS's memory, volumes, uptime and load. You learn raw keys without extra packages and how to give the terminal back its settings.
- A login greeting with text/templateA Go program fills a text/template with the facts of the NAS (greeting, model, uptime, CPU, load, free space, tip of the day) and frames the result. You learn templates with your own functions and a struct as their data.
- A NAS summary on screen and as JSONA Go program collects the CPU, temperature, memory, data volumes and network ports of the NAS into structs and prints them as a screen with bars, or with -json as JSON. You learn structs with json tags, the flag package and one source of facts for two outputs.
- Packet catcher: a game with goroutinesIn this Go game packets fall down the screen and you catch them with a switch moved by the arrow keys; three missed packets end the game. You learn goroutines, channels and select, with one goroutine for the clock and one for the keys.
- A status page of the NAS with net/httpA Go program serves the model, uptime, CPU, load, memory and data volumes of the NAS as a web page that reloads every 5 seconds, so you can watch it from any browser on your network. You learn net/http, html/template and a clean stop on Ctrl+C.
- Find duplicate files with a pool of workersA Go program finds duplicate files in a folder of the NAS. It compares sizes first, hashes only the files that share a size with SHA-256 in a pool of goroutines, and shows each group with the space its extra copies take. You learn worker pools, channels and sync.WaitGroup.