Skip to content
ChiefFowksPublic

About

An autonomous civilization game for the M5Stack CardputerZero and Cardputer-Adv. Grow a tribe from the Stone Age to the Pre-Singularity through 12 eras, watch your village evolve, and meet other players' civilizations over Bluetooth LE and LoRa to trade, ally and fend off raiders.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

9 Commits

Folders and files

Repository files navigation

Cardputer Civ — simulation core

Headless, dependency-free C++17 core for an autonomous civilization game on the M5Stack CardputerZero (Linux / Raspberry Pi CM0). No UI, no radio driver, no clock inside: you drive it, so it runs identically on a PC (tests, demo) and on the device.

make test     # 1429 checks
make e2e      # Python signs an update pack, the shipping C++ verifier checks it (needs: pip install cryptography)
make demo     # 5 civilizations on a fake radio: ./build/sim_demo [days] [seed] [-v]

Using it

cz::Engine e(seed);                 // new civilization   (or e.loadFile(path))
e.loadStoredUpdate(dataDir + "/update.czpack");   // startup, before the first tick (see "Updating the app")
e.log.sink = &mySink;               // IAlertSink: play a tone per EventKind (sound only, no vibration)
// every secondsPerTick (default 60):  e.tick();
// every ~1 s:                         e.poll(unixSeconds);  for (auto& f : e.takeOutbox()) radio.send(f);
// on receive (LoRa / BLE / ...):      e.onPacket(bytes, len, unixSeconds);
// every few minutes + on exit:        e.saveFile(path);     // atomic
// on start after downtime:            e.catchUp(secondsAway, secondsPerTick);   // alerts muted, capped at 1440 turns

The UI reads e.civ (stats), e.dip.peers (discovered civs), e.log.events (history) directly.

The ages

12 eras, 3 techs each (36 total). Finishing an era's third tech ends it.

# Era Techs
1 Stone Age Fire, Stone Tools, Agriculture
2 Bronze Age Pottery, Bronze Working, Writing
3 Iron Age Masonry, Iron Working, Currency
4 Classical Age Philosophy, Engineering, Law
5 Medieval Age Feudalism, Castles, Universities
6 Renaissance Printing Press, Gunpowder, Navigation
7 Industrial Age Steam Power, Railroads, Electricity
8 Modern Age Mass Production, Computers, Internet
9 Information Age Satellites, Robotics, Biotechnology
10 Space Age Fusion Power, Orbital Habitats, Nanotechnology
11 Age of Intelligence Machine Learning, Quantum Computing, Artificial General Intelligence
12 Pre-Singularity Neural Interfaces, Mind Uploading, Recursive Self-Improvement

Learning the last tech raises a Milestone alert: " stands on the threshold of the Singularity!" That is the end of the tree; the Singularity itself is deliberately not simulated.

Pacing at 60 s per turn (measured): Bronze Age ~5 h, Modern Age ~6 days, Pre-Singularity ~17-19 days, threshold ~22 days solo. Allies reach it in ~16-18 days. A warlord civilization is far slower because its warriors don't study. Final population is ~500,000 (beacons encode stats with a 12-bit mantissa/4-bit exponent, so neighbours see them to ~0.02% instead of saturating at 65,535).

What's in the box

File Role
core/civ.* Economy, population, research, decisions, personality
core/tech.h 36-tech tree, 12 eras
core/diplomacy.* Discovery, trade, alliances, tech sharing, raids
core/protocol.h Over-the-air frames (<=64 B, CRC16), protocol v2
core/engine.* Facade: tick/poll/packets, save/load, offline catch-up, update install
core/balance.h Every tuning number
core/tunables.h The subset of balance a signed pack may change, with hard bounds
core/update.*, core/update_key.h Owner-signed update packs
core/ed25519.* SHA-512 + Ed25519 (checked against Python cryptography)
tools/czsign.py Owner-only: make your key, sign packs
tools/czpack_check.cpp Applies a pack file exactly like the app does
tools/sim_demo.cpp Multi-civ world with scripted encounters and one warlord

