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
@@ -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))
}
}
}