Orbi-Fax Codebreaker: the day's five-letter code in six tries on teletext page 888, Practice mode, the wizard drops in

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-09 11:22:47 +00:00
co-authored by Claude Opus 5.5
parent 254c5fc09a
commit 111a9f5d5b
5 changed files with 348 additions and 5 deletions
@@ -110,6 +110,12 @@ internal object ArcadeGames {
tv.orbit.classic.arcade.tangle.TestCardTangleScreen(it)
}
val Codebreaker: ArcadeGame = GameDef("Codebreaker", "Orbi-Fax Codebreaker", "Crack the day's code on page 888", "A five-letter word in six tries, on Orbi-Fax's teletext.", Mascot.Luna,
kidsSuitable = true, original = true, launchable = true, ScoreKind.Solved, keepsLevels = true, legacyRecordKey = null,
listOf(Control("◀▶▲▼", "Choose a key"), Control("OK", "Type it"), Control("Back", "Delete a letter, or pause")), "Green: right place. Yellow: elsewhere in the word. Blue: not in it.") {
tv.orbit.classic.arcade.codebreaker.CodebreakerScreen(it)
}
// Classics: the eight Kotlin games, unchanged, each in a thin wrapper.
val OrbMan: ArcadeGame = GameDef("OrbMan", "Star Chase", "Maze chase starring Ollie", "Help Ollie clear the stars, and dodge Blaze, Zip, Drift and Luna.", Mascot.Ollie,
kidsSuitable = true, original = false, launchable = true, ScoreKind.Points, keepsLevels = false, legacyRecordKey = "orb_man_best",
@@ -140,7 +146,7 @@ internal object ArcadeGames {
listOf(Control("◀▶▲▼", "Point"), Control("OK", "Pick up / put down"), Control("OK twice", "Send a card home"), Control("Back", "Put back, or pause")),
"Klondike, one card at a time: build each suit home, ace to king.") { PatienceScreen(it) }
val originals = listOf(OrbiRaiders, ChannelChaos, Hive, NightShift, Orbiteroids, QuizNight, TestCardTangle)
val originals = listOf(OrbiRaiders, ChannelChaos, Hive, NightShift, Orbiteroids, QuizNight, TestCardTangle, Codebreaker)
val classics = listOf(OrbMan, Blast, Sky, Snake, Blocks, Bricks, Pairs, Patience)
val all = originals + classics
@@ -0,0 +1,73 @@
package tv.orbit.classic.arcade.codebreaker
/**
* Orbi-Fax Codebreaker (9 November 2026): a daily word puzzle on Orbi-Fax's teletext page 888. Find the five-letter code
* word in six tries; after each try every letter is marked: in the right place (green), in the word but elsewhere
* (yellow), or not in it at all (blue). The same word for everyone on the day; a Practice mode for as many as you like.
* Free, no streaks. The wizard of page 999 drops in now and then. The game has no screen in it, so it can be tested.
*/
internal const val CODE_LEN = 5
internal const val CODE_TRIES = 6
/** A letter's mark after a try. */
internal enum class Mark { None, Absent, Present, Right }
/** The words: family-friendly, all five letters, A to Z only. */
internal val CodeWords: List<String> = """
APPLE BEACH BRAVE BREAD BRICK BRUSH CANDY CHAIR CHALK CHEER CHESS CLOCK CLOUD COAST CRANE CROWN DANCE DREAM DRINK EAGLE
EARTH FAIRY FEAST FIELD FLAME FLOAT FLOOR FLUTE FRESH FROST FRUIT GHOST GIANT GLOBE GRAPE GRASS HAPPY HEART HONEY HORSE
HOUSE JELLY JUICE LAUGH LEMON LIGHT LUCKY MAGIC MANGO MAPLE MATCH MOUSE MUSIC NIGHT NOBLE OCEAN OLIVE ORBIT OTTER PAINT
PANDA PAPER PARTY PEACH PEARL PIANO PILOT PIZZA PLANE PLANT PLATE RADIO RAVEN RIVER ROBIN ROBOT SALAD SCARF SHARK SHEEP
SHELL SHINE SKATE SLEEP SMILE SNAIL SNAKE SOLAR SPACE SPOON SPORT STAGE STAMP STARS STORM STORY SUGAR SUNNY SWEET TABLE
TEETH TIGER TOAST TOWER TRAIN TREAT TRUCK TULIP UNCLE VOICE WATCH WATER WHALE WHEAT WHEEL WORLD YACHT ZEBRA BADGE BAKER
BASIL BERRY BLAZE BLOOM BOARD BOOTS BRAIN BRASS BUNNY CABIN CAMEL CANOE CARDS CHIRP CLIMB COMET COUCH CRAFT CRISP DAISY
DELTA DIARY DOZEN DRAMA DRIFT DRUMS FENCE FERRY FLASH FLOCK FOCUS GLASS GLOVE GRAIN GRAVY GUARD GUEST HEDGE HIPPO HOBBY
IGLOO IVORY JEWEL KAYAK KOALA LADLE LASER LEAFY LEDGE LILAC LLAMA LUNAR MEDAL MELON METAL MINTY MODEL MOOSE MOTOR MUDDY
NURSE NUTTY OASIS OPERA PASTA PATCH PEDAL PENNY PETAL PIXEL PLAZA POLAR POPPY PRISM PUPPY QUACK QUEEN QUEST QUILT RANCH
RELAY RHINO RIDER ROAST ROYAL RUGBY SAUCE SCALE SCOUT SHADE SHORE SLIDE SLOTH SNACK SOCKS SONIC SPICE SPRAY SQUID STEAM
STICK STONE STRAW SWAMP SWING SWIRL TEDDY THEME THUMB TIDAL TOPAZ TORCH TOWEL TRAIL TROUT VIDEO VINYL WAGON WALTZ WHISK
WINDY WITTY YODEL YOUTH ZESTY CHIME CLOAK CORAL CRUMB GECKO GLEAM HAVEN JOLLY KITES PLUMS
""".trim().split(Regex("\\s+"))
/** The day's word: the same everywhere on [day], going through the list in a fixed shuffled order. */
internal fun codeWordFor(day: java.time.LocalDate): String {
val order = CodeWords.indices.shuffled(java.util.Random(888_999L))
return CodeWords[order[Math.floorMod(day.toEpochDay(), CodeWords.size.toLong()).toInt()]]
}
/** The marks for [guess] against [word], counting repeated letters as Wordle-style games do (each letter in the word used once). */
internal fun markGuess(guess: String, word: String): Array<Mark> {
val marks = Array(CODE_LEN) { Mark.Absent }
val left = IntArray(26)
for (i in 0 until CODE_LEN) if (guess[i] == word[i]) marks[i] = Mark.Right else left[word[i] - 'A']++
for (i in 0 until CODE_LEN) if (marks[i] != Mark.Right && left[guess[i] - 'A'] > 0) { marks[i] = Mark.Present; left[guess[i] - 'A']-- }
return marks
}
internal class CodebreakerGame(val word: String) {
val guesses = ArrayList<String>(CODE_TRIES)
val marks = ArrayList<Array<Mark>>(CODE_TRIES)
/** The try being typed. */
val typing = StringBuilder()
/** What's known about each letter, A to Z, for the keyboard: the best mark it has had. */
val known = Array(26) { Mark.None }
val won get() = marks.isNotEmpty() && marks.last().all { it == Mark.Right }
val lost get() = !won && guesses.size == CODE_TRIES
val over get() = won || lost
fun type(ch: Char): Boolean { if (over || typing.length >= CODE_LEN || ch !in 'A'..'Z') return false; typing.append(ch); return true }
fun delete(): Boolean { if (typing.isEmpty()) return false; typing.setLength(typing.length - 1); return true }
/** Enter: a full five letters is a try. Any letters are allowed (there's no dictionary to fall foul of). */
fun enter(): Boolean {
if (over || typing.length < CODE_LEN) return false
val g = typing.toString(); typing.setLength(0)
val m = markGuess(g, word)
guesses += g; marks += m
for (i in 0 until CODE_LEN) { val k = g[i] - 'A'; if (m[i].ordinal > known[k].ordinal) known[k] = m[i] }
return true
}
}
/** The wizard of page 999 drops in: on a win in two tries or fewer, and on one day in seven. */
internal fun wizardVisits(game: CodebreakerGame, day: java.time.LocalDate) = (game.won && game.guesses.size <= 2) || Math.floorMod(day.toEpochDay(), 7L) == 3L
@@ -0,0 +1,208 @@
package tv.orbit.classic.arcade.codebreaker
import android.graphics.Bitmap
import android.view.KeyEvent
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import tv.orbit.classic.ArcadeBackdrop
import tv.orbit.classic.ORBI_FAX_WIZARD
import tv.orbit.classic.Teletext
import tv.orbit.classic.TeletextPage
import tv.orbit.classic.TeletextRenderer
import tv.orbit.classic.arcade.ArcadeColours
import tv.orbit.classic.arcade.ArcadeGames
import tv.orbit.classic.arcade.ArcadeKey
import tv.orbit.classic.arcade.ArcadePauseMenu
import tv.orbit.classic.arcade.ArcadePlay
import tv.orbit.classic.arcade.ClassicTitle
import tv.orbit.classic.arcade.Control
import tv.orbit.classic.arcade.HowToPlayCard
import tv.orbit.classic.arcade.KeyFooter
import tv.orbit.classic.arcade.RunEnd
import tv.orbit.classic.arcade.gameKeys
/** The on-screen keyboard: three rows of letters, then Delete and Try on the bottom row (each row fits teletext's 40 columns). */
internal val CodeKeys: List<List<String>> = listOf(
"QWERTYUIOP".map { it.toString() }, "ASDFGHJKL".map { it.toString() }, "ZXCVBNM".map { it.toString() } + listOf("DEL", "TRY"))
/** Where the keyboard's cursor goes on ◀▶▲▼, kept on the keys of its row. */
internal fun codeCursor(row: Int, col: Int, dx: Int, dy: Int): Pair<Int, Int> {
val r = (row + dy).coerceIn(0, CodeKeys.lastIndex)
val c = (if (dy != 0) col else col + dx).coerceIn(0, CodeKeys[r].lastIndex)
return r to c
}
private enum class CStage { Title, Play, Wizard }
/** The day's saved result, "date,tries,won". */
private fun dailyDone(saved: String?, day: java.time.LocalDate) = saved?.startsWith("$day,") == true
/** Builds page 888 for the game as it stands: header, title, the six tries, the keyboard or the result, the fastext line. */
internal fun buildCodePage(page: TeletextPage, g: CodebreakerGame, day: java.time.LocalDate, daily: Boolean, row: Int, col: Int) {
page.clear()
page.put(0, 1, "P888", Teletext.WHITE); page.put(0, 7, "ORBI-FAX", Teletext.YELLOW)
page.put(0, 18, if (daily) "DAILY CODE" else "PRACTICE", Teletext.CYAN)
val date = "%02d %s".format(day.dayOfMonth, day.month.name.take(3))
page.put(0, 39 - date.length, date, Teletext.WHITE)
page.rule(1, Teletext.BLUE)
page.put(2, 2, "CODEBREAKER", Teletext.CYAN, double = true)
page.put(2, 25, "Five letters,", Teletext.WHITE); page.put(3, 25, "six tries.", Teletext.WHITE)
for (t in 0 until CODE_TRIES) {
val r = 5 + t * 2
for (i in 0 until CODE_LEN) {
val c = 12 + i * 4
val (ch, fg, bg) = when {
t < g.guesses.size -> Triple(g.guesses[t][i], if (g.marks[t][i] == Mark.Absent) Teletext.WHITE else Teletext.BLACK, when (g.marks[t][i]) { Mark.Right -> Teletext.GREEN; Mark.Present -> Teletext.YELLOW; else -> Teletext.BLUE })
t == g.guesses.size && i < g.typing.length && !g.over -> Triple(g.typing[i], Teletext.BLACK, Teletext.WHITE)
else -> Triple('.', Teletext.WHITE, Teletext.BLACK)
}
page.put(r, c - 1, " $ch ", fg, background = bg)
}
}
if (!g.over) {
CodeKeys.forEachIndexed { kr, keys ->
var c = intArrayOf(0, 2, 1)[kr]
keys.forEachIndexed { kc, key ->
val m = if (key.length == 1) g.known[key[0] - 'A'] else Mark.None
val focused = kr == row && kc == col
val bg = when { focused -> Teletext.MAGENTA; m == Mark.Right -> Teletext.GREEN; m == Mark.Present -> Teletext.YELLOW; m == Mark.Absent -> Teletext.BLUE; else -> Teletext.BLACK }
val fg = if (focused || m == Mark.Absent || m == Mark.None) Teletext.WHITE else Teletext.BLACK
page.put(18 + kr * 2, c, " $key ", fg, background = bg)
c += key.length + 3
}
}
page.put(24, 1, "OK TYPES A LETTER TRY CHECKS THE WORD", Teletext.CYAN)
} else {
if (g.won) { page.put(18, 4, "CODE CRACKED!", Teletext.GREEN, double = true); page.put(21, 4, "In ${g.guesses.size} ${if (g.guesses.size == 1) "try" else "tries"}. Very good.", Teletext.WHITE) }
else { page.put(18, 4, "OUT OF TRIES", Teletext.RED, double = true); page.put(21, 4, "The word was ${g.word}.", Teletext.WHITE) }
page.put(22, 4, if (daily) "A new code tomorrow." else "Try another any time.", Teletext.CYAN)
page.put(24, 1, "OK > CONTINUE", Teletext.YELLOW)
}
}
/** The wizard drops in (his Orbi-Fax art, unchanged): page 999, on the side. */
internal fun buildWizardPage(page: TeletextPage, won: Boolean) {
page.clear()
page.put(0, 1, "P999", Teletext.WHITE); page.put(0, 7, "ORBI-FAX", Teletext.YELLOW)
page.art(3, 1, ORBI_FAX_WIZARD)
if (won) {
page.put(5, 21, "HMM. CLEVER.", Teletext.YELLOW, double = true)
page.put(9, 21, "Cracked my code", Teletext.WHITE); page.put(10, 21, "already?", Teletext.WHITE)
page.put(13, 21, "I'm still watching", Teletext.CYAN); page.put(14, 21, "page 1000.", Teletext.CYAN)
} else {
page.put(5, 21, "STILL HERE?", Teletext.YELLOW, double = true)
page.put(9, 21, "Codes are my", Teletext.WHITE); page.put(10, 21, "speciality.", Teletext.WHITE)
page.put(13, 21, "Same time", Teletext.CYAN); page.put(14, 21, "tomorrow, then.", Teletext.CYAN)
}
page.put(24, 1, "OK > CONTINUE", Teletext.YELLOW)
}
@Composable
internal fun CodebreakerScreen(play: ArcadePlay) {
val gameDef = ArcadeGames.Codebreaker
val latestPlay by rememberUpdatedState(play)
val today = remember { java.time.LocalDate.now() }
var saved by remember { mutableStateOf(play.level["code.daily"]) }
var practice by remember { mutableStateOf(play.level["mode"] == "Practice") }
var stage by remember { mutableStateOf(CStage.Title) }
var howTo by remember { mutableStateOf(false) }
var paused by remember { mutableStateOf(false) }
var game by remember { mutableStateOf(CodebreakerGame(codeWordFor(today))) }
var daily by remember { mutableStateOf(true) }
var cr by remember { mutableIntStateOf(0) }; var cc by remember { mutableIntStateOf(0) }
var version by remember { mutableIntStateOf(0) }
val focus = remember { FocusRequester() }
// Page 888, drawn into one small bitmap only when something on it changes.
val page = remember { TeletextPage() }
val pixels = remember { IntArray(Teletext.WIDTH * Teletext.HEIGHT) }
val bitmap = remember { Bitmap.createBitmap(Teletext.WIDTH, Teletext.HEIGHT, Bitmap.Config.ARGB_8888) }
val image = remember(bitmap) { bitmap.asImageBitmap() }
val doneToday = dailyDone(saved, today)
fun start(todays: Boolean) {
daily = todays
game = CodebreakerGame(if (todays) codeWordFor(today) else CodeWords[java.util.Random().nextInt(CodeWords.size)])
cr = 0; cc = 0; paused = false; version++; stage = CStage.Play
}
fun finish() {
if (daily) { val v = "$today,${game.guesses.size},${game.won}"; saved = v; latestPlay.setLevel("code.daily", v) }
latestPlay.onRunEnd(RunEnd(game.guesses.size, finished = game.won, detail = if (daily) "Daily code" else "Practice"))
}
LaunchedEffect(stage, paused) { if (stage != CStage.Title && !paused) runCatching { focus.requestFocus() } }
BackHandler(stage != CStage.Title && !paused) { if (stage == CStage.Play && game.typing.isNotEmpty()) { game.delete(); version++ } else paused = true }
if (stage == CStage.Title) {
ClassicTitle(gameDef, ArcadeBackdrop.Teletext, ArcadeColours.Cyan, if (!practice && doneToday) "Back tomorrow for a new one!" else "Can you crack today's code?",
listOf("Codes cracked" to "${play.best}", "Today's" to if (doneToday) (if (saved!!.endsWith("true")) "Cracked ★" else "Tried") else "Waiting"),
timed = false, difficulty = play.difficulty, refocus = !howTo, kicker = "AN ORBIT ARCADE ORIGINAL",
mode = if (practice) "Practice" else "Daily code", modes = 2, onMode = { practice = !practice; latestPlay.setLevel("mode", if (practice) "Practice" else "Daily") },
playLabel = if (practice) "A practice code" else if (doneToday) "Practise instead" else "Today's code",
onPlay = { start(todays = !practice && !doneToday) }, onHowTo = { howTo = true }, onBack = { latestPlay.onLeave() },
note = "Find the five-letter word in six tries, on Orbi-Fax page 888. Green: right letter, right place. Yellow: in the word, somewhere else. Blue: not in it. One code a day, the same for everyone; practise as much as you like.")
if (howTo) HowToPlayCard(gameDef, firstRun = false, everyTime = null, onEveryTime = {}, onPlay = { howTo = false }, onBack = { howTo = false })
return
}
// Redraw the page into the bitmap when the game, the cursor or the stage change: never frame by frame.
var drawn by remember { mutableIntStateOf(0) }
LaunchedEffect(version, cr, cc, stage) {
if (stage == CStage.Wizard) buildWizardPage(page, game.won) else buildCodePage(page, game, today, daily, cr, cc)
TeletextRenderer.render(page, pixels)
bitmap.setPixels(pixels, 0, Teletext.WIDTH, 0, 0, Teletext.WIDTH, Teletext.HEIGHT)
image.prepareToDraw()
drawn++
}
val keys = Modifier.focusRequester(focus).focusable().gameKeys(enabled = !paused,
// Back by context: letters typed come off one at a time; with none, Back pauses.
active = { stage == CStage.Play && game.typing.isNotEmpty() }, cancel = { game.delete(); version++ }, pause = { paused = true }) { key, native ->
if (native.action != KeyEvent.ACTION_DOWN) return@gameKeys key != ArcadeKey.Other
if (stage == CStage.Wizard) { if (key == ArcadeKey.Ok) stage = CStage.Title; return@gameKeys true }
if (game.over) {
if (key == ArcadeKey.Ok) { if (wizardVisits(game, today)) stage = CStage.Wizard else stage = CStage.Title }
return@gameKeys true
}
when (key) {
ArcadeKey.Left -> { val (r, c) = codeCursor(cr, cc, -1, 0); cr = r; cc = c }
ArcadeKey.Right -> { val (r, c) = codeCursor(cr, cc, 1, 0); cr = r; cc = c }
ArcadeKey.Up -> { val (r, c) = codeCursor(cr, cc, 0, -1); cr = r; cc = c }
ArcadeKey.Down -> { val (r, c) = codeCursor(cr, cc, 0, 1); cr = r; cc = c }
ArcadeKey.Ok -> if (native.repeatCount == 0) {
when (val k = CodeKeys[cr][cc]) {
"DEL" -> game.delete()
"TRY" -> if (game.enter() && game.over) finish()
else -> game.type(k[0])
}
version++
}
else -> return@gameKeys false
}
true
}
Box(Modifier.fillMaxSize().background(Color.Black)) {
Column(Modifier.fillMaxSize().then(keys).padding(start = 32.dp, end = 32.dp, top = 12.dp, bottom = 10.dp), horizontalAlignment = Alignment.CenterHorizontally) {
// The page, at teletext's 4:3, with its dots kept sharp.
Canvas(Modifier.weight(1f).aspectRatio(4f / 3f)) {
drawn // redraw after the bitmap changes
drawImage(image, IntOffset.Zero, IntSize(Teletext.WIDTH, Teletext.HEIGHT), IntOffset.Zero, IntSize(size.width.toInt(), size.height.toInt()), filterQuality = FilterQuality.None)
}
Spacer(Modifier.height(6.dp))
KeyFooter(if (game.over || stage == CStage.Wizard) listOf(Control("OK", "Continue"), Control("Back", "Pause"))
else listOf(Control("◀▶▲▼", "Choose a key"), Control("OK", "Type it"), Control("Back", if (game.typing.isNotEmpty()) "Delete a letter" else "Pause")))
}
if (paused) ArcadePauseMenu(gameDef, if (daily) "Daily code · try ${game.guesses.size + 1} of $CODE_TRIES" else "Practice · try ${game.guesses.size + 1} of $CODE_TRIES",
onResume = { paused = false }, onRestart = { if (!daily) start(false) else paused = false }, onExit = { latestPlay.onLeave() })
}
}
@@ -16,7 +16,7 @@ class KidsArcadeTest {
@Test fun grownUpsSeeEveryGame() {
assertEquals(ArcadeGames.all.map { it.id }, ids(grown))
assertEquals(15, ids(grown).size)
assertEquals(16, ids(grown).size)
// A grown-up's Arcade for Kids setting means nothing.
assertEquals(ArcadeGames.all.map { it.id }, ids(grown.withKidsArcade(KidsArcade.Off)))
assertEquals(ArcadeGames.all.map { it.id }, ids(null))
@@ -70,16 +70,16 @@ class KidsArcadeTest {
@Test fun theFamilyLineSaysWhatKidsReallySee() {
// The audit: "On: the games chosen for Kids" promised a choice that didn't exist.
assertEquals("Off: no Arcade for Kids", arcadeForKidsLine(kids.withKidsArcade(KidsArcade.Off)))
assertEquals("Kids-suitable games: 13 to play", arcadeForKidsLine(kids.withKidsArcade(KidsArcade.KidsSuitable)))
assertEquals("Kids-suitable games: 14 to play", arcadeForKidsLine(kids.withKidsArcade(KidsArcade.KidsSuitable)))
assertEquals("Chosen games: 2 to play", arcadeForKidsLine(kids.withKidsArcade(KidsArcade.Chosen, setOf("Pairs", "Sky", "Retired"))))
assertEquals("Chosen games: none chosen yet, so no Arcade", arcadeForKidsLine(kids.withKidsArcade(KidsArcade.Chosen, emptySet())))
}
@Test fun everyGameIsDescribed() {
assertEquals(ArcadeGames.all.size, ArcadeGames.all.map { it.id }.toSet().size)
assertEquals(7, ArcadeGames.originals.size); assertEquals(8, ArcadeGames.classics.size)
assertEquals(8, ArcadeGames.originals.size); assertEquals(8, ArcadeGames.classics.size)
// All five Originals play now (Orbiteroids, the last, 9 November 2026); every Classic does.
assertEquals(listOf("OrbiRaiders", "ChannelChaos", "Hive", "NightShift", "Orbiteroids", "QuizNight", "TestCardTangle"), ArcadeGames.originals.filter { it.launchable }.map { it.id })
assertEquals(listOf("OrbiRaiders", "ChannelChaos", "Hive", "NightShift", "Orbiteroids", "QuizNight", "TestCardTangle", "Codebreaker"), ArcadeGames.originals.filter { it.launchable }.map { it.id })
assertTrue(ArcadeGames.classics.all { it.launchable })
ArcadeGames.all.forEach { g ->
assertTrue(g.id, g.controls.isNotEmpty()); assertTrue(g.id, g.title.isNotBlank()); assertTrue(g.id, g.goal.isNotBlank())
@@ -0,0 +1,56 @@
package tv.orbit.classic.arcade.codebreaker
import org.junit.Assert.*
import org.junit.Test
import tv.orbit.classic.TeletextPage
class CodebreakerTest {
@Test fun theWordsAreFiveCapitalLettersAndNoneTwice() {
assertTrue(CodeWords.size >= 250)
assertTrue(CodeWords.all { w -> w.length == CODE_LEN && w.all { it in 'A'..'Z' } })
assertEquals(CodeWords.size, CodeWords.toSet().size)
}
@Test fun theDaysWordIsTheSameAllDayAndDiffersTomorrow() {
val d = java.time.LocalDate.of(2026, 11, 9)
assertEquals(codeWordFor(d), codeWordFor(d)); assertNotEquals(codeWordFor(d), codeWordFor(d.plusDays(1)))
assertTrue(codeWordFor(d) in CodeWords)
// Every word comes round before any repeats.
assertEquals(CodeWords.size, (0 until CodeWords.size).map { codeWordFor(d.plusDays(it.toLong())) }.toSet().size)
}
@Test fun lettersAreMarkedAsWordleStyleGamesDo() {
assertArrayEquals(Array(5) { Mark.Right }, markGuess("ORBIT", "ORBIT"))
// R and B in ORBIT but elsewhere; the rest not in it.
assertArrayEquals(arrayOf(Mark.Present, Mark.Present, Mark.Absent, Mark.Absent, Mark.Absent), markGuess("RBXYZ", "ORBIT"))
// A repeated letter only counts as often as it's in the word: one P in APPLE's second place, the first P present.
assertArrayEquals(arrayOf(Mark.Present, Mark.Right, Mark.Absent, Mark.Absent, Mark.Absent), markGuess("PPXYZ", "APPLE"))
assertArrayEquals(arrayOf(Mark.Absent, Mark.Right, Mark.Right, Mark.Absent, Mark.Absent), markGuess("XPPPZ", "APPLE"))
}
@Test fun aGameTakesSixTriesAndRemembersWhatItLearned() {
val g = CodebreakerGame("ORBIT")
"TRAIN".forEach { g.type(it) }; assertFalse(g.type('X'))
assertTrue(g.delete()); assertTrue(g.type('N'))
assertTrue(g.enter()); assertEquals(1, g.guesses.size)
assertEquals(Mark.Present, g.known['T' - 'A']); assertEquals(Mark.Right, g.known['R' - 'A']); assertEquals(Mark.Absent, g.known['A' - 'A'])
assertFalse(g.enter()) // nothing typed
"ORBIT".forEach { g.type(it) }; g.enter()
assertTrue(g.won); assertTrue(g.over); assertFalse(g.type('A'))
val lose = CodebreakerGame("ORBIT")
repeat(CODE_TRIES) { "ZZZZZ".forEach { lose.type(it) }; lose.enter() }
assertTrue(lose.lost)
}
@Test fun theKeyboardFitsTheTeletextPageAndTheCursorStaysOnIt() {
val starts = intArrayOf(0, 2, 1)
CodeKeys.forEachIndexed { r, keys -> assertTrue("row $r", starts[r] + keys.sumOf { it.length + 3 } - 1 <= 40) }
assertEquals(0 to 9, codeCursor(0, 9, 1, 0)); assertEquals(1 to 8, codeCursor(0, 9, 0, 1)); assertEquals(2 to 8, codeCursor(2, 8, 5, 5))
// Building the page and the wizard's page doesn't trip on anything.
val page = TeletextPage()
val g = CodebreakerGame("ORBIT"); "TRAIN".forEach { g.type(it) }
buildCodePage(page, g, java.time.LocalDate.of(2026, 11, 9), daily = true, row = 2, col = 8)
assertTrue(page.rowText(0).contains("ORBI-FAX")); assertTrue(page.rowText(5).contains("T")); assertTrue(page.rowText(22).contains("TRY"))
buildWizardPage(page, won = true); assertTrue(page.rowText(5).contains("CLEVER"))
}
}