Behaviour summary

  • Start: 12 people, stone age, a generated name. Population is capped by a carrying capacity that grows with tech.
  • Autonomy: every 6 turns the civilization re-splits its workers (farmers, wood, stone, metal, scholars, warriors) and picks what to research. Wisdom rises with techs known: low wisdom = noisy, sometimes misjudged allocations; high wisdom = near-optimal (tested: primitive noise 0.46 vs advanced 0.00).
  • Alerts (EventKind): Milestone (tech, era, population), Discovery (new civ + its stats), Alliance, Danger (famine, raid, turn to conquest). Info is log-only.
  • Discovery: beacon every ~30 s (name, era, pop, attack, defense, 64-bit tech mask; 27 B payload). First sighting raises a Discovery event with the stats.
  • Trade: only while in range; each side trades surplus for deficit at fixed prices; greedy civs haggle (rejected unless allied). The offerer escrows goods; a lost packet is refunded after a timeout.
  • Alliances: need 3+ separate meetings and good relations; max 3 allies. +8% research each, and an in-range ally teaches techs you lack at 40% cost. Lapse after 14 days unseen; an ally who raids you loses the alliance.
  • Dark civilizations: ~4% are born warlike; a long famine can also embitter a people. They raid weaker-looking non-allied civs in range, don't trade, and research slower.
  • Raid safety: the defender resolves the fight with its own numbers; the attacker's claim is clamped to its beacon; loot <= 12% of each stockpile, <= what its soldiers can carry, and <= 65,535 of any one resource; 6 h shield after a raid; 12 h per-attacker cooldown; population never drops below 3.

The app (build/civ-zero)

A self-contained C++ program: it draws straight to the LCD (/dev/fb0, 320x170 RGB565), reads the keyboard from evdev (tca8418c, exclusive grab) and plays alert tones through aplay (tones are synthesized in code). No graphics library needed.

Keys: Z left / C right (or Tab) switch screens, 1-4 jump, F up / X down scroll or change volume, M mute, Esc/Q quit (asks first). Physical arrow keys, if the keyboard sends them, work too. Screens: 1 Civilization (era, techs, population, resources, research), 2 Peers (neighbours met, stats, relation, allies), 3 Log (events, ~ = while you were away), 4 Radio (LoRa/Bluetooth/GPS status, volume). Alerts: a banner plus a different sound for milestone / discovery / alliance / danger. No vibration.

Run it: build/civ-zero (options: --tick-seconds N for faster turns, --no-radio, --no-sound, --no-fb --seconds N --ppm out.ppm for headless runs). Install on a CardputerZero without the store: sh packaging/install-dev.sh (undo with uninstall-dev.sh).

Playing from a PC (screen mirror)

The game always runs on the CardputerZero (real LoRa / Bluetooth / GPS); a viewer on your PC shows its screen and sends keys.

  1. On the device, add mirror = 1 to ~/.config/civ-zero/civ-zero.conf (or start with civ-zero --mirror).
  2. On the PC (needs Python 3 with tkinter and the ssh command): python tools/civ-mirror.py rk9@DEVICE_IP. Enter the SSH password when asked; a window opens with the live screen. Z/C/F/X, 1-4, M, Enter, Esc, Tab, Q work from the PC keyboard; the device keyboard keeps working too.

The mirror listens on the device's loopback only (127.0.0.1:47890), so it is reachable only through the SSH tunnel the viewer opens. Protocol: server sends CZFR + 320x170 RGB888 whenever the picture changes; client sends one key byte at a time.

Settings: ~/.config/civ-zero/civ-zero.conf (all optional)

policy = lora_plus_ble       # lora_plus_ble | lora_preferred | ble_only | lora_only
sound = 1
volume = 2                   # 0..3
seconds_per_tick = 60        # game speed
use_gps = 1
mirror = 0                   # 1 = stream the screen to tools/civ-mirror.py
busy_gpio = 22               # radio keys from the Radio layer section also work here
freq_hz = 915000000

The save lives in ~/.local/share/civ-zero/ (save.bin). While the app is closed the civilization does not meet anyone, but missed turns are replayed on the next start (up to one day). A background service (so it keeps meeting people with the screen off) is not built yet.

Not yet verified on a device: screen output, keyboard mapping (F/X/Z/C as requested), alert sound output (tries plughw:CARD=ES8389Audio,DEV=0, falls back to default), the store package layout. The GPS is shown but not used by the game.

Radio layer (LoRa + Bluetooth)

The engine only produces/consumes ≤64-byte frames; radio/ moves them. RadioManager owns the radios and picks which are live.

Policy Behaviour
LoraPlusBle (default) Bluetooth is always on. LoRa is added when the M5Stack unit is detected, and dropped back to Bluetooth-only the moment it fails.
LoraPreferred Literal "BT only when LoRa is missing": Bluetooth is off while LoRa works, reopened immediately if LoRa fails.
BleOnly / LoraOnly Force one radio.

Why the default keeps Bluetooth on: a device that has switched Bluetooth off can never meet one that has no LoRa unit (different radios), which would split the player base. LoraPreferred exists, and a test documents the effect.

