Orbi-Raiders Story mode prototype (0.110.11-story, versionCode 294)

Story (20 waves, four bosses, a checkpoint after each, per profile and
difficulty) or Endless on the title; Endless brings back the bosses met in
Story. New bosses: the Rogue Satellite Array, the Corrupt Pixel Queen (who
splits) and the wizard of page 999 from Orbi-Fax (his art exactly, through
Orbi-Fax's own renderer) with five telegraphed phases. Orbi-Fax pages: Paul's
teaser after the Dead Channel and page 999 before the last wave; Reduce
motion shows them whole. The wizard dusts himself off at the end. Finishing
Story saves storyComplete with its date in one write, read by
tv.orbit.classic.ArcadeProgress.isStoryComplete (replaces the Orbi-Fax
branch's stub).

18 new tests incl. a bot through Story on each difficulty and 0 bytes
allocated over 10,000 ticks. Docs: docs/orbi-raiders-story.md and its
VERIFICATION. Testing only: not installed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-08 23:21:06 +00:00
co-authored by Claude Opus 5.5
parent 2fd550f81e
commit 2d5dc54cef
17 changed files with 1143 additions and 59 deletions
+2 -2
View File
@@ -9,8 +9,8 @@ android {
applicationId = "tv.orbit.classic"
minSdk = 26
targetSdk = 36
versionCode = 293
versionName = "0.110.10-household"
versionCode = 294
versionName = "0.110.11-story"
}
buildFeatures { compose = true }
// The finished build for the TVs (Paul, 6 November 2026: the test build stuttered on the box). Not debuggable, so
@@ -0,0 +1,40 @@
package tv.orbit.classic
import android.content.Context
import tv.orbit.classic.arcade.ArcadeGames
import tv.orbit.classic.arcade.ArcadeProfileData
import tv.orbit.classic.arcade.ArcadeRepo
import tv.orbit.classic.arcade.Difficulty
/**
* The Arcade's progress API (replaces the Orbi-Fax branch's stub of the same name and place). What other parts of Orbit may read about a profile's Arcade progress (8 November 2026, agreed with the Orbi-Fax work).
* Read only: nothing outside the Arcade writes Arcade data. Local to this TV; nothing here is shared between rooms.
*
* - [isStoryComplete]: the profile has beaten the final boss of Orbi-Raiders' Story. Saved in that profile's Arcade file,
* game "OrbiRaiders", level progress "storyComplete" = "true" with "storyCompleteAt" (epoch ms), written together in one
* save. "Reset level progress" for Orbi-Raiders clears it; "Clear high scores" doesn't.
*/
// Holds only the application context, which lives as long as the app.
@android.annotation.SuppressLint("StaticFieldLeak")
internal object ArcadeProgress {
const val STORY_COMPLETE = "storyComplete"
const val STORY_COMPLETE_AT = "storyCompleteAt"
@Volatile private var app: Context? = null
fun init(context: Context) { app = context.applicationContext }
/** True when [profileId] has finished Orbi-Raiders' Story on this TV. False when unknown or before Orbit is ready. */
fun isStoryComplete(profileId: String): Boolean {
val context = app ?: return false
return runCatching { storyComplete(ArcadeRepo.get(context).store.load(profileId)) }.getOrDefault(false)
}
fun storyComplete(data: ArcadeProfileData): Boolean = data.game(ArcadeGames.OrbiRaiders.id).level[STORY_COMPLETE] == "true"
/** The values saved, in one write, when a profile finishes Story. */
fun storyCompleteValues(nowMs: Long, difficulty: Difficulty): Map<String, String> = mapOf(
STORY_COMPLETE to "true", STORY_COMPLETE_AT to nowMs.toString(),
tv.orbit.classic.arcade.raiders.StorySave.doneKey(difficulty) to "1",
// The next Story run on this difficulty starts from the beginning again.
tv.orbit.classic.arcade.raiders.StorySave.checkpointKey(difficulty) to "1")
}
@@ -77,6 +77,7 @@ class MainActivity : ComponentActivity() {
InstallSnapshot.screenOpen = true
OrbitCompanion.activity = java.lang.ref.WeakReference(this)
super.onCreate(savedInstanceState)
tv.orbit.classic.ArcadeProgress.init(this)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
Motion.load(OrbitSettings(this))
// The guide's logos, decoded ahead on a background thread so the guide opens with them ready.
@@ -135,6 +135,7 @@ internal fun OrbitArcade(modifier: Modifier, onPlaying: (Boolean) -> Unit, onExi
readSetting = { key -> game.settings.firstOrNull { it.key == key }?.let { settingFor(latestData.game(game.id), it, repo::legacyFlag) } ?: true },
writeSetting = { key, on -> update { d -> d.withGame(game.id) { it.copy(settings = it.settings + (key to on)) } } },
writeLevel = { key, value -> update { d -> d.withGame(game.id) { it.copy(level = it.level + (key to value)) } } },
writeLevels = { values -> update { d -> d.withGame(game.id) { it.copy(level = it.level + values) } } },
onRunEnd = { end -> update { recordRun(it, game.id, game.scoreKind, end, System.currentTimeMillis()) } },
onRunEndIn = { table, end -> if (table in scoreTables(game.id)) update { recordRun(it, table, game.scoreKind, end, System.currentTimeMillis()) } },
onLeave = { session = SessionState.Exited; playing = null },
@@ -32,12 +32,15 @@ internal class ArcadePlay(
/** What the game keeps through a level reset ([GameRecord.kept]), and where it writes it. */
val kept: Map<String, String> = emptyMap(),
private val writeKept: (Map<String, String>) -> Unit = {},
/** Writes several level-progress values in one save, so they land together or not at all. */
private val writeLevels: (Map<String, String>) -> Unit = { m -> m.forEach { (k, v) -> writeLevel(k, v) } },
/** Saves a run into another of the game's High Scores tables ([scoreTables]): BumbleHive Hard's. */
val onRunEndIn: (String, RunEnd) -> Unit = { _, end -> onRunEnd(end) },
) {
fun setting(key: String) = readSetting(key)
fun setSetting(key: String, on: Boolean) = writeSetting(key, on)
fun setLevel(key: String, value: String) = writeLevel(key, value)
fun setLevels(values: Map<String, String>) = writeLevels(values)
/** Merges these into the kept values. */
fun setKept(values: Map<String, String>) = writeKept(values)
}
@@ -27,7 +27,7 @@ internal class ArcadeRepo private constructor(context: Context) {
// Holds only the application context, which lives as long as the app.
@android.annotation.SuppressLint("StaticFieldLeak")
@Volatile private var made: ArcadeRepo? = null
fun get(context: Context): ArcadeRepo = made ?: synchronized(this) { made ?: ArcadeRepo(context).also { made = it } }
fun get(context: Context): ArcadeRepo = made ?: synchronized(this) { made ?: ArcadeRepo(context).also { made = it; tv.orbit.classic.ArcadeProgress.init(context) } }
}
}
@@ -70,6 +70,9 @@ private class Hud {
var power by mutableStateOf<Power?>(null)
var powerSecs by mutableIntStateOf(0)
var boss by mutableStateOf(false)
var bossName by mutableStateOf(Boss.DeadChannel.upper)
/** The wizard's last words: letters showing, or -1 when he isn't speaking. */
var ending by mutableIntStateOf(-1)
var bossPct by mutableIntStateOf(100)
/** Positive: "WAVE n" as a wave comes in; negative: "WAVE n CLEARED"; 0: nothing. */
var banner by mutableIntStateOf(0)
@@ -78,7 +81,9 @@ private class Hud {
frame++
score = sim.score; multiplier = sim.multiplier; wave = sim.wave; bars = sim.bars; maxBars = sim.maxBars
meterPct = (sim.meter * 100).toInt(); power = sim.power; powerSecs = kotlin.math.ceil(sim.powerLeft).toInt()
boss = sim.bossOn; bossPct = if (sim.bossMax > 0) (sim.bossHp * 100 / sim.bossMax) else 0
boss = sim.bossOn; bossName = sim.boss.upper
ending = if (sim.phase == Phase.Ending || sim.phase == Phase.Complete) sim.endingShown() else -1
bossPct = if (sim.bossMax > 0) (sim.bossHp * 100 / sim.bossMax) else 0
banner = when { sim.phase == Phase.Cleared -> -sim.wave; sim.formY < -10f && !sim.bossOn -> sim.wave; else -> 0 }
}
}
@@ -112,12 +117,16 @@ internal fun OrbiRaidersScreen(play: ArcadePlay) {
// The best including runs saved a moment ago, before the Arcade's own copy has caught up (Retry straight after a record).
var bestSeen by remember { mutableIntStateOf(play.best) }
var howTo by remember { mutableStateOf(false) }
// Story or Endless, remembered per profile. Neither ever resets the other: Story keeps its checkpoints, Endless its best wave.
var mode by remember { mutableStateOf(play.level["mode"]?.let { m -> RaidersMode.entries.firstOrNull { it.name == m } } ?: RaidersMode.Endless) }
val book = remember {
RaidersRunBook({ end -> bestSeen = maxOf(bestSeen, end.score); latestPlay.onRunEnd(end) }, { wave -> latestPlay.setLevel("bestWave", wave.toString()) }, play.level["bestWave"]?.toIntOrNull() ?: 0)
RaidersRunBook({ end -> bestSeen = maxOf(bestSeen, end.score); latestPlay.onRunEnd(end) },
{ wave -> if (sim.mode == RaidersMode.Endless) latestPlay.setLevel("bestWave", wave.toString()) }, play.level["bestWave"]?.toIntOrNull() ?: 0)
}
val density = LocalDensity.current
val measurer = rememberTextMeasurer()
val art = remember(density) { RaidersArt(density, measurer) }
val story = remember(density) { StoryArt(density, measurer) }
LaunchedEffect(Unit) { play.audio.preload(R.raw.power_drift_net, R.raw.power_wide_orbit, R.raw.power_blaze_run, R.raw.power_double_luna, R.raw.power_zip_split) }
// However the screen goes away mid-run (sleep timer, profile switch, Orbit closing), the run is saved.
DisposableEffect(Unit) { onDispose { book.end(sim, finished = false) } }
@@ -126,7 +135,9 @@ internal fun OrbiRaidersScreen(play: ArcadePlay) {
val p = latestPlay
bestBefore = maxOf(p.best, bestSeen)
sim.bursts = !Motion.reduce
sim.newRun(pilot, p.difficulty, seed = (System.nanoTime() and 0x7fffffff).toInt().coerceAtLeast(1))
sim.calm = Motion.reduce
sim.newRun(pilot, p.difficulty, seed = (System.nanoTime() and 0x7fffffff).toInt().coerceAtLeast(1), mode = mode,
startAt = if (mode == RaidersMode.Story) StorySave.startWave(p.level, p.difficulty) else 1, metMask = StorySave.metMask(p.level))
controls.autoFire = p.autoFire
controls.release(); stepper.reset(); hud.read(sim)
book.begin()
@@ -147,10 +158,18 @@ internal fun OrbiRaidersScreen(play: ArcadePlay) {
if (ev and Events.POWER != 0) audio.cue(R.raw.power_drift_net, .6f, soundsOn)
if (ev and Events.OVERDRIVE != 0) audio.cue(overdriveSound(sim.pilot), .7f, soundsOn)
if (ev and Events.BOSS_DOWN != 0) audio.cue(R.raw.power_wide_orbit, .7f, soundsOn)
// Story: who's been met (Endless brings them back), and finishing it, saved to this profile at once.
if (ev and Events.BOSS_MET != 0) latestPlay.setLevel(StorySave.MET, sim.metMask.toString())
if (ev and Events.STORY_DONE != 0) latestPlay.setLevels(tv.orbit.classic.ArcadeProgress.storyCompleteValues(System.currentTimeMillis(), sim.difficulty))
}
hud.read(sim)
if (sim.over) { book.end(sim, finished = true); stage = Stage.Result }
else if (sim.phase == Phase.Checkpoint) stage = Stage.Result
else if (sim.phase == Phase.Complete) { book.end(sim, finished = true); stage = Stage.Result }
else if (sim.phase == Phase.Checkpoint) {
// A boss beaten in Story: the checkpoint is saved for this profile and difficulty.
if (sim.mode == RaidersMode.Story) StoryPlan.checkpointAfter(sim.wave)?.let { latestPlay.setLevel(StorySave.checkpointKey(sim.difficulty), it.toString()) }
stage = Stage.Result
}
}
val playFocus = remember { FocusRequester() }
@@ -159,7 +178,10 @@ internal fun OrbiRaidersScreen(play: ArcadePlay) {
when (stage) {
Stage.Title -> {
val storyLine = if (StorySave.done(play.level, play.difficulty) && StorySave.startWave(play.level, play.difficulty) == 1) "Complete ★"
else StorySave.startWave(play.level, play.difficulty).let { if (it == 1) "From wave 1" else "From wave $it" }
TitleScreen(pilot, play.best, book.bestWave, play.difficulty.title, refocus = !howTo, onPilot = { pilot = it; latestPlay.setLevel("pilot", it.name) },
mode = mode, storyLine = storyLine, onMode = { mode = if (mode == RaidersMode.Story) RaidersMode.Endless else RaidersMode.Story; latestPlay.setLevel("mode", mode.name) },
onPlay = ::startRun, onHowTo = { howTo = true }, onBack = { latestPlay.onLeave() })
if (howTo) HowToPlayCard(game, firstRun = false, everyTime = null, onEveryTime = {}, onPlay = { howTo = false }, onBack = { howTo = false })
}
@@ -175,9 +197,14 @@ internal fun OrbiRaidersScreen(play: ArcadePlay) {
val key = arcadeKey(n.keyCode)
val down = n.action == KeyEvent.ACTION_DOWN
if (pausesGame(key) && key != tv.orbit.classic.arcade.ArcadeKey.Back) { if (down) pause(); return@onPreviewKeyEvent true }
// Story's pages and the wizard's last words: OK goes on.
if (key == tv.orbit.classic.arcade.ArcadeKey.Ok && (sim.phase == Phase.Fax || sim.phase == Phase.Ending)) {
if (down && n.repeatCount == 0) { if (sim.phase == Phase.Fax) sim.skipFax() else sim.skipEnding() }
return@onPreviewKeyEvent true
}
controls.key(key, down, n.repeatCount)
}) {
PlayScreen(art, sim, hud, calm, play.reduceFlashing)
PlayScreen(art, story, sim, hud, calm, play.reduceFlashing)
if (stage == Stage.Result) ResultCard(sim, bestBefore,
onNext = { sim.continueRun(); controls.release(); stepper.reset(); hud.read(sim); stage = Stage.Play },
onRetry = { book.end(sim, finished = sim.over); startRun() },
@@ -193,7 +220,8 @@ internal fun OrbiRaidersScreen(play: ArcadePlay) {
// ---------- Title (frame 10) ----------
@Composable
private fun TitleScreen(chosen: Pilot, best: Int, bestWave: Int, difficulty: String, refocus: Boolean, onPilot: (Pilot) -> Unit, onPlay: () -> Unit, onHowTo: () -> Unit, onBack: () -> Unit) {
private fun TitleScreen(chosen: Pilot, best: Int, bestWave: Int, difficulty: String, refocus: Boolean, onPilot: (Pilot) -> Unit,
mode: RaidersMode, storyLine: String, onMode: () -> Unit, onPlay: () -> Unit, onHowTo: () -> Unit, onBack: () -> Unit) {
val cards = remember { Pilot.entries.associateWith { FocusRequester() } }
val playButton = remember { FocusRequester() }
// On opening, and again when How to Play closes.
@@ -239,6 +267,9 @@ private fun TitleScreen(chosen: Pilot, best: Int, bestWave: Int, difficulty: Str
}
Column(Modifier.width(190.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
ArcadeButton("Play", Modifier.fillMaxWidth().focusRequester(playButton), icon = "▶", primary = true, height = 34.dp, onClick = onPlay)
// Story (20 waves, four bosses, a checkpoint after each) or Endless.
ArcadeButton(mode.title, Modifier.fillMaxWidth(), icon = if (mode == RaidersMode.Story) "📖" else "∞", height = 34.dp,
detail = if (mode == RaidersMode.Story) storyLine else "Every 5th wave a boss", onClick = onMode)
ArcadeButton("How to Play", Modifier.fillMaxWidth(), icon = "?", height = 34.dp, onClick = onHowTo)
ArcadeButton("Back to Arcade", Modifier.fillMaxWidth(), icon = "←", height = 34.dp, onClick = onBack)
}
@@ -313,7 +344,7 @@ private fun StarField() = Canvas(Modifier.fillMaxSize()) {
// ---------- Play (frames 11 and 12) ----------
@Composable
private fun PlayScreen(art: RaidersArt, sim: RaidersSim, hud: Hud, calm: Boolean, reduceFlashing: Boolean) {
private fun PlayScreen(art: RaidersArt, story: StoryArt, sim: RaidersSim, hud: Hud, calm: Boolean, reduceFlashing: Boolean) {
Box(Modifier.fillMaxSize().background(ArcadeColours.Night)) {
Column(Modifier.fillMaxSize().padding(start = 24.dp, end = 24.dp, top = 14.dp, bottom = 10.dp)) {
Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(14.dp)) {
@@ -322,7 +353,7 @@ private fun PlayScreen(art: RaidersArt, sim: RaidersSim, hud: Hud, calm: Boolean
val start = remember { System.nanoTime() }
Canvas(Modifier.fillMaxSize()) {
hud.frame // redraw every frame, without recomposing
drawRaidersField(art, sim, (System.nanoTime() - start) / 1e9f, calm, reduceFlashing)
drawRaidersField(art, story, sim, (System.nanoTime() - start) / 1e9f, calm, reduceFlashing)
}
FieldWords(hud, Modifier.fillMaxSize())
}
@@ -363,10 +394,14 @@ private fun LeftHud(hud: Hud, modifier: Modifier) {
private fun FieldWords(hud: Hud, modifier: Modifier) {
Box(modifier) {
if (hud.boss) Row(Modifier.align(Alignment.TopCenter).padding(top = 2.dp).fillMaxWidth(.62f)) {
Text("THE DEAD CHANNEL", color = ArcadeColours.Ink, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 3.sp)
Text(hud.bossName, color = ArcadeColours.Ink, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 3.sp)
Spacer(Modifier.weight(1f))
Text("${hud.bossPct}%", color = ArcadeColours.Muted, fontSize = 12.sp)
}
// The wizard's last words, typing out (all at once under Reduce motion).
if (hud.ending >= 0) Text(StoryPlan.ENDING.take(hud.ending), Modifier.align(Alignment.BottomCenter).padding(bottom = 46.dp).fillMaxWidth(.8f)
.background(ArcadeColours.Night.copy(alpha = .85f), RoundedCornerShape(10.dp)).border(1.dp, ArcadeColours.Cyan, RoundedCornerShape(10.dp)).padding(10.dp),
color = ArcadeColours.Ink, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, textAlign = TextAlign.Center)
val b = hud.banner
if (b != 0) Text(if (b > 0) "WAVE $b" else "WAVE ${-b} CLEARED", Modifier.align(Alignment.Center),
color = ArcadeColours.Yellow, fontFamily = Anton, fontSize = 34.sp)
@@ -431,6 +466,8 @@ private fun ResultCard(sim: RaidersSim, bestBefore: Int, onNext: () -> Unit, onR
LaunchedEffect(Unit) { runCatching { first.requestFocus() } }
BackHandler(onBack = onBack)
val cleared = !sim.over
val complete = sim.phase == Phase.Complete
val story = sim.mode == RaidersMode.Story
val newRecord = sim.score > bestBefore && sim.score > 0
val calm = Motion.reduce
Box(Modifier.fillMaxSize().onBackKey(action = onBack).background(ArcadeColours.Night.copy(alpha = .82f)), contentAlignment = Alignment.Center) {
@@ -438,16 +475,28 @@ private fun ResultCard(sim: RaidersSim, bestBefore: Int, onNext: () -> Unit, onR
if (newRecord) Cheer(OrbCharacter.Blaze, calm, 0f)
Column(Modifier.width(520.dp).background(ArcadeColours.PanelDeep, RoundedCornerShape(14.dp)).border(1.dp, ArcadeColours.Line, RoundedCornerShape(14.dp)).padding(20.dp),
horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(if (cleared) "ORBI-RAIDERS · WAVE ${sim.wave} CLEARED" else "ORBI-RAIDERS · SIGNAL LOST ON WAVE ${sim.wave}", color = ArcadeColours.Muted, fontSize = 13.sp, letterSpacing = 3.sp)
Text(when {
complete -> "ORBI-RAIDERS · STORY COMPLETE"
story && cleared -> "STORY · CHAPTER ${StoryPlan.chapterOf(sim.wave)} CLEARED · CHECKPOINT SAVED"
cleared -> "ORBI-RAIDERS · WAVE ${sim.wave} CLEARED"
else -> "ORBI-RAIDERS · SIGNAL LOST ON WAVE ${sim.wave}"
}, color = ArcadeColours.Muted, fontSize = 13.sp, letterSpacing = 3.sp)
if (complete) Text("The Orbit network is safe. For now.", color = ArcadeColours.Cyan, fontSize = 15.sp, fontWeight = FontWeight.SemiBold)
if (newRecord) Text("NEW RECORD", Modifier.background(ArcadeColours.Pink, RoundedCornerShape(14.dp)).padding(horizontal = 14.dp, vertical = 2.dp), color = ArcadeColours.Ink, fontSize = 16.sp, fontWeight = FontWeight.Bold)
Text("SCORE", color = ArcadeColours.Muted, fontSize = 13.sp, letterSpacing = 2.sp)
Text("%,d".format(sim.score), color = ArcadeColours.Ink, fontFamily = Anton, fontSize = 54.sp)
Text(if (bestBefore > 0) "Previous best ${"%,d".format(bestBefore)}" else "Your first Orbi-Raiders score", color = ArcadeColours.Ink, fontSize = 14.sp)
Text(if (cleared) "Next Wave carries this score on. It's saved when the run ends." else "Saved to your high scores. Household Records update on their own.", color = ArcadeColours.Muted, fontSize = 13.sp)
Text(when {
complete -> "Saved to your high scores. Endless now brings back every boss you've met."
story && cleared -> "Next Wave goes on. If the signal's lost, Story starts again from here."
cleared -> "Next Wave carries this score on. It's saved when the run ends."
story -> "Saved to your high scores. Play goes on from your last checkpoint."
else -> "Saved to your high scores. Household Records update on their own."
}, color = ArcadeColours.Muted, fontSize = 13.sp)
Spacer(Modifier.height(6.dp))
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
if (cleared) ArcadeButton("Next Wave", Modifier.width(150.dp).focusRequester(first), icon = "▶", primary = true, height = 34.dp, onClick = onNext)
ArcadeButton("Retry", Modifier.width(150.dp).then(if (!cleared) Modifier.focusRequester(first) else Modifier), icon = "↻", height = 34.dp, onClick = onRetry)
if (cleared && !complete) ArcadeButton("Next Wave", Modifier.width(150.dp).focusRequester(first), icon = "▶", primary = true, height = 34.dp, onClick = onNext)
ArcadeButton(if (complete) "Play again" else "Retry", Modifier.width(150.dp).then(if (!cleared || complete) Modifier.focusRequester(first) else Modifier), icon = "↻", height = 34.dp, onClick = onRetry)
ArcadeButton("Back to Arcade", Modifier.width(160.dp), icon = "←", height = 34.dp, onClick = onBack)
}
}
@@ -281,7 +281,7 @@ internal class RaidersArt(density: Density, measurer: TextMeasurer) {
}
/** The whole field for one frame, in the world's units, scaled to fit [size]. */
internal fun DrawScope.drawRaidersField(art: RaidersArt, sim: RaidersSim, time: Float, calm: Boolean, reduceFlashing: Boolean) = with(art) {
internal fun DrawScope.drawRaidersField(art: RaidersArt, story: StoryArt, sim: RaidersSim, time: Float, calm: Boolean, reduceFlashing: Boolean) = with(art) {
val k = minOf(size.width / FIELD_W, size.height / FIELD_H)
val ox = (size.width - FIELD_W * k) / 2
val oy = (size.height - FIELD_H * k) / 2
@@ -292,11 +292,26 @@ internal fun DrawScope.drawRaidersField(art: RaidersArt, sim: RaidersSim, time:
scale(k, k, Offset.Zero) {
// Double Luna's slow time: a steady soft purple over the field.
if (sim.slow < 1f) drawRect(Color(0xFFA77BFF), Offset.Zero, Size(FIELD_W, FIELD_H), alpha = .1f)
// Story: an Orbi-Fax page takes the whole field.
if (sim.phase == Phase.Fax) { with(story) { faxPage(sim) }; return@scale }
val wizardOn = sim.bossOn && sim.boss == Boss.Wizard
if (wizardOn && sim.wizardPhase == WizardPhase.Overload) with(story) { overloadCard(time, still = reduceFlashing || calm) }
signal(sim.bars, sim.maxBars)
if (sim.phase == Phase.Ending || sim.phase == Phase.Complete) with(story) { wizard(sim.bossX, sim.bossY + 20f, 116f, 1f, tinted = false) }
if (sim.bossOn) {
if (sim.bossAttack == 1 && sim.bossWarn > 0f) beam(sim.beamX, warn = true, on = false)
if (sim.beamOn > 0f) beam(sim.beamX, warn = false, on = true)
boss(sim.bossX, sim.bossY, sim.bossAttack, sim.bossWarn, sim.bossTint > 0f, time, calm)
val warnBeam = sim.bossAttack == 1 && sim.bossWarn > 0f && sim.boss != Boss.Wizard
if (warnBeam) beam(sim.beamX, warn = true, on = false)
if (warnBeam && sim.boss == Boss.SatelliteArray) beam(sim.beam2X, warn = true, on = false)
if (sim.beamOn > 0f) { beam(sim.beamX, warn = false, on = true); if (sim.boss == Boss.SatelliteArray) beam(sim.beam2X, warn = false, on = true) }
when (sim.boss) {
Boss.DeadChannel -> boss(sim.bossX, sim.bossY, sim.bossAttack, sim.bossWarn, sim.bossTint > 0f, time, calm)
Boss.SatelliteArray -> with(story) { satelliteArray(sim.bossX, sim.bossY, sim.bossWarn, sim.bossTint > 0f) }
Boss.PixelQueen -> with(story) { pixelQueen(sim.bossX, sim.bossY, sim.bossHp / sim.bossMax.toFloat(), sim.bossWarn, sim.bossTint > 0f) }
Boss.Wizard -> with(story) {
wizard(sim.bossX, sim.bossY + 10f, 116f, if (calm) 1f else 1f - sim.bossEnter / 1.6f, sim.bossTint > 0f)
wizardWarnings(sim, time, calm)
}
}
// The boss's health, as frame 12's bar.
val frac = sim.bossHp / sim.bossMax.toFloat()
drawRoundRect(Color(0xFF1C2E66), Offset(80f, 6f), Size(FIELD_W - 160f, 5f), CornerRadius(2.5f))
@@ -306,7 +321,7 @@ internal fun DrawScope.drawRaidersField(art: RaidersArt, sim: RaidersSim, time:
for (d in sim.drops) if (d.active) badge(d.power, d.x, d.y, 7f)
val shotColour = RaidersColours.pilot(sim.pilot)
for (s in sim.shots) if (s.active) shot(s, shotColour)
for (s in sim.enemyShots) if (s.active) enemyShot(s)
for (s in sim.enemyShots) if (s.active) { if (s.style == 0) enemyShot(s) else with(story) { fastextShape(s.style, Offset(s.x, s.y)) } }
for (s in sim.sparks) if (s.active) spark(s)
if (sim.ringR > 0f) ringSweep(sim.shipX, SHIP_Y, sim.ringR)
if (!sim.over) {
@@ -46,7 +46,8 @@ internal class RaidersControls(var autoFire: Boolean = false) {
}
/** What a run reports when it ends. */
internal fun raidersRunEnd(sim: RaidersSim, finished: Boolean) = RunEnd(sim.score, finished, "Wave ${sim.wave} · ${sim.pilot.title}")
internal fun raidersRunEnd(sim: RaidersSim, finished: Boolean) =
RunEnd(sim.score, finished, (if (sim.mode == RaidersMode.Story) "Story · " else "") + "Wave ${sim.wave} · ${sim.pilot.title}")
/**
* Saves every run once, however it ends: the signal lost, Retry, Back to Arcade, Exit from the pause menu, or the screen
@@ -89,6 +89,8 @@ internal class Shot {
var pierce = 0
/** The enemy (pool index) this shot last went through, so a piercing shot can't hit it twice. */
var last = -1
/** How an invader's shot looks (the wizard's): 0 plain, 1-4 the Fastext red, green, yellow and cyan, 5 static. */
var style = 0
}
internal class Drop {
@@ -192,10 +194,36 @@ internal object Events {
const val BOSS_DOWN = 64
const val GAME_OVER = 128
const val SHOT = 256
/** A boss met for the first time in this run (Story remembers who Endless may bring back). */
const val BOSS_MET = 512
/** Story finished: the wizard has said his piece. */
const val STORY_DONE = 1024
}
/** Where a wave stands. */
internal enum class Phase { Playing, Cleared, Checkpoint, Over }
/**
* Where a wave stands. [Fax] is an Orbi-Fax page over the field (Story: the teaser after the Dead Channel, and the wizard's
* page before the last wave); [Ending] is the wizard dusting himself off; [Complete] is Story finished.
*/
internal enum class Phase { Playing, Cleared, Checkpoint, Over, Fax, Ending, Complete }
/** Which Orbi-Fax page is showing in [Phase.Fax]. */
internal object FaxPage {
const val NONE = 0
/** After the Dead Channel in Story, a couple of seconds, no explanation (Paul's words). */
const val TEASER = 1
/** Before the wizard's wave. */
const val WIZARD = 2
val TEASER_LINES = arrayOf("ORBI-FAX", "P999", "", "SIGNAL RESTORED", "TRANSMISSION INTERRUPTED", "", "DO NOT PROCEED TO PAGE 999", "", "RETURN TO INDEX ........ 100")
val TEASER_CHARS = TEASER_LINES.sumOf { it.length }
/** Letters a second as a page types out (the teaser is quicker: it's a glimpse). */
const val TYPE_RATE = 18f
const val TEASER_RATE = 80f
const val TEASER_HOLD = 1.2f
const val WIZARD_HOLD = 2.5f
const val ENDING_HOLD = 3f
}
internal class RaidersSim(var pilot: Pilot = Pilot.Ollie, difficulty: Difficulty = Difficulty.Normal, var seed: Int = 1,
/** Reduce motion: no bursts of sparks. The rules are otherwise the same. */
@@ -261,7 +289,40 @@ internal class RaidersSim(var pilot: Pilot = Pilot.Ollie, difficulty: Difficulty
var bossHp = 0; private set
var bossMax = 1; private set
var bossX = FIELD_W / 2; private set
val bossY = 80f
var bossY = 80f; private set
/** Which boss this is. */
var boss = Boss.DeadChannel; private set
var bossHalfW = 56f; private set
var bossHalfH = 44f; private set
/** The wizard stepping out of the page: seconds left (he can't attack or be hit until he's out). */
var bossEnter = 0f; private set
var wizardPhase = WizardPhase.PageFlip; private set
/** Telegraphs: where the wizard will flip to, the gap in his static storm, where Return to Index will pull the ship. */
var flipToX = 0f; private set
var gapX = 0f; private set
var indexX = 0f; private set
/** The Satellite Array's second beam. */
var beam2X = 0f; private set
/** The Pixel Queen's swoop, seconds left, and how far down she is. */
var swoop = 0f; private set
private var swoopFromX = 0f
private var splitsLeft = 2
/** In Overload, which of his other attacks comes next. */
private var subAttack = 0
private var indexVolleyIn = 0f
private val shipTrail = FloatArray(120)
private var trailAt = 0
// ---------- Story ----------
var mode = RaidersMode.Endless; private set
/** Bosses met in Story (bits by [Boss]), so Endless can bring them back. */
var metMask = 0; private set
var fax = FaxPage.NONE; private set
var faxT = 0f; private set
var endingT = 0f; private set
private var wizardPageSeen = false
/** Reduce motion: the Orbi-Fax pages and the wizard's words appear at once instead of typing out. */
var calm = false
private var bossVx = 26f
/** 0 static rain, 1 the test-card beam, 2 two little sprites. */
var bossAttack = 0; private set
@@ -284,7 +345,7 @@ internal class RaidersSim(var pilot: Pilot = Pilot.Ollie, difficulty: Difficulty
val over get() = phase == Phase.Over
/** The slow-time factor while Double Luna is on: everything but the ship runs at this speed. */
val slow get() = if (odLeft > 0f && pilot.overdrive == Overdrive.DoubleLuna) .6f else 1f
val bossWave get() = wave % 5 == 0
val bossWave get() = if (mode == RaidersMode.Story) StoryPlan.bossAt(wave) != null else wave % 5 == 0
/** How fast the formation is sliding sideways now (units a second, + is right). */
val formVx get() = if (entering || bossOn) 0f else formDir * tuning.sway * (1f + (wave - 1) * .05f)
@@ -292,13 +353,15 @@ internal class RaidersSim(var pilot: Pilot = Pilot.Ollie, difficulty: Difficulty
// ---------- runs and waves ----------
fun newRun(pilot: Pilot = this.pilot, difficulty: Difficulty = this.difficulty, seed: Int = this.seed) {
fun newRun(pilot: Pilot = this.pilot, difficulty: Difficulty = this.difficulty, seed: Int = this.seed,
mode: RaidersMode = this.mode, startAt: Int = 1, metMask: Int = this.metMask) {
this.pilot = pilot; this.difficulty = difficulty; this.tuning = Tuning.of(difficulty); this.seed = seed
this.mode = mode; this.metMask = metMask; wizardPageSeen = false; fax = FaxPage.NONE; faxT = 0f; endingT = 0f
score = 0; streak = 0; meter = 0f; wave = 1
maxBars = pilot.bars; bars = maxBars
lunaShield = pilot.shieldEvery > 0f; lunaIn = pilot.shieldEvery
clock = 0f; damage = 0; ticks = 0
startWave(1)
startWave(if (mode == RaidersMode.Story && startAt in StoryPlan.starts) startAt else 1)
}
private fun clearAll() {
@@ -320,7 +383,15 @@ internal class RaidersSim(var pilot: Pilot = Pilot.Ollie, difficulty: Difficulty
// Each wave's own seed: the same run seed and wave always build the same wave.
rng.reseed(seed * 31 + n * 7919)
enemyFireIn = 1.6f; diveIn = 3f / tuning.dives
if (bossWave) startBoss() else layoutWave(n)
if (!bossWave) { layoutWave(n); return }
boss = if (mode == RaidersMode.Story) StoryPlan.bossAt(n)!! else endlessBoss(n, metMask)
// Story: Orbi-Fax cuts in before the wizard's wave, once a run (Restart Level doesn't show it again).
if (mode == RaidersMode.Story && boss == Boss.Wizard && !wizardPageSeen) {
wizardPageSeen = true; entering = false; formY = 0f
phase = Phase.Fax; fax = FaxPage.WIZARD; faxT = 0f
return
}
startBoss()
}
/** Restart Level from the pause menu: this wave again, from how things stood when it began. */
@@ -361,18 +432,62 @@ internal class RaidersSim(var pilot: Pilot = Pilot.Ollie, difficulty: Difficulty
}
private fun startBoss() {
bossOn = true; bossMax = tuning.bossHp + (wave / 5 - 1) * 20; bossHp = bossMax
bossX = FIELD_W / 2; bossVx = 26f; bossAttack = 0; bossWarn = 0f; bossNext = 2.2f; beamOn = 0f; bossTint = 0f
// Story's bosses get tougher in turn; in Endless each fifth wave adds 20, as before. The wizard has half again.
val tier = if (mode == RaidersMode.Story) StoryPlan.BOSSES.indexOfFirst { it.second == boss }.coerceAtLeast(0) else wave / 5 - 1
bossMax = tuning.bossHp + tier * 20 + (if (boss == Boss.Wizard) tuning.bossHp / 2 else 0); bossHp = bossMax
bossOn = true; bossX = FIELD_W / 2; bossY = 80f; bossAttack = 0; bossWarn = 0f; beamOn = 0f; bossTint = 0f
bossVx = when (boss) { Boss.DeadChannel -> 26f; Boss.SatelliteArray -> 18f; Boss.PixelQueen -> 34f; Boss.Wizard -> 20f }
bossHalfW = when (boss) { Boss.DeadChannel -> 56f; Boss.SatelliteArray -> 74f; Boss.PixelQueen -> 40f; Boss.Wizard -> 34f }
bossHalfH = when (boss) { Boss.DeadChannel -> 44f; Boss.SatelliteArray -> 30f; Boss.PixelQueen -> 36f; Boss.Wizard -> 50f }
bossEnter = if (boss == Boss.Wizard) 1.6f else 0f
bossNext = 2.2f + bossEnter
splitsLeft = 2; swoop = 0f; subAttack = 0; indexVolleyIn = 0f; wizardPhase = WizardPhase.PageFlip
for (k in shipTrail.indices) shipTrail[k] = shipX
entering = false; formY = 0f
if (mode == RaidersMode.Story && metMask and boss.bit == 0) { metMask = metMask or boss.bit; events = events or Events.BOSS_MET }
}
// ---------- Story's pages ----------
/** How many letters of the Orbi-Fax page are showing (all of them under Reduce motion). */
fun faxShown(): Int = when (fax) {
FaxPage.TEASER -> if (calm) FaxPage.TEASER_CHARS else minOf(FaxPage.TEASER_CHARS, (faxT * FaxPage.TEASER_RATE).toInt())
FaxPage.WIZARD -> if (calm) StoryPlan.CUT_IN_CHARS else minOf(StoryPlan.CUT_IN_CHARS, (faxT * FaxPage.TYPE_RATE).toInt())
else -> 0
}
private fun faxLength(): Float = when (fax) {
FaxPage.TEASER -> (if (calm) 0f else FaxPage.TEASER_CHARS / FaxPage.TEASER_RATE) + FaxPage.TEASER_HOLD + (if (calm) 1.3f else 0f)
else -> (if (calm) 0f else StoryPlan.CUT_IN_CHARS / FaxPage.TYPE_RATE) + FaxPage.WIZARD_HOLD
}
/** OK on an Orbi-Fax page: on to what comes next. */
fun skipFax() { if (phase == Phase.Fax) endFax() }
private fun endFax() {
val page = fax
fax = FaxPage.NONE; faxT = 0f
if (page == FaxPage.TEASER) { phase = Phase.Checkpoint } else { phase = Phase.Playing; startBoss() }
}
/** How many letters of the wizard's last words are showing. */
fun endingShown(): Int = if (calm) StoryPlan.ENDING.length else minOf(StoryPlan.ENDING.length, (endingT * FaxPage.TYPE_RATE).toInt())
fun skipEnding() { if (phase == Phase.Ending) finishStory() }
private fun finishStory() { phase = Phase.Complete; events = events or Events.STORY_DONE }
// ---------- the tick ----------
fun step(input: RaidersInput) {
if (phase == Phase.Over || phase == Phase.Checkpoint) return
if (phase == Phase.Over || phase == Phase.Checkpoint || phase == Phase.Complete) return
ticks++
val dt = STEP
clock += dt
if (phase == Phase.Fax) { faxT += dt; if (faxT >= faxLength()) endFax(); return }
if (phase == Phase.Ending) {
endingT += dt
if (endingT >= (if (calm) 0f else StoryPlan.ENDING.length / FaxPage.TYPE_RATE) + FaxPage.ENDING_HOLD) finishStory()
return
}
if (shake > 0f) shake = maxOf(0f, shake - dt)
if (hitFlash > 0f) hitFlash = maxOf(0f, hitFlash - dt)
moveShip(input, dt)
@@ -393,7 +508,14 @@ internal class RaidersSim(var pilot: Pilot = Pilot.Ollie, difficulty: Difficulty
events = events or Events.WAVE_CLEAR
} else if (phase == Phase.Cleared) {
phaseT += dt
if (phaseT > 1.6f) { if (bossWave) phase = Phase.Checkpoint else startWave(wave + 1) }
if (phaseT > 1.6f) {
when {
!bossWave -> startWave(wave + 1)
// Story: after the Dead Channel, a glimpse of Orbi-Fax. No explanation.
mode == RaidersMode.Story && boss == Boss.DeadChannel -> { phase = Phase.Fax; fax = FaxPage.TEASER; faxT = 0f }
else -> phase = Phase.Checkpoint
}
}
}
}
@@ -415,6 +537,7 @@ internal class RaidersSim(var pilot: Pilot = Pilot.Ollie, difficulty: Difficulty
else -> v + input.move * accel * dt
}.coerceIn(-top, top)
shipX += shipVx * dt
shipTrail[trailAt] = shipX; trailAt = (trailAt + 1) % shipTrail.size
if (shipX < 16f) { shipX = 16f; shipVx = 0f }
if (shipX > FIELD_W - 16f) { shipX = FIELD_W - 16f; shipVx = 0f }
}
@@ -476,6 +599,11 @@ internal class RaidersSim(var pilot: Pilot = Pilot.Ollie, difficulty: Difficulty
}
private fun timers(dt: Float) {
if (indexVolleyIn > 0f) {
indexVolleyIn -= dt
// Return to Index: the ship is back where it was, and a volley comes down there. Dodge again.
if (indexVolleyIn <= 0f) { indexVolleyIn = 0f; for (k in -1..1) enemyShot(indexX + k * 16f, bossY + 40f, 0f, tuning.shotSpeed * 1.1f, 5) }
}
if (safe > 0f) safe = maxOf(0f, safe - dt)
if (power != null) {
powerLeft -= dt
@@ -564,39 +692,105 @@ internal class RaidersSim(var pilot: Pilot = Pilot.Ollie, difficulty: Difficulty
}
private fun moveBoss(dt: Float) {
if (bossEnter > 0f) { bossEnter = maxOf(0f, bossEnter - dt); return }
if (boss == Boss.Wizard) {
val f = bossHp / bossMax.toFloat()
wizardPhase = when { f > .8f -> WizardPhase.PageFlip; f > .6f -> WizardPhase.StaticStorm; f > .4f -> WizardPhase.Fastext; f > .2f -> WizardPhase.ReturnToIndex; else -> WizardPhase.Overload }
}
if (swoop > 0f) {
// The Pixel Queen swoops down the warned column and back up.
swoop = maxOf(0f, swoop - dt)
val p = 1f - swoop / SWOOP_TIME
bossX = swoopFromX + (beamX - swoopFromX) * minOf(1f, p * 3f)
bossY = 80f + sin(p * 3.1416f) * 150f
if (abs(bossX - shipX) < 34f && bossY + bossHalfH > SHIP_Y - 8f) hurt()
if (swoop == 0f) { bossY = 80f; swoopFromX = bossX }
return
}
val edge = if (boss == Boss.SatelliteArray) 100f else 90f
bossX += bossVx * dt
if (bossX < 90f) { bossX = 90f; bossVx = abs(bossVx) }
if (bossX > FIELD_W - 90f) { bossX = FIELD_W - 90f; bossVx = -abs(bossVx) }
if (bossX < edge) { bossX = edge; bossVx = abs(bossVx) }
if (bossX > FIELD_W - edge) { bossX = FIELD_W - edge; bossVx = -abs(bossVx) }
if (beamOn > 0f) {
beamOn = maxOf(0f, beamOn - dt)
if (abs(shipX - beamX) < 13f) hurt()
if (abs(shipX - beamX) < 13f || (boss == Boss.SatelliteArray && abs(shipX - beam2X) < 13f)) hurt()
}
if (bossWarn > 0f) {
bossWarn -= dt
if (bossWarn <= 0f) {
bossWarn = 0f
when (bossAttack) {
0 -> for (k in -2..2) { val a = k * .28f; enemyShot(bossX + k * 10f, bossY + 40f, sin(a) * tuning.shotSpeed, cos(a) * tuning.shotSpeed) }
1 -> beamOn = .7f
else -> {
var minions = 0
for (e in enemies) if (e.active && e.kind == Kind.MINION) minions++
if (minions < 4) { spawn(Kind.MINION, bossX - 80f, bossY, M_FREE)?.let { it.x = it.slotX; it.y = bossY }; spawn(Kind.MINION, bossX + 80f, bossY, M_FREE)?.let { it.x = it.slotX; it.y = bossY } }
}
}
bossAttack = (bossAttack + 1) % 3
bossNext = 2.4f / tuning.fire.coerceAtLeast(.6f)
}
if (bossWarn <= 0f) { bossWarn = 0f; bossFire() }
return
}
bossNext -= dt
if (bossNext <= 0f) {
// Every attack is warned first: the antennas glow, or the beam's column is outlined where the ship is now.
bossWarn = tuning.warn
if (bossAttack == 1) beamX = shipX
if (bossNext <= 0f) bossWarnStart()
}
/** The attack the wizard makes now: his phase's own, or (Overload) each of the others in turn. */
private fun wizardMove(): Int = if (wizardPhase == WizardPhase.Overload) subAttack else wizardPhase.ordinal
/** Every attack is warned first, for [Tuning.warn] seconds (Return to Index longer): what's coming, and where. */
private fun bossWarnStart() {
bossWarn = tuning.warn
when (boss) {
Boss.DeadChannel -> if (bossAttack == 1) beamX = shipX
Boss.SatelliteArray -> if (bossAttack == 1) { beamX = shipX; beam2X = if (shipX < FIELD_W / 2) shipX + 90f else shipX - 90f }
Boss.PixelQueen -> if (bossAttack == 1) { beamX = shipX; swoopFromX = bossX }
Boss.Wizard -> when (wizardMove()) {
0 -> { var x = 70f + rng.nextFloat() * (FIELD_W - 140f); if (abs(x - bossX) < 60f) x = if (bossX < FIELD_W / 2) bossX + 120f else bossX - 120f; flipToX = x }
1 -> gapX = 60f + rng.nextFloat() * (FIELD_W - 120f)
3 -> { indexX = shipTrail[trailAt]; bossWarn = tuning.warn + .5f }
else -> {}
}
}
}
private fun bossFire() {
val speed = tuning.shotSpeed
when (boss) {
Boss.DeadChannel -> when (bossAttack) {
0 -> for (k in -2..2) { val a = k * .28f; enemyShot(bossX + k * 10f, bossY + 40f, sin(a) * speed, cos(a) * speed) }
1 -> beamOn = .7f
else -> spawnPair(Kind.MINION, 80f)
}
Boss.SatelliteArray -> when (bossAttack) {
0 -> aimed(3, .16f, 0)
1 -> beamOn = .8f
else -> spawnPair(Kind.SATELLITE, 70f)
}
Boss.PixelQueen -> when (bossAttack) {
0 -> for (k in -3..3) { val a = k * .22f; enemyShot(bossX + k * 6f, bossY + 30f, sin(a) * speed, cos(a) * speed) }
1 -> swoop = SWOOP_TIME
else -> spawnPair(Kind.PIXEL, 50f)
}
Boss.Wizard -> when (wizardMove()) {
0 -> { bossX = flipToX; aimed(3, .18f, 0) }
1 -> { var x = 12f; while (x < FIELD_W) { if (abs(x - gapX) > 36f) enemyShot(x, bossY + 30f, 0f, speed * .55f, 5); x += 26f } }
2 -> aimed(4, .2f, 1)
else -> { shipX = indexX; shipVx = 0f; safe = maxOf(safe, .4f); indexVolleyIn = .5f }
}
}
bossAttack = (bossAttack + 1) % 3
if (boss == Boss.Wizard) subAttack = (subAttack + 1) % 4
val pace = if (boss == Boss.Wizard && wizardPhase == WizardPhase.Overload) .8f else 1f
bossNext = 2.4f * pace / tuning.fire.coerceAtLeast(.6f)
}
/** [n] shots fanned round the line to the ship; [style] 1 gives each the next Fastext colour. */
private fun aimed(n: Int, spread: Float, style: Int) {
val base = kotlin.math.atan2(shipX - bossX, SHIP_Y - bossY)
for (k in 0 until n) {
val a = base + (k - (n - 1) / 2f) * spread
enemyShot(bossX, bossY + bossHalfH * .6f, sin(a) * tuning.shotSpeed, cos(a) * tuning.shotSpeed, if (style == 0) 0 else style + k)
}
}
private fun spawnPair(kind: Int, apart: Float) {
var n = 0
for (e in enemies) if (e.active && e.mode == M_FREE) n++
if (n >= 4) return
spawn(kind, bossX - apart, bossY, M_FREE)?.let { it.x = it.slotX; it.y = bossY }
spawn(kind, bossX + apart, bossY, M_FREE)?.let { it.x = it.slotX; it.y = bossY }
}
private fun enemyFire(dt: Float) {
if (phase != Phase.Playing) return
enemyFireIn -= dt
@@ -617,8 +811,8 @@ internal class RaidersSim(var pilot: Pilot = Pilot.Ollie, difficulty: Difficulty
}
}
private fun enemyShot(x: Float, y: Float, vx: Float, vy: Float) {
for (s in enemyShots) if (!s.active) { s.active = true; s.x = x; s.y = y; s.vx = vx; s.vy = vy; return }
private fun enemyShot(x: Float, y: Float, vx: Float, vy: Float, style: Int = 0) {
for (s in enemyShots) if (!s.active) { s.active = true; s.x = x; s.y = y; s.vx = vx; s.vy = vy; s.style = style; return }
}
private fun moveShots(dt: Float, edt: Float) {
@@ -626,7 +820,7 @@ internal class RaidersSim(var pilot: Pilot = Pilot.Ollie, difficulty: Difficulty
if (!s.active) continue
s.x += s.vx * dt; s.y += s.vy * dt
if (s.y < -10f || s.x < -10f || s.x > FIELD_W + 10f) { s.active = false; continue }
if (bossOn && abs(s.x - bossX) < 56f + s.halfW && abs(s.y - bossY) < 44f) { s.active = false; hitBoss(1); continue }
if (bossOn && bossEnter <= 0f && abs(s.x - bossX) < bossHalfW + s.halfW && abs(s.y - bossY) < bossHalfH) { s.active = false; hitBoss(1); continue }
for (i in enemies.indices) {
val e = enemies[i]
if (!e.active || i == s.last || !e.hittable()) continue
@@ -695,13 +889,28 @@ internal class RaidersSim(var pilot: Pilot = Pilot.Ollie, difficulty: Difficulty
private fun hitBoss(dmg: Int) {
bossHp -= dmg; bossTint = .12f; damage += dmg
// The Pixel Queen splits off four Corrupt Pixels at two thirds and at one third, and speeds up each time.
if (boss == Boss.PixelQueen && bossHp > 0 && splitsLeft > 0 && bossHp * 3 <= bossMax * splitsLeft) {
splitsLeft--
for (k in 0 until 4) spawn(Kind.PIXEL, (bossX - 45f + k * 30f).coerceIn(12f, FIELD_W - 12f), bossY + 10f, M_FREE)?.let { it.x = it.slotX; it.y = bossY + 10f }
bossVx *= 1.25f
}
score += 5 * multiplier
meter = minOf(1f, meter + .006f * dmg)
if (bossHp <= 0) {
bossOn = false; bossHp = 0; beamOn = 0f; bossWarn = 0f
bossOn = false; bossHp = 0; beamOn = 0f; bossWarn = 0f; swoop = 0f; indexVolleyIn = 0f
score += 1500 * (wave / 5)
for (e in enemies) if (e.active && e.kind == Kind.MINION) kill(e)
events = events or Events.BOSS_DOWN
if (mode == RaidersMode.Story && boss == Boss.Wizard) {
// He doesn't explode: the field clears and he dusts himself off.
for (e in enemies) e.active = false
for (sh in enemyShots) sh.active = false
phase = Phase.Ending; endingT = 0f
return
}
for (e in enemies) if (e.active && e.kind == Kind.MINION) kill(e)
// What the other bosses sent down goes with them.
for (e in enemies) if (e.active && e.mode == M_FREE) e.active = false
if (bursts) burst(bossX, bossY, Kind.COUNT)
}
}
@@ -770,6 +979,15 @@ internal class RaidersSim(var pilot: Pilot = Pilot.Ollie, difficulty: Difficulty
internal fun moveShipTo(x: Float) { shipX = x; shipVx = 0f }
/** Jumps straight to wave [n] of the current run. */
internal fun startTestWave(n: Int) = startWave(n)
/** Takes [dmg] off the boss as if shot. */
internal fun damageBoss(dmg: Int) { if (bossOn) hitBoss(dmg) }
/** Beats the boss outright. */
internal fun beatBoss() { if (bossOn) { bossEnter = 0f; hitBoss(bossHp) } }
// ---------- reading ----------
fun livingEnemies(): Int { var n = 0; for (e in enemies) if (e.active) n++; return n }
@@ -785,6 +1003,7 @@ internal class RaidersSim(var pilot: Pilot = Pilot.Ollie, difficulty: Difficulty
fun takeEvents(): Int { val e = events; events = 0; return e }
companion object {
const val SWOOP_TIME = 1.6f
private val POWERS = Power.entries.toTypedArray()
private val POWER_WEIGHTS = POWERS.sumOf { it.weight }
fun dist(ax: Float, ay: Float, bx: Float, by: Float): Float { val dx = ax - bx; val dy = ay - by; return sqrt(dx * dx + dy * dy) }
@@ -0,0 +1,91 @@
package tv.orbit.classic.arcade.raiders
import tv.orbit.classic.arcade.Difficulty
/**
* Orbi-Raiders Story mode (prototype, 8 November 2026, from Paul's idea): defend the Orbit network, and every fifth wave
* something bigger turns up, until the wizard of page 999 steps out of Orbi-Fax himself.
*/
internal enum class RaidersMode(val title: String) { Endless("Endless"), Story("Story") }
/**
* The bosses. [title] is what's shown; the wizard has no approved name yet, so his is one string, to change in one place.
*/
internal enum class Boss(val title: String) {
DeadChannel("The Dead Channel"),
SatelliteArray("Rogue Satellite Array"),
PixelQueen("The Corrupt Pixel Queen"),
Wizard(WIZARD_TITLE);
val upper = title.uppercase()
val bit get() = 1 shl ordinal
}
/** The wizard's title on screen (Paul to name him: "The Keeper of 999" is an idea, not decided). */
internal const val WIZARD_TITLE = "The wizard of page 999"
/** The wizard's five phases, in order as his health runs down. */
internal enum class WizardPhase(val title: String) {
PageFlip("Page Flip"), StaticStorm("Static Storm"), Fastext("Fastext Barrage"), ReturnToIndex("Return to Index"), Overload("999 Overload")
}
/**
* Story, all in one table (Paul chose 20 waves and 4 bosses): which wave each boss is on. A checkpoint follows every boss.
* To make Story 30 waves with 3 bosses, change [WAVES] and [BOSSES]; nothing else depends on the numbers.
*/
internal object StoryPlan {
const val WAVES = 20
val BOSSES: List<Pair<Int, Boss>> = listOf(5 to Boss.DeadChannel, 10 to Boss.SatelliteArray, 15 to Boss.PixelQueen, 20 to Boss.Wizard)
private val byWave = arrayOfNulls<Boss>(WAVES + 1).also { a -> for ((w, b) in BOSSES) a[w] = b }
fun bossAt(wave: Int): Boss? = if (wave in 1..WAVES) byWave[wave] else null
/** The final boss's wave: Orbi-Fax cuts in before it. */
val finalWave = BOSSES.last().first
/** Where a run starts again after beating the boss on [wave]: the next wave, or null after the last. */
fun checkpointAfter(wave: Int): Int? = if (bossAt(wave) != null && wave < WAVES) wave + 1 else null
/** Valid places to start a Story run: wave 1 and the wave after each boss but the last. */
val starts: List<Int> = listOf(1) + BOSSES.mapNotNull { (w, _) -> checkpointAfter(w) }
/** Which chapter a wave is in, from 1. */
fun chapterOf(wave: Int): Int = BOSSES.indexOfFirst { (w, _) -> wave <= w }.let { if (it < 0) BOSSES.size else it + 1 }
/** Orbi-Fax's page before the final boss (Paul's words). */
val CUT_IN_LINES = listOf("YOU AGAIN?", "I TOLD YOU TO TURN BACK.", "NOW YOU'VE BROUGHT A SPACESHIP?")
/** The same words wrapped to fit beside him on the page (19 cells of double-height text). */
val CUT_IN: Array<String> = CUT_IN_LINES.flatMap { wrap(it, 19) }.toTypedArray()
val CUT_IN_CHARS = CUT_IN.sumOf { it.length }
fun wrap(text: String, width: Int): List<String> {
val out = ArrayList<String>(); var line = ""
for (word in text.split(' ')) {
line = if (line.isEmpty()) word else if (line.length + 1 + word.length <= width) "$line $word" else { out += line; word }
}
if (line.isNotEmpty()) out += line
return out
}
/** What he says when he's beaten: no explosion, he dusts himself off. */
const val ENDING = "Very well. You may stay. But don't touch page 1000."
}
/** In Endless, every fifth wave: the bosses this player has met in Story take turns (the Dead Channel until then). */
internal fun endlessBoss(wave: Int, metMask: Int): Boss {
val met = (metMask or Boss.DeadChannel.bit)
var count = 0
for (b in Boss.entries) if (met and b.bit != 0) count++
var pick = (wave / 5 - 1).coerceAtLeast(0) % count
for (b in Boss.entries) if (met and b.bit != 0) { if (pick == 0) return b; pick-- }
return Boss.DeadChannel
}
/** Where Story progress lives in the profile's Orbi-Raiders level progress: a checkpoint per difficulty. */
internal object StorySave {
fun checkpointKey(d: Difficulty) = "story.checkpoint.${d.name}"
fun doneKey(d: Difficulty) = "story.done.${d.name}"
const val MET = "story.met"
/** The wave a Story run starts on: the saved checkpoint if it's a real one, else wave 1. */
fun startWave(level: Map<String, String>, d: Difficulty): Int =
level[checkpointKey(d)]?.toIntOrNull()?.takeIf { it in StoryPlan.starts } ?: 1
fun metMask(level: Map<String, String>): Int = level[MET]?.toIntOrNull()?.and((1 shl Boss.entries.size) - 1) ?: 0
fun done(level: Map<String, String>, d: Difficulty) = level[doneKey(d)] == "1"
}
@@ -0,0 +1,204 @@
package tv.orbit.classic.arcade.raiders
import android.graphics.Bitmap
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.scale
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextMeasurer
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.sp
import tv.orbit.classic.ORBI_FAX_WIZARD
import tv.orbit.classic.Teletext
import tv.orbit.classic.TeletextPage
import tv.orbit.classic.TeletextRenderer
import kotlin.math.sin
/**
* Story mode's drawing: the Orbi-Fax pages, drawn by Orbi-Fax's own [TeletextRenderer] into one small bitmap (only when a
* letter is added), and the wizard, his Orbi-Fax mosaic art ([ORBI_FAX_WIZARD]) rendered once the same way, exactly as on
* page 999, never redrawn. Nothing in Orbi-Fax is changed. The new bosses are drawn in code like the Dead Channel.
*/
internal class StoryArt(density: Density, measurer: TextMeasurer) {
private val page = TeletextPage()
private val pixels = IntArray(Teletext.WIDTH * Teletext.HEIGHT)
private val pageBitmap: Bitmap = androidx.core.graphics.createBitmap(Teletext.WIDTH, Teletext.HEIGHT)
private val pageImage: ImageBitmap = pageBitmap.asImageBitmap()
private var pageKey = -1
/** The wizard, 18 x 18 mosaic cells = 108 x 180 teletext dots, black made see-through. */
private val wizard: ImageBitmap = run {
val p = TeletextPage(); p.art(0, 0, ORBI_FAX_WIZARD)
val dots = IntArray(Teletext.WIDTH * Teletext.HEIGHT)
TeletextRenderer.render(p, dots)
val w = 18 * Teletext.CELL_W; val h = 18 * Teletext.CELL_H
val crop = IntArray(w * h) { i -> dots[(i / w) * Teletext.WIDTH + i % w].let { if (it == Teletext.PALETTE[Teletext.BLACK]) 0 else it } }
Bitmap.createBitmap(crop, w, h, Bitmap.Config.ARGB_8888).asImageBitmap()
}
private val wizardSize = IntSize(18 * Teletext.CELL_W, 18 * Teletext.CELL_H)
private val label = TextStyle(fontSize = 9.sp, fontWeight = FontWeight.Bold)
private val index: TextLayoutResult = measurer.measure("INDEX", label, density = density)
private val pages: Array<TextLayoutResult> = arrayOf("P100", "P305", "P471", "P628", "P888", "P999").map { measurer.measure(it, label, density = density) }.toTypedArray()
private val labelScale = 9f / index.size.height.coerceAtLeast(1)
private val thin = Stroke(1f)
private val dashes = Stroke(1.2f, pathEffect = androidx.compose.ui.graphics.PathEffect.dashPathEffect(floatArrayOf(4f, 3f)))
private val tri = Path().apply { moveTo(0f, -4f); lineTo(4f, 3f); lineTo(-4f, 3f); close() }
private val diamond = Path().apply { moveTo(0f, -4.5f); lineTo(4f, 0f); lineTo(0f, 4.5f); lineTo(-4f, 0f); close() }
// Teletext's colours, for the wizard's shots and his test card.
private val tt = Array(8) { Color(Teletext.PALETTE[it]) }
/** On screen, a teletext dot is wider than it is tall (a 4:3 page of 240 x 250 dots). */
private val dotAspect = (4f / 3f) * Teletext.HEIGHT / Teletext.WIDTH
// ---------- the Orbi-Fax pages ----------
private fun buildPage(fax: Int, shown: Int) {
page.clear()
var left = shown
fun line(row: Int, col: Int, text: String, colour: Int, double: Boolean = false) {
if (text.isEmpty()) return
page.put(row, col, text, colour, double = double)
// Not typed yet: those letters are blank.
for (k in maxOf(0, left) until text.length) page.chars[row * Teletext.COLS + col + k] = ' '
left -= text.length
}
if (fax == FaxPage.TEASER) {
val colours = intArrayOf(Teletext.YELLOW, Teletext.WHITE, Teletext.WHITE, Teletext.GREEN, Teletext.RED, Teletext.WHITE, Teletext.YELLOW, Teletext.WHITE, Teletext.CYAN)
for (i in FaxPage.TEASER_LINES.indices) line(3 + i * 2, 6, FaxPage.TEASER_LINES[i], colours[i])
} else {
// As Orbi-Fax's own page 999: the header, the wizard on the left, the words beside him in double height.
page.put(0, 0, "P999", Teletext.WHITE); page.put(0, 5, " ORBI-FAX ", Teletext.YELLOW, Teletext.BLUE); page.put(0, 18, "999", Teletext.WHITE)
page.art(2, 1, ORBI_FAX_WIZARD)
page.rule(1, Teletext.CYAN, 19, Teletext.COLS)
page.rule(14, Teletext.CYAN, 19, Teletext.COLS, bits = 0b000011)
val lines = StoryPlan.CUT_IN
for (i in lines.indices) line(3 + i * 2, 21, lines[i], if (i == lines.lastIndex) Teletext.YELLOW else Teletext.WHITE, double = true)
}
TeletextRenderer.render(page, pixels)
pageBitmap.setPixels(pixels, 0, Teletext.WIDTH, 0, 0, Teletext.WIDTH, Teletext.HEIGHT)
}
/** An Orbi-Fax page over the whole field: black, with the page at 4:3 in the middle. */
fun DrawScope.faxPage(sim: RaidersSim) {
val shown = sim.faxShown()
val key = sim.fax * 10_000 + shown
if (key != pageKey) { pageKey = key; buildPage(sim.fax, shown) }
drawRect(Color.Black, Offset(-20f, -20f), Size(FIELD_W + 40f, FIELD_H + 40f))
val h = FIELD_H; val w = h * 4f / 3f
drawImage(pageImage, IntOffset.Zero, IntSize(Teletext.WIDTH, Teletext.HEIGHT), IntOffset(((FIELD_W - w) / 2).toInt(), 0), IntSize(w.toInt(), h.toInt()), filterQuality = FilterQuality.None)
}
// ---------- the wizard ----------
/** The wizard, centred on ([x], [y]), [height] units tall; [grow] 0 to 1 as he steps out of the page. */
fun DrawScope.wizard(x: Float, y: Float, height: Float, grow: Float, tinted: Boolean) {
val h = height * (.35f + .65f * grow)
val w = h * wizardSize.width / wizardSize.height * dotAspect
drawImage(wizard, IntOffset.Zero, wizardSize, IntOffset((x - w / 2).toInt(), (y - h / 2).toInt()), IntSize(w.toInt(), h.toInt()),
alpha = if (tinted) .7f else (.4f + .6f * grow), filterQuality = FilterQuality.None)
}
/** His telegraphs: where he'll flip to, the gap in the storm, the four Fastext buttons, the index marker. */
fun DrawScope.wizardWarnings(sim: RaidersSim, time: Float, calm: Boolean) {
if (sim.bossWarn <= 0f) return
val move = if (sim.wizardPhase == WizardPhase.Overload) -1 else sim.wizardPhase.ordinal
// In Overload the next move isn't known here, so every telegraph that has a place is shown.
if (move == 0 || move == -1 && sim.flipToX > 0f) {
drawRoundRect(tt[Teletext.CYAN], Offset(sim.flipToX - 30f, sim.bossY - 45f), Size(60f, 90f), CornerRadius(4f), style = dashes)
// The page numbers race (they hold still under Reduce motion).
val n = if (calm) pages.lastIndex else ((time * 14f).toInt() % pages.size)
translate(sim.flipToX - 14f, sim.bossY - 58f) { scale(labelScale, labelScale, Offset.Zero) { drawText(pages[n], tt[Teletext.YELLOW]) } }
}
if (move == 1) {
var x = 12f
while (x < FIELD_W) { if (kotlin.math.abs(x - sim.gapX) > 36f) drawCircle(tt[Teletext.WHITE], 2f, Offset(x, sim.bossY + 30f), alpha = .6f); x += 26f }
drawLine(tt[Teletext.GREEN], Offset(sim.gapX - 30f, sim.bossY + 38f), Offset(sim.gapX + 30f, sim.bossY + 38f), 2f)
}
if (move == 2) for (k in 0 until 4) {
val c = Offset(sim.bossX - 24f + k * 16f, sim.bossY + 52f)
fastextShape(k + 1, c, 1.3f)
}
if (move == 3 || move == -1 && sim.indexX > 0f) {
drawLine(tt[Teletext.YELLOW], Offset(sim.indexX, SHIP_Y - 26f), Offset(sim.indexX, SHIP_Y + 14f), 2f)
drawRect(tt[Teletext.YELLOW], Offset(sim.indexX - 14f, SHIP_Y - 14f), Size(28f, 28f), style = thin)
translate(sim.indexX - 13f, SHIP_Y - 36f) { scale(labelScale, labelScale, Offset.Zero) { drawText(index, tt[Teletext.YELLOW]) } }
}
}
/** A Fastext shot: red square, green triangle, yellow circle, cyan diamond, so they never rely on colour alone. */
fun DrawScope.fastextShape(style: Int, at: Offset, k: Float = 1f) {
when (style) {
1 -> drawRect(tt[Teletext.RED], Offset(at.x - 3.5f * k, at.y - 3.5f * k), Size(7f * k, 7f * k))
2 -> translate(at.x, at.y) { scale(k, k, Offset.Zero) { drawPath(tri, tt[Teletext.GREEN]) } }
3 -> drawCircle(tt[Teletext.YELLOW], 3.8f * k, at)
4 -> translate(at.x, at.y) { scale(k, k, Offset.Zero) { drawPath(diamond, tt[Teletext.CYAN]) } }
else -> { drawCircle(tt[Teletext.WHITE], 2f, at, alpha = .8f); drawCircle(tt[Teletext.WHITE], 1.2f, at + Offset(3f, -2f), alpha = .6f) }
}
}
/** 999 Overload: the field becomes a corrupted test card. With Reduce flashing on (or Reduce motion) it holds still. */
fun DrawScope.overloadCard(time: Float, still: Boolean) {
val bars = intArrayOf(Teletext.WHITE, Teletext.YELLOW, Teletext.CYAN, Teletext.GREEN, Teletext.MAGENTA, Teletext.RED, Teletext.BLUE, Teletext.BLACK)
val w = FIELD_W / bars.size
for (i in bars.indices) {
val drift = if (still) 0f else sin(time * .8f + i) * 3f
drawRect(tt[bars[i]], Offset(i * w, drift), Size(w + 1f, FIELD_H), alpha = .13f)
}
drawCircle(tt[Teletext.WHITE], 70f, Offset(FIELD_W / 2, FIELD_H / 2 - 10f), alpha = .08f)
}
// ---------- the other new bosses ----------
/** The Rogue Satellite Array: three dishes on a long truss, the middle one the core. Playful, not scary. */
fun DrawScope.satelliteArray(x: Float, y: Float, warn: Float, tinted: Boolean) {
translate(x, y) {
drawRect(RaidersColours.Satellite, Offset(-74f, -4f), Size(148f, 8f), alpha = if (tinted) .7f else 1f)
for (i in -1..1) {
val dx = i * 58f
val core = i == 0
drawRoundRect(RaidersColours.Panel, Offset(dx - (if (core) 22f else 16f), -24f), Size(if (core) 44f else 32f, 20f), CornerRadius(4f))
drawArc(RaidersColours.Satellite, 200f, 140f, false, Offset(dx - 14f, 2f), Size(28f, 18f), style = Stroke(2f))
drawCircle(if (warn > 0f) RaidersColours.Warn else RaidersColours.Signal, 3f, Offset(dx, 12f))
}
// The core's face.
drawCircle(RaidersColours.Navy, 3.2f, Offset(-7f, -14f)); drawCircle(RaidersColours.Navy, 3.2f, Offset(7f, -14f))
drawCircle(Color.White, 1f, Offset(-8f, -15f)); drawCircle(Color.White, 1f, Offset(6f, -15f))
}
}
/** The Corrupt Pixel Queen: a big block of pink pixels with a crown, smiling; she loses blocks as she splits. */
fun DrawScope.pixelQueen(x: Float, y: Float, hpFrac: Float, warn: Float, tinted: Boolean) {
translate(x, y) {
val blocks = 6
val cell = 12f
val missing = ((1f - hpFrac) * 8).toInt()
for (r in 0 until blocks) for (c in 0 until blocks) {
val edge = (r == 0 || c == 0 || r == blocks - 1 || c == blocks - 1)
if (edge && (r * 7 + c * 3) % 9 < missing) continue
val colour = if ((r + c) % 2 == 0) RaidersColours.Pixel else Color(0xFFD63C8A)
drawRect(if (tinted) Color(0xFFFFB3D9) else colour, Offset(-36f + c * cell, -30f + r * cell), Size(cell - 1f, cell - 1f))
}
// Crown.
for (k in 0 until 3) drawRect(if (warn > 0f) RaidersColours.Warn else RaidersColours.Flame, Offset(-24f + k * 18f, -42f), Size(10f, 10f))
drawCircle(RaidersColours.Navy, 4.5f, Offset(-10f, -6f)); drawCircle(RaidersColours.Navy, 4.5f, Offset(10f, -6f))
drawCircle(Color.White, 1.4f, Offset(-11.5f, -7.5f)); drawCircle(Color.White, 1.4f, Offset(8.5f, -7.5f))
drawArc(RaidersColours.Navy, 20f, 140f, false, Offset(-12f, 0f), Size(24f, 12f), style = Stroke(2f))
}
}
}
@@ -16,7 +16,9 @@ internal object RaidersBot {
var threat = Float.NaN
// Shots from 80 above down to just past the ship, near enough to walk into.
for (s in sim.enemyShots) if (s.active && s.y < SHIP_Y + 12f && SHIP_Y - s.y < 80f && abs(s.x - x) < 20f) { threat = s.x; break }
if (sim.bossOn && (sim.beamOn > 0f || (sim.bossAttack == 1 && sim.bossWarn > 0f)) && abs(sim.beamX - x) < 22f) threat = sim.beamX
val beamy = sim.bossOn && (sim.beamOn > 0f || (sim.bossAttack == 1 && sim.bossWarn > 0f) || sim.swoop > 0f) && sim.boss != Boss.Wizard
if (beamy && abs(sim.beamX - x) < 22f) threat = sim.beamX
if (beamy && sim.boss == Boss.SatelliteArray && abs(sim.beam2X - x) < 22f) threat = sim.beam2X
if (!threat.isNaN()) {
input.move = if (threat > x) -1 else if (threat < x) 1 else if (x > FIELD_W / 2) -1 else 1
if (x < 24f) input.move = 1
@@ -0,0 +1,239 @@
package tv.orbit.classic.arcade.raiders
import org.junit.Assert.*
import org.junit.Test
import tv.orbit.classic.arcade.Difficulty
/** Orbi-Raiders Story mode (prototype): the wave table, checkpoints, the Orbi-Fax pages and the bosses' phases. */
class RaidersStoryTest {
private val idle = RaidersInput()
private fun story(d: Difficulty = Difficulty.Normal, start: Int = 1, seed: Int = 3) =
RaidersSim(Pilot.Ollie, d, seed).apply { newRun(mode = RaidersMode.Story, startAt = start) }
// ---------- the table ----------
@Test fun storyIsTwentyWavesWithFourBossesInOneTable() {
assertEquals(20, StoryPlan.WAVES)
assertEquals(listOf(5 to Boss.DeadChannel, 10 to Boss.SatelliteArray, 15 to Boss.PixelQueen, 20 to Boss.Wizard), StoryPlan.BOSSES)
for (w in 1..20) assertEquals("wave $w", StoryPlan.BOSSES.firstOrNull { it.first == w }?.second, StoryPlan.bossAt(w))
assertNull(StoryPlan.bossAt(0)); assertNull(StoryPlan.bossAt(21))
assertEquals(listOf(1, 6, 11, 16), StoryPlan.starts)
assertEquals(6, StoryPlan.checkpointAfter(5)); assertNull(StoryPlan.checkpointAfter(20)); assertNull(StoryPlan.checkpointAfter(7))
assertEquals(listOf(1, 1, 2, 4, 4), listOf(1, 5, 6, 16, 20).map { StoryPlan.chapterOf(it) })
assertEquals("The wizard of page 999", Boss.Wizard.title)
}
@Test fun theWizardsPageIsPaulsWordsWrappedToFit() {
assertEquals(listOf("YOU AGAIN?", "I TOLD YOU TO TURN BACK.", "NOW YOU'VE BROUGHT A SPACESHIP?"), StoryPlan.CUT_IN_LINES)
assertEquals(StoryPlan.CUT_IN_LINES.joinToString(" "), StoryPlan.CUT_IN.joinToString(" "))
assertTrue(StoryPlan.CUT_IN.all { it.length <= 19 })
assertEquals("Very well. You may stay. But don't touch page 1000.", StoryPlan.ENDING)
assertEquals(listOf("ORBI-FAX", "P999", "", "SIGNAL RESTORED", "TRANSMISSION INTERRUPTED", "", "DO NOT PROCEED TO PAGE 999", "", "RETURN TO INDEX ........ 100"), FaxPage.TEASER_LINES.toList())
}
@Test fun endlessBringsBackTheBossesMetInStoryInTurn() {
assertEquals(listOf(Boss.DeadChannel, Boss.DeadChannel), listOf(5, 10).map { endlessBoss(it, 0) })
val all = Boss.entries.fold(0) { m, b -> m or b.bit }
assertEquals(listOf(Boss.DeadChannel, Boss.SatelliteArray, Boss.PixelQueen, Boss.Wizard, Boss.DeadChannel), listOf(5, 10, 15, 20, 25).map { endlessBoss(it, all) })
val two = Boss.PixelQueen.bit
assertEquals(listOf(Boss.DeadChannel, Boss.PixelQueen, Boss.DeadChannel), listOf(5, 10, 15).map { endlessBoss(it, two) })
// In the game: an Endless run with the Queen met meets her on wave 10.
val sim = RaidersSim(Pilot.Ollie, Difficulty.Normal, 3).apply { newRun(mode = RaidersMode.Endless, metMask = two) }
sim.startTestWave(10)
assertTrue(sim.bossOn); assertEquals(Boss.PixelQueen, sim.boss)
}
// ---------- checkpoints and saves ----------
@Test fun checkpointsAreSavedPerProfileAndDifficultyAndModesNeverResetEachOther() {
var level = emptyMap<String, String>()
assertEquals(1, StorySave.startWave(level, Difficulty.Normal))
level = level + (StorySave.checkpointKey(Difficulty.Normal) to "11") + (StorySave.checkpointKey(Difficulty.Gentle) to "6") + ("bestWave" to "23")
assertEquals(11, StorySave.startWave(level, Difficulty.Normal)); assertEquals(6, StorySave.startWave(level, Difficulty.Gentle)); assertEquals(1, StorySave.startWave(level, Difficulty.Tricky))
// A checkpoint that isn't one is ignored.
assertEquals(1, StorySave.startWave(level + (StorySave.checkpointKey(Difficulty.Normal) to "13"), Difficulty.Normal))
// A run in either mode starts where that mode left off, and Endless's best wave stays.
val s = RaidersSim(Pilot.Ollie, Difficulty.Normal, 3)
s.newRun(mode = RaidersMode.Story, startAt = StorySave.startWave(level, Difficulty.Normal)); assertEquals(11, s.wave); assertEquals(Boss.SatelliteArray, StoryPlan.bossAt(10))
s.newRun(mode = RaidersMode.Endless); assertEquals(1, s.wave)
s.newRun(mode = RaidersMode.Story, startAt = StorySave.startWave(level, Difficulty.Normal)); assertEquals(11, s.wave)
assertEquals("23", level["bestWave"])
}
@Test fun beatingABossReachesACheckpointAndContinuesOnTheNextWave() {
val s = story(start = 6)
s.startTestWave(10)
assertEquals(Boss.SatelliteArray, s.boss)
s.beatBoss()
repeat(120) { s.step(idle) }
assertEquals(Phase.Checkpoint, s.phase)
assertEquals(11, StoryPlan.checkpointAfter(s.wave))
s.continueRun(); assertEquals(11, s.wave); assertEquals(Phase.Playing, s.phase)
}
// ---------- the Orbi-Fax pages ----------
@Test fun afterTheDeadChannelTheTeaserShowsForACoupleOfSecondsThenTheCheckpoint() {
val s = story(start = 1)
s.startTestWave(5); assertEquals(Boss.DeadChannel, s.boss)
s.beatBoss()
repeat(100) { s.step(idle) }
assertEquals(Phase.Fax, s.phase); assertEquals(FaxPage.TEASER, s.fax)
var t = 0; while (s.phase == Phase.Fax && t < 600) { s.step(idle); t++ }
assertEquals(Phase.Checkpoint, s.phase)
assertEquals("about 2.5 s", 2.5f, t / 60f + 100 / 60f - 1.6f, .45f)
// OK skips it; Reduce motion shows it all at once.
val k = story(); k.calm = true; k.startTestWave(5); k.beatBoss(); repeat(100) { k.step(idle) }
assertEquals(FaxPage.TEASER_CHARS, k.faxShown()); k.skipFax(); assertEquals(Phase.Checkpoint, k.phase)
}
@Test fun theWizardsPageTypesOutThenHeStepsOutOnceARun() {
val s = story(start = 16)
s.startTestWave(20)
assertEquals(Phase.Fax, s.phase); assertEquals(FaxPage.WIZARD, s.fax); assertFalse(s.bossOn)
assertEquals(0, s.faxShown())
repeat(30) { s.step(idle) }
assertTrue(s.faxShown() in 1 until StoryPlan.CUT_IN_CHARS)
s.skipFax()
assertEquals(Phase.Playing, s.phase); assertTrue(s.bossOn); assertEquals(Boss.Wizard, s.boss); assertTrue(s.bossEnter > 0f)
// Restart Level doesn't show the page again.
s.restartWave(); assertEquals(Phase.Playing, s.phase); assertTrue(s.bossOn)
// Reduce motion: the whole page at once.
val c = story(start = 16); c.calm = true; c.startTestWave(20); assertEquals(StoryPlan.CUT_IN_CHARS, c.faxShown())
}
@Test fun beatingTheWizardEndsStoryWithHisWordsNotAnExplosion() {
val s = story(start = 16)
s.startTestWave(20); s.skipFax(); repeat(120) { s.step(idle) }
s.beatBoss()
assertEquals(Phase.Ending, s.phase); assertEquals(0, s.liveSparks()); assertEquals(0, s.livingEnemies())
var events = 0
var t = 0; while (s.phase == Phase.Ending && t < 1200) { s.step(idle); events = events or s.takeEvents(); t++ }
assertEquals(Phase.Complete, s.phase); assertTrue(events and Events.STORY_DONE != 0)
assertEquals(StoryPlan.ENDING.length, s.endingShown())
}
// ---------- the bosses ----------
@Test fun everyBossAttackIsWarnedFirst() {
for (b in StoryPlan.BOSSES) {
val s = story(start = StoryPlan.starts.last { it <= b.first })
s.startTestWave(b.first); s.skipFax()
var warned = 0; var attacks = 0; var lastWarn = 0f
for (t in 0 until 60 * 40) {
s.step(idle)
if (s.bossWarn > 0f && lastWarn <= 0f) warned++
if (s.bossWarn <= 0f && lastWarn > 0f) attacks++
lastWarn = s.bossWarn
if (s.over) s.newRun(mode = RaidersMode.Story, startAt = StoryPlan.starts.last { it <= b.first }).also { s.startTestWave(b.first); s.skipFax() }
}
assertTrue("${b.second} attacked", attacks >= 3)
assertTrue("${b.second}: every attack warned ($warned warnings, $attacks attacks)", warned >= attacks)
}
}
@Test fun theWizardGoesThroughHisFivePhasesAsHisHealthFalls() {
val s = story(start = 16)
s.startTestWave(20); s.skipFax(); repeat(120) { s.step(idle) }
val seen = LinkedHashSet<WizardPhase>()
while (s.bossOn) { s.damageBoss(1); s.step(idle); seen += s.wizardPhase }
assertEquals(WizardPhase.entries.toList(), seen.toList())
}
@Test fun returnToIndexPullsTheShipBackToWhereItWasAfterAWarning() {
val s = story(start = 16)
s.startTestWave(20); s.skipFax(); repeat(120) { s.step(idle) }
// Down to Return to Index.
while (s.wizardPhase != WizardPhase.ReturnToIndex) { s.damageBoss(1); s.step(idle) }
val left = RaidersInput().apply { move = -1 }; val right = RaidersInput().apply { move = 1 }
var pulled = false
for (t in 0 until 60 * 20) {
s.step(if ((t / 90) % 2 == 0) left else right)
if (s.bossWarn > 0f && s.indexX > 0f) {
val warnFor = s.bossWarn; val target = s.indexX
assertTrue("warned for at least the usual warning", warnFor > 0f)
while (s.bossWarn > 0f) s.step(right)
assertEquals(target, s.shipX, .5f); pulled = true; break
}
}
assertTrue(pulled)
}
@Test fun thePixelQueenSplitsAsSheWeakens() {
val s = story(start = 11)
s.startTestWave(15)
assertEquals(Boss.PixelQueen, s.boss)
val before = s.livingEnemies()
while (s.bossHp > s.bossMax * 2 / 3) s.damageBoss(1)
assertTrue(s.livingEnemies() >= before + 4)
}
@Test fun fastextShotsAreFourDifferentStyles() {
val s = story(start = 16)
s.startTestWave(20); s.skipFax(); repeat(120) { s.step(idle) }
while (s.wizardPhase != WizardPhase.Fastext) { s.damageBoss(1); s.step(idle) }
val styles = HashSet<Int>()
for (t in 0 until 60 * 12) { s.step(idle); for (sh in s.enemyShots) if (sh.active) styles += sh.style }
assertTrue("styles $styles", styles.containsAll(listOf(1, 2, 3, 4)))
}
// ---------- the bot through Story ----------
private class Run(val cleared: Boolean, val seconds: Float, val wave: Int, val continues: Int)
/** A player who, like a child, goes on from the last checkpoint when the signal's lost (up to [continues] times). */
private fun play(d: Difficulty, seed: Int, continues: Int): Run {
val sim = RaidersSim(Pilot.Ollie, d, seed)
sim.newRun(mode = RaidersMode.Story)
val input = RaidersInput()
var checkpoint = 1; var used = 0; var ticks = 0L
while (ticks < 60L * 60 * 40) {
RaidersBot.fill(sim, input); sim.step(input); ticks++
when (sim.phase) {
Phase.Checkpoint -> { checkpoint = StoryPlan.checkpointAfter(sim.wave) ?: checkpoint; sim.continueRun() }
Phase.Complete -> return Run(true, ticks / 60f, sim.wave, used)
Phase.Over -> { if (used++ >= continues) return Run(false, ticks / 60f, sim.wave, used - 1); sim.newRun(seed = seed + used * 101, mode = RaidersMode.Story, startAt = checkpoint, metMask = sim.metMask) }
else -> {}
}
}
return Run(false, ticks / 60f, sim.wave, used)
}
@Test fun theBotThroughStoryOnEachDifficulty() {
val report = StringBuilder("Orbi-Raiders Story (bot, Ollie, 16 seeds a difficulty):\n")
val rates = HashMap<Difficulty, Double>()
for (d in Difficulty.entries) {
val one = (1..16).map { play(d, it * 977, 0) }
val five = (1..16).map { play(d, it * 977, 5) }
fun pct(l: List<Run>) = 100.0 * l.count { it.cleared } / l.size
val clearedTimes = five.filter { it.cleared }.map { it.seconds }
report.append("%-7s no continues: %5.1f%% cleared (mean wave %.1f) | up to 5 continues from checkpoints: %5.1f%% cleared, mean %.1f min, mean continues %.1f%n".format(
d.title, pct(one), one.map { it.wave }.average(), pct(five), if (clearedTimes.isEmpty()) 0.0 else clearedTimes.average() / 60.0, five.map { it.continues }.average()))
rates[d] = pct(five)
}
println(report)
// The difficulties order how often Story is finished, and Gentle is finishable.
assertTrue(report.toString(), rates[Difficulty.Gentle]!! >= rates[Difficulty.Normal]!! && rates[Difficulty.Normal]!! >= rates[Difficulty.Tricky]!!)
assertTrue(report.toString(), rates[Difficulty.Gentle]!! >= 50.0)
}
@Test fun storyPlayAllocatesNothingAndStaysUnderTheSpriteCap() {
val sim = RaidersSim(Pilot.Ollie, Difficulty.Normal, 5).apply { newRun(mode = RaidersMode.Story, startAt = 16) }
val input = RaidersInput()
fun tick() {
RaidersBot.fill(sim, input); sim.step(input)
if (sim.phase == Phase.Fax) sim.skipFax()
if (sim.over || sim.phase == Phase.Complete || sim.phase == Phase.Checkpoint) sim.newRun(mode = RaidersMode.Story, startAt = 16)
}
repeat(3_000) { tick() }
val mx = java.lang.management.ManagementFactory.getThreadMXBean() as com.sun.management.ThreadMXBean
val thread = Thread.currentThread().id
var most = 0
val before = mx.getThreadAllocatedBytes(thread)
for (i in 0 until 10_000) { tick(); most = maxOf(most, sim.liveSprites()) }
val allocated = mx.getThreadAllocatedBytes(thread) - before
println("Orbi-Raiders Story: 10,000 ticks of the last chapter allocated $allocated bytes; most sprites at once $most")
assertTrue("allocated $allocated", allocated < 16 * 1024)
assertTrue("sprites $most", most <= 60)
}
}
@@ -0,0 +1,62 @@
package tv.orbit.classic.arcade.raiders
import org.junit.Assert.*
import org.junit.Test
import tv.orbit.classic.arcade.ArcadeProfileData
import tv.orbit.classic.ArcadeProgress
import tv.orbit.classic.arcade.ArcadeRun
import tv.orbit.classic.arcade.Difficulty
import tv.orbit.classic.arcade.GameRecord
import tv.orbit.classic.arcade.ResetAction
import tv.orbit.classic.arcade.RunEnd
import tv.orbit.classic.arcade.ScoreKind
import tv.orbit.classic.arcade.applyReset
import tv.orbit.classic.arcade.decodeArcade
import tv.orbit.classic.arcade.encodeArcade
import tv.orbit.classic.arcade.recordRun
/** Story's saves in the profile's Arcade file, and the storyComplete flag Orbi-Fax will read (ArcadeProgress). */
class StoryProgressTest {
private val id = "OrbiRaiders"
private fun withLevel(vararg kv: Pair<String, String>) = ArcadeProfileData("kid").withGame(id) { GameRecord(level = kv.toMap(), runs = listOf(ArcadeRun(4200, 1L, "Wave 23 · Ollie"))) }
@Test fun finishingStorySavesTheFlagAndDateTogetherAndItSurvivesTheFile() {
val values = ArcadeProgress.storyCompleteValues(1_794_180_000_000L, Difficulty.Normal)
assertEquals("true", values[ArcadeProgress.STORY_COMPLETE]); assertEquals("1794180000000", values[ArcadeProgress.STORY_COMPLETE_AT])
assertEquals("1", values[StorySave.doneKey(Difficulty.Normal)]); assertEquals("1", values[StorySave.checkpointKey(Difficulty.Normal)])
val before = withLevel("bestWave" to "23")
assertFalse(ArcadeProgress.storyComplete(before))
// One write with every value (as ArcadePlay.setLevels does).
val after = before.withGame(id) { it.copy(level = it.level + values) }
val back = decodeArcade(encodeArcade(after), "kid")!!
assertTrue(ArcadeProgress.storyComplete(back))
assertEquals("23", back.game(id).level["bestWave"])
assertTrue(StorySave.done(back.game(id).level, Difficulty.Normal)); assertFalse(StorySave.done(back.game(id).level, Difficulty.Gentle))
}
@Test fun resettingLevelProgressClearsTheFlagButClearingHighScoresDoesnt() {
val done = withLevel(ArcadeProgress.STORY_COMPLETE to "true", ArcadeProgress.STORY_COMPLETE_AT to "5")
assertTrue(ArcadeProgress.storyComplete(applyReset(done, id, ResetAction.ClearHighScores, 9L)))
assertFalse(ArcadeProgress.storyComplete(applyReset(done, id, ResetAction.ResetLevelProgress, 9L)))
assertFalse(ArcadeProgress.storyComplete(applyReset(done, id, ResetAction.ResetSettings, 9L)).not())
// Another profile is its own.
assertFalse(ArcadeProgress.storyComplete(ArcadeProfileData("other")))
}
@Test fun switchingModesNeverResetsEitherModesProgressCheckpointsOrScores() {
var d = withLevel("bestWave" to "23", StorySave.checkpointKey(Difficulty.Normal) to "11", StorySave.checkpointKey(Difficulty.Gentle) to "16", StorySave.MET to "3")
val runsBefore = d.game(id).runs
// The title's mode switch writes only "mode".
for (m in listOf("Story", "Endless", "Story")) d = d.withGame(id) { it.copy(level = it.level + ("mode" to m)) }
val l = d.game(id).level
assertEquals("23", l["bestWave"]); assertEquals(11, StorySave.startWave(l, Difficulty.Normal)); assertEquals(16, StorySave.startWave(l, Difficulty.Gentle)); assertEquals(3, StorySave.metMask(l))
assertEquals(runsBefore, d.game(id).runs)
// A Story run and an Endless run both go to the same High Scores without disturbing each other.
val s = RaidersSim(Pilot.Ollie, Difficulty.Normal, 3).apply { newRun(mode = RaidersMode.Story, startAt = 11) }
val storyEnd = raidersRunEnd(s, finished = false)
assertTrue(storyEnd.detail!!.startsWith("Story · Wave 11"))
d = recordRun(d, id, ScoreKind.Points, RunEnd(900, true, storyEnd.detail), 10L)
assertEquals(listOf(4200, 900), d.game(id).runs.map { it.score })
assertEquals(11, StorySave.startWave(d.game(id).level, Difficulty.Normal)); assertEquals("23", d.game(id).level["bestWave"])
}
}
+40
View File
@@ -0,0 +1,40 @@
# Orbi-Raiders Story mode: verification (8 November 2026)
Branch `raiders-story` from `hive-household-0.110.10` (`2fd550f`), 0.110.11-story, versionCode 294. Not installed, no adb,
nothing pushed or merged. What it is: `docs/orbi-raiders-story.md`.
| | 0.110.10-household (293) | 0.110.11-story (294) |
|---|---|---|
| Build (debug, release) | passed | passed |
| Kotlin unit tests | 933 run, 24 skipped, 0 failed | **951 run, 24 skipped, 0 failed** (18 new) |
| Lint | 0 errors, 87 warnings | **0 errors, 87 warnings** (no new ones) |
| Release APK | 47,859,291 bytes | 47,875,671 bytes (**+16,380**) |
## New tests
- `RaidersStoryTest` (15): the 20-wave, 4-boss table and its checkpoints; the wizard's page is Paul's words wrapped to fit;
the teaser's lines exactly; Endless brings back met bosses in turn; checkpoints per difficulty and modes never resetting
each other; a boss beaten reaches a checkpoint and continues; the teaser shows about 2.5 s then the checkpoint, OK skips
it, Reduce motion shows it whole; the wizard's page types out, he steps out, once a run; beating him ends Story with his
words, no explosion; every boss attack is warned first; the wizard's five phases in order; Return to Index pulls the ship
back after a warning; the Pixel Queen splits; Fastext shots are four styles; **the bot through Story on each difficulty**;
**allocation and sprites**.
- `StoryProgressTest` (3): storyComplete and its date saved together and surviving the file; Reset level progress clears
it, Clear high scores doesn't; switching modes never resets either mode's progress, checkpoints or scores.
## The bot through Story (Ollie, 16 seeds a difficulty)
| | No continues | Up to 5 continues from checkpoints |
|---|---|---|
| Gentle | 37.5% cleared (mean wave 18.4) | **100% cleared**, mean 9.3 min, 1.3 continues |
| Normal | 0% (mean wave 11.0) | 12.5% cleared, mean 12.7 min, 4.8 continues |
| Tricky | 0% (mean wave 9.1) | 0% |
The bot is simple (it dodges straight shots and beams, and doesn't read the wizard's telegraphs), so these are a floor, not
a target. Gentle, where Kids start, is finishable; Normal and Tricky may want tuning once Paul has played.
**Allocation**: 10,000 ticks of the last chapter (cut-in and wizard), 0 bytes; most sprites at once 44 (limit 60).
## Not checked
Nothing seen running: drawing, the pages, the step-out, the ending, focus and sound on the TV are unchecked until an install.
+117
View File
@@ -0,0 +1,117 @@
# Orbi-Raiders Story mode (prototype, 8 November 2026)
Branch `raiders-story` from `hive-household-0.110.10` (`2fd550f`), version 0.110.11-story, versionCode 294. For testing
only: not installed. From Paul's idea: defend the Orbit network, and every fifth wave something bigger turns up, until the
wizard of page 999 steps out of Orbi-Fax.
## Title: Story or Endless
A Mode button under Play switches between **Story** (shows "From wave n" or "Complete ★") and **Endless** (today's game).
The choice is remembered per profile. Switching never resets either: Story keeps its checkpoints, Endless its best wave, and
both put runs in the same High Scores (Story runs are marked "Story · Wave n · Pilot").
In Endless every fifth wave is a boss, as before. Once a player has met bosses in Story, Endless takes turns with them (in
Story's order), the Dead Channel until then.
## Story: one table
`raiders/RaidersStory.kt`, `StoryPlan`: 20 waves (Paul's choice), a boss every fifth, a checkpoint after each.
| Wave | Boss | After it |
|---|---|---|
| 5 | The Dead Channel | Orbi-Fax teaser (below), checkpoint at wave 6 |
| 10 | Rogue Satellite Array | checkpoint at wave 11 |
| 15 | The Corrupt Pixel Queen | checkpoint at wave 16 |
| 20 | The wizard of page 999 | his last words, Story complete |
Ordinary waves are Endless's waves 1 to 19 (same kinds arriving, same sizes). Changing the length is `WAVES` and `BOSSES`
only.
**Checkpoints** are saved in the profile's Orbi-Raiders level progress, one per difficulty (`story.checkpoint.Gentle` and
so on): Play in Story starts from the last one. Losing all signal ends the run (saved to High Scores); playing again goes on
from the checkpoint with full signal and the score from 0. Finishing Story sets the checkpoint back to wave 1.
## The bosses
Every attack is warned first, for the difficulty's warning time (Gentle 1.4 s, Normal 1.0 s, Tricky 0.75 s), and scales
with Gentle, Normal and Tricky like the Dead Channel (health 45 / 60 / 80 plus 20 for each boss in turn; the wizard has half
again).
- **The Dead Channel** (wave 5): unchanged.
- **Rogue Satellite Array** (wave 10): three dishes on a truss. Aimed triple shot; two beams at once (both columns outlined
first); drops two Rogue Satellites.
- **The Corrupt Pixel Queen** (wave 15): a block of pink pixels with a crown. A seven-shot spray; a swoop down the column
outlined under the ship and back up; drops two Corrupt Pixels. **She splits**: at two thirds and one third health she
throws off four Corrupt Pixels (which split again) and speeds up.
- **The wizard of page 999** (wave 20): five phases as his health falls, each with its own telegraph:
1. **Page Flip** (100-80%): a dashed outline where he'll appear, with page numbers racing above it (still under Reduce
motion); he teleports there and fires three.
2. **Static Storm** (80-60%): dots across the field show the row of static that's coming and a green bar marks the gap.
3. **Fastext Barrage** (60-40%): four shots fanned at the ship, red square, green triangle, yellow circle and cyan diamond,
the four shapes shown at his feet first (never colour alone).
4. **Return to Index** (40-20%): an INDEX marker on the ship's line where the ship was 2 s ago, warned for half a second
longer than usual; then the ship is pulled back there (with 0.4 s of safety) and a volley follows 0.5 s later. Dodge
again.
5. **999 Overload** (20-0%): the field becomes a corrupted test card in the eight teletext colours, faint; it drifts
gently, and holds still with Reduce flashing (on by default) or Reduce motion. His other four attacks in turn, 25%
quicker.
## The Orbi-Fax pages
Both are drawn by Orbi-Fax's own teletext renderer (`TeletextPage`, `TeletextRenderer`), unchanged, into one 240 × 250
bitmap redrawn only when a letter is added. OK goes straight on. Reduce motion shows each page whole at once.
- **After the Dead Channel** (Paul's words, no explanation), for about 2.5 s:
```
ORBI-FAX
P999
SIGNAL RESTORED
TRANSMISSION INTERRUPTED
DO NOT PROCEED TO PAGE 999
RETURN TO INDEX ........ 100
```
- **Before wave 20**: the screen goes black and page 999 appears as in Orbi-Fax: the header, the wizard on the left, and
"YOU AGAIN?", "I TOLD YOU TO TURN BACK.", "NOW YOU'VE BROUGHT A SPACESHIP?" typing out beside him in double height (18
letters a second, then 2.5 s). Then he steps out of the page into the game (1.6 s, growing from page size; he can't attack
or be hit until he's out). Shown once a run: Restart Level goes straight to him.
## The wizard
His art is Orbi-Fax's exactly: `ORBI_FAX_WIZARD` (OrbiFaxArt.kt, generated from design/orbi-fax), 18 × 18 teletext mosaic
cells in the eight teletext colours, rendered once by `TeletextRenderer` into a 108 × 180 bitmap (black made see-through)
and drawn with no smoothing, at the page's 4:3 dot shape. Not redrawn, nothing in Orbi-Fax changed. Friendly and
funny-grumpy; no Ceefax or BBC anything. His name is one string, `WIZARD_TITLE = "The wizard of page 999"`, for Paul to
change ("The Keeper of 999" is an idea, not decided).
**Ending**: beaten, he doesn't explode. The field clears and his words type out under him: "Very well. You may stay. But
don't touch page 1000." (OK skips; 3 s after.) Then the result card: "ORBI-RAIDERS · STORY COMPLETE" and "The Orbit network
is safe. For now." No Orbi-Fax page changes are made here; page 1000 is the Orbi-Fax work's.
## storyComplete, for Orbi-Fax
- Saved in the profile's Arcade file (`filesDir/arcade/<profile>.json`), game `OrbiRaiders`, level progress:
`storyComplete` = `"true"` and `storyCompleteAt` = epoch ms, with `story.done.<Difficulty>` and the checkpoint reset,
all in one save (`ArcadePlay.setLevels`, one `ArcadeStore.update`).
- Read only, through `tv.orbit.classic.ArcadeProgress.isStoryComplete(profileId: String): Boolean`, file
`android/app/src/main/java/tv/orbit/classic/ArcadeProgress.kt` (the same path and package as the Orbi-Fax branch's stub,
so the merge replaces it). It needs `ArcadeProgress.init(context)`, called in `MainActivity.onCreate`.
- "Reset level progress" for Orbi-Raiders clears it; "Clear high scores" doesn't. Local to the TV; nothing is shared
between rooms.
## Performance
The simulation stays in its pools: the last chapter (waves 16-20, the cut-in and the wizard) ran 10,000 ticks with 0 bytes allocated
(24 in one earlier run: JVM noise) and at most 44 sprites at once (limit 60). The pages are redrawn into their bitmap only when a letter
appears; the wizard is one bitmap made once.
## Known gaps
- **Nothing has been seen running** (no installs tonight): the new bosses' drawing, the pages on the TV, his step-out and
the ending are checked by the compiler and tests only.
- No new sounds: the bosses use the existing power-up cues.
- Story is hard for the test bot on Normal and Tricky (see VERIFICATION): it's a simple bot, but the numbers are the place to
start tuning after Paul and his daughter have played it.