Files
Quadrapassel/SPECIFICATION.md
T

405 lines
22 KiB
Markdown

# Quadrapassel for CoCo — implementation specification
Revision: November 10, 2026. This is an implementation contract, not a claim that
the CoCo game is already built. The Mac source was reviewed to prepare this
document; the implementation chat uses this document without access to that source.
Provenance and the exact reference revision are in [docs/PROVENANCE.md](docs/PROVENANCE.md).
## 1. Product requirements and priorities
Build a responsive falling-block game for a stock 6809 CoCo, predominantly in C
using standard CMOC APIs. Develop and test with **official VCC Plus 3.5.5 (48)**
installed in `/Applications`. No custom emulator build or MCP integration.
| Priority | Requirement |
| --- | --- |
| Primary | CoCo 3 with 128 KB: full rules, seven distinct piece colors, keyboard and joystick |
| Compatibility | CoCo 2 with 64 KB: same rules and controls, accepted color/detail reduction |
| Optional | CoCo 3 with 512 KB or more: baseline works; enhancements only for a demonstrated benefit |
Use one standard floppy image. Prefer one shared rules engine and, where practical,
one executable. Separate display-specific executables on the same disk are allowed
if memory layout makes that simpler. Do not duplicate the rules between variants.
Memory figures are KB. Do not require 512 KB for the seven colors or core gameplay.
Standard CMOC first is a requirement, not just a preference. The exception process
in [AGENTS.md](AGENTS.md) applies before any assembly, custom hardware/framebuffer
code, VCC-specific extension API, or other implementation outside standard CMOC.
Published documentation may be read to assess an exception; this does not approve it.
## 2. Board, pieces and coordinates
- The board has **10 columns and 20 visible rows**, indexed from `(0,0)` at top left.
Empty cells and the seven piece colors are distinguishable logical values.
- An active piece has a type, rotation state `0..3`, and an origin `(x,y)` for its
4 by 4 definition. Settled cells do not include the active piece or its shadow.
- Use the exact four states for each piece in
[docs/reference/pieces.json](docs/reference/pieces.json). Rows run top to bottom;
columns left to right; `#` is occupied. Do not replace this table with a modern
rotation system. Repeated states for S, Z, I and O are intentional.
| Type index | Piece | Reference color |
| --- | --- | --- |
| 0 | L | Red |
| 1 | J | Green |
| 2 | T | Blue |
| 3 | S | Light gray |
| 4 | Z | Yellow |
| 5 | I | Purple |
| 6 | O | Orange |
The seven-color requirement means seven distinct piece colors, not seven total
screen colors. Black, text, borders and shadow can use additional palette slots.
Exact modern Mac RGB values are not required; choose readable CoCo approximations.
To spawn a piece, compute the minimum occupied column `xmin`, occupied width `w`,
and minimum occupied row `ymin` from its current state. Set
`x = floor((10-w)/2)-xmin`, `y = -ymin`. Thus its first occupied row starts at board
row zero even when its 4 by 4 definition has an empty first row. Test collision at
spawn. If any visible occupied cell overlaps a settled cell, end the game.
Movement rejects a result with an occupied cell outside columns `0..9`, below
row 19, or overlapping a settled cell at row zero or below. Cells above row zero
are allowed while moving/rotating, but must never index the board array. If locking
would leave an occupied cell above the board, end the game safely; do not write
out of bounds. This is an explicit safety rule for the CoCo implementation.
## 3. Movement, rotation and locking
Left/right moves one column immediately, then repeats after **200 ms**, then
every **40 ms** while held. A blocked move does not alter the board. If opposing
directions are held, the first held direction wins until released; then use the
remaining direction. Alias keys for the same action share one logical held state.
Rotation, hold and hard drop are edge actions, without automatic repeat.
Counterclockwise rotation advances the table state by `+1 modulo 4`; clockwise
uses `-1 modulo 4`. Try horizontal adjustments in this order: **0, +1, -1, +2, -2**.
If the current piece origin has `y < 0`, also use a downward adjustment of one row
for every candidate; otherwise use zero. Accept the first valid candidate. If
all fail, retain the exact previous piece and origin. There are no other kicks,
floor kicks, spin bonuses, or modern SRS rules.
Gravity interval in milliseconds is `round(80 + 800 * 0.75^(level-1))`, with the
source's minimum clamp of 10 ms. In practice the formula approaches 80 ms.
Use an integer lookup or integer calculation; a floating-point library is not
required. Preserve elapsed time when converting to 50/60 Hz ticks so rounding
does not accumulate major speed differences.
Pressing soft drop attempts one downward move immediately, then uses an **80 ms**
gravity interval while held. Release restores normal gravity. Hard drop moves to
the lowest valid row and locks immediately. Neither type of drop awards points.
On an ordinary gravity tick, lock when the downward move fails; there is no extra
modern lock-delay/reset mechanic.
On lock: place cells, identify all full rows, record whether original row 19 is
among them, remove those rows simultaneously, compact survivors downward while
preserving order, insert empty rows at the top, update lines/score/level, reset
the hold allowance and spawn the next piece. Visual effects must not change this
ordering or block controls unnecessarily.
## 4. Next piece, hold and landing shadow
Show one next piece and a separate held piece. Ordinary new pieces and pieces
retrieved from hold start in rotation zero at their computed spawn location.
Hold is usable once per locked piece. With no held piece, store the active type,
activate the preview, and generate a new preview. With a held piece, swap active
and held types without consuming or replacing the next preview. A second hold
before a lock does nothing. A replacement that cannot spawn ends the game.
**Intentional CoCo correction:** the reviewed Mac implementation's nonempty-hold
branch clears the held slot and overwrites the next slot. This specification uses
the conventional persistent hold swap described above, rather than carrying that
anomaly into the new game. Test the queue preservation explicitly.
Landing shadow is off by default. When enabled, show the lowest valid placement
of the current piece without changing game state. Use a subdued outline/stipple
appropriate to the display; the Mac reference opacity is 37.5%, not a CoCo alpha
blending requirement. Recompute after movement, rotation, hold and board changes.
## 5. Piece selection and repeatability
Normal selection is weighted balancing, **not a seven-piece bag**. Keep a count
for each type, initially zero. Let `m` be the lowest count and
`r[i] = max(1, count[i]-m)`. Select a type proportionally to weight `1/(r[i]*r[i])`,
then increment that type's count. Lower-frequency types become more likely;
duplicates and runs remain possible. Rebase all counts by their minimum when
needed to prevent overflow. A documented fixed-point approximation is acceptable
if tests preserve the intended weighting and no type becomes permanently excluded.
Seeded games accept a 32-bit seed and reproduce the same initial board and piece
stream in the CoCo port. A documented compact PRNG is allowed; bit-for-bit GLib/Mac
random-stream compatibility is not required. Keep cosmetic randomness separate.
Support a test-supplied explicit piece sequence for rule fixtures; do not expose
test hooks as undocumented end-user features. Freeze the PRNG and draw ordering
once CoCo seed fixtures are published, or version changes clearly.
Also provide optional **Difficult Pieces**, off by default. For each type and each
of its four rotations, consider horizontally reachable positions from the spawn
row, drop the candidate and evaluate the resulting compacted board:
`metric = 5000 * rows_cleared - 5 * sum(column_heights)`
A column height is `20 - first_occupied_row`, or zero for an empty column. Retain
the best metric for each type. Add a random integer in `[-2,1]` to each best metric
(the source's upper bound is exclusive despite its comment), then stably sort
types by ascending metric. Draw an integer `0..98`: `<75` selects the worst,
`<92` the second worst, `<98` the third worst, otherwise the fourth worst.
Choose a uniformly random rotation `0..3` for that difficult piece. A type with
no valid placement ranks worst. Simulations must have no effects on actual score,
sound, preview, input or persistence. Document the candidate-board timing and
freeze it in tests; use the settled board at preview-generation time.
This search can be staged across updates in C if needed. Measure it separately;
do not solve its cost with unapproved assembly or silently remove the option.
## 6. Difficulty, levels and scoring
Difficulty is an integer from **-1 through 15**, default **0**. For `d >= 0`,
`level = d + 1 + floor(total_lines/10)`. For `d = -1` (Relaxed), level stays at one.
Start with `max(d,0)` bottom rows prefilled. For each such row, select one random
column that must remain empty. Each other cell independently has a 50% chance of
being filled with one of the seven colors. Rows above are empty. Thus prefill
never starts with a full row. Initial score and cleared-line count are zero.
After a clear, add the number of cleared rows to the line count **before computing
the level used for scoring that clear**. The active game's rule is immutable.
| Rows cleared | Regular points multiplied by level |
| --- | --- |
| 0 | 0 |
| 1 | 40 |
| 2 | 100 |
| 3 | 300 |
| 4 | 1200 |
If the cleared rows include the original bottom row, add:
- **Modern (default):** `100 * level * rows_cleared`.
- **Classic (40.2):** `10000 * level`, once for that clear.
There is no bonus merely for moving a row down into the bottom position, and no
additional all-clear, combo, spin, or drop score. Use a minimum 32-bit score type.
Handle numeric overflow explicitly rather than wrapping negative; document the
display/storage limit. Do not accidentally use CMOC's 16-bit `int` for scores.
Authoritative numeric cases are in
[docs/reference/scoring.json](docs/reference/scoring.json). Examples at level one:
bottom-row clears of 1/2/3/4 rows give **140/300/600/1600** Modern and
**10040/10100/10300/11200** Classic. A single bottom-row clear from nine prior lines
at difficulty zero advances to level two and gives **280** or **20080**.
## 7. Controls and menus
### Keyboard
| Input | Action |
| --- | --- |
| Left/Right or A/D | Move with repeat |
| Up or W | Rotate in preferred direction, default counterclockwise |
| Q / E | Rotate counterclockwise / clockwise |
| Down or S | Soft drop while held |
| Space | Hard drop |
| H | Hold |
| P | Pause/resume |
| Enter | Start from title/game over; select in menus |
| BREAK | Pause/open actions while playing; cancel/back in menus |
No Mac Command shortcuts are required. A live New Game or Quit action must offer
a cancelable confirmation. Releasing keys while paused must not leave stuck
movement after resume. Clear transient input on menu/state transitions and require
release before a held confirm key can activate a second screen.
### Standard analog joystick
Support right and left ports, default right, using standard CMOC joystick APIs.
The primary experience must work with **one button** and no keyboard assistance.
Do not require a USB-specific mapping, a second button or a VCC-only extension.
Default mapping to implement and usability-test:
- Left/right: movement with the same repeat timing as keyboard.
- Down: soft drop while held.
- Up: one hard drop, rearmed only after returning to neutral.
- Short button press/release: rotate in the preferred direction, once on release.
- Button held for 400 ms: pause and open the actions menu, without triggering a
rotation on release. That menu provides Resume, Hold, Rotate Other Way,
Settings, New Game and Quit. Hold/Rotate Other Way performs that action and
resumes; disable Hold if already used. This makes every essential action
available with a one-button controller.
- Menus: up/down choose, button selects after a release guard; include a visible
Back/Cancel entry. Left/right adjusts settings where relevant.
The short-press/long-press scheme is a CoCo adaptation, not behavior claimed for
the Mac port. Measure release-to-rotation latency; tune usability in ordinary C.
Document any mapping refinement and preserve access to all actions.
Sample input regularly. Calibrate neutral explicitly at the player's request;
do not silently recenter a deliberately held stick during play. For `0..63` axes,
a reasonable starting dead zone is center ±6, with activation beyond ±10 and
hysteresis back into the inner zone. Clamp near endpoints. On diagonals, prioritize
the dominant axis for edge actions so a horizontal motion does not accidentally
hard-drop. Require neutral between upward edge actions. Missing/disconnected
controllers must not prevent keyboard use or cause uncontrollable menu movement;
allow joystick input to be disabled. Validate actual axis/button readings, not
keyboard presses presented as joystick evidence.
## 8. Screens, appearance and sound
### Title and layout
Use [the supplied image](docs/reference/title-reference.png) as visual inspiration:
dark background/grid, bright falling-block shapes and a large readable title.
The game title is **Quadrapassel for CoCo**. Show Start, Settings, Controls, Scores
and Credits, with keyboard and joystick selection. Adapt to native resolution;
do not embed a scaled Mac screenshot or claim the reference is a running CoCo.
A small animation is desirable if responsive. Full gameplay does not wait for
an unskippable title animation. Do not require streaming image assets.
Keep all 20 rows visible. Show score, level, cleared lines, next piece, held
piece, and the active scoring mode. Pause/game-over overlays are unmistakable.
Keep blocks visually square after the CoCo image's display aspect correction;
logical pixels need not be square. Use a readable bitmap font and clear focus
indication. A board using about 160 of 192 lines leaves room for framing/status;
final geometry is determined by the standard API prototype.
CoCo 3: begin with standard CMOC `hscreen(2)` / `hset()` and palette APIs for the
320 by 192, 16-color display. Redraw changed regions with those APIs; avoid
redrawing the entire screen unnecessarily. Measure before proposing a different
drawing method. Preserve BASIC graphics workspace and return to text cleanly.
CoCo 2: begin with standard `pmode(3, buffer)`, `pcls()` and `screen()` plus
documented CMOC graphics-library operations. PMODE 3 is 128 by 192 with four
colors and a 6,144-byte framebuffer. Distinguish pieces by patterns/outlines as
well as the available colors; all seven logical piece types remain intact.
Do not rely on artifact colors or a 6847T1-only feature for basic readability.
Offer Plain (flat), Modern (dark outlines, default), and Clean (light edging)
styles as low-cost approximations. Grid outlines default off. Avoid allocating
separate full-screen bitmaps per theme. CoCo 2 may reduce decorative details,
but that must be disclosed, not presented as seven-color output.
### Sound
Use standard CMOC sound APIs initially. Approximate the reference's event
distinctions with short tones; waveform fidelity and background music are not
requirements. The following synthesis descriptions are CoCo design targets,
not measured transcriptions of the original audio:
| Event | Target |
| --- | --- |
| Successful sideways move | Quiet, very short tick |
| Successful rotation | Brief higher chirp distinct from movement |
| Lock with no clear | Short lower landing tone |
| One-row clear | Short bright confirmation |
| Two-row clear | Slightly longer rising confirmation |
| Three/four-row clear | Shared more celebratory sequence |
| Game over | Distinct descending phrase |
No sound for rejected moves. Sound defaults on and can be muted. Drop motion
does not produce a tone per fallen row. Measure blocking behavior of standard
sound calls and input responsiveness with sound enabled. If adequate feedback
requires a custom driver or assembly, request the documented review before
implementing it. A sound requirement does not waive that gate.
## 9. Preferences and high scores
Defaults: difficulty 0; Modern scoring; Modern style; counterclockwise preferred
rotation; grid and landing shadow off; sound on; Difficult Pieces off; custom
seed off with stored seed zero; joystick right port.
Settings must be accessible from the title and paused game. Theme/grid/shadow/
sound/controls can apply immediately. Difficulty, random seed, Difficult Pieces
and scoring rule apply to the next game. Display that distinction clearly.
For a scoring-rule change, offer **Keep Scores**, **Reset Scores**, and **Cancel**.
Explain that keeping scores may mix different scoring rules. Reset clears every
category, and if a game is active it continues but its score cannot subsequently
be saved. Cancel changes nothing. The current game always retains its initial
scoring mode; no retroactive recalculation. Failure to save/reset must be reported
without silently claiming success or erasing unrelated files.
Store a bounded top-ten table per difficulty and normal/difficult-pieces mode.
Include three-character initials, score, and a Modern/Classic marker for clarity.
Sort descending by score with stable ordering of ties. This bounded storage and
explicit marker are CoCo adaptations. No wall-clock date, Mac scoreboard import,
localization framework or Mac window preferences are required.
Use documented standard CMOC disk APIs. Keep settings/scores in named disk files
with a version identifier, length/range validation and corruption detection.
Use a recoverable two-slot or equivalent bounded save scheme and test interrupted
writes; do not assume a modern filesystem's atomic rename. Missing files mean
defaults/empty scores. Read-only media keeps play functional and reports that
changes cannot be saved. Write on explicit changes/game completion, not each
frame. Never reformat the user's disk as a recovery action.
## 10. Memory, speed, disk and launch
Start with measurements rather than a bespoke memory manager. The board itself
needs only 200 bytes at one byte per cell; bitmask piece definitions need 56
bytes. A 320 by 192, 16-color framebuffer needs 30,720 bytes. These arithmetic
facts make 128 KB a plausible target, but do not prove a valid address layout.
Record code/data/stack, graphics workspace, BASIC/ROM/disk requirements and free
headroom from the actual linked build. Avoid allocating a second full framebuffer
by default. Standard CMOC's BASIC-backed graphics APIs must retain their workspace.
The installed public `vcc/gime.h` extension requires 512 KB and reserves physical
RAM beyond 128 KB. It is a separate helper, not the standard `coco.h` graphics API.
It is neither the baseline solution nor an approved exception.
Use stock-compatible CoCo speeds with the supported `setHighSpeed()` API only
where appropriate and validated. Record actual speed. Restore the required state
before disk operations and exit according to public API documentation. Do not
hide performance issues with emulator overclocking or require a 6309. Test the
6809 path first; 6309 compatibility is a separate useful check.
Use a standard 35-track, 18-sector, 256-byte-per-sector floppy image (161,280 raw
bytes). Actual file capacity is lower after directory, allocation and boot space.
Reserve documented DOS-launcher tracks and space for scores/settings. Report real
used/free granules; an initial program/assets target below 128 KiB is a planning
budget, not a claim of available capacity. No second disk is required to play.
Use the installed VCC Plus disk-project workflow and documented DOS-launch option.
Autodetect CoCo 2 vs CoCo 3 with a documented standard CMOC mechanism when possible;
do not perform a destructive RAM probe. Provide a boot-time manual display/target
choice if safe detection is unavailable. Optional 512 KB enhancements may require
manual selection; baseline operation must be safe without probing expanded RAM.
If boot glue would require writing custom assembly or raw hardware code, request
review first; use the existing supported loader when sufficient.
The final README gives a short **DOS** loading recipe and a separately verified
manual fallback, with the actual filenames/commands from the delivered disk.
Do not publish placeholder loading commands as tested instructions.
## 11. Acceptance and evidence
1. API prototype: actual 128 KB CoCo 3, seven-color screen, readable text, moving
blocks, keyboard/joystick readings, sound, clean return and repeated disk access.
2. Rules: all 28 rotation states; left/right boundaries; every kick candidate;
rejected rotation unchanged; top spawn/block-out; gravity and hard/soft drop;
simultaneous row compaction; hold queue preservation; shadow correctness.
3. Scoring: every fixture in `scoring.json`, including level transitions, Relaxed,
bottom/non-bottom clears, both modes, and values above 32,767.
4. Randomness: deterministic CoCo seeds, weighted selection, difficult-piece metric
fixtures, no simulation side effects, prefill never full.
5. Input: repeat timings, conflicting keys, aliases, pause/release, menu guards,
one-button-only start/play/hold/pause/settings/quit, both joystick ports and
calibration. Capture a diagnostic showing actual sampled axes/buttons.
6. Persistence: save/reload, read-only disk, absent/corrupt/partial data, reset/cancel,
rule changes during play, all categories, and no writes outside designated files.
7. Performance: measure input-to-visible-action and worst update times on ordinary
6809 settings. Target visible keyboard/joystick action within two video fields
after the relevant edge (button rotation uses its release edge). Report p95 and
worst values, separately for ordinary play, clears, sound and Difficult Pieces.
A missed target prompts analysis/review, not unauthorized assembly.
8. Configuration: separate evidence for CoCo 3 128 KB; baseline on 512 KB; 64 KB
CoCo 2 in XRoar/hardware; PAL/NTSC timing if both claimed. A CoCo 3 compatibility
run of the CoCo 2 executable is labeled accordingly. Brian may supply XRoar evidence.
9. Delivery: top-level built `Quadrapassel.DSK`; source/build recipe; actual guest-only
title and gameplay PNGs; concise run instructions, controls and credits; recorded
revision/build/configuration, disk hash, memory budget, and test matrix.
No test is passed merely because the game compiled or the screenshot looks right.
Keep pending external tests and unavailable MCP capabilities visible. The reference
image and specification fixtures are not emulator validation evidence.