Details: anti-flap (LoRa must probe present twice in a row), exponential backoff on open failures, TTL'd TX queue (stale news is dropped, oldest dropped on overflow), LoRa duty-cycle token bucket (default 1%), cross-radio dedupe so a frame heard on both radios is processed once.

  • LoRa, Cap LoRa-1262 (your hardware) – Sx1262Radio drives the bare SX1262 chip over spidev + GPIO + I2C (antenna-switch expander). Detection is real: reset the chip, read the sync-word register (0x1424). Polled IRQs, health check via GetStatus, TX queue, half-duplex handling. Settings and pins come from a key=value file (loadPinConfig: busy_gpio, reset_gpio, i2c_addr, freq_hz, sf, tx_power_dbm, ...). Default 915 MHz, SF8/125 kHz, 14 dBm — set the band for your region.
  • GPS – NmeaParser (GGA/RMC, checksum-verified) for the Cap's GPS on the header UART (115200). Not wired into the game yet.
  • LoRa, serial modules (E220-type) – LoraRadio: transparent UART module, link framing [0xA5][len][frame], resync after noise via the frame CRC.
  • Bluetooth – raw HCI, non-connectable advertising of 24-byte chunks (manufacturer data, company id 0xFFFF), passive scanning, per-advertiser reassembly; only CRC-valid frames are delivered.

