Orbi-Raiders: playable prototype (Arcade Stage D)

The Orbi-Raiders card is now a game: pilot select (Ollie, Blaze, Luna, Zip,
each with an Overdrive), waves of Static Sprites, Signal Gremlins, Corrupt
Pixels, Rogue Satellites and Void Broadcasts, The Dead Channel every fifth
wave, six power-ups (one timed at a time), combo scoring, the shared pause
and How to Play, and a result card. Every run is saved per profile however
it ends. Kids-suitable; Kids start on Gentle.

Pure, seeded, pooled simulation on a fixed 60 Hz step (0 bytes allocated
over 10,000 ticks), drawn in code on the Canvas with cached paths and the
cast library's faces. Arcade Settings gains Difficulty, Auto-fire and
Reduce flashing (on by default); ArcadeAudio can pause every cue.

42 new unit tests including pilot balance, determinism and allocation.
Docs: docs/orbi-raiders-prototype.md, docs/VERIFICATION-orbi-raiders.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-08 20:28:29 +00:00
co-authored by Claude Opus 5.5
parent cdc362967c
commit 03cc53c94f
18 changed files with 2641 additions and 16 deletions
@@ -90,6 +90,11 @@ internal class ArcadeAudio(private val context: Context, private val prefs: () -
runCatching { player?.setVolume(level, level); if (player?.isPlaying != true) player?.start() }
}
/** Pause: every cue still sounding stops where it is, and the music too; [resumeAll] carries on. */
fun pauseAll() { runCatching { pool?.autoPause() }; stopMusic() }
fun resumeAll() { if (!released) runCatching { pool?.autoResume() } }
fun stopMusic() { runCatching { if (player?.isPlaying == true) player?.pause() } }
fun release() {
@@ -67,10 +67,13 @@ private val BackPause = Control("Back", "Pause")
/** Every game, in the Arcade's order: the five Orbit Originals, then the eight Classics. */
internal object ArcadeGames {
// Orbit Originals (Stage B frames 01-05). Only BumbleHive is playable in Stage C; the rest are cards for now.
// Orbit Originals (Stage B frames 01-05). BumbleHive and (Stage D) Orbi-Raiders are playable; the rest are cards for now.
// Playable from Stage D (prototype): tv.orbit.classic.arcade.raiders.
val OrbiRaiders: ArcadeGame = GameDef("OrbiRaiders", "Orbi-Raiders", "Keep Orbit on air", "Keep the Orbit signal on air against glitchy invaders.", Mascot.Ollie,
kidsSuitable = true, original = true, launchable = false, ScoreKind.Points, keepsLevels = true, legacyRecordKey = null,
listOf(Control("◀▶", "Move"), Control("OK", "Fire"), Control("Hold OK", "Auto-fire"), Control("▲", "Overdrive"), BackPause), "Keep the Orbit signal on air: each hit costs a bar.")
kidsSuitable = true, original = true, launchable = true, ScoreKind.Points, keepsLevels = true, legacyRecordKey = null,
listOf(Control("◀▶", "Move"), Control("OK", "Fire"), Control("Hold OK", "Auto-fire"), Control("▲", "Overdrive, when the meter is full"), BackPause),
"Keep the Orbit signal on air: each hit costs a bar.",
listOf(GameSetting("sounds", "Sound effects"))) { tv.orbit.classic.arcade.raiders.OrbiRaidersScreen(it) }
val ChannelChaos: ArcadeGame = GameDef("ChannelChaos", "Channel Chaos", "Sort the signals", "Send every signal to its channel before the screens jam.", Mascot.Ollie,
kidsSuitable = true, original = true, launchable = false, ScoreKind.Points, keepsLevels = true, legacyRecordKey = null,
listOf(Control("◀▶▲▼", "Send a signal"), Control("OK", "Bin the static"), BackPause), "Three jammed screens and the run ends.")
@@ -133,7 +133,8 @@ internal fun OrbitArcade(modifier: Modifier, onPlaying: (Boolean) -> Unit, onExi
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)) } } },
onRunEnd = { end -> update { recordRun(it, game.id, game.scoreKind, end, System.currentTimeMillis()) } },
onLeave = { session = SessionState.Exited; playing = null })
onLeave = { session = SessionState.Exited; playing = null },
difficulty = difficultyFor(data, profile.kind), autoFire = autoFireFor(data), reduceFlashing = reduceFlashingFor(data))
key(game.id) { game.Content(play) }
return
}
@@ -182,7 +183,8 @@ internal fun OrbitArcade(modifier: Modifier, onPlaying: (Boolean) -> Unit, onExi
ArcadePage.Play -> GameShelves(visible, data, pick, firstCard, kids = profile.kind == ProfileKind.Kids, onChosen = { chosen = it }, onPlay = ::launch, onMenu = { settingsFor = it })
ArcadePage.HighScores -> HighScoresPage(profile, visible, data, household)
ArcadePage.HowTo -> HowToPage(visible)
ArcadePage.Settings -> ArcadeSettingsPage(profile, data, onChange = { key, on -> update { it.copy(settings = it.settings + (key to on)) } }, onReset = { page = ArcadePage.Reset })
ArcadePage.Settings -> ArcadeSettingsPage(profile, data, onChange = { key, on -> update { it.copy(settings = it.settings + (key to on)) } },
onChoice = { key, value -> update { it.copy(choices = it.choices + (key to value)) } }, onReset = { page = ArcadePage.Reset })
ArcadePage.Reset -> ResetPage(profile, visible, data, onReset = { id, action -> update { applyReset(it, id, action, System.currentTimeMillis()) } })
}
}
@@ -165,11 +165,11 @@ private fun SettingsCard(title: String, icon: String, modifier: Modifier = Modif
}
/**
* Arcade Settings for one profile. Only choices that work today are here (Stage C changes no gameplay, so the frame's
* difficulty, auto-fire and the like wait for the games that use them).
* Arcade Settings for one profile. Only choices that work today are here: Difficulty, Auto-fire and Reduce flashing came
* with Orbi-Raiders (Stage D); the frame's aim help, slower speed, hints and the like wait for games that use them.
*/
@Composable
internal fun ArcadeSettingsPage(profile: Profile, data: ArcadeProfileData, onChange: (String, Boolean) -> Unit, onReset: () -> Unit) {
internal fun ArcadeSettingsPage(profile: Profile, data: ArcadeProfileData, onChange: (String, Boolean) -> Unit, onChoice: (String, String) -> Unit, onReset: () -> Unit) {
val context = LocalContext.current
val settings = remember { OrbitSettings(context) }
val audio = AudioPrefs.of(data.settings)
@@ -194,11 +194,20 @@ internal fun ArcadeSettingsPage(profile: Profile, data: ArcadeProfileData, onCha
}
}
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {
SettingsCard("Gameplay", "🎮") {
val difficulty = difficultyFor(data, profile.kind)
// OK steps through Gentle, Normal and Tricky; all three are shown, the chosen one lit.
DifficultyRow(difficulty) { onChoice("difficulty", Difficulty.entries[(difficulty.ordinal + 1) % Difficulty.entries.size].name) }
val autoFire = autoFireFor(data)
ToggleRow("Auto-fire", autoFire, detail = "The ship fires on its own: no need to hold OK") { onChange("autoFire", !autoFire) }
}
SettingsCard("Accessibility", "?") {
var reduce by remember { mutableStateOf(Motion.reduce) }
ToggleRow("Reduce motion", reduce, detail = "Everywhere in Orbit, not just the Arcade") {
reduce = !reduce; settings.reduceMotion = reduce; Motion.reduce = reduce
}
val calm = reduceFlashingFor(data)
ToggleRow("Reduce flashing", calm, detail = "No flashes of the screen; hits only tint the sprite") { onChange("reduceFlashing", !calm) }
}
SettingsCard("Look", "★") {
var look by remember { mutableStateOf(ArcadeLook.backdrop) }
@@ -209,6 +218,25 @@ internal fun ArcadeSettingsPage(profile: Profile, data: ArcadeProfileData, onCha
}
}
/** Difficulty, as frame 05 draws it: the three choices side by side, the chosen one filled. OK moves to the next. */
@Composable
private fun DifficultyRow(chosen: Difficulty, onNext: () -> Unit) {
var focused by remember { mutableStateOf(false) }
val corner = RoundedCornerShape(6.dp)
Row(Modifier.fillMaxWidth().heightIn(min = 26.dp).onFocusChanged { focused = it.isFocused }.background(if (focused) ArcadeColours.FocusFill else ArcadeColours.Panel.copy(alpha = 0f), corner)
.border(if (focused) 2.dp else 0.dp, if (focused) ArcadeColours.Yellow else ArcadeColours.Panel.copy(alpha = 0f), corner).clickable(onClick = onNext).padding(horizontal = 10.dp, vertical = 3.dp),
verticalAlignment = Alignment.CenterVertically) {
Text("Difficulty", Modifier.weight(1f), color = ArcadeColours.Ink, fontSize = 14.sp)
Row(Modifier.background(ArcadeColours.Night, RoundedCornerShape(10.dp)).padding(2.dp)) {
Difficulty.entries.forEach { d ->
val on = d == chosen
Text(d.title, Modifier.background(if (on) ArcadeColours.Cyan else ArcadeColours.Night, RoundedCornerShape(9.dp)).padding(horizontal = 8.dp, vertical = 1.dp),
color = if (on) ArcadeColours.Night else ArcadeColours.Muted, fontSize = 12.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.Normal)
}
}
}
}
// ---------- Reset Progress (frame 22) ----------
/** What each action would clear, in plain words, or why it can't be used here. */
@@ -25,6 +25,10 @@ internal class ArcadePlay(
private val writeLevel: (String, String) -> Unit,
val onRunEnd: (RunEnd) -> Unit,
val onLeave: () -> Unit,
/** Arcade Settings › Gameplay and Accessibility, for the games that use them (Stage D). */
val difficulty: Difficulty = Difficulty.Normal,
val autoFire: Boolean = false,
val reduceFlashing: Boolean = true,
) {
fun setting(key: String) = readSetting(key)
fun setSetting(key: String, on: Boolean) = writeSetting(key, on)
@@ -48,6 +48,8 @@ internal data class ArcadeProfileData(
val settings: Map<String, Boolean> = emptyMap(),
/** Games by id, most recently played first. */
val recent: List<String> = emptyList(),
/** Arcade-wide choices that aren't on/off (Stage D): "difficulty" is Gentle, Normal or Tricky. */
val choices: Map<String, String> = emptyMap(),
) {
fun game(id: String) = games[id] ?: GameRecord()
fun withGame(id: String, change: (GameRecord) -> GameRecord) = copy(games = games + (id to change(game(id))))
@@ -103,6 +105,7 @@ internal fun encodeArcade(data: ArcadeProfileData): String = JSONObject()
.put("profileId", data.profileId)
.put("settings", JSONObject(data.settings as Map<*, *>))
.put("recent", JSONArray(data.recent))
.put("choices", JSONObject(data.choices as Map<*, *>))
.put("games", JSONObject().also { games ->
data.games.toSortedMap().forEach { (id, g) ->
games.put(id, JSONObject()
@@ -137,7 +140,8 @@ internal fun decodeArcade(text: String, profileId: String): ArcadeProfileData? {
g.optLong("lastPlayed"), resets?.optLong("scores") ?: 0, resets?.optLong("levels") ?: 0, resets?.optLong("settings") ?: 0)
}.toMap()
}.orEmpty()
return ArcadeProfileData(profileId, games, bools(o.optJSONObject("settings")), strings(o.optJSONArray("recent")).take(6))
val choices = o.optJSONObject("choices")?.let { c -> c.keys().asSequence().mapNotNull { k -> (c.opt(k) as? String)?.let { k to it } }.toMap() }.orEmpty()
return ArcadeProfileData(profileId, games, bools(o.optJSONObject("settings")), strings(o.optJSONArray("recent")).take(6), choices)
}
/** A profile id as a file name: letters, digits, '-' and '_' only, and never the household file's name. */
@@ -228,3 +232,18 @@ internal object HouseholdRecords {
}.associateBy { it.key }
}.getOrDefault(emptyMap())
}
// ---------- Gameplay choices (Stage D, frame 05's Gameplay card) ----------
/** How hard a game pushes. Kids start on Gentle; everyone else on Normal, until they choose. */
internal enum class Difficulty(val title: String) { Gentle("Gentle"), Normal("Normal"), Tricky("Tricky") }
internal fun difficultyFor(data: ArcadeProfileData, kind: tv.orbit.classic.ProfileKind?): Difficulty =
data.choices["difficulty"]?.let { v -> Difficulty.entries.firstOrNull { it.name == v } }
?: if (kind == tv.orbit.classic.ProfileKind.Kids) Difficulty.Gentle else Difficulty.Normal
/** Auto-fire assist: the ship fires on its own, no button held. Off until chosen. */
internal fun autoFireFor(data: ArcadeProfileData) = data.settings["autoFire"] ?: false
/** Reduce flashing: on unless turned off. No full-screen flashes; a hit only tints the sprite. */
internal fun reduceFlashingFor(data: ArcadeProfileData) = data.settings["reduceFlashing"] ?: true
@@ -0,0 +1,466 @@
package tv.orbit.classic.arcade.raiders
import android.view.KeyEvent
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
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.drawscope.Stroke
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.tv.material3.Text
import tv.orbit.classic.Anton
import tv.orbit.classic.Motion
import tv.orbit.classic.OrbCharacter
import tv.orbit.classic.OrbDir
import tv.orbit.classic.R
import tv.orbit.classic.arcade.ArcadeButton
import tv.orbit.classic.arcade.ArcadeColours
import tv.orbit.classic.arcade.ArcadeGameLoop
import tv.orbit.classic.arcade.ArcadeGames
import tv.orbit.classic.arcade.ArcadePauseMenu
import tv.orbit.classic.arcade.ArcadePlay
import tv.orbit.classic.arcade.Control
import tv.orbit.classic.arcade.HowToPlayCard
import tv.orbit.classic.arcade.KeyFooter
import tv.orbit.classic.arcade.PauseWhenHidden
import tv.orbit.classic.arcade.arcadeKey
import tv.orbit.classic.arcade.pausesGame
import tv.orbit.classic.drawOrbChaser
import tv.orbit.classic.drawOrbMascot
import kotlin.math.abs
import kotlin.math.sin
/** Where Orbi-Raiders is: choosing a pilot, playing, or a result card (a boss beaten, or the signal lost). */
private enum class Stage { Title, Play, Result }
/**
* The numbers round the field. Each is its own state, read only by the small piece of screen that shows it, so a kill
* redraws the score and nothing else; the field itself redraws every frame from [frame] without recomposing.
*/
private class Hud {
var frame by mutableLongStateOf(0L)
var score by mutableIntStateOf(0)
var multiplier by mutableIntStateOf(1)
var wave by mutableIntStateOf(1)
var bars by mutableIntStateOf(3)
var maxBars by mutableIntStateOf(3)
var meterPct by mutableIntStateOf(0)
var power by mutableStateOf<Power?>(null)
var powerSecs by mutableIntStateOf(0)
var boss by mutableStateOf(false)
var bossPct by mutableIntStateOf(100)
/** Positive: "WAVE n" as a wave comes in; negative: "WAVE n CLEARED"; 0: nothing. */
var banner by mutableIntStateOf(0)
fun read(sim: RaidersSim) {
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
banner = when { sim.phase == Phase.Cleared -> -sim.wave; sim.formY < -10f && !sim.bossOn -> sim.wave; else -> 0 }
}
}
private fun overdriveSound(p: Pilot) = when (p.overdrive) {
Overdrive.WideOrbit -> R.raw.power_wide_orbit
Overdrive.BlazeRun -> R.raw.power_blaze_run
Overdrive.DoubleLuna -> R.raw.power_double_luna
Overdrive.ZipSplit -> R.raw.power_zip_split
}
/**
* Orbi-Raiders (Arcade Stage D, prototype). Frames 10-13 of Stage B: choose a pilot, keep the Orbit signal on air against
* the waves, the Dead Channel every fifth wave, and the shared pause menu and How to Play. Every run is saved when it ends.
*/
@Composable
internal fun OrbiRaidersScreen(play: ArcadePlay) {
val game = ArcadeGames.OrbiRaiders
val latestPlay by rememberUpdatedState(play)
val calm = Motion.reduce
var stage by remember { mutableStateOf(Stage.Title) }
var pilot by remember { mutableStateOf(play.level["pilot"]?.let { n -> Pilot.entries.firstOrNull { it.name == n } } ?: Pilot.Ollie) }
val sim = remember { RaidersSim(pilot, play.difficulty, seed = 1, bursts = !calm) }
val controls = remember { RaidersControls(play.autoFire) }
val input = remember { RaidersInput() }
val stepper = remember { FixedStep() }
val hud = remember { Hud() }
var paused by remember { mutableStateOf(false) }
var soundsOn by remember { mutableStateOf(play.setting("sounds")) }
var bestBefore by remember { mutableIntStateOf(play.best) }
// 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) }
val book = remember {
RaidersRunBook({ end -> bestSeen = maxOf(bestSeen, end.score); latestPlay.onRunEnd(end) }, { wave -> latestPlay.setLevel("bestWave", wave.toString()) }, play.level["bestWave"]?.toIntOrNull() ?: 0)
}
val density = LocalDensity.current
val measurer = rememberTextMeasurer()
val art = remember(density) { RaidersArt(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) } }
fun startRun() {
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))
controls.autoFire = p.autoFire
controls.release(); stepper.reset(); hud.read(sim)
book.begin()
paused = false; stage = Stage.Play
}
fun pause() { if (stage == Stage.Play && !paused) { paused = true; controls.release(); stepper.reset(); play.audio.pauseAll() } }
fun resume() { paused = false; controls.release(); stepper.reset(); play.audio.resumeAll() }
fun leave() { book.end(sim, finished = sim.over); latestPlay.onLeave() }
PauseWhenHidden(alive = stage == Stage.Play && !paused) { pause() }
// The loop runs only in play: paused, or on a result card, nothing moves and no time is counted.
ArcadeGameLoop(running = stage == Stage.Play && !paused) { _, dt ->
val n = stepper.ticks(dt, paused)
for (i in 0 until n) { controls.fill(input); sim.step(input) }
val ev = sim.takeEvents()
if (ev != 0) {
val audio = latestPlay.audio
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)
}
hud.read(sim)
if (sim.over) { book.end(sim, finished = true); stage = Stage.Result }
else if (sim.phase == Phase.Checkpoint) stage = Stage.Result
}
val playFocus = remember { FocusRequester() }
LaunchedEffect(stage, paused) { if (stage == Stage.Play && !paused) runCatching { playFocus.requestFocus() } }
BackHandler(enabled = stage == Stage.Play && !paused) { pause() }
when (stage) {
Stage.Title -> {
TitleScreen(pilot, play.best, book.bestWave, play.difficulty.title, refocus = !howTo, onPilot = { pilot = it; latestPlay.setLevel("pilot", it.name) },
onPlay = ::startRun, onHowTo = { howTo = true }, onBack = { latestPlay.onLeave() })
if (howTo) HowToPlayCard(game, firstRun = false, everyTime = null, onEveryTime = {}, onPlay = { howTo = false }, onBack = { howTo = false })
}
Stage.Play, Stage.Result -> {
Box(Modifier.fillMaxSize().focusRequester(playFocus).focusable().onPreviewKeyEvent { e ->
if (stage != Stage.Play || paused) return@onPreviewKeyEvent false
val n = e.nativeKeyEvent
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 }
controls.key(key, down, n.repeatCount)
}) {
PlayScreen(art, 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() },
onBack = ::leave)
}
if (paused && stage == Stage.Play) ArcadePauseMenu(game, "Orbi-Raiders · Wave ${sim.wave} · ${"%,d".format(sim.score)}",
onResume = ::resume, onRestart = { sim.restartWave(); hud.read(sim); resume() }, onExit = ::leave,
sound = if (soundsOn) "Effects on" else "Effects off", onSound = { soundsOn = !soundsOn; latestPlay.setSetting("sounds", soundsOn) })
}
}
}
// ---------- 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) {
val cards = remember { Pilot.entries.associateWith { FocusRequester() } }
val playButton = remember { FocusRequester() }
// On opening, and again when How to Play closes.
LaunchedEffect(refocus) { if (refocus) runCatching { cards.getValue(chosen).requestFocus() } }
BackHandler(onBack = onBack)
Box(Modifier.fillMaxSize().background(ArcadeColours.Night)) {
StarField()
Column(Modifier.fillMaxSize().padding(start = 48.dp, end = 48.dp, top = 22.dp, bottom = 12.dp)) {
Row(Modifier.fillMaxWidth().height(150.dp), verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally) {
Text("AN ORBIT ARCADE ORIGINAL", color = ArcadeColours.Muted, fontSize = 13.sp, letterSpacing = 5.sp)
Box(contentAlignment = Alignment.Center) {
// The orange orbit runs wholly behind the word (Stage B refinement).
Canvas(Modifier.width(470.dp).height(100.dp)) {
drawOval(Color(0xFFFF8A3D), Offset(size.width * .02f, size.height * .12f), Size(size.width * .96f, size.height * .8f), style = Stroke(5.dp.toPx()))
drawCircle(Color(0xFFFF8A3D), 8.dp.toPx(), Offset(size.width * .95f, size.height * .3f))
}
Text("ORBI-RAIDERS", color = ArcadeColours.Ink, fontFamily = Anton, fontSize = 64.sp,
style = androidx.compose.ui.text.TextStyle(shadow = androidx.compose.ui.graphics.Shadow(ArcadeColours.Pink, Offset(4f, 5f), 0f)))
}
}
Row(verticalAlignment = Alignment.CenterVertically) {
Text("Choose your\npilot, crew!", Modifier.background(ArcadeColours.Ink, RoundedCornerShape(12.dp)).padding(horizontal = 12.dp, vertical = 6.dp),
color = ArcadeColours.Night, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, textAlign = TextAlign.Center)
Canvas(Modifier.size(70.dp)) { drawOrbMascot(center, size.minDimension * .3f) }
}
}
Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text("Choose your pilot", color = ArcadeColours.Ink, fontSize = 16.sp, fontWeight = FontWeight.SemiBold)
Text("Each ship flies a little differently", color = ArcadeColours.Muted, fontSize = 14.sp)
Spacer(Modifier.weight(1f))
Text(difficulty, Modifier.background(ArcadeColours.Cyan, RoundedCornerShape(10.dp)).padding(horizontal = 8.dp), color = ArcadeColours.Night, fontSize = 12.sp, fontWeight = FontWeight.Bold)
}
Spacer(Modifier.height(8.dp))
Row(Modifier.fillMaxWidth().height(206.dp), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Row(Modifier.weight(1f).fillMaxHeight(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Pilot.entries.forEach { p ->
PilotCard(p, Modifier.weight(1f).fillMaxHeight().focusRequester(cards.getValue(p)).onPreviewKeyEvent { e ->
// ▼ goes to the menu, as the footer says.
if (e.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { if (e.nativeKeyEvent.action == KeyEvent.ACTION_DOWN) runCatching { playButton.requestFocus() }; true } else false
}, onFocus = { onPilot(p) }, onPlay = { onPilot(p); onPlay() })
}
}
Column(Modifier.width(190.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
ArcadeButton("Play", Modifier.fillMaxWidth().focusRequester(playButton), icon = "▶", primary = true, height = 34.dp, onClick = onPlay)
ArcadeButton("How to Play", Modifier.fillMaxWidth(), icon = "?", height = 34.dp, onClick = onHowTo)
ArcadeButton("Back to Arcade", Modifier.fillMaxWidth(), icon = "←", height = 34.dp, onClick = onBack)
}
}
Spacer(Modifier.height(10.dp))
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
Row { Text("Your best ", color = ArcadeColours.Muted, fontSize = 14.sp); Text(if (best > 0) "%,d".format(best) else "—", color = ArcadeColours.Ink, fontSize = 14.sp, fontWeight = FontWeight.Bold) }
Row { Text("Best wave ", color = ArcadeColours.Muted, fontSize = 14.sp); Text(if (bestWave > 0) "$bestWave" else "—", color = ArcadeColours.Ink, fontSize = 14.sp, fontWeight = FontWeight.Bold) }
Text("🔒 No Household record: Orbi-Raiders is new since profiles", color = ArcadeColours.Muted, fontSize = 13.sp)
}
Spacer(Modifier.weight(1f))
KeyFooter(listOf(Control("◀▶", "Choose a pilot"), Control("▼", "Menu"), Control("OK", "Play"), Control("Back", "Arcade home")))
}
}
}
@Composable
private fun PilotCard(p: Pilot, modifier: Modifier, onFocus: () -> Unit, onPlay: () -> Unit) {
var focused by remember { mutableStateOf(false) }
val corner = RoundedCornerShape(10.dp)
val colour = RaidersColours.pilot(p)
Column(modifier.onFocusChanged { focused = it.isFocused; if (it.isFocused) onFocus() }.clip(corner)
.background(if (focused) ArcadeColours.FocusFill else ArcadeColours.PanelDeep, corner)
.border(if (focused) 3.dp else 1.dp, if (focused) ArcadeColours.Yellow else ArcadeColours.Line, corner).clickable(onClick = onPlay).padding(10.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text("LIVES", color = ArcadeColours.Muted, fontSize = 11.sp, letterSpacing = 2.sp)
Spacer(Modifier.weight(1f))
SignalBars(p.bars, 3, Modifier.size(28.dp, 16.dp))
}
Canvas(Modifier.fillMaxWidth().weight(1f)) {
val r = size.minDimension * .44f
drawCircle(Color.White.copy(alpha = .08f), r, center)
// The pilot's rocket, big, as on the frame; the face from the cast library.
val k = size.minDimension / 40f
val c = center
drawPath(androidx.compose.ui.graphics.Path().apply {
moveTo(c.x, c.y - 16 * k); cubicTo(c.x + 7 * k, c.y - 10 * k, c.x + 7 * k, c.y + 4 * k, c.x + 5 * k, c.y + 10 * k)
lineTo(c.x - 5 * k, c.y + 10 * k); cubicTo(c.x - 7 * k, c.y + 4 * k, c.x - 7 * k, c.y - 10 * k, c.x, c.y - 16 * k); close()
}, ArcadeColours.Ink)
for (side in floatArrayOf(-1f, 1f)) drawPath(androidx.compose.ui.graphics.Path().apply {
moveTo(c.x + side * 5 * k, c.y); lineTo(c.x + side * 13 * k, c.y + 8 * k); lineTo(c.x + side * 13 * k, c.y + 11 * k); lineTo(c.x + side * 5 * k, c.y + 8 * k); close()
}, colour)
drawCircle(Color(0xFFFFC23D), 2.4f * k, c + Offset(-1.8f * k, 13 * k)); drawCircle(Color(0xFFFFC23D), 2.4f * k, c + Offset(1.8f * k, 13 * k))
drawCircle(Color(0xFF14213D), 5 * k, c + Offset(0f, -3 * k))
when (p) {
Pilot.Ollie -> drawOrbMascot(c + Offset(0f, -3 * k), 2.6f * k, OrbDir.Down)
Pilot.Blaze -> drawOrbChaser(c + Offset(0f, -3 * k), 3.6f * k, OrbCharacter.Blaze, OrbDir.Down, false, false, false, 0f)
Pilot.Luna -> drawOrbChaser(c + Offset(0f, -3 * k), 3.6f * k, OrbCharacter.Luna, OrbDir.Down, false, false, false, 0f)
Pilot.Zip -> drawOrbChaser(c + Offset(0f, -3 * k), 3.6f * k, OrbCharacter.Zip, OrbDir.Down, false, false, false, 0f)
}
}
Text(p.title.uppercase(), color = colour, fontFamily = Anton, fontSize = 24.sp)
Text(p.line, color = ArcadeColours.Ink, fontSize = 13.sp, lineHeight = 15.sp, maxLines = 2)
}
}
@Composable
private fun SignalBars(bars: Int, max: Int, modifier: Modifier) = Canvas(modifier) {
val w = size.width / (max * 1.5f)
for (i in 0 until max) {
val h = size.height * (.45f + .55f * i / (max - 1).coerceAtLeast(1))
drawRoundRect(if (i < bars) ArcadeColours.Cyan else Color(0xFF2A3A62), Offset(i * w * 1.5f, size.height - h), Size(w, h), CornerRadius(w * .25f))
}
}
@Composable
private fun StarField() = Canvas(Modifier.fillMaxSize()) {
val r = java.util.Random(23)
repeat(80) { drawCircle(Color.White.copy(alpha = .2f + r.nextFloat() * .5f), .7f + r.nextFloat() * 1.3f, Offset(r.nextFloat() * size.width, r.nextFloat() * size.height)) }
}
// ---------- Play (frames 11 and 12) ----------
@Composable
private fun PlayScreen(art: RaidersArt, 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)) {
LeftHud(hud, Modifier.width(120.dp).fillMaxHeight())
Box(Modifier.weight(1f).fillMaxHeight().clip(RoundedCornerShape(14.dp)).border(2.dp, ArcadeColours.Line, RoundedCornerShape(14.dp))) {
val start = remember { System.nanoTime() }
Canvas(Modifier.fillMaxSize()) {
hud.frame // redraw every frame, without recomposing
drawRaidersField(art, sim, (System.nanoTime() - start) / 1e9f, calm, reduceFlashing)
}
FieldWords(hud, Modifier.fillMaxSize())
}
RightHud(art, sim, hud, Modifier.width(124.dp).fillMaxHeight())
}
Spacer(Modifier.height(6.dp))
KeyFooter(listOf(Control("◀▶", "Move"), Control("OK", "Fire"), Control("Hold OK", "Auto-fire"), Control("▲", "Overdrive"), Control("Back", "Pause")))
}
}
}
@Composable
private fun HudLabel(text: String) = Text(text, color = ArcadeColours.Muted, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp)
@Composable
private fun LeftHud(hud: Hud, modifier: Modifier) {
Column(modifier.padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) {
HudLabel("SCORE")
Text("%,d".format(hud.score), color = ArcadeColours.Ink, fontFamily = Anton, fontSize = 30.sp)
val m = hud.multiplier
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Text("×$m", Modifier.background(if (m > 1) ArcadeColours.Pink else ArcadeColours.PanelDeep, RoundedCornerShape(12.dp)).padding(horizontal = 10.dp),
color = ArcadeColours.Ink, fontFamily = Anton, fontSize = 18.sp)
Text("combo", color = ArcadeColours.Muted, fontSize = 13.sp)
}
Spacer(Modifier.height(10.dp))
HudLabel("WAVE")
Text(if (hud.boss) "BOSS" else "${hud.wave}", color = ArcadeColours.Ink, fontFamily = Anton, fontSize = 30.sp)
Spacer(Modifier.height(10.dp))
HudLabel("SIGNAL")
SignalBars(hud.bars, hud.maxBars, Modifier.size(52.dp, 36.dp))
Text(when (hud.bars) { 1 -> "1 bar left"; else -> "${hud.bars} bars left" }, color = ArcadeColours.Muted, fontSize = 13.sp)
}
}
/** Words over the field: the boss's name and health, and the wave coming in or cleared. */
@Composable
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)
Spacer(Modifier.weight(1f))
Text("${hud.bossPct}%", color = ArcadeColours.Muted, fontSize = 12.sp)
}
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)
Text("ORBIT SIGNAL", Modifier.align(Alignment.BottomCenter).padding(start = 140.dp, bottom = 2.dp), color = ArcadeColours.Muted, fontSize = 11.sp, letterSpacing = 3.sp)
}
}
@Composable
private fun RightHud(art: RaidersArt, sim: RaidersSim, hud: Hud, modifier: Modifier) {
Column(modifier.padding(top = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp)) {
HudLabel("OVERDRIVE")
// The pilot's face in an orange ring, then the meter filling up.
Canvas(Modifier.size(40.dp)) {
drawCircle(Color(0xFF14213D), size.minDimension / 2)
drawCircle(Color(0xFFFF8A3D), size.minDimension / 2, style = Stroke(2.dp.toPx()))
drawImage(art.faces[sim.pilot.ordinal], androidx.compose.ui.unit.IntOffset.Zero, androidx.compose.ui.unit.IntSize(96, 96),
androidx.compose.ui.unit.IntOffset((size.width * .1f).toInt(), (size.height * .1f).toInt()), androidx.compose.ui.unit.IntSize((size.width * .8f).toInt(), (size.height * .8f).toInt()))
}
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Text("${hud.meterPct}%", color = ArcadeColours.Ink, fontSize = 13.sp)
Canvas(Modifier.size(18.dp, 120.dp)) {
val full = hud.meterPct / 100f
drawRoundRect(Color(0xFF0C1F4A), cornerRadius = CornerRadius(size.width / 2))
drawRoundRect(Color(0xFF2A3A62), cornerRadius = CornerRadius(size.width / 2), style = Stroke(1.dp.toPx()))
if (full > 0f) drawRoundRect(if (full >= 1f) ArcadeColours.Yellow else Color(0xFFFF6A2B), Offset(0f, size.height * (1 - full)), Size(size.width, size.height * full), CornerRadius(size.width / 2))
}
}
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
tv.orbit.classic.arcade.KeyCap("▲")
Text(if (hud.meterPct >= 100) "now!" else "when full", color = if (hud.meterPct >= 100) ArcadeColours.Yellow else ArcadeColours.Muted, fontSize = 13.sp)
}
Spacer(Modifier.height(8.dp))
HudLabel("POWER-UP")
PowerBadge(art, sim, hud)
}
}
/** The timed power-up on now: its badge with a ring for the time left, and its name and seconds in words (not colour alone). */
@Composable
private fun PowerBadge(art: RaidersArt, sim: RaidersSim, hud: Hud) {
val p = hud.power
Canvas(Modifier.size(56.dp)) {
hud.frame
val r = size.minDimension / 2
drawCircle(Color(0xFF2A3A62), r * .92f, style = Stroke(3.dp.toPx()))
val now = sim.power ?: return@Canvas
drawArc(RaidersColours.power(now), -90f, 360f * (sim.powerLeft / now.seconds).coerceIn(0f, 1f), false, Offset(size.width / 2 - r * .92f, size.height / 2 - r * .92f),
Size(r * 1.84f, r * 1.84f), style = Stroke(3.dp.toPx()))
with(art) { badge(now, size.width / 2, size.height / 2, r * .6f) }
}
if (p != null) {
Text(p.title, color = ArcadeColours.Ink, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, textAlign = TextAlign.Center)
Text("${hud.powerSecs} s left", color = RaidersColours.power(p), fontSize = 13.sp)
} else Text(if (sim.pilot == Pilot.Luna && sim.shieldIn > 0f) "Luna's shield regrowing" else "None yet", color = ArcadeColours.Muted, fontSize = 12.sp, textAlign = TextAlign.Center)
}
// ---------- Result (frame 13) ----------
@Composable
private fun ResultCard(sim: RaidersSim, bestBefore: Int, onNext: () -> Unit, onRetry: () -> Unit, onBack: () -> Unit) {
val first = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { first.requestFocus() } }
BackHandler(onBack = onBack)
val cleared = !sim.over
val newRecord = sim.score > bestBefore && sim.score > 0
val calm = Motion.reduce
Box(Modifier.fillMaxSize().background(ArcadeColours.Night.copy(alpha = .82f)), contentAlignment = Alignment.Center) {
Row(verticalAlignment = Alignment.CenterVertically) {
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)
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)
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)
ArcadeButton("Back to Arcade", Modifier.width(160.dp), icon = "←", height = 34.dp, onClick = onBack)
}
}
if (newRecord) Cheer(OrbCharacter.Zip, calm, 1.3f)
}
KeyFooter(listOf(Control("◀▶", "Choose"), Control("OK", "Select"), Control("Back", "Arcade home")), Modifier.align(Alignment.BottomStart).padding(start = 24.dp, end = 24.dp, bottom = 10.dp))
}
}
/** Blaze or Zip cheering a new record, eyes up and bouncing; still under Reduce motion. The cast as drawn everywhere else. */
@Composable
private fun Cheer(who: OrbCharacter, calm: Boolean, offset: Float) {
var t by remember { mutableLongStateOf(0L) }
LaunchedEffect(calm) { if (!calm) { val start = withFrameMillis { it }; while (true) withFrameMillis { t = it - start } } }
Canvas(Modifier.size(110.dp, 140.dp)) {
val r = size.width * .32f
val hop = if (calm) 0f else abs(sin(t / 260.0 + offset)).toFloat() * r * .45f
val c = Offset(size.width / 2, size.height * .55f - hop)
drawOrbChaser(c, r, who, OrbDir.Up, false, false, false, t / 140f, lookAt = Offset(0f, -1f))
for (k in 0..2) drawCircle(Color(0xFFFFE066).copy(alpha = .8f), r * .08f, Offset(size.width * (.2f + .3f * k), size.height * (.12f + .06f * (k % 2))))
}
}
@@ -0,0 +1,323 @@
package tv.orbit.classic.arcade.raiders
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.ImageBitmap
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.CanvasDrawScope
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.LayoutDirection
import androidx.compose.ui.unit.sp
import tv.orbit.classic.OrbCharacter
import tv.orbit.classic.OrbDir
import tv.orbit.classic.arcade.hexPath
import tv.orbit.classic.drawOrbChaser
import tv.orbit.classic.drawOrbMascot
import tv.orbit.classic.starPath
import kotlin.math.sin
/**
* Orbi-Raiders' drawing. Everything is drawn in code on the Canvas, like the other games: no bitmaps from disk. The
* shapes are built once here (paths, strokes, the "999" on the Dead Channel's dial), so a frame of play draws without
* allocating. The pilots' faces come from the cast library unchanged ([drawOrbMascot], [drawOrbChaser]), drawn once into
* small bitmaps at the start, because the cast functions build little lists as they draw.
*/
internal object RaidersColours {
val Field = Color(0xFF070F2E)
val FieldEdge = Color(0xFF3D63B8)
val Navy = Color(0xFF14213D)
val Ink = Color(0xFFF4F6FB)
val Static = Color(0xFFB9C2D6)
val StaticDark = Color(0xFF7D879E)
val Gremlin = Color(0xFF5BD46A)
val Satellite = Color(0xFFC3CAD9)
val Panel = Color(0xFF4C7DFF)
val Pixel = Color(0xFFFF4FA3)
val Void = Color(0xFF6C4BD8)
val Signal = Color(0xFF35D6F2)
val EnemyShot = Color(0xFF5BD46A)
val Flame = Color(0xFFFFC23D)
val Warn = Color(0xFFFFDE59)
val Crt = Color(0xFF5A6278)
val CrtDark = Color(0xFF3E4458)
fun pilot(p: Pilot) = when (p) {
Pilot.Ollie -> Color(0xFFF7A928)
Pilot.Blaze -> OrbCharacter.Blaze.colour
Pilot.Luna -> OrbCharacter.Luna.colour
Pilot.Zip -> OrbCharacter.Zip.colour
}
fun power(p: Power) = when (p) {
Power.SignalShield -> Color(0xFF35D6F2)
Power.TurboTuner -> Color(0xFFFF8A3D)
Power.RewindBurst -> Color(0xFFA77BFF)
Power.DoubleBroadcast -> Color(0xFFFF4FA3)
Power.GuideBomb -> Color(0xFF5BD46A)
Power.OrbitOverdrive -> Color(0xFFFF6A2B)
}
val sparks = arrayOf(Static, Gremlin, Satellite, Pixel, Pixel, Color(0xFFA77BFF), Static, Warn)
}
/** The cast's faces, drawn once into bitmaps from the cast library, for the ships and the HUD. */
internal fun pilotFace(p: Pilot, px: Int, density: Density): ImageBitmap {
val image = ImageBitmap(px, px)
CanvasDrawScope().draw(density, LayoutDirection.Ltr, androidx.compose.ui.graphics.Canvas(image), Size(px.toFloat(), px.toFloat())) {
val c = Offset(px / 2f, px / 2f); val r = px * .3f
when (p) {
Pilot.Ollie -> drawOrbMascot(c, r, OrbDir.Up)
Pilot.Blaze -> drawOrbChaser(c, r * 1.1f, OrbCharacter.Blaze, OrbDir.Up, false, false, false, 0f)
Pilot.Luna -> drawOrbChaser(c, r * 1.1f, OrbCharacter.Luna, OrbDir.Up, false, false, false, 0f)
Pilot.Zip -> drawOrbChaser(c, r * 1.1f, OrbCharacter.Zip, OrbDir.Up, false, false, false, 0f)
}
}
return image
}
internal class RaidersArt(density: Density, measurer: TextMeasurer) {
val faces = Pilot.entries.map { pilotFace(it, 96, density) }.toTypedArray()
private val faceSize = IntSize(96, 96)
private val thin = Stroke(1f)
private val mid = Stroke(1.6f, cap = StrokeCap.Round)
private val thick = Stroke(2.4f, cap = StrokeCap.Round)
private val ring = Stroke(3f)
/** The rocket, nose up, centred on (0, 0). */
private val body = Path().apply { moveTo(0f, -16f); cubicTo(7f, -10f, 7f, 4f, 5f, 10f); lineTo(-5f, 10f); cubicTo(-7f, 4f, -7f, -10f, 0f, -16f); close() }
private val nose = Path().apply { moveTo(0f, -16f); cubicTo(3.6f, -13f, 5f, -11f, 5.6f, -9f); lineTo(-5.6f, -9f); cubicTo(-5f, -11f, -3.6f, -13f, 0f, -16f); close() }
private val finL = Path().apply { moveTo(-5f, 0f); lineTo(-13f, 8f); lineTo(-13f, 11f); lineTo(-5f, 8f); close() }
private val finR = Path().apply { moveTo(5f, 0f); lineTo(13f, 8f); lineTo(13f, 11f); lineTo(5f, 8f); close() }
private val flame = Path().apply { moveTo(-3f, 10f); quadraticTo(0f, 22f, 3f, 10f); close() }
private val bolt = Path().apply { moveTo(3f, -10f); lineTo(-6f, 1f); lineTo(-1f, 1f); lineTo(-4f, 10f); lineTo(6f, -2f); lineTo(1f, -2f); close() }
private val zig = Path().apply { moveTo(-2f, -5f); lineTo(2f, -2f); lineTo(-2f, 1f); lineTo(2f, 4f) }
// Power-up badges, built at radius 1 and scaled.
private val hex = hexPath(Offset.Zero, 1f)
private val shield = Path().apply { moveTo(0f, -.55f); lineTo(.42f, -.38f); quadraticTo(.42f, .25f, 0f, .58f); quadraticTo(-.42f, .25f, -.42f, -.38f); close() }
private val rewind = Path().apply { moveTo(-.05f, 0f); lineTo(.4f, -.35f); lineTo(.4f, .35f); close(); moveTo(-.45f, 0f); lineTo(0f, -.35f); lineTo(0f, .35f); close() }
private val bolts = Path().apply { for (dx in floatArrayOf(-.2f, .2f)) { moveTo(dx + .12f, -.5f); lineTo(dx - .14f, .02f); lineTo(dx + .04f, .02f); lineTo(dx - .1f, .5f); lineTo(dx + .16f, -.06f); lineTo(dx - .02f, -.06f); close() } }
private val star = starPath(Offset.Zero, .36f, .16f, 0f)
private val badgeStroke = Stroke(.12f, cap = StrokeCap.Round)
private val badgeEdge = Stroke(.1f)
/** The Dead Channel's dial: a faint 999, measured once. */
val nines: TextLayoutResult = measurer.measure("999", TextStyle(fontSize = 13.sp, fontWeight = FontWeight.Bold), density = density)
private val nineScale = 14f / nines.size.height.coerceAtLeast(1)
fun DrawScope.ship(p: Pilot, x: Float, y: Float, alpha: Float, tint: Boolean, flicker: Float) {
val colour = RaidersColours.pilot(p)
translate(x, y) {
drawPath(flame, RaidersColours.Flame, alpha = alpha * (.8f + .2f * flicker))
drawPath(finL, colour, alpha = alpha); drawPath(finR, colour, alpha = alpha)
drawPath(body, if (tint) Color(0xFFFFB3B3) else RaidersColours.Ink, alpha = alpha)
drawPath(nose, colour, alpha = alpha)
drawCircle(RaidersColours.Navy, 4.6f, Offset(0f, -3f), alpha = alpha)
drawImage(faces[p.ordinal], IntOffset.Zero, faceSize, IntOffset(-4, -7), IntSize(8, 8), alpha = alpha)
}
}
fun DrawScope.shieldBubble(x: Float, y: Float, alpha: Float) {
drawCircle(RaidersColours.Signal, 17f, Offset(x, y - 2f), alpha = .18f * alpha)
drawCircle(RaidersColours.Signal, 17f, Offset(x, y - 2f), alpha = .8f * alpha, style = mid)
}
fun DrawScope.eyes(x: Float, y: Float, r: Float, look: Float) {
drawCircle(Color.White, r, Offset(x - r * 1.3f, y)); drawCircle(Color.White, r, Offset(x + r * 1.3f, y))
drawCircle(RaidersColours.Navy, r * .5f, Offset(x - r * 1.3f + look * r * .3f, y + r * .2f)); drawCircle(RaidersColours.Navy, r * .5f, Offset(x + r * 1.3f + look * r * .3f, y + r * .2f))
}
/** One invader. [wobble] is time, for the still-or-moving bits (none of it flashes). */
fun DrawScope.enemy(e: Enemy, wobble: Float, calm: Boolean) {
val tinted = e.tint > 0f
val a = e.alpha()
val w = if (calm) 0f else sin(wobble * 3f + e.phase)
translate(e.x, e.y) {
when (e.kind) {
Kind.STATIC, Kind.MINION -> {
val s = if (e.kind == Kind.MINION) .8f else 1f
scale(s, s, Offset.Zero) {
// A fuzzy ball of static.
for (k in 0 until 8) { val ang = k * .785f + w * .1f; drawCircle(RaidersColours.StaticDark, 3f, Offset(kotlin.math.cos(ang) * 7f, sin(ang) * 7f)) }
drawCircle(if (tinted) Color.White else RaidersColours.Static, 7.5f, Offset.Zero)
drawCircle(RaidersColours.StaticDark, 1f, Offset(-3f, 4f)); drawCircle(RaidersColours.StaticDark, 1f, Offset(2f, 5f)); drawCircle(RaidersColours.StaticDark, .8f, Offset(4f, 2f))
eyes(0f, -1.5f, 2.2f, 0f)
}
}
Kind.GREMLIN -> {
drawPath(bolt, if (tinted) Color.White else RaidersColours.Gremlin)
eyes(0f, -1f, 1.9f, if (e.diving) 1f else 0f)
drawPath(zig, RaidersColours.Gremlin, alpha = .7f, style = thin)
}
Kind.SATELLITE -> {
// Solar panels dim as its armour goes.
val armour = .45f + .55f * (e.hp / 3f)
drawRect(RaidersColours.Panel, Offset(-15f, -4f), Size(6f, 8f), alpha = armour)
drawRect(RaidersColours.Panel, Offset(9f, -4f), Size(6f, 8f), alpha = armour)
drawLine(RaidersColours.StaticDark, Offset(-9f, 0f), Offset(9f, 0f), 1.2f)
drawRoundRect(if (tinted) Color.White else RaidersColours.Satellite, Offset(-8f, -6f), Size(16f, 12f), CornerRadius(3f))
drawLine(RaidersColours.StaticDark, Offset(2f, -6f), Offset(4f, -11f), 1f)
drawCircle(Color(0xFFFF6B6B), 1.4f, Offset(4f, -11f))
eyes(0f, -1f, 2f, 0f)
}
Kind.PIXEL, Kind.PIXEL_SMALL -> {
val h = if (e.kind == Kind.PIXEL) 8f else 4.5f
drawRect(if (tinted) Color.White else RaidersColours.Pixel, Offset(-h, -h), Size(h * 2, h * 2))
drawRect(RaidersColours.Pixel, Offset(h * .7f, -h * 1.35f), Size(h * .5f, h * .5f))
drawRect(Color.White.copy(alpha = .35f), Offset(-h * .8f, -h * .8f), Size(h * .5f, h * .5f))
eyes(0f, -h * .1f, h * .24f, 0f)
}
Kind.VOID -> {
// A purple set that fades in and out: dimmer means it can't be hit.
drawLine(RaidersColours.Void, Offset(-3f, -7f), Offset(-6f, -12f), 1.2f, alpha = a)
drawLine(RaidersColours.Void, Offset(3f, -7f), Offset(6f, -12f), 1.2f, alpha = a)
drawRoundRect(if (tinted) Color.White else RaidersColours.Void, Offset(-10f, -7f), Size(20f, 15f), CornerRadius(3f), alpha = a)
drawRoundRect(RaidersColours.Navy, Offset(-7f, -4.5f), Size(14f, 9f), CornerRadius(2f), alpha = a)
drawCircle(Color.White, 1.4f, Offset(-2.6f, -.8f), alpha = a); drawCircle(Color.White, 1.4f, Offset(2.6f, -.8f), alpha = a)
}
}
}
}
fun DrawScope.shot(s: Shot, colour: Color) = drawRoundRect(colour, Offset(s.x - s.halfW * .6f, s.y - 6f), Size(s.halfW * 1.2f, 12f), CornerRadius(1.5f))
fun DrawScope.enemyShot(s: Shot) = translate(s.x, s.y) { drawPath(zig, RaidersColours.EnemyShot, style = mid) }
/** A power-up's hexagon badge, with its own colour and symbol (the word is always beside it in the HUD). */
fun DrawScope.badge(p: Power, x: Float, y: Float, r: Float, alpha: Float = 1f) {
val colour = RaidersColours.power(p)
translate(x, y) {
scale(r, r, Offset.Zero) {
if (p == Power.OrbitOverdrive) drawOval(colour, Offset(-1.5f, -.45f), Size(3f, .9f), alpha = alpha, style = badgeStroke)
drawPath(hex, colour, alpha = alpha)
drawPath(hex, Color.White, alpha = .35f * alpha, style = badgeEdge)
val ink = Color.White
when (p) {
Power.SignalShield -> drawPath(shield, ink, alpha = alpha)
Power.TurboTuner -> { drawArc(ink, 160f, 220f, false, Offset(-.45f, -.45f), Size(.9f, .9f), alpha = alpha, style = badgeStroke); drawLine(ink, Offset.Zero, Offset(.25f, -.25f), .12f, StrokeCap.Round, alpha = alpha) }
Power.RewindBurst -> drawPath(rewind, ink, alpha = alpha)
Power.DoubleBroadcast -> drawPath(bolts, ink, alpha = alpha)
Power.GuideBomb -> for (i in -1..1) for (j in -1..1) drawRect(ink, Offset(i * .24f - .08f, j * .24f - .08f), Size(.16f, .16f), alpha = alpha)
Power.OrbitOverdrive -> { drawCircle(ink, .45f, Offset.Zero, alpha = alpha, style = badgeStroke); drawPath(star, ink, alpha = alpha) }
}
}
}
}
/**
* The Dead Channel (frame 12): an old CRT set showing a test card with a big grin, a faint 999 on its dial. Playful,
* not scary. [warn] is how far through an attack's warning it is (the antennas light up); still under Reduce motion.
*/
fun DrawScope.boss(x: Float, y: Float, attack: Int, warn: Float, tinted: Boolean, time: Float, calm: Boolean) {
translate(x, y) {
val glow = if (warn > 0f) 1f else if (calm) .35f else .3f + .1f * sin(time * 2f)
drawCircle(Color(0xFF6C4BD8), 70f, Offset.Zero, alpha = .14f * glow + .04f)
// Antennas, tips lit while it warns of the next attack.
drawLine(RaidersColours.Static, Offset(-14f, -42f), Offset(-32f, -66f), 2f)
drawLine(RaidersColours.Static, Offset(14f, -42f), Offset(30f, -68f), 2f)
val tip = if (warn > 0f && attack != 1) RaidersColours.Warn else Color(0xFFA77BFF)
drawCircle(tip, 4f, Offset(-32f, -66f)); drawCircle(tip, 4f, Offset(30f, -68f))
// Cabinet, legs and the static under it.
drawRoundRect(RaidersColours.CrtDark, Offset(-34f, 36f), Size(8f, 8f), CornerRadius(2f)); drawRoundRect(RaidersColours.CrtDark, Offset(26f, 36f), Size(8f, 8f), CornerRadius(2f))
drawRoundRect(if (tinted) Color(0xFF8A93A8) else RaidersColours.Crt, Offset(-58f, -42f), Size(116f, 82f), CornerRadius(10f))
drawRoundRect(RaidersColours.CrtDark, Offset(-50f, -35f), Size(76f, 66f), CornerRadius(8f))
// The test card: grey bars, then the grinning face.
for (i in 0 until 6) drawRect(Color(0xFFE6E8EE).copy(alpha = 1f - i * .12f), Offset(-47f + i * 11.8f, -32f), Size(11.8f, 60f))
drawCircle(Color(0xFFF2F3F7), 21f, Offset(-12f, -2f))
drawLine(Color(0xFFB9C2D6), Offset(-33f, -2f), Offset(9f, -2f), .8f); drawLine(Color(0xFFB9C2D6), Offset(-12f, -23f), Offset(-12f, 19f), .8f)
drawCircle(RaidersColours.Navy, 5f, Offset(-20f, -7f)); drawCircle(RaidersColours.Navy, 5f, Offset(-4f, -7f))
drawCircle(Color.White, 1.6f, Offset(-21.5f, -8.5f)); drawCircle(Color.White, 1.6f, Offset(-5.5f, -8.5f))
drawArc(RaidersColours.Navy, 20f, 140f, true, Offset(-27f, -6f), Size(30f, 20f))
drawArc(Color.White, 25f, 130f, true, Offset(-24.5f, -4.5f), Size(25f, 14f))
for (k in 0 until 5) drawLine(RaidersColours.Navy, Offset(-21f + k * 4.5f, 3f), Offset(-21f + k * 4.5f, 8.5f), .7f)
// The dial panel, with a faint 999.
drawRoundRect(Color(0xFF2B1C24), Offset(30f, -32f), Size(22f, 14f), CornerRadius(2f))
translate(31f, -32f) { scale(nineScale, nineScale, Offset.Zero) { drawText(nines, Color(0xFFFF6B6B), alpha = .55f) } }
drawCircle(RaidersColours.CrtDark, 7f, Offset(41f, 2f)); drawLine(RaidersColours.Static, Offset(41f, 2f), Offset(41f, -4f), 1.6f)
drawCircle(RaidersColours.CrtDark, 6f, Offset(41f, 24f)); drawLine(RaidersColours.Static, Offset(37f, 24f), Offset(45f, 24f), 1.6f)
translate(-30f, 50f) { drawPath(zig, RaidersColours.Static, style = thin) }
translate(30f, 50f) { drawPath(zig, RaidersColours.Static, style = thin) }
}
}
/** The beam's column: outlined while it warns, filled while it's on. Never a flash: a steady soft band. */
fun DrawScope.beam(x: Float, warn: Boolean, on: Boolean) {
if (warn) drawRect(RaidersColours.Warn, Offset(x - 12f, 120f), Size(24f, FIELD_H - 120f), alpha = .7f, style = thin)
if (on) {
drawRect(Color.White, Offset(x - 12f, 120f), Size(24f, FIELD_H - 120f), alpha = .28f)
for (i in 0 until 4) drawRect(RaidersColours.Static, Offset(x - 12f + i * 6f, 120f), Size(3f, FIELD_H - 120f), alpha = .35f)
}
}
/** The Orbit signal along the bottom: a dome with a bar for each life left. */
fun DrawScope.signal(bars: Int, max: Int) {
val cx = FIELD_W / 2
drawLine(RaidersColours.FieldEdge, Offset(0f, FIELD_H - 6f), Offset(FIELD_W, FIELD_H - 6f), .8f, alpha = .7f)
drawArc(Color(0xFF1C2E66), 180f, 180f, true, Offset(cx - 26f, FIELD_H - 26f), Size(52f, 40f))
for (i in 0 until max) {
val h = 5f + i * 4f
drawRoundRect(if (i < bars) RaidersColours.Signal else Color(0xFF2A3A62), Offset(cx - 9f + i * 7f, FIELD_H - 8f - h), Size(5f, h), CornerRadius(1.2f))
}
}
fun DrawScope.ringSweep(x: Float, y: Float, r: Float) = drawCircle(Color(0xFFF7A928), r, Offset(x, y), alpha = .8f, style = ring)
fun DrawScope.spark(s: Spark) = drawCircle(RaidersColours.sparks[s.colour.coerceIn(0, RaidersColours.sparks.size - 1)], 1.6f, Offset(s.x, s.y), alpha = (s.life / .45f).coerceIn(0f, 1f))
}
/** 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) {
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
// Screen shake: none at all under Reduce motion.
val shakeX = if (calm || sim.shake <= 0f) 0f else sin(time * 70f) * sim.shake * 6f * k
drawRect(RaidersColours.Field)
translate(ox + shakeX, oy) {
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)
signal(sim.bars, sim.maxBars)
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)
// 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))
drawRoundRect(Color(0xFFFF4FA3), Offset(80f, 6f), Size((FIELD_W - 160f) * frac, 5f), CornerRadius(2.5f))
}
for (e in sim.enemies) if (e.active) enemy(e, time, calm)
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.sparks) if (s.active) spark(s)
if (sim.ringR > 0f) ringSweep(sim.shipX, SHIP_Y, sim.ringR)
if (!sim.over) {
// Safe after a hit: steady see-through with Reduce flashing on, a gentle blink with it off.
val safe = sim.safe > 0f
val alpha = when { !safe -> 1f; reduceFlashing || calm -> .5f; else -> if (sin(time * 20f) > 0f) .9f else .35f }
ship(sim.pilot, sim.shipX, SHIP_Y, alpha, tint = sim.hitFlash > 0f, flicker = if (calm) 1f else sin(time * 30f))
if (sim.power == Power.SignalShield || sim.odShield || sim.lunaShield) shieldBubble(sim.shipX, SHIP_Y, if (sim.power == Power.SignalShield || sim.odShield) 1f else .6f)
}
}
}
// The one full-screen effect, a soft flash when the ship loses a bar: only with Reduce flashing off.
if (!reduceFlashing && !calm && sim.hitFlash > 0f) drawRect(Color.White, alpha = .18f * sim.hitFlash / .15f)
}
@@ -0,0 +1,66 @@
package tv.orbit.classic.arcade.raiders
import tv.orbit.classic.arcade.ArcadeKey
import tv.orbit.classic.arcade.RepeatGuard
import tv.orbit.classic.arcade.RunEnd
import tv.orbit.classic.arcade.RunTracker
/**
* The remote in play, screen-free so it's tested. Left and right are held to move (the ship speeds up while held). OK
* fires: one press is one shot, and holding it keeps firing at the pilot's fixed rate; the remote's own repeats of a held
* OK never add shots, because [RepeatGuard] lets each press act once and the hold is followed by down and up alone. ▲ is
* one Overdrive per press, guarded the same way. With Auto-fire on, the ship fires without OK.
*/
internal class RaidersControls(var autoFire: Boolean = false) {
private val guard = RepeatGuard(setOf(ArcadeKey.Ok, ArcadeKey.Up))
private var left = false
private var right = false
private var okHeld = false
private var pressed = false
private var overdrive = false
/** A key in play; true when the game used it. Back isn't handled here (it pauses, through the screen). */
fun key(key: ArcadeKey, down: Boolean, repeatCount: Int): Boolean = when (key) {
ArcadeKey.Left -> { left = down; true }
ArcadeKey.Right -> { right = down; true }
ArcadeKey.Ok -> {
if (guard.accept(key, down, repeatCount)) pressed = true
okHeld = down
true
}
ArcadeKey.Up -> { if (guard.accept(key, down, repeatCount)) overdrive = true; true }
ArcadeKey.Down -> true
else -> false
}
/** Fills this tick's input: presses are used once, held keys stay until they're let go. */
fun fill(input: RaidersInput) {
input.move = (if (right) 1 else 0) - (if (left) 1 else 0)
input.fire = autoFire || okHeld || pressed
input.overdrive = overdrive
pressed = false; overdrive = false
}
/** Paused, or the window lost the remote: a release may never come, so nothing stays held. */
fun release() { left = false; right = false; okHeld = false; pressed = false; overdrive = false; guard.reset() }
}
/** What a run reports when it ends. */
internal fun raidersRunEnd(sim: RaidersSim, finished: Boolean) = RunEnd(sim.score, finished, "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
* going away (sleep timer, profile switch). It also keeps the best wave reached, as the game's level progress.
*/
internal class RaidersRunBook(report: (RunEnd) -> Unit, private val saveBestWave: (Int) -> Unit, var bestWave: Int) {
private val tracker = RunTracker(report)
val open get() = tracker.open
fun begin() = tracker.begin()
fun end(sim: RaidersSim, finished: Boolean) {
if (!tracker.open) return
if (sim.wave > bestWave) { bestWave = sim.wave; saveBestWave(sim.wave) }
tracker.end(raidersRunEnd(sim, finished))
}
}
@@ -0,0 +1,809 @@
package tv.orbit.classic.arcade.raiders
import tv.orbit.classic.arcade.Difficulty
import kotlin.math.abs
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt
/**
* Orbi-Raiders (Arcade Stage D prototype, 8 November 2026): the game's rules, with no drawing and no Android in them, so
* every rule is tested on the PC. Built from Stage B frames 10-13 and the power-up sheet.
*
* It runs on a fixed step ([STEP] seconds, [FixedStep]) apart from the screen's frames, and it never allocates once it has
* started: enemies, shots, falling power-ups and sparks all live in pools made up front, and a full pool simply skips the
* spawn. Waves come from a seeded generator, so the same seed always gives the same game.
*/
/** The world the game is played in, in its own units; the screen scales it to fit. */
internal const val FIELD_W = 420f
internal const val FIELD_H = 300f
/** One simulation tick: 60 a second, whatever the screen's frame rate. */
internal const val STEP = 1f / 60f
internal const val SHIP_Y = FIELD_H - 34f
internal const val SHOT_SPEED = 380f
/** How far Ollie's Wide Orbit ring reaches from the ship. */
internal const val RING_REACH = 220f
/** The Orbit signal along the bottom: an invader that gets this low costs a bar. */
internal const val SIGNAL_Y = FIELD_H - 18f
// Pool sizes. Together they cap what can be on screen at once: 64 + 40 + 32 + 4 + the boss = 141 sprites, under 150.
internal const val MAX_ENEMIES = 64
internal const val MAX_SHOTS = 40
internal const val MAX_ENEMY_SHOTS = 32
internal const val MAX_DROPS = 4
internal const val MAX_SPARKS = 40
internal const val MAX_SPRITES = MAX_ENEMIES + MAX_SHOTS + MAX_ENEMY_SHOTS + MAX_DROPS + 1
/** The invaders (proposal decisions): kinds as numbers, so the pools hold no objects that change type. */
internal object Kind {
const val STATIC = 0 // Static Sprites: the basic invader
const val GREMLIN = 1 // Signal Gremlins: zigzag dives
const val SATELLITE = 2 // Rogue Satellites: armoured, three hits
const val PIXEL = 3 // Corrupt Pixels: split into two small ones when hit
const val PIXEL_SMALL = 4
const val VOID = 5 // Void Broadcasts: fade in and out, only hittable while showing
const val MINION = 6 // The Dead Channel's little static sprites
const val COUNT = 7
val hp = intArrayOf(1, 1, 3, 1, 1, 2, 1)
val points = intArrayOf(10, 20, 30, 15, 5, 40, 10)
val radius = floatArrayOf(9f, 9f, 10f, 9f, 5f, 9f, 7f)
val names = arrayOf("Static Sprite", "Signal Gremlin", "Rogue Satellite", "Corrupt Pixel", "Pixel bit", "Void Broadcast", "Static Sprite")
}
private const val M_FORM = 0
private const val M_DIVE = 1
private const val M_RETURN = 2
private const val M_FREE = 3
internal class Enemy {
var active = false
var kind = 0
var hp = 0
var x = 0f
var y = 0f
var slotX = 0f
var slotY = 0f
var mode = M_FORM
var t = 0f
var diveX = 0f
/** Seconds of the white hit tint left (drawn as a tint on the sprite only, never a flash of the screen). */
var tint = 0f
var phase = 0f
/** Already caught by this Wide Orbit ring. */
var ringHit = false
val diving get() = mode == M_DIVE
/** Void Broadcasts fade in and out; they can be hit only while they're showing. */
fun alpha(): Float = if (kind != Kind.VOID) 1f else .5f + .5f * sin(t * 1.5f + phase)
fun hittable() = kind != Kind.VOID || alpha() > .45f
}
internal class Shot {
var active = false
var x = 0f
var y = 0f
var vx = 0f
var vy = 0f
var halfW = 3f
var pierce = 0
/** The enemy (pool index) this shot last went through, so a piercing shot can't hit it twice. */
var last = -1
}
internal class Drop {
var active = false
var x = 0f
var y = 0f
var power = Power.SignalShield
}
internal class Spark {
var active = false
var x = 0f
var y = 0f
var vx = 0f
var vy = 0f
var life = 0f
var colour = 0
}
/** The six power-ups (Stage B power-up sheet, timings from the approved proposal). Four are timed and only one of those is ever on. */
internal enum class Power(val title: String, val line: String, val seconds: Float, val weight: Int) {
SignalShield("Signal Shield", "Soaks up one hit", 8f, 22),
TurboTuner("Turbo Tuner", "Faster ship", 8f, 18),
RewindBurst("Rewind Burst", "Pushes the wave back up", 3f, 14),
DoubleBroadcast("Double Broadcast", "Two shots", 10f, 22),
GuideBomb("Guide Bomb", "Clears the weak invaders", 0f, 12),
OrbitOverdrive("Orbit Overdrive", "Fills Overdrive", 0f, 12);
val timed get() = seconds > 0f
}
/** Each pilot's Overdrive, fired with ▲ when the meter is full. */
internal enum class Overdrive(val title: String, val seconds: Float) {
WideOrbit("Wide Orbit", 1.1f), BlazeRun("Blaze Run", 3f), DoubleLuna("Double Luna", 3.5f), ZipSplit("Zip Split", 2.2f)
}
/**
* The four pilots (frame 10). Balanced against each other at Normal by [RaidersBalanceTest]: what one gains, it pays for.
* [fireGap] is seconds between shots, [shotHalfW] half a shot's width, [shieldEvery] how often Luna's shield regrows (0: never).
*/
internal enum class Pilot(val title: String, val line: String, val speed: Float, val fireGap: Float, val shotHalfW: Float, val pierce: Int, val bars: Int,
val shieldEvery: Float, val overdrive: Overdrive) {
Ollie("Ollie", "Balanced", 1f, .22f, 3f, 0, 3, 0f, Overdrive.WideOrbit),
Blaze("Blaze", "Fast, narrow shot", 1.2f, .22f, 2.2f, 0, 3, 0f, Overdrive.BlazeRun),
Luna("Luna", "Shield regrows, slower fire", 1f, .25f, 3f, 0, 3, 50f, Overdrive.DoubleLuna),
Zip("Zip", "Shots pierce, one less life", 1f, .23f, 3f, 1, 2, 0f, Overdrive.ZipSplit),
}
/** How hard the invaders push (Arcade Settings › Difficulty; Kids start on Gentle). */
internal class Tuning(
/** Multiplies how often the invaders shoot. */
val fire: Float,
val shotSpeed: Float,
/** Multiplies how often the Gremlins dive. */
val dives: Float,
/** How fast the formation sways, units a second. */
val sway: Float,
/** The chance a fallen invader drops a power-up. */
val dropChance: Float,
val bossHp: Int,
/** How long the boss warns before each attack. */
val warn: Float,
/** Seconds the ship can't be hit after losing a bar. */
val safe: Float,
/** Fewer rows of invaders. */
val rowsLess: Int,
) {
companion object {
val Gentle = Tuning(.5f, 70f, .55f, 12f, .11f, 45, 1.4f, 2.2f, 1)
val Normal = Tuning(1f, 92f, 1f, 16f, .075f, 60, 1.0f, 1.6f, 0)
val Tricky = Tuning(1.45f, 118f, 1.4f, 22f, .055f, 80, .75f, 1.2f, 0)
fun of(d: Difficulty) = when (d) { Difficulty.Gentle -> Gentle; Difficulty.Normal -> Normal; Difficulty.Tricky -> Tricky }
}
}
/** A small seeded generator (xorshift), so a wave is the same every time for the same seed, and nothing is allocated. */
internal class SeededRandom(seed: Int) {
private var s = if (seed == 0) 0x2545F491 else seed
fun reseed(seed: Int) { s = if (seed == 0) 0x2545F491 else seed }
fun nextInt(): Int { var x = s; x = x xor (x shl 13); x = x xor (x ushr 17); x = x xor (x shl 5); s = x; return x }
fun nextInt(n: Int): Int = ((nextInt().toLong() and 0x7fffffffL) % n).toInt()
fun nextFloat(): Float = (nextInt() ushr 8) / 16777216f
}
/** What the remote is asking for this tick. [fire] is held or pressed; [overdrive] is one press of ▲. */
internal class RaidersInput {
var move = 0
var fire = false
var overdrive = false
fun clear() { move = 0; fire = false; overdrive = false }
}
/** Bits set during a tick for the screen's sounds; read and cleared by the screen. */
internal object Events {
const val KILL = 1
const val HIT = 2
const val SHIELDED = 4
const val POWER = 8
const val OVERDRIVE = 16
const val WAVE_CLEAR = 32
const val BOSS_DOWN = 64
const val GAME_OVER = 128
const val SHOT = 256
}
/** Where a wave stands. */
internal enum class Phase { Playing, Cleared, Checkpoint, Over }
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. */
var bursts: Boolean = true) {
var tuning = Tuning.of(difficulty)
private set
var difficulty = difficulty
private set
val enemies = Array(MAX_ENEMIES) { Enemy() }
val shots = Array(MAX_SHOTS) { Shot() }
val enemyShots = Array(MAX_ENEMY_SHOTS) { Shot() }
val drops = Array(MAX_DROPS) { Drop() }
val sparks = Array(MAX_SPARKS) { Spark() }
private val rng = SeededRandom(seed)
private val kinds = IntArray(Kind.COUNT)
// The ship.
var shipX = FIELD_W / 2; private set
var shipVx = 0f; private set
private var fireIn = 0f
var bars = 3; private set
var maxBars = 3; private set
/** Seconds the ship can't be hit (after losing a bar). */
var safe = 0f; private set
var lunaShield = false; private set
private var lunaIn = 0f
/** Double Luna's own shield. */
var odShield = false; private set
// Score.
var score = 0; private set
var streak = 0; private set
val multiplier get() = when { streak >= 50 -> 4; streak >= 25 -> 3; streak >= 10 -> 2; else -> 1 }
// Overdrive.
var meter = 0f; private set
var odLeft = 0f; private set
var odTotal = 0f; private set
var ringR = -1f; private set
private var volleyIn = 0f
// The one timed power-up.
var power: Power? = null; private set
var powerLeft = 0f; private set
// The wave.
var wave = 1; private set
var phase = Phase.Playing; private set
private var phaseT = 0f
private var formX = 0f
var formY = 0f; private set
private var formDir = 1f
private var entering = true
private var enemyFireIn = 1.5f
private var diveIn = 3f
private var waveScore = 0
private var waveBars = 3
private var waveMeter = 0f
// The Dead Channel.
var bossOn = false; private set
var bossHp = 0; private set
var bossMax = 1; private set
var bossX = FIELD_W / 2; private set
val bossY = 80f
private var bossVx = 26f
/** 0 static rain, 1 the test-card beam, 2 two little sprites. */
var bossAttack = 0; private set
var bossWarn = 0f; private set
private var bossNext = 2f
var beamX = 0f; private set
var beamOn = 0f; private set
var bossTint = 0f; private set
/** Shake left, for the screen (it draws none under Reduce motion). */
var shake = 0f; private set
/** A ship hit, for the screen's one optional soft flash (off with Reduce flashing). */
var hitFlash = 0f; private set
var events = 0
var clock = 0f; private set
/** Total damage done, for the balance tests. */
var damage = 0; private set
var ticks = 0L; private set
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
/** 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)
init { newRun(pilot, difficulty, seed) }
// ---------- runs and waves ----------
fun newRun(pilot: Pilot = this.pilot, difficulty: Difficulty = this.difficulty, seed: Int = this.seed) {
this.pilot = pilot; this.difficulty = difficulty; this.tuning = Tuning.of(difficulty); this.seed = seed
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)
}
private fun clearAll() {
for (e in enemies) e.active = false
for (s in shots) s.active = false
for (s in enemyShots) s.active = false
for (d in drops) d.active = false
for (s in sparks) s.active = false
power = null; powerLeft = 0f; odLeft = 0f; ringR = -1f; odShield = false
bossOn = false; beamOn = 0f; bossWarn = 0f
}
private fun startWave(n: Int) {
clearAll()
wave = n; phase = Phase.Playing; phaseT = 0f
waveScore = score; waveBars = bars; waveMeter = meter
shipX = FIELD_W / 2; shipVx = 0f; safe = 1f; fireIn = 0f; shake = 0f
formX = 0f; formY = -130f; formDir = 1f; entering = true
// 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)
}
/** Restart Level from the pause menu: this wave again, from how things stood when it began. */
fun restartWave() {
score = waveScore; bars = waveBars; meter = waveMeter; streak = 0
startWave(wave)
}
/** Next Wave from a boss's result card. */
fun continueRun() { if (phase == Phase.Checkpoint) startWave(wave + 1) }
/** The rows of a wave: which kinds may appear depends on how far in the run it is. */
private fun layoutWave(n: Int) {
var count = 0
kinds[count++] = Kind.STATIC
if (n >= 2) kinds[count++] = Kind.GREMLIN
if (n >= 3) kinds[count++] = Kind.PIXEL
if (n >= 4) kinds[count++] = Kind.SATELLITE
if (n >= 6) kinds[count++] = Kind.VOID
val rows = (2 + (n - 1) / 2 - tuning.rowsLess).coerceIn(2, 5)
val cols = (5 + n / 2).coerceAtMost(8)
val dx = 38f; val dy = 30f
val left = FIELD_W / 2 - (cols - 1) * dx / 2
for (r in 0 until rows) {
// The top row is the toughest kind available; the rest are drawn from the wave's kinds.
val kind = if (r == 0 && n >= 4) Kind.SATELLITE else kinds[rng.nextInt(count)]
for (c in 0 until cols) spawn(kind, left + c * dx, 34f + r * dy, M_FORM)
}
}
private fun spawn(kind: Int, slotX: Float, slotY: Float, mode: Int): Enemy? {
for (e in enemies) if (!e.active) {
e.active = true; e.kind = kind; e.hp = Kind.hp[kind]; e.slotX = slotX; e.slotY = slotY; e.mode = mode
e.x = slotX + formX; e.y = slotY + formY; e.t = 0f; e.tint = 0f; e.phase = rng.nextFloat() * 6.283f; e.ringHit = false
return e
}
return null
}
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
entering = false; formY = 0f
}
// ---------- the tick ----------
fun step(input: RaidersInput) {
if (phase == Phase.Over || phase == Phase.Checkpoint) return
ticks++
val dt = STEP
clock += dt
if (shake > 0f) shake = maxOf(0f, shake - dt)
if (hitFlash > 0f) hitFlash = maxOf(0f, hitFlash - dt)
moveShip(input, dt)
firing(input, dt)
overdrive(input, dt)
timers(dt)
val edt = dt * slow
moveFormation(edt)
moveEnemies(edt)
if (bossOn) moveBoss(edt)
enemyFire(edt)
moveShots(dt, edt)
moveDrops(dt)
moveSparks(dt)
if (phase == Phase.Playing && livingEnemies() == 0 && !bossOn) {
phase = Phase.Cleared; phaseT = 0f
score += 100 * wave
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) }
}
}
private fun moveShip(input: RaidersInput, dt: Float) {
val blazeRun = odLeft > 0f && pilot.overdrive == Overdrive.BlazeRun
if (blazeRun) {
// Blaze dashes from side to side on his own, firing all the way.
val p = 1f - odLeft / odTotal
shipX = FIELD_W / 2 + sin(p * 6.283f * 1.5f) * (FIELD_W / 2 - 24f); shipVx = 0f
return
}
val top = 190f * pilot.speed * (if (power == Power.TurboTuner) 1.45f else 1f)
val accel = 1500f
val v = shipVx
shipVx = when {
input.move == 0 -> if (v > 0) maxOf(0f, v - 2200f * dt) else minOf(0f, v + 2200f * dt)
// Turning round is quicker than setting off, so it never feels like ice.
input.move * v < 0 -> v + input.move * accel * 2.4f * dt
else -> v + input.move * accel * dt
}.coerceIn(-top, top)
shipX += shipVx * dt
if (shipX < 16f) { shipX = 16f; shipVx = 0f }
if (shipX > FIELD_W - 16f) { shipX = FIELD_W - 16f; shipVx = 0f }
}
private fun firing(input: RaidersInput, dt: Float) {
fireIn -= dt
val blazeRun = odLeft > 0f && pilot.overdrive == Overdrive.BlazeRun
if (!(input.fire || blazeRun) || fireIn > 0f || phase != Phase.Playing) return
fireIn = pilot.fireGap / (if (blazeRun) 4f else 1f)
if (power == Power.DoubleBroadcast) { shoot(shipX - 5f, 0f); shoot(shipX + 5f, 0f) } else shoot(shipX, 0f)
events = events or Events.SHOT
}
private fun shoot(x: Float, vx: Float) {
for (s in shots) if (!s.active) {
s.active = true; s.x = x; s.y = SHIP_Y - 12f; s.vx = vx; s.vy = -SHOT_SPEED; s.halfW = pilot.shotHalfW; s.pierce = pilot.pierce; s.last = -1
return
}
}
private fun overdrive(input: RaidersInput, dt: Float) {
if (input.overdrive && meter >= 1f && odLeft <= 0f && phase == Phase.Playing) {
meter = 0f; odTotal = pilot.overdrive.seconds; odLeft = odTotal
events = events or Events.OVERDRIVE
when (pilot.overdrive) {
Overdrive.WideOrbit -> { ringR = 0f; for (e in enemies) e.ringHit = false }
Overdrive.DoubleLuna -> odShield = true
Overdrive.ZipSplit -> volleyIn = 0f
Overdrive.BlazeRun -> {}
}
}
if (odLeft <= 0f) return
odLeft = maxOf(0f, odLeft - dt)
when (pilot.overdrive) {
Overdrive.WideOrbit -> {
// A ring sweeps out from the ship: one hit on everything it passes, a big one on the boss.
val before = ringR
ringR = (1f - odLeft / odTotal) * RING_REACH
for (i in enemies.indices) {
val e = enemies[i]
if (!e.active || e.ringHit) continue
val d = dist(e.x, e.y, shipX, SHIP_Y)
if (d <= ringR) { e.ringHit = true; hitEnemy(i, 1) }
}
// It also sweeps away the invaders' shots it passes.
for (sh in enemyShots) if (sh.active && dist(sh.x, sh.y, shipX, SHIP_Y) <= ringR) sh.active = false
if (bossOn && before < dist(bossX, bossY, shipX, SHIP_Y) - 40f && ringR >= dist(bossX, bossY, shipX, SHIP_Y) - 40f) hitBoss(6)
if (odLeft <= 0f) ringR = -1f
}
Overdrive.ZipSplit -> {
volleyIn -= dt
if (volleyIn <= 0f) {
volleyIn = .24f
for (k in -2..2) shoot(shipX + k * 2f, k * 70f)
}
}
else -> {}
}
}
private fun timers(dt: Float) {
if (safe > 0f) safe = maxOf(0f, safe - dt)
if (power != null) {
powerLeft -= dt
if (powerLeft <= 0f) { power = null; powerLeft = 0f }
}
if (pilot.shieldEvery > 0f && !lunaShield) {
lunaIn -= dt
if (lunaIn <= 0f) { lunaShield = true; lunaIn = pilot.shieldEvery }
}
if (odLeft <= 0f) odShield = false
if (bossTint > 0f) bossTint = maxOf(0f, bossTint - dt)
}
private fun moveFormation(dt: Float) {
if (bossOn) return
if (entering) {
formY += 110f * dt
if (formY >= 0f) { formY = 0f; entering = false }
return
}
// Rewind Burst pushes the whole wave back up.
if (power == Power.RewindBurst) formY = maxOf(-40f, formY - 22f * dt)
var minX = Float.MAX_VALUE; var maxX = -Float.MAX_VALUE; var lowest = -Float.MAX_VALUE
for (e in enemies) if (e.active && e.mode == M_FORM) {
if (e.slotX < minX) minX = e.slotX
if (e.slotX > maxX) maxX = e.slotX
if (e.slotY > lowest) lowest = e.slotY
}
if (minX == Float.MAX_VALUE) return
formX += formVx * dt
if (minX + formX < 18f && formDir < 0) { formDir = 1f; formY += 7f }
if (maxX + formX > FIELD_W - 18f && formDir > 0) { formDir = -1f; formY += 7f }
// Reaching the Orbit signal costs a bar, and the wave is pushed back up.
if (lowest + formY > SIGNAL_Y - 40f) { hurt(); formY -= 60f }
}
private fun moveEnemies(dt: Float) {
diveIn -= dt
if (diveIn <= 0f) {
diveIn = (3.4f - minOf(wave, 10) * .12f) / tuning.dives
startDive()
}
for (i in enemies.indices) {
val e = enemies[i]
if (!e.active) continue
e.t += dt
if (e.tint > 0f) e.tint = maxOf(0f, e.tint - dt)
when (e.mode) {
M_FORM -> { e.x = e.slotX + formX; e.y = e.slotY + formY }
M_DIVE -> {
// Zigzag down, drifting towards where the ship is.
e.y += (62f + wave * 2f) * tuning.dives.coerceAtMost(1.2f) * dt
e.diveX += (shipX - e.diveX) * .35f * dt
e.x = (e.diveX + sin(e.t * 4.5f) * 30f).coerceIn(10f, FIELD_W - 10f)
if (e.y > FIELD_H + 14f) { e.mode = M_RETURN; e.y = -16f }
}
M_RETURN -> {
val tx = e.slotX + formX; val ty = e.slotY + formY
val d = dist(e.x, e.y, tx, ty)
if (d < 3f) { e.mode = M_FORM } else { val k = minOf(1f, 150f * dt / d); e.x += (tx - e.x) * k; e.y += (ty - e.y) * k }
}
M_FREE -> {
e.y += 20f * dt
e.x = (e.slotX + sin(e.t * 1.3f + e.phase) * 26f).coerceIn(10f, FIELD_W - 10f)
if (e.y > SIGNAL_Y - 30f) e.active = false
}
}
// A diving invader that reaches the ship hits it.
if (e.active && e.mode != M_FORM && abs(e.x - shipX) < Kind.radius[e.kind] + 9f && abs(e.y - SHIP_Y) < Kind.radius[e.kind] + 8f) {
e.active = false
hurt()
}
}
}
private fun startDive() {
if (bossOn) return
// A Gremlin from the formation, chosen by the wave's generator.
var n = 0
for (e in enemies) if (e.active && e.mode == M_FORM && e.kind == Kind.GREMLIN) n++
if (n == 0) return
var pick = rng.nextInt(n)
for (e in enemies) if (e.active && e.mode == M_FORM && e.kind == Kind.GREMLIN) {
if (pick-- == 0) { e.mode = M_DIVE; e.t = 0f; e.diveX = e.x; return }
}
}
private fun moveBoss(dt: Float) {
bossX += bossVx * dt
if (bossX < 90f) { bossX = 90f; bossVx = abs(bossVx) }
if (bossX > FIELD_W - 90f) { bossX = FIELD_W - 90f; bossVx = -abs(bossVx) }
if (beamOn > 0f) {
beamOn = maxOf(0f, beamOn - dt)
if (abs(shipX - beamX) < 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)
}
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
}
}
private fun enemyFire(dt: Float) {
if (phase != Phase.Playing) return
enemyFireIn -= dt
if (enemyFireIn > 0f) return
val rate = tuning.fire * (1f + (wave - 1) * .07f) * (if (power == Power.RewindBurst) .35f else 1f)
enemyFireIn = 1.35f / rate
var n = 0
for (e in enemies) if (e.active && e.y > 0f && e.hittable()) n++
if (n == 0) return
var pick = rng.nextInt(n)
for (e in enemies) if (e.active && e.y > 0f && e.hittable()) {
if (pick-- == 0) {
// Satellites aim a little; the rest drop straight down.
val vx = if (e.kind == Kind.SATELLITE) ((shipX - e.x) / (SHIP_Y - e.y).coerceAtLeast(40f)).coerceIn(-.4f, .4f) * tuning.shotSpeed else 0f
enemyShot(e.x, e.y + 8f, vx, tuning.shotSpeed)
return
}
}
}
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 moveShots(dt: Float, edt: Float) {
for (s in shots) {
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 }
for (i in enemies.indices) {
val e = enemies[i]
if (!e.active || i == s.last || !e.hittable()) continue
val r = Kind.radius[e.kind]
if (abs(s.x - e.x) < r + s.halfW && abs(s.y - e.y) < r + 4f) {
hitEnemy(i, 1)
if (s.pierce > 0) { s.pierce--; s.last = i } else { s.active = false }
break
}
}
}
for (s in enemyShots) {
if (!s.active) continue
s.x += s.vx * edt; s.y += s.vy * edt
if (s.y > FIELD_H + 6f) { s.active = false; continue }
if (abs(s.x - shipX) < 9f && abs(s.y - SHIP_Y) < 10f) { s.active = false; hurt() }
}
}
private fun moveDrops(dt: Float) {
for (d in drops) {
if (!d.active) continue
d.y += 55f * dt
if (abs(d.x - shipX) < 17f && abs(d.y - SHIP_Y) < 15f) { d.active = false; collect(d.power) }
else if (d.y > FIELD_H + 10f) d.active = false
}
}
private fun moveSparks(dt: Float) {
for (s in sparks) {
if (!s.active) continue
s.life -= dt
if (s.life <= 0f) { s.active = false; continue }
s.x += s.vx * dt; s.y += s.vy * dt
}
}
// ---------- hits ----------
internal fun hitEnemy(i: Int, dmg: Int) {
val e = enemies[i]
e.hp -= dmg; e.tint = .12f
damage += dmg
if (e.kind == Kind.SATELLITE && e.hp > 0) { score += 5 * multiplier; return }
if (e.hp > 0) return
kill(e)
}
private fun kill(e: Enemy) {
e.active = false
streak++
score += Kind.points[e.kind] * multiplier
meter = minOf(1f, meter + if (e.kind == Kind.PIXEL_SMALL) .015f else .045f)
events = events or Events.KILL
if (bursts) burst(e.x, e.y, e.kind)
// A Corrupt Pixel splits into two small ones beside where it was.
// Its place in the pool is free now and may be reused by the first half, so read it all first.
val kind = e.kind; val x = e.x; val y = e.y; val slotX = e.slotX; val slotY = e.slotY
val mode = if (e.mode == M_FORM) M_FORM else M_RETURN
if (kind == Kind.PIXEL) {
spawn(Kind.PIXEL_SMALL, slotX - 8f, slotY, mode)?.let { it.x = x - 8f; it.y = y }
spawn(Kind.PIXEL_SMALL, slotX + 8f, slotY, mode)?.let { it.x = x + 8f; it.y = y }
}
if (kind != Kind.PIXEL_SMALL && rng.nextFloat() < tuning.dropChance) dropPower(x, y)
}
private fun hitBoss(dmg: Int) {
bossHp -= dmg; bossTint = .12f; damage += dmg
score += 5 * multiplier
meter = minOf(1f, meter + .006f * dmg)
if (bossHp <= 0) {
bossOn = false; bossHp = 0; beamOn = 0f; bossWarn = 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 (bursts) burst(bossX, bossY, Kind.COUNT)
}
}
/** The ship is hit: a shield takes it if there is one, otherwise a bar of signal goes and the combo starts again. */
internal fun hurt() {
if (safe > 0f || phase != Phase.Playing) return
if (odLeft > 0f && pilot.overdrive == Overdrive.BlazeRun) return
when {
power == Power.SignalShield -> { power = null; powerLeft = 0f }
odShield -> odShield = false
lunaShield -> { lunaShield = false; lunaIn = pilot.shieldEvery }
else -> {
bars--; streak = 0
safe = tuning.safe; shake = .35f; hitFlash = .15f
events = events or Events.HIT
if (bars <= 0) { bars = 0; phase = Phase.Over; events = events or Events.GAME_OVER }
return
}
}
safe = .6f
events = events or Events.SHIELDED
}
private fun dropPower(x: Float, y: Float) {
var pick = rng.nextInt(POWER_WEIGHTS)
var chosen = Power.SignalShield
for (p in POWERS) { if (pick < p.weight) { chosen = p; break }; pick -= p.weight }
for (d in drops) if (!d.active) { d.active = true; d.x = x; d.y = y; d.power = chosen; return }
}
/** A caught power-up. A timed one replaces whichever timed one was on: only one at a time. */
fun collect(p: Power) {
events = events or Events.POWER
when (p) {
Power.GuideBomb -> for (i in enemies.indices) {
val e = enemies[i]
if (e.active && (e.kind == Kind.STATIC || e.kind == Kind.PIXEL_SMALL || e.kind == Kind.GREMLIN || e.kind == Kind.MINION)) { damage += e.hp; kill(e) }
}
Power.OrbitOverdrive -> meter = 1f
else -> { power = p; powerLeft = p.seconds }
}
}
private fun burst(x: Float, y: Float, colour: Int) {
var made = 0
for (s in sparks) if (!s.active) {
val a = made * 1.047f + rng.nextFloat() * .5f
s.active = true; s.x = x; s.y = y; s.vx = cos(a) * 60f; s.vy = sin(a) * 60f; s.life = .45f; s.colour = colour
if (++made == 6) return
}
}
// ---------- for the tests: a field set up by hand ----------
/** An empty field mid-wave: no invaders, no shots, nobody firing or diving, and the formation holding still. */
internal fun emptyField() { clearAll(); entering = false; formX = 0f; formY = 0f; formDir = 0f; phase = Phase.Playing; safe = 0f; diveIn = 1e9f; enemyFireIn = 1e9f }
internal fun place(kind: Int, x: Float, y: Float): Enemy = spawn(kind, x, y, M_FORM)!!
internal fun moveShipTo(x: Float) { shipX = x; shipVx = 0f }
// ---------- reading ----------
fun livingEnemies(): Int { var n = 0; for (e in enemies) if (e.active) n++; return n }
fun liveShots(): Int { var n = 0; for (s in shots) if (s.active) n++; return n }
fun liveEnemyShots(): Int { var n = 0; for (s in enemyShots) if (s.active) n++; return n }
fun liveDrops(): Int { var n = 0; for (d in drops) if (d.active) n++; return n }
fun liveSparks(): Int { var n = 0; for (s in sparks) if (s.active) n++; return n }
fun liveSprites() = livingEnemies() + liveShots() + liveEnemyShots() + liveDrops() + (if (bossOn) 1 else 0)
/** Seconds until Luna's shield is back (0 when it's up or she isn't flying). */
val shieldIn get() = if (lunaShield || pilot.shieldEvery <= 0f) 0f else lunaIn
/** Takes the tick's events for the screen. */
fun takeEvents(): Int { val e = events; events = 0; return e }
companion object {
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) }
/** Combo multiplier for a run of kills without being hit: x2 from 10, x3 from 25, x4 from 50. */
fun multiplierFor(streak: Int) = when { streak >= 50 -> 4; streak >= 25 -> 3; streak >= 10 -> 2; else -> 1 }
}
}
/**
* The fixed step: the screen's frame times in, a number of [STEP] ticks out. Time while paused is thrown away, and a long
* frame never turns into a burst of more than [MAX_TICKS] ticks.
*/
internal class FixedStep {
private var acc = 0f
fun ticks(dtNanos: Long, paused: Boolean): Int {
if (paused) { acc = 0f; return 0 }
acc += (dtNanos / 1e9f).coerceIn(0f, .1f)
var n = 0
while (acc >= STEP && n < MAX_TICKS) { acc -= STEP; n++ }
if (n == MAX_TICKS) acc = 0f
return n
}
/** How far into the next tick we are, 0 to 1, for smooth drawing. */
val alpha get() = acc / STEP
fun reset() { acc = 0f }
companion object { const val MAX_TICKS = 5 }
}