Limits to know

  • Cap LoRa-1262 on CardputerZero – confirmed on real hardware: the header's 5V rail is OFF by default and must be switched on by writing 1 to /sys/class/leds/ext_5v_out/brightness (LinuxSx1262Bus::powerOn, done automatically; needs root or a udev rule). After that the antenna-switch expander answers at I2C 0x43 and the SX1262 answers on /dev/spidev0.1 (sync word 1424); the GPS streams NMEA on /dev/serial0 (ttyS0, 115200). Use build/hwprobe --find-busy and --radio-selftest to check a unit.
  • Radio init (from M5Stack's example code, to be confirmed on hardware): TCXO powered from DIO3 at 3.0 V (tcxo_code = 6), LDO regulator (use_ldo = 1), antenna switch via the I2C expander (DIO2 switch control off), 140 mA over-current limit. Without the TCXO setup the first on-device test opened fine but never completed a transmission. hwprobe --radio-selftest prints the chip's device-error flags to diagnose this.
  • Bluetooth bring-up: sudo systemctl stop bluetooth; sudo ./build/hwprobe --ble-test --listen 12; sudo systemctl start bluetooth.
  • Still unconfirmed: which of GPIO22/GPIO23 is BUSY (GPIO26 idles high but is a power-enable pin on other Caps, so it is never driven; reset is not used). busy_gpio = -1 / reset_gpio = -1 run without those pins for first tests.
  • (older note) Cap LoRa-1262 pins were partly guessed. SPI0 (GPIO11/10/9, CS1=GPIO7) and I2C1 (GPIO2/3) come from the CardputerZero header table; BUSY (22), NRESET (26), the I2C expander address (0x43) and DIO2-as-antenna-switch are guesses and the Cap's connector-to-header mapping is not in the docs. Check against the Cap schematic and override in the config file. The Linux backend is untested on hardware. Power off before inserting/removing the Cap (M5Stack: no hot-swap) and fit the antenna first.
  • The Cap is detected at start-up and re-probed while closed; a chip that stops answering is treated as unplugged and the device falls back to Bluetooth.
  • Transparent UART LoRa units (E220-type, not the Cap) have no handshake, so "detection" = the serial node exists + stays healthy, plus the LoraDetect::Assume setting. LoRaWAN AT-command units are not supported as-is.
  • The Bluetooth backend (HciSocketTransport) is untested on real hardware; everything above it is tested against a simulated HCI controller that enforces HCI rules (reset first, one outstanding command, LE-meta event mask). Raw HCI needs root, the adapter down, and bluetoothd stopped.
  • Tests: make test (core 1429 checks + radio 816 checks).

Updating the app later (owner only)

There are two channels, and they do different jobs.

1. Store release — code, new eras/techs, protocol or UI changes

Publish a new version with M5's czdev tool, logged in with your GitHub account:

./czdev login
./czdev bump   --deb build/<app>_<version>_arm64.deb     # check the next version number
./czdev publish ...                                      # forks the packages repo and opens a PR; CI validates it

Honest limits: the store's CI runs "maintainer/ownership and version checks", but its public docs do not say how ownership is decided, so I can't promise the store alone stops someone else publishing under your package name. Protect your GitHub account (2FA), claim the package name early, and treat signed packs (below) as the channel that is cryptographically yours. Devices update through the on-device App Store when a new version is published.

2. Signed update packs — balance and pacing, no store review

A pack retunes the knobs listed by python3 tools/czsign.py knobs (research speed, cost curves, growth, raid loot, event odds, upkeep, ...). It is accepted only if signed by your private key.

One-time setup, on your own computer:

pip install cryptography
python3 tools/czsign.py keygen            # writes czupdate.key (mode 600) and prints your public key
# paste the printed public key into core/update_key.h, rebuild, publish the app
# BACK UP czupdate.key somewhere safe and private. Never commit it, never upload it.

Until a key is pasted in, update packs are disabled (all-zero key), so a fresh checkout is safe.

Each update:

echo '{"message":"Slower late game","set":{"SCI_RATE":0.01,"TECH_COST_LATE_GROWTH":1.45}}' > spec.json
python3 tools/czsign.py sign spec.json --version 2 --out update.czpack
python3 tools/czsign.py show update.czpack --pubkey <your public key hex>   # optional check

Get update.czpack onto devices however suits you (host it for the app to download, or copy it into the app's data folder), then the app calls e.installUpdateFile(inboxPath, dataDir + "/update.czpack"). It is kept on disk and re-applied at every start with e.loadStoredUpdate(...). (Downloading is up to the daemon; the core only verifies and applies.)

Rules the device enforces:

  • Valid Ed25519 signature from your key, checked before anything inside the pack is read.
  • version must be higher than the last installed pack (replays are refused, and the counter survives restarts).
  • Every value must be inside its hard bounds, else the whole pack is rejected and nothing changes.
  • A pack is a complete snapshot: knobs it doesn't list go back to their defaults. Publish a pack with an empty set to undo everything.
  • Unknown knob ids are ignored, so a newer pack still works on an older app.

What packs cannot do: change tech effects/names, add eras, change the radio protocol or the UI. Those need a store release.

If the key leaks, anyone could push (bounded) balance changes to every device; the fix is a new app release with a new key. If you lose the key, you can never sign another pack; same fix. Neither can be revoked remotely.

Compatibility notes

  • Radio protocol v2. Devices speaking a different PROTO_VERSION silently ignore each other, so bumping it splits the player base. Keep it stable; add fields only with a plan for old devices.
  • Save format v2 (64-bit tech mask, update counter). v1 saves do not load; nothing shipped used v1. Next time the format changes, add a migration instead of rejecting old saves.

Known limits / open items

  1. Frames are not authenticated (CRC only), so a hostile device could impersonate a civ id. Damage is bounded by the caps above; signed beacons are a later step (the Ed25519 code is already here).
  2. After the threshold, everything plateaus. Needs a post-game goal if you want one.
  3. Wood/stone/metal are mostly upkeep and tech materials; trade volume is modest once civs are wise.
  4. A lost accept packet can duplicate/lose one trade's goods (capped at 20% of a stockpile). A 3-phase commit would fix it.
  5. Event history is not saved (stats, peers and progress are).
  6. Balance knobs are process-wide, not per Engine (fine on the device: one civilization per process).
  7. Signature verification speed on the CM0 itself is unmeasured; on a PC the whole suite (~250 verifications) runs in under a second.
  8. CMakeLists.txt is untested (no cmake in my sandbox); the Makefile is what the tests ran with. The core also passes the suite under ASan + UBSan.

Not built yet

Radio driver (M5Stack LoRa unit and/or built-in Bluetooth LE), LVGL UI (320x170), background daemon / packaging, store metadata, update download.

Cardputer-Adv

The same game runs on the Cardputer-Adv (ESP32-S3). See adv/README.md for the PlatformIO build. The UI scales to 240x135, and both devices share the core, protocol and radio settings, so they can meet each other.

Naming, starting over, and the living scene

  • New game: the first start asks you to name your people. Type a name (letters, digits, space, - and ', up to 12 characters) and press Enter, press Tab for a new random name, or just press Enter / Esc to take the generated one.
  • Rename: on screen 4 (Radio), press N. Esc cancels.
  • Reset: on screen 4, press R, confirm with Enter, then name the new people. Esc at the naming step abandons the reset. A reset starts a brand-new civilization (new identity, personality and name) from the Stone Age; peers, alliances and the log are cleared. Signed balance updates are kept.
  • Scene: the Civ screen shows a small animated village that follows your era: tents and campfires in the Stone Age, then huts, temples, castles, windmills, factories with trains, skyscrapers, rocket launches, drones, and finally a glowing orb. Villagers walk, work, stand guard and study with era-appropriate tools; there is a day/night cycle. The number of villagers grows with your population.

Community

Join the Civ Zero Discord for tips, neighbour meetups and exclusive in-game codes: https://discord.gg/FWJcjj6DQK

Codes

On screen 4 press K, type a code and press Enter. Codes are single-use per save and give a one-off benefit (resources, knowledge, people or free technologies). The app contains only hashes of the valid codes, so reading the source does not reveal any. Five wrong tries in a row lock entry for five minutes. A device cannot redeem the same code twice, and codes survive a reset (they stay used).

About

An autonomous civilization game for the M5Stack CardputerZero and Cardputer-Adv. Grow a tribe from the Stone Age to the Pre-Singularity through 12 eras, watch your village evolve, and meet other players' civilizations over Bluetooth LE and LoRa to trade, ally and fend off raiders.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages