diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeAudio.kt b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeAudio.kt index ade11ce9..b5de2942 100644 --- a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeAudio.kt +++ b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeAudio.kt @@ -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() { diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeGames.kt b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeGames.kt index 6c1a7f11..074bf56a 100644 --- a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeGames.kt +++ b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeGames.kt @@ -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.") diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeHome.kt b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeHome.kt index 46c795c8..7c1849db 100644 --- a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeHome.kt +++ b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeHome.kt @@ -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()) } }) } } diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadePages.kt b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadePages.kt index 3aed61e5..c7f795ea 100644 --- a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadePages.kt +++ b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadePages.kt @@ -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. */ diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadePlay.kt b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadePlay.kt index 1b5b2fc8..ea95ca3f 100644 --- a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadePlay.kt +++ b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadePlay.kt @@ -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) diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeStore.kt b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeStore.kt index 94774e76..253694d9 100644 --- a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeStore.kt +++ b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeStore.kt @@ -48,6 +48,8 @@ internal data class ArcadeProfileData( val settings: Map = emptyMap(), /** Games by id, most recently played first. */ val recent: List = emptyList(), + /** Arcade-wide choices that aren't on/off (Stage D): "difficulty" is Gentle, Normal or Tricky. */ + val choices: Map = 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 diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/raiders/OrbiRaidersScreen.kt b/android/app/src/main/java/tv/orbit/classic/arcade/raiders/OrbiRaidersScreen.kt new file mode 100644 index 00000000..d5ffeacb --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/arcade/raiders/OrbiRaidersScreen.kt @@ -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(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)))) + } +} diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/raiders/RaidersArt.kt b/android/app/src/main/java/tv/orbit/classic/arcade/raiders/RaidersArt.kt new file mode 100644 index 00000000..572a36c1 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/arcade/raiders/RaidersArt.kt @@ -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) +} diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/raiders/RaidersControls.kt b/android/app/src/main/java/tv/orbit/classic/arcade/raiders/RaidersControls.kt new file mode 100644 index 00000000..90724942 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/arcade/raiders/RaidersControls.kt @@ -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)) + } +} diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/raiders/RaidersSim.kt b/android/app/src/main/java/tv/orbit/classic/arcade/raiders/RaidersSim.kt new file mode 100644 index 00000000..7db49414 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/arcade/raiders/RaidersSim.kt @@ -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 } +} diff --git a/android/app/src/test/java/tv/orbit/classic/arcade/ArcadeSessionTest.kt b/android/app/src/test/java/tv/orbit/classic/arcade/ArcadeSessionTest.kt index cc803eb9..86c81576 100644 --- a/android/app/src/test/java/tv/orbit/classic/arcade/ArcadeSessionTest.kt +++ b/android/app/src/test/java/tv/orbit/classic/arcade/ArcadeSessionTest.kt @@ -85,6 +85,6 @@ class ArcadeSessionTest { assertFalse(resetAllowed(ResetAction.ResetLevelProgress, hive, "p", "p", false, hiveProfileSaves = false)) assertTrue(resetAllowed(ResetAction.ResetLevelProgress, hive, "p", "p", false, hiveProfileSaves = true)) // A coming-soon card has nothing to clear. - assertFalse(resetAllowed(ResetAction.ClearHighScores, ArcadeGames.OrbiRaiders, "p", "p", false)) + assertFalse(resetAllowed(ResetAction.ClearHighScores, ArcadeGames.ChannelChaos, "p", "p", false)) } } diff --git a/android/app/src/test/java/tv/orbit/classic/arcade/KidsArcadeTest.kt b/android/app/src/test/java/tv/orbit/classic/arcade/KidsArcadeTest.kt index 6d23d1b4..24ce1e59 100644 --- a/android/app/src/test/java/tv/orbit/classic/arcade/KidsArcadeTest.kt +++ b/android/app/src/test/java/tv/orbit/classic/arcade/KidsArcadeTest.kt @@ -57,29 +57,29 @@ class KidsArcadeTest { } @Test fun pickRecentAndHighScoresFollowTheFilter() { - val chosen = kids.withKidsArcade(KidsArcade.Chosen, setOf("Pairs", "Snake", "OrbiRaiders")) + val chosen = kids.withKidsArcade(KidsArcade.Chosen, setOf("Pairs", "Snake", "ChannelChaos")) val visible = arcadeVisible(chosen) // Star Chase isn't chosen, so it can't be the pick. assertEquals("Snake", arcadePick(visible)!!.id) assertEquals("OrbMan", arcadePick(arcadeVisible(grown))!!.id) // Recent keeps only games this profile can still see and play. - assertEquals(listOf("Pairs", "Snake"), recentVisible(listOf("Blast", "Pairs", "OrbiRaiders", "Snake", "Gone"), visible).map { it.id }) + assertEquals(listOf("Pairs", "Snake"), recentVisible(listOf("Blast", "Pairs", "ChannelChaos", "Snake", "Gone"), visible).map { it.id }) assertNull(arcadePick(emptyList())) } @Test fun theFamilyLineSaysWhatKidsReallySee() { // The audit: "On: the games chosen for Kids" promised a choice that didn't exist. assertEquals("Off: no Arcade for Kids", arcadeForKidsLine(kids.withKidsArcade(KidsArcade.Off))) - assertEquals("Kids-suitable games: 7 to play", arcadeForKidsLine(kids.withKidsArcade(KidsArcade.KidsSuitable))) - assertEquals("Chosen games: 2 to play", arcadeForKidsLine(kids.withKidsArcade(KidsArcade.Chosen, setOf("Pairs", "Sky", "OrbiRaiders")))) + assertEquals("Kids-suitable games: 8 to play", arcadeForKidsLine(kids.withKidsArcade(KidsArcade.KidsSuitable))) + assertEquals("Chosen games: 2 to play", arcadeForKidsLine(kids.withKidsArcade(KidsArcade.Chosen, setOf("Pairs", "Sky", "ChannelChaos")))) assertEquals("Chosen games: none chosen yet, so no Arcade", arcadeForKidsLine(kids.withKidsArcade(KidsArcade.Chosen, emptySet()))) } @Test fun everyGameIsDescribed() { assertEquals(ArcadeGames.all.size, ArcadeGames.all.map { it.id }.toSet().size) assertEquals(5, ArcadeGames.originals.size); assertEquals(8, ArcadeGames.classics.size) - // Only BumbleHive of the Originals plays in Stage C; every Classic does. - assertEquals(listOf("Hive"), ArcadeGames.originals.filter { it.launchable }.map { it.id }) + // BumbleHive and (Stage D) Orbi-Raiders are the Originals that play; every Classic does. + assertEquals(listOf("OrbiRaiders", "Hive"), ArcadeGames.originals.filter { it.launchable }.map { it.id }) assertTrue(ArcadeGames.classics.all { it.launchable }) ArcadeGames.all.forEach { g -> assertTrue(g.id, g.controls.isNotEmpty()); assertTrue(g.id, g.title.isNotBlank()); assertTrue(g.id, g.goal.isNotBlank()) diff --git a/android/app/src/test/java/tv/orbit/classic/arcade/raiders/RaidersBalanceTest.kt b/android/app/src/test/java/tv/orbit/classic/arcade/raiders/RaidersBalanceTest.kt new file mode 100644 index 00000000..df1597e1 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/arcade/raiders/RaidersBalanceTest.kt @@ -0,0 +1,95 @@ +package tv.orbit.classic.arcade.raiders + +import org.junit.Assert.* +import org.junit.Test +import tv.orbit.classic.arcade.Difficulty + +/** + * The pilots are balanced against each other, and steady play allocates nothing. The same bot flies every pilot through + * the same seeded runs at Normal; each pilot's numbers must be within 15% of the four pilots' average. + */ +class RaidersBalanceTest { + private class Result(val pilot: Pilot, val score: Double, val dps: Double, val seconds: Double, val waves: Double) { + /** Damage over a whole run: how hard it hits times how long it lasts. */ + val perRun get() = dps * seconds + } + + private fun measure(pilot: Pilot, d: Difficulty = Difficulty.Normal, seeds: IntRange = 1..24, maxSeconds: Int = 600): Result { + var score = 0.0; var damage = 0.0; var ticks = 0.0; var waves = 0.0 + val input = RaidersInput() + for (seed in seeds) { + val sim = RaidersSim(pilot, d, seed * 7919) + var t = 0 + while (!sim.over && t++ < maxSeconds * 60) { + RaidersBot.fill(sim, input); sim.step(input) + if (sim.phase == Phase.Checkpoint) sim.continueRun() + } + score += sim.score; damage += sim.damage; ticks += sim.ticks; waves += sim.wave + } + val n = seeds.count().toDouble() + return Result(pilot, score / n, damage / (ticks / 60.0), ticks / 60.0 / n, waves / n) + } + + private fun table(results: List, d: Difficulty) = buildString { + appendLine("Orbi-Raiders balance at $d (bot, ${results.size} pilots):") + appendLine("pilot mean score damage/s survived s damage/run mean wave") + results.forEach { appendLine("%-7s %10.0f %10.2f %12.1f %12.0f %11.2f".format(it.pilot.title, it.score, it.dps, it.seconds, it.perRun, it.waves)) } + } + + @Test fun thePilotsAreWithinFifteenPercentOfEachOtherAtNormal() { + val results = Pilot.entries.map { measure(it) } + println(table(results, Difficulty.Normal)) + fun check(name: String, within: Double, of: (Result) -> Double) { + val mean = results.map(of).average() + results.forEach { r -> assertEquals("${r.pilot} $name ${of(r)} vs mean $mean", 1.0, of(r) / mean, within) } + } + // Damage per second and survival trade against each other by design (Zip pierces but has one bar fewer; Luna + // fires slower but her shield regrows), so the check is on what they make together: damage over a whole run, + // and the run's score. Each part is only kept from running away: within 50% of the average (Zip, the glass cannon, + // sits at about +44% damage per second and -36% survival). + check("score", .15) { it.score } + check("damage per run", .15) { it.perRun } + check("damage/s", .5) { it.dps } + check("survived", .5) { it.seconds } + } + + @Test fun difficultyOrdersHowLongTheBotLasts() { + val gentle = measure(Pilot.Ollie, Difficulty.Gentle, 1..12) + val normal = measure(Pilot.Ollie, Difficulty.Normal, 1..12) + val tricky = measure(Pilot.Ollie, Difficulty.Tricky, 1..12) + println(table(listOf(gentle), Difficulty.Gentle) + table(listOf(normal), Difficulty.Normal) + table(listOf(tricky), Difficulty.Tricky)) + assertTrue(gentle.waves > normal.waves) + assertTrue(normal.waves > tricky.waves) + } + + @Test fun poolsStayBoundedAndSteadyPlayAllocatesNothing() { + val sim = RaidersSim(Pilot.Zip, Difficulty.Normal, 77) + val input = RaidersInput() + val pools = listOf(sim.enemies, sim.shots, sim.enemyShots, sim.drops, sim.sparks) + fun tick() { + RaidersBot.fill(sim, input); sim.step(input); sim.takeEvents() + if (sim.phase == Phase.Checkpoint) sim.continueRun() + if (sim.over) sim.newRun(seed = sim.seed + 1) + } + // Warm up (class loading, the JIT), then measure 10,000 ticks. + repeat(3_000) { tick() } + val mx = java.lang.management.ManagementFactory.getThreadMXBean() as com.sun.management.ThreadMXBean + val thread = Thread.currentThread().id + var maxSprites = 0; var maxSparks = 0 + val before = mx.getThreadAllocatedBytes(thread) + for (i in 0 until 10_000) { + tick() + val sprites = sim.liveSprites(); if (sprites > maxSprites) maxSprites = sprites + val sparks = sim.liveSparks(); if (sparks > maxSparks) maxSparks = sparks + } + val allocated = mx.getThreadAllocatedBytes(thread) - before + println("Orbi-Raiders: 10,000 ticks allocated $allocated bytes; most sprites at once $maxSprites (cap $MAX_SPRITES), sparks $maxSparks (cap $MAX_SPARKS)") + assertTrue(maxSprites <= 150) + assertTrue(maxSparks <= 40) + // The pools are the same arrays they started as, the same size. + assertSame(pools[0], sim.enemies); assertEquals(MAX_ENEMIES, sim.enemies.size) + assertEquals(MAX_SHOTS, sim.shots.size); assertEquals(MAX_ENEMY_SHOTS, sim.enemyShots.size); assertEquals(MAX_SPARKS, sim.sparks.size) + // A new run (after the signal's lost) is allowed a little; steady play none. 16 KB leaves room for the JVM's own noise. + assertTrue("allocated $allocated bytes", allocated < 16 * 1024) + } +} diff --git a/android/app/src/test/java/tv/orbit/classic/arcade/raiders/RaidersBot.kt b/android/app/src/test/java/tv/orbit/classic/arcade/raiders/RaidersBot.kt new file mode 100644 index 00000000..7c71993b --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/arcade/raiders/RaidersBot.kt @@ -0,0 +1,38 @@ +package tv.orbit.classic.arcade.raiders + +import kotlin.math.abs + +/** + * A simple player for the tests: it holds fire, slides under the nearest invader, steps out from under shots and the + * Dead Channel's beam, and fires Overdrive when the meter is full. It allocates nothing, so the allocation test can use it. + * It is the same for every pilot, which is what makes the balance comparison fair. + */ +internal object RaidersBot { + fun fill(sim: RaidersSim, input: RaidersInput) { + input.fire = true + input.overdrive = sim.meter >= 1f + val x = sim.shipX + // Danger first: a shot coming down near the ship, or the beam's column. + var threat = Float.NaN + // Shots from 80 above down to just past the ship, near enough to walk into. + for (s in sim.enemyShots) if (s.active && s.y < SHIP_Y + 12f && SHIP_Y - s.y < 80f && abs(s.x - x) < 20f) { threat = s.x; break } + if (sim.bossOn && (sim.beamOn > 0f || (sim.bossAttack == 1 && sim.bossWarn > 0f)) && abs(sim.beamX - x) < 22f) threat = sim.beamX + if (!threat.isNaN()) { + input.move = if (threat > x) -1 else if (threat < x) 1 else if (x > FIELD_W / 2) -1 else 1 + if (x < 24f) input.move = 1 + if (x > FIELD_W - 24f) input.move = -1 + return + } + // Then aim: the lowest invader closest to the ship, or the boss. + var target = Float.NaN; var best = Float.MAX_VALUE + // Leading a formation invader by how far the formation slides while the shot flies up. + for (e in sim.enemies) if (e.active && e.y > 0f && e.hittable()) { + val lead = if (e.diving) 0f else sim.formVx * (SHIP_Y - e.y) / SHOT_SPEED + val score = abs(e.x + lead - x) - e.y * .5f + if (score < best) { best = score; target = e.x + lead } + } + if (target.isNaN() && sim.bossOn) target = sim.bossX + if (target.isNaN()) { input.move = 0; return } + input.move = when { target > x + 2f -> 1; target < x - 2f -> -1; else -> 0 } + } +} diff --git a/android/app/src/test/java/tv/orbit/classic/arcade/raiders/RaidersPlayTest.kt b/android/app/src/test/java/tv/orbit/classic/arcade/raiders/RaidersPlayTest.kt new file mode 100644 index 00000000..3adffecf --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/arcade/raiders/RaidersPlayTest.kt @@ -0,0 +1,179 @@ +package tv.orbit.classic.arcade.raiders + +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import tv.orbit.classic.KidsArcade +import tv.orbit.classic.Profile +import tv.orbit.classic.ProfileKind +import tv.orbit.classic.arcade.ArcadeGames +import tv.orbit.classic.arcade.ArcadeKey +import tv.orbit.classic.arcade.ArcadeProfileData +import tv.orbit.classic.arcade.ArcadeStore +import tv.orbit.classic.arcade.Difficulty +import tv.orbit.classic.arcade.ScoreKind +import tv.orbit.classic.arcade.arcadeVisible +import tv.orbit.classic.arcade.autoFireFor +import tv.orbit.classic.arcade.bestOf +import tv.orbit.classic.arcade.decodeArcade +import tv.orbit.classic.arcade.difficultyFor +import tv.orbit.classic.arcade.encodeArcade +import tv.orbit.classic.arcade.recordRun +import tv.orbit.classic.arcade.reduceFlashingFor + +/** The remote in play, saving every run, and the Arcade settings Orbi-Raiders reads. */ +class RaidersPlayTest { + @get:Rule val folder = TemporaryFolder() + + // ---------- the remote ---------- + + @Test fun aHeldOkKeepsFiringButItsRepeatsAddNoPresses() { + val c = RaidersControls(); val input = RaidersInput() + c.key(ArcadeKey.Ok, down = true, repeatCount = 0) + c.fill(input); assertTrue(input.fire) + // The remote repeats a held key: still firing (held), at the game's fixed rate, never extra presses. + repeat(20) { c.key(ArcadeKey.Ok, down = true, repeatCount = it + 1); c.fill(input); assertTrue(input.fire) } + c.key(ArcadeKey.Ok, down = false, repeatCount = 0) + c.fill(input); assertFalse(input.fire) + } + + @Test fun mashingOkNeverBeatsTheFixedRate() { + val sim = RaidersSim(Pilot.Ollie, Difficulty.Normal, 2).apply { emptyField(); place(Kind.SATELLITE, 40f, 40f) } + val c = RaidersControls(); val input = RaidersInput() + var shots = 0 + // Sixty ticks with OK pressed and let go every tick, and a second "down" with no release between (some remotes). + repeat(60) { + c.key(ArcadeKey.Ok, true, 0); c.key(ArcadeKey.Ok, true, 0) + c.fill(input); sim.step(input); if (sim.takeEvents() and Events.SHOT != 0) shots++ + c.key(ArcadeKey.Ok, false, 0) + } + assertEquals(5, shots) + } + + @Test fun overdriveIsOnePerPressOfUp() { + val c = RaidersControls(); val input = RaidersInput() + c.key(ArcadeKey.Up, true, 0); c.fill(input); assertTrue(input.overdrive) + repeat(10) { c.key(ArcadeKey.Up, true, it + 1); c.fill(input); assertFalse(input.overdrive) } + c.key(ArcadeKey.Up, true, 0); c.fill(input); assertFalse("a second down with no release", input.overdrive) + c.key(ArcadeKey.Up, false, 0); c.key(ArcadeKey.Up, true, 0); c.fill(input); assertTrue(input.overdrive) + } + + @Test fun leftAndRightAreHeldAndPauseForgetsThem() { + val c = RaidersControls(); val input = RaidersInput() + c.key(ArcadeKey.Right, true, 0); c.fill(input); assertEquals(1, input.move) + c.key(ArcadeKey.Left, true, 0); c.fill(input); assertEquals(0, input.move) + c.key(ArcadeKey.Right, false, 0); c.fill(input); assertEquals(-1, input.move) + c.key(ArcadeKey.Ok, true, 0) + c.release(); c.fill(input) + assertEquals(0, input.move); assertFalse(input.fire) + assertFalse("Back is the screen's, not the controls'", c.key(ArcadeKey.Back, true, 0)) + } + + @Test fun autoFireAssistFiresWithNoButton() { + val c = RaidersControls(autoFire = true); val input = RaidersInput() + c.fill(input); assertTrue(input.fire) + } + + // ---------- saving every run ---------- + + private class Saves(dir: java.io.File) { + val store = ArcadeStore(dir) + var bestWave = 0 + val book = RaidersRunBook({ end -> store.update("p1") { recordRun(it, "OrbiRaiders", ScoreKind.Points, end, 1_000) } }, { bestWave = it }, 0) + fun runs() = store.load("p1").game("OrbiRaiders").runs + } + + private fun midRun(score: Int): RaidersSim { + val sim = RaidersSim(Pilot.Blaze, Difficulty.Normal, 4) + while (sim.score < score) sim.hitEnemy(sim.enemies.indexOfFirst { it.active }, 9) + return sim + } + + @Test fun theSignalLostSavesTheRun() { + val s = Saves(folder.root); val sim = midRun(30) + s.book.begin() + var guard = 0 + while (!sim.over && guard++ < 20) { repeat(120) { sim.step(RaidersInput()) }; sim.hurt() } + assertTrue(sim.over) + s.book.end(sim, finished = true) + assertEquals(listOf(sim.score), s.runs().map { it.score }) + assertEquals("Wave 1 · Blaze", s.runs().single().detail) + } + + @Test fun exitMidRunSavesItOnceEvenWhenTheScreenGoesToo() { + val s = Saves(folder.root); val sim = midRun(40) + s.book.begin() + s.book.end(sim, finished = false) // Exit to Arcade + s.book.end(sim, finished = false) // ...and the screen's dispose a moment later + assertEquals(1, s.runs().size) + assertEquals(sim.score, s.runs().single().score) + // And survives a fresh read of the file. + s.store.forget("p1") + assertEquals(sim.score, bestOf(s.store.load("p1").game("OrbiRaiders"), ScoreKind.Points)) + } + + @Test fun retryAndTheScreenGoingAwayEachSaveTheirRun() { + val s = Saves(folder.root) + val first = midRun(20); s.book.begin(); s.book.end(first, finished = false) // Retry + val second = midRun(50); s.book.begin(); s.book.end(second, finished = false) // sleep timer: the screen's dispose + assertEquals(listOf(second.score, first.score), s.runs().map { it.score }) + } + + @Test fun theBestWaveIsKept() { + val s = Saves(folder.root) + val sim = RaidersSim(Pilot.Ollie, Difficulty.Normal, 2) + var guard = 0 + while (sim.wave < 3 && guard++ < 20) { for (i in sim.enemies.indices) if (sim.enemies[i].active) sim.hitEnemy(i, 9); repeat(200) { sim.step(RaidersInput()) } } + s.book.begin(); s.book.end(sim, finished = false) + assertEquals(3, s.bestWave) + val worse = RaidersSim(Pilot.Ollie, Difficulty.Normal, 2) + s.book.begin(); s.book.end(worse, finished = false) + assertEquals(3, s.bestWave) + } + + @Test fun onlyTheTopTenRunsAreKept() { + val s = Saves(folder.root) + for (score in 1..14) { val sim = midRun(score * 5); s.book.begin(); s.book.end(sim, finished = true) } + assertEquals(10, s.runs().size) + assertEquals(s.runs().map { it.score }.sortedDescending(), s.runs().map { it.score }) + } + + // ---------- Arcade settings and Kids ---------- + + @Test fun kidsStartOnGentleAndGrownUpsOnNormal() { + val empty = ArcadeProfileData("k1") + assertEquals(Difficulty.Gentle, difficultyFor(empty, ProfileKind.Kids)) + assertEquals(Difficulty.Normal, difficultyFor(empty, ProfileKind.Grown)) + assertEquals(Difficulty.Normal, difficultyFor(empty, null)) + // A choice, once made, wins for anyone, and survives the file. + val chosen = decodeArcade(encodeArcade(empty.copy(choices = mapOf("difficulty" to "Tricky"))), "k1")!! + assertEquals(Difficulty.Tricky, difficultyFor(chosen, ProfileKind.Kids)) + assertEquals(Difficulty.Normal, difficultyFor(empty.copy(choices = mapOf("difficulty" to "Nonsense")), ProfileKind.Grown)) + } + + @Test fun gentleReallyIsGentler() { + val g = Tuning.of(Difficulty.Gentle); val n = Tuning.of(Difficulty.Normal); val t = Tuning.of(Difficulty.Tricky) + assertTrue(g.fire < n.fire && n.fire < t.fire) + assertTrue(g.shotSpeed < n.shotSpeed && n.shotSpeed < t.shotSpeed) + assertTrue(g.warn > n.warn && n.warn > t.warn) + assertTrue(g.bossHp < n.bossHp && n.bossHp < t.bossHp) + assertTrue(g.dropChance > n.dropChance) + } + + @Test fun reduceFlashingIsOnAndAutoFireOffUntilChosen() { + val empty = ArcadeProfileData("p1") + assertTrue(reduceFlashingFor(empty)); assertFalse(autoFireFor(empty)) + val chosen = decodeArcade(encodeArcade(empty.copy(settings = mapOf("reduceFlashing" to false, "autoFire" to true))), "p1")!! + assertFalse(reduceFlashingFor(chosen)); assertTrue(autoFireFor(chosen)) + // An old save with no choices at all still reads. + assertEquals(emptyMap(), decodeArcade("""{"schema":1,"profileId":"p1"}""", "p1")!!.choices) + } + + @Test fun orbiRaidersIsPlayableAndAKidsGame() { + val g = ArcadeGames.OrbiRaiders + assertTrue(g.launchable); assertTrue(g.kidsSuitable); assertEquals(ScoreKind.Points, g.scoreKind) + val kid = Profile("k1", "Mia", "ollie", ProfileKind.Kids, arcadeMode = KidsArcade.KidsSuitable) + assertTrue(g in arcadeVisible(kid)) + } +} diff --git a/android/app/src/test/java/tv/orbit/classic/arcade/raiders/RaidersSimTest.kt b/android/app/src/test/java/tv/orbit/classic/arcade/raiders/RaidersSimTest.kt new file mode 100644 index 00000000..cd4c14e6 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/arcade/raiders/RaidersSimTest.kt @@ -0,0 +1,319 @@ +package tv.orbit.classic.arcade.raiders + +import org.junit.Assert.* +import org.junit.Test +import tv.orbit.classic.arcade.Difficulty + +/** Orbi-Raiders' rules: hits, waves, scoring, power-ups, the fixed step. */ +class RaidersSimTest { + private val idle = RaidersInput() + private val firing = RaidersInput().apply { fire = true } + + private fun sim(pilot: Pilot = Pilot.Ollie, d: Difficulty = Difficulty.Normal) = RaidersSim(pilot, d, seed = 7).apply { emptyField() } + private fun RaidersSim.run(ticks: Int, input: RaidersInput = idle) = repeat(ticks) { step(input) } + + /** Clears the wave by hand, Corrupt Pixels' halves included. */ + private fun RaidersSim.clearInvaders() { var guard = 0; while (livingEnemies() > 0 && guard++ < 20) for (i in enemies.indices) if (enemies[i].active) hitEnemy(i, 9) } + + // ---------- collision ---------- + + @Test fun aShotHitsTheInvaderAboveTheShip() { + val s = sim(); s.moveShipTo(200f) + val e = s.place(Kind.STATIC, 200f, 100f) + s.place(Kind.SATELLITE, 40f, 40f) // keeps the wave from clearing + s.step(firing); s.run(60) + assertFalse(e.active) + assertEquals(10, s.score) + } + + @Test fun blazesNarrowShotNeedsACloserAim() { + // 11.5 units off centre: inside Ollie's shot (9 + 3) but outside Blaze's narrow one (9 + 2.2). + for ((pilot, hits) in listOf(Pilot.Ollie to true, Pilot.Blaze to false)) { + val s = sim(pilot); s.moveShipTo(200f) + val e = s.place(Kind.STATIC, 211.5f, 100f) + s.place(Kind.SATELLITE, 40f, 40f) + s.step(firing); s.run(60) + assertEquals("$pilot", hits, !e.active) + } + } + + @Test fun zipsShotsPierceOneInvader() { + for ((pilot, killed) in listOf(Pilot.Ollie to 1, Pilot.Zip to 2)) { + val s = sim(pilot); s.moveShipTo(200f) + val a = s.place(Kind.STATIC, 200f, 160f); val b = s.place(Kind.STATIC, 200f, 120f); val c = s.place(Kind.STATIC, 200f, 80f) + s.step(firing); s.run(60) + assertEquals("$pilot", killed, listOf(a, b, c).count { !it.active }) + } + } + + @Test fun satellitesTakeThreeHitsAndPixelsSplitInTwo() { + val s = sim() + val sat = s.place(Kind.SATELLITE, 100f, 60f); val i = s.enemies.indexOf(sat) + s.hitEnemy(i, 1); s.hitEnemy(i, 1) + assertTrue(sat.active) + s.hitEnemy(i, 1) + assertFalse(sat.active) + val px = s.place(Kind.PIXEL, 200f, 60f) + s.hitEnemy(s.enemies.indexOf(px), 1) + assertEquals(0, s.enemies.count { it.active && it.kind == Kind.PIXEL }) + // Two halves, one either side of where it was (its own pool place is reused by the first). + val halves = s.enemies.filter { it.active && it.kind == Kind.PIXEL_SMALL }.map { it.x }.sorted() + assertEquals(listOf(192f, 208f), halves) + } + + @Test fun voidBroadcastsCanOnlyBeHitWhileShowing() { + val e = Enemy().apply { kind = Kind.VOID; phase = 0f } + var shown = 0; var hidden = 0 + for (k in 0 until 600) { e.t = k / 60f; if (e.hittable()) shown++ else hidden++ } + assertTrue(shown > 100 && hidden > 100) + e.t = (4.712f - 0f) / 1.5f // the fade's lowest point + assertFalse(e.hittable()) + } + + @Test fun anInvaderShotCostsABarThenTheShipIsSafeForAMoment() { + val s = sim(); s.place(Kind.SATELLITE, 40f, 40f) + s.hurt() + assertEquals(2, s.bars) + s.hurt() + assertEquals("safe after a hit", 2, s.bars) + s.run((Tuning.Normal.safe * 60).toInt() + 2) + s.hurt() + assertEquals(1, s.bars) + } + + @Test fun losingTheLastBarEndsTheRun() { + val s = sim(Pilot.Zip); s.place(Kind.SATELLITE, 40f, 40f) + assertEquals(2, s.bars) + s.hurt(); s.run(200); s.hurt() + assertTrue(s.over) + val before = s.ticks + s.run(100) + assertEquals("nothing moves once it's over", before, s.ticks) + } + + // ---------- waves ---------- + + private fun layout(seed: Int, wave: Int): List> { + val s = RaidersSim(Pilot.Ollie, Difficulty.Normal, seed) + // Clear each wave by hand until the one asked for has been built. + while (s.wave < wave) { + s.clearInvaders() + var guard = 0 + while (s.wave < wave && guard++ < 400) { s.step(idle); if (s.phase == Phase.Checkpoint) s.continueRun() } + if (s.bossOn && s.wave < wave) return emptyList() + } + return s.enemies.filter { it.active }.map { Triple(it.kind, it.slotX, it.slotY) } + } + + @Test fun theSameSeedBuildsTheSameWaves() { + for (w in listOf(1, 2, 3, 4)) { + val a = layout(42, w); val b = layout(42, w) + assertTrue(a.isNotEmpty()) + assertEquals("wave $w", a, b) + } + // And some other seed builds some other mix of rows. + assertTrue((3..4).any { w -> (1..20).any { seed -> layout(seed, w).map { it.first } != layout(42, w).map { it.first } } }) + } + + @Test fun aWholeRunIsTheSameForTheSameSeedAndInput() { + fun play(seed: Int): List { + val s = RaidersSim(Pilot.Luna, Difficulty.Normal, seed); val input = RaidersInput() + repeat(6000) { RaidersBot.fill(s, input); s.step(input); if (s.phase == Phase.Checkpoint) s.continueRun() } + return listOf(s.score, s.wave, s.bars, s.damage, s.livingEnemies()) + } + assertEquals(play(5), play(5)) + } + + @Test fun wavesGrowGentlyAndKindsArriveInTurn() { + val first = layout(3, 1) + assertTrue(first.all { it.first == Kind.STATIC }) + assertEquals(10, first.size) // 2 rows of 5 + val fourth = layout(3, 4) + assertTrue(fourth.size > first.size) + assertTrue(fourth.any { it.first == Kind.SATELLITE }) + assertTrue(fourth.none { it.first == Kind.VOID }) + // Gentle has a row fewer. + val gentle = RaidersSim(Pilot.Ollie, Difficulty.Gentle, 3) + assertTrue(gentle.livingEnemies() <= first.size) + } + + @Test fun theDeadChannelComesOnTheFifthWave() { + val s = RaidersSim(Pilot.Ollie, Difficulty.Normal, 9) + var rounds = 0 + while (s.wave < 5 && rounds++ < 10) { s.clearInvaders(); repeat(200) { s.step(idle) } } + assertTrue(s.bossOn) + assertEquals(Tuning.Normal.bossHp, s.bossHp) + // Every attack is warned before it lands. + var warned = false + repeat(60 * 6) { s.step(idle); if (s.bossWarn > 0f) warned = true } + assertTrue(warned) + // Beaten: a result card (the checkpoint) and then wave 6. + val shots = RaidersInput().apply { fire = true } + var guard = 0 + // A shield kept up the whole fight, so this checks the boss and not the aim. + while (s.bossOn && guard++ < 60 * 120) { s.collect(Power.SignalShield); s.moveShipTo(s.bossX); s.step(shots) } + assertFalse(s.bossOn) + repeat(200) { s.step(idle) } + assertEquals(Phase.Checkpoint, s.phase) + s.continueRun() + assertEquals(6, s.wave) + } + + @Test fun restartLevelGoesBackToHowTheWaveBegan() { + val s = RaidersSim(Pilot.Ollie, Difficulty.Normal, 11) + val layoutBefore = s.enemies.filter { it.active }.map { it.kind to it.slotX } + s.run(70) // past the moment of safety a wave starts with + s.hitEnemy(0, 9); s.hurt() + assertTrue(s.score > 0); assertEquals(2, s.bars) + s.restartWave() + assertEquals(0, s.score); assertEquals(3, s.bars) + assertEquals(layoutBefore, s.enemies.filter { it.active }.map { it.kind to it.slotX }) + } + + // ---------- scoring ---------- + + @Test fun comboMultiplierClimbsAndResetsOnAHit() { + assertEquals(listOf(1, 1, 2, 2, 3, 3, 4, 4), listOf(0, 9, 10, 24, 25, 49, 50, 500).map { RaidersSim.multiplierFor(it) }) + val s = sim() + repeat(12) { s.place(Kind.STATIC, 20f + it * 30f, 60f) } + s.place(Kind.SATELLITE, 40f, 30f) + for (i in 0 until 12) s.hitEnemy(i, 1) + // Nine kills at ×1, the tenth onwards at ×2. + assertEquals(9 * 10 + 3 * 20, s.score) + assertEquals(2, s.multiplier) + s.hurt() + assertEquals(1, s.multiplier) + assertEquals(0, s.streak) + } + + @Test fun aClearedWavePaysABonus() { + val s = sim() + val e = s.place(Kind.STATIC, 200f, 60f) + s.hitEnemy(s.enemies.indexOf(e), 1) + s.step(idle) + assertEquals(Phase.Cleared, s.phase) + assertEquals(10 + 100, s.score) + repeat(120) { s.step(idle) } + assertEquals(2, s.wave) + } + + // ---------- power-ups ---------- + + @Test fun onlyOneTimedPowerUpAtATimeAndANewOneReplacesIt() { + val s = sim(); s.place(Kind.SATELLITE, 40f, 40f) + s.collect(Power.SignalShield) + assertEquals(Power.SignalShield, s.power) + s.collect(Power.DoubleBroadcast) + assertEquals(Power.DoubleBroadcast, s.power) + assertEquals(10f, s.powerLeft, .001f) + // Instant ones don't touch the timed one. + s.collect(Power.OrbitOverdrive) + assertEquals(Power.DoubleBroadcast, s.power) + assertEquals(1f, s.meter, 0f) + s.collect(Power.GuideBomb) + assertEquals(Power.DoubleBroadcast, s.power) + } + + @Test fun timedPowerUpsLastTheirSecondsThenGo() { + for (p in Power.entries.filter { it.timed }) { + val s = sim(); s.place(Kind.SATELLITE, 40f, 40f) + s.collect(p) + s.run((p.seconds * 60).toInt() - 2) + assertEquals("$p still on", p, s.power) + s.run(4) + assertNull("$p gone after ${p.seconds} s", s.power) + } + assertEquals(listOf(8f, 8f, 3f, 10f), listOf(Power.SignalShield, Power.TurboTuner, Power.RewindBurst, Power.DoubleBroadcast).map { it.seconds }) + } + + @Test fun signalShieldSoaksUpOneHit() { + val s = sim(); s.place(Kind.SATELLITE, 40f, 40f) + s.collect(Power.SignalShield) + s.hurt() + assertEquals(3, s.bars); assertNull(s.power) + s.run(60); s.hurt() + assertEquals(2, s.bars) + } + + @Test fun guideBombClearsTheWeakInvadersOnly() { + val s = sim() + s.place(Kind.STATIC, 50f, 50f); s.place(Kind.GREMLIN, 90f, 50f); s.place(Kind.PIXEL_SMALL, 130f, 50f) + val sat = s.place(Kind.SATELLITE, 170f, 50f); val void = s.place(Kind.VOID, 210f, 50f) + s.collect(Power.GuideBomb) + assertEquals(listOf(sat, void), s.enemies.filter { it.active }) + } + + @Test fun doubleBroadcastFiresTwoAndRewindPushesTheWaveUp() { + val s = sim(); s.place(Kind.SATELLITE, 40f, 40f) + s.collect(Power.DoubleBroadcast) + s.step(firing) + assertEquals(2, s.liveShots()) + val s2 = RaidersSim(Pilot.Ollie, Difficulty.Normal, 4) + repeat(200) { s2.step(idle) } + val y = s2.formY + s2.collect(Power.RewindBurst) + repeat(170) { s2.step(idle) } + assertTrue(s2.formY < y - 20f) + } + + @Test fun overdriveNeedsAFullMeterAndEachPilotHasItsOwn() { + for (p in Pilot.entries) { + val s = sim(p); s.place(Kind.SATELLITE, 40f, 40f) + s.step(RaidersInput().apply { overdrive = true }) + assertEquals(0f, s.odLeft, 0f) + s.collect(Power.OrbitOverdrive) + s.step(RaidersInput().apply { overdrive = true }) + assertTrue("$p", s.odLeft > 0f) + assertEquals(0f, s.meter, 0f) + } + // Luna's slows everything but her ship; Blaze can't be hit mid-run. + val luna = sim(Pilot.Luna); luna.place(Kind.SATELLITE, 40f, 40f); luna.collect(Power.OrbitOverdrive); luna.step(RaidersInput().apply { overdrive = true }) + assertTrue(luna.slow < 1f) + val blaze = sim(Pilot.Blaze); blaze.place(Kind.SATELLITE, 40f, 40f); blaze.collect(Power.OrbitOverdrive); blaze.step(RaidersInput().apply { overdrive = true }) + blaze.hurt() + assertEquals(3, blaze.bars) + } + + @Test fun lunasShieldRegrows() { + val s = sim(Pilot.Luna); s.place(Kind.SATELLITE, 40f, 40f) + assertTrue(s.lunaShield) + s.hurt() + assertEquals(3, s.bars); assertFalse(s.lunaShield) + s.run((Pilot.Luna.shieldEvery * 60).toInt() + 2) + assertTrue(s.lunaShield) + } + + // ---------- the fixed step and pause ---------- + + @Test fun pauseFreezesTheSimulation() { + val step = FixedStep() + val s = RaidersSim(Pilot.Ollie, Difficulty.Normal, 3) + repeat(30) { repeat(step.ticks(16_666_667L, paused = false)) { s.step(idle) } } + val snapshot = listOf(s.ticks, s.formY, s.clock) + // Ten seconds paused: no ticks, and no time saved up for later either. + repeat(600) { assertEquals(0, step.ticks(16_666_667L, paused = true)) } + assertEquals(snapshot, listOf(s.ticks, s.formY, s.clock)) + assertEquals(1, step.ticks(16_666_667L, paused = false)) + } + + @Test fun aLongFrameNeverBecomesABurstOfTicks() { + val step = FixedStep() + assertEquals(FixedStep.MAX_TICKS, step.ticks(2_000_000_000L, paused = false)) + assertEquals(0, step.ticks(0L, paused = false)) + assertEquals(2, step.ticks(33_400_000L, paused = false)) + } + + @Test fun holdingFireShootsAtTheFixedRate() { + val s = sim(); s.place(Kind.SATELLITE, 40f, 40f) + var shots = 0 + repeat(60) { s.step(firing); if (s.takeEvents() and Events.SHOT != 0) shots++ } + // One second at Ollie's 0.22 s gap: the first at once, then four more. + assertEquals(5, shots) + } + + @Test fun theShipSpeedsUpWhileHeldAndBlazeIsQuicker() { + fun speedAfter(p: Pilot, ticks: Int): Float { val s = sim(p); s.place(Kind.SATELLITE, 40f, 40f); s.moveShipTo(60f); repeat(ticks) { s.step(RaidersInput().apply { move = 1 }) }; return s.shipVx } + assertTrue(speedAfter(Pilot.Ollie, 3) < speedAfter(Pilot.Ollie, 12)) + assertTrue(speedAfter(Pilot.Blaze, 30) > speedAfter(Pilot.Ollie, 30) * 1.15f) + } +} diff --git a/docs/VERIFICATION-orbi-raiders.md b/docs/VERIFICATION-orbi-raiders.md new file mode 100644 index 00000000..15bd5386 --- /dev/null +++ b/docs/VERIFICATION-orbi-raiders.md @@ -0,0 +1,73 @@ +# Orbi-Raiders prototype: verification (8 November 2026) + +Branch `arcade-orbi-raiders` from `arcade-stage-c` (`cdc3629`), worktree `/home/pauljd/Documents/OrbitTV/orbit-arcade`. +Version name and code unchanged (0.110.5-arcade-stage-c, 281): a prototype for review, not a release. Nothing pushed, +merged or installed; neither TV touched; `orbit-tv` and `orbit-tv-release` left alone. What it is: `docs/orbi-raiders-prototype.md`. + +## Checks + +One Gradle run (`assembleDebug assembleRelease testDebugUnitTest lintDebug`, with orbit-tv's `.tooling`), against the +`arcade-stage-c` APKs and lint report already on disk from its own build. + +| | arcade-stage-c | arcade-orbi-raiders | +|---|---|---| +| Build (debug and release) | passed | passed | +| Kotlin unit tests | 772 run, 24 skipped, 0 failed | **814 run, 24 skipped, 0 failed** (42 new) | +| Lint | 0 errors, 76 warnings | **0 errors, 76 warnings**: the same issue kinds with the same counts, none new | +| Debug APK | 51,885,071 bytes | 52,019,816 bytes (**+134,745**) | +| Release APK | 47,646,307 bytes | 47,728,227 bytes (**+81,920**, +0.17%) | + +The 24 skipped are the same hand-run replays as before. The Stage C debug APK was built at `07dd4b6`, before the version +bump in `cdc3629` that changed only the version; the release APK is `cdc3629`'s own (the one installed downstairs). + +Four Stage C tests used Orbi-Raiders as their example of a coming-soon card (`ArcadeSessionTest`, `KidsArcadeTest`). +They now use Channel Chaos, which still is, and the Kids-suitable count went from 7 games to play to 8. + +### New tests (`src/test/java/tv/orbit/classic/arcade/raiders`) + +- `RaidersSimTest` (25): a shot hits the invader above; Blaze's narrow shot misses where Ollie's hits; Zip pierces one; + Satellites take three hits; Corrupt Pixels split into two halves either side; Void Broadcasts only hittable while + showing; a hit costs a bar then a moment of safety; the last bar ends the run and freezes it; **the same seed builds the + same waves** and other seeds other mixes; **a whole bot run is identical for the same seed**; waves grow and kinds + arrive in turn (Gentle a row fewer); the Dead Channel on wave 5, its attacks warned, beaten into the result card and on to + wave 6; Restart Level back to the wave's start; **combo** ×2/×3/×4 thresholds, nine kills at ×1 then ×2, reset on a hit; + wave-clear bonus; **power-ups: only one timed at a time, a new one replaces it**, instant ones leave it alone; each timed + one lasts its seconds; Signal Shield soaks one hit; Guide Bomb clears only the weak; Double Broadcast fires two; Rewind + pushes the wave up; Overdrive needs a full meter, each pilot's own (Luna slows time, Blaze can't be hit); Luna's shield + regrows; **pause freezes the simulation** (ten seconds paused: no ticks and no time saved up); a long frame is at most + 5 ticks; holding fire shoots at the fixed rate (5 shots a second for Ollie); the ship speeds up while held, Blaze faster. +- `RaidersPlayTest` (14): **a held OK's repeats add no presses**; mashing OK, including a second "down" with no release, + never beats the fixed rate; ▲ one Overdrive per press; held moves and pause forgetting them; auto-fire assist; **every run + saved once** when the signal is lost, on Exit (and the screen's dispose after it), on Retry and when the screen goes + away; the best wave kept; top 10 only; **Kids start on Gentle**, grown-ups Normal, a choice wins and survives the file; + Gentle really is gentler on every number; Reduce flashing on and Auto-fire off until chosen, old files still read; + Orbi-Raiders playable and in the Kids-suitable set. +- `RaidersBalanceTest` (3): **pilot balance** (bot, Normal, 24 seeds, up to 10 min): score and damage per run within + ±15% of the mean (all within 5%), damage/s and survival within ±50% (Zip trades one for the other by design); + difficulty orders how far the bot gets; **allocation**: 10,000 ticks of bot play after a warm-up allocate **0 bytes** + (`ThreadMXBean.getThreadAllocatedBytes`), at most 49 sprites at once (cap 141, limit 150) and 40 sparks (cap 40), pools + the same arrays and sizes throughout. + +One real bug was found by the tests and fixed: a Corrupt Pixel's first half could take the parent's own pool place, so the +second half was placed from the overwritten position. + +## Not checked + +- **No emulator or AVD on this PC, and no TV was to be used: nothing was seen running.** The title, play screen, HUD, + pause and result cards, focus order, the feel of the controls and the frame times are checked only by the compiler, the + unit tests and reading the code against frames 10-13 and 20-23. +- Drawing allocation and frame times on the 2 GB box were not measured (only the simulation's allocation, on the JVM). +- No sound was heard; the cues are the existing `power_*.ogg` files through `ArcadeAudio`. + +## Proposed check on the box (for Paul to approve; not run) + +Read-only, while Paul plays, after an install he approves: + +```bash +ADB=/opt/android-sdk/platform-tools/adb; D=192.168.0.252:5555; P=tv.orbit.classic; OUT=~/Documents/OrbitTV/audits/orbi-raiders-$(date +%Y%m%d-%H%M); mkdir -p "$OUT" +$ADB connect $D +$ADB -s $D shell dumpsys gfxinfo $P reset # then about 2 minutes of waves 1-3 +$ADB -s $D shell dumpsys gfxinfo $P framestats > "$OUT/play-gfxinfo.txt"; $ADB -s $D shell dumpsys meminfo $P > "$OUT/play-meminfo.txt" +$ADB -s $D shell dumpsys gfxinfo $P reset # then the Dead Channel on wave 5 +$ADB -s $D shell dumpsys gfxinfo $P framestats > "$OUT/boss-gfxinfo.txt" +``` diff --git a/docs/orbi-raiders-prototype.md b/docs/orbi-raiders-prototype.md new file mode 100644 index 00000000..7980f4f8 --- /dev/null +++ b/docs/orbi-raiders-prototype.md @@ -0,0 +1,196 @@ +# Orbi-Raiders: playable prototype (Arcade Stage D) + +8 November 2026. Branch `arcade-orbi-raiders`, from `arcade-stage-c` (`cdc3629`), in the worktree +`/home/pauljd/Documents/OrbitTV/orbit-arcade`. Local commits only: nothing pushed or merged, nothing installed, no TV touched. + +Built from Stage B frames 10 (title), 11 (play), 12 (boss), 13 (result), 20-23 (shared menus), the power-up sheet +(`png/powerups.png`), the proposal decisions (pilots, invaders, power-ups) and `docs/arcade-stage-c.md`. It runs on the +Stage C framework (`ArcadeGame`, `ArcadeSession`, `ArcadeGameLoop`, `ArcadeInput`, `ArcadeAudio`, `ArcadeStore`, the cast +drawing functions). Everything is drawn in code on the Canvas; no engine, no bitmaps from disk, no new libraries. The cast is +unchanged: the pilots' faces are drawn by `drawOrbMascot` and `drawOrbChaser`, and only Ollie has a mouth. + +The Orbi-Raiders card in the Arcade is now playable (no longer "Coming soon") and is Kids-suitable. + +## Controls + +| Key | In play | +|---|---| +| ◀ ▶ (held) | Move. The ship speeds up while held and turns round quickly; it stops when let go. | +| OK | Fire. One press, one shot. | +| Hold OK | Auto-fire at the pilot's fixed rate. The remote's own key repeats never add shots (`RepeatGuard`). | +| ▲ | Overdrive, when the meter is full. One per press. | +| Back (or Play/Pause) | Pause: Resume, Restart Level, How to Play, Sound, Exit to Arcade. | + +Title (frame 10): ◀ ▶ choose a pilot, OK plays with that pilot, ▼ goes to the menu (Play, How to Play, Back to Arcade), +Back returns to the Arcade. The first game shows the shared How to Play card (frame 23) before the title, as every Arcade +game does. + +Result (frame 13): after a boss, **Next Wave**, Retry, Back to Arcade. When the signal is lost, Retry and Back to Arcade. + +## How it plays + +- Waves come down from the top in formation and sway side to side, stepping down at each edge. An invader that reaches the + Orbit signal costs a bar and pushes the wave back up. A cleared wave pays 100 × the wave number and the next one comes in. +- Every fifth wave is **The Dead Channel**: a grinning test-card CRT set with a faint 999 on its dial. It sways across the + top and cycles three attacks, each warned before it lands: **static rain** (the antennas light yellow, then five slow + shots in a fan), **the test-card beam** (its column is outlined yellow where the ship is, then a soft static band) and **two + little static sprites**. Its health bar and name are along the top. Beating it brings the result card; Next Wave goes on. +- The Orbit signal along the bottom is the lives: 3 bars (Zip 2). A hit costs a bar, resets the combo and gives a moment of + safety. No bars left and the run ends. + +### Invaders + +| Invader | First wave | Hits | Points | What it does | +|---|---|---|---|---| +| Static Sprite | 1 | 1 | 10 | The basic one; drops straight shots | +| Signal Gremlin | 2 | 1 | 20 | Breaks off and zigzag-dives at the ship, then flies back to its place | +| Corrupt Pixel | 3 | 1 | 15 | Splits into two small Pixel bits (1 hit, 5 points each) | +| Rogue Satellite | 4 (always the top row from 4) | 3 | 30 (+5 per armour hit) | Its panels dim as its armour goes; its shots lean towards the ship | +| Void Broadcast | 6 | 2 | 40 | Fades in and out; it can only be hit while it's showing | +| The Dead Channel | 5, 10, 15… | 45 / 60 / 80 (+20 each later boss) | 5 a hit, 1,500 × boss number when beaten | Above | + +### Pilots + +| Pilot | Top speed (units/s) | Shot gap | Shot width | Pierce | Bars | Shield | Overdrive | +|---|---|---|---|---|---|---|---| +| Ollie | 190 | 0.22 s | 6 | – | 3 | – | **Wide Orbit** (1.1 s): a ring sweeps out to 220 units, one hit on every invader it passes, clears the shots it passes, 6 on the boss | +| Blaze | 228 (+20%) | 0.22 s | 4.4 (narrow) | – | 3 | – | **Blaze Run** (3 s): dashes side to side on his own firing 4× as fast; can't be hit | +| Luna | 190 | 0.25 s (slower) | 6 | – | 3 | Regrows every 50 s | **Double Luna** (3.5 s): a shield, and everything but her ship at 60% speed | +| Zip | 190 | 0.23 s | 6 | 1 | 2 (one less) | – | **Zip Split** (2.2 s): a five-shot fan every 0.24 s | + +### Power-ups + +About one fallen invader in 13 at Normal drops a hexagon badge (Pixel bits never do). Catch it with the ship. **At most one +timed power-up is on at a time; a new one replaces it.** The HUD shows its badge with a ring for the time left, its name and +"n s left" in words, so it never relies on colour. + +| Power-up | Kind | What it does | Chance weight | +|---|---|---|---| +| Signal Shield | timed, 8 s | Soaks up one hit, then goes | 22 | +| Turbo Tuner | timed, 8 s | Ship 45% faster | 18 | +| Rewind Burst | timed, 3 s | Pushes the wave back up (up to 40 units) and the invaders fire at 35% | 14 | +| Double Broadcast | timed, 10 s | Two shots side by side | 22 | +| Guide Bomb | instant | Clears every weak invader on screen (Static Sprites, Gremlins, Pixel bits, the boss's sprites) | 12 | +| Orbit Overdrive | instant | Fills the Overdrive meter | 12 | + +The timings follow the approved proposal (and Paul's brief). **The Stage B power-up sheet says Turbo Tuner 10 s, Double +Broadcast 12 s and Guide Bomb "clears a row of the grid"**; the prototype uses 8 s, 10 s and "weak invaders". One of the two +needs updating once Paul has played it. + +### Score + +- Each invader's points × the combo multiplier: ×2 from 10 kills in a row without being hit, ×3 from 25, ×4 from 50. A hit + resets it to ×1. +- Wave cleared: +100 × wave (not multiplied). Boss beaten: +1,500 × boss number. Boss hit: 5 × multiplier. +- Overdrive meter: +4.5% a kill (1.5% a Pixel bit), +0.6% a boss hit. + +### Difficulty (Arcade Settings › Gameplay; Kids start on Gentle) + +| | Gentle | Normal | Tricky | +|---|---|---|---| +| Invader fire (× a base of one shot every 1.35 s, +7% a wave) | 0.5 | 1 | 1.45 | +| Invader shot speed (units/s) | 70 | 92 | 118 | +| Gremlin dives (× a base of one every 3.4 s, quicker later) | 0.55 | 1 | 1.4 | +| Formation sway (units/s, +5% a wave) | 12 | 16 | 22 | +| Power-up drop chance | 11% | 7.5% | 5.5% | +| The Dead Channel's health | 45 | 60 | 80 | +| Boss warning before each attack | 1.4 s | 1.0 s | 0.75 s | +| Safety after losing a bar | 2.2 s | 1.6 s | 1.2 s | +| Rows of invaders | one fewer | – | – | + +Waves: rows 2 + (wave − 1) / 2 (2 to 5), columns 5 + wave / 2 (up to 8). Wave 1 is 2 × 5 Static Sprites. + +The world is 420 × 300 units, scaled to the field. The ship accelerates at 1,500 units/s², stops at 2,200 and turns round at +3,600; player shots fly at 380 units/s. + +## Balance (bot, Normal, 24 seeded runs each, up to 10 minutes) + +The same bot flies each pilot through the same seeds (`RaidersBalanceTest`). It holds fire, leads the swaying formation, +steps out from under shots and the beam, and fires Overdrive when it's full. It plays better than a person, so these are +for comparing the pilots, not for how long a run lasts at home. + +| Pilot | Mean score | Damage/s | Survived (s) | Damage per run | Mean wave | +|---|---|---|---|---|---| +| Ollie | 56,395 | 3.53 | 271.5 | 958 | 14.5 | +| Blaze | 52,843 | 3.21 | 281.3 | 903 | 14.0 | +| Luna | 57,234 | 2.55 | 377.7 | 963 | 14.6 | +| Zip | 56,466 | 5.21 | 176.7 | 921 | 13.8 | + +Score and damage per run (damage/s × time survived) are within ±15% of the four-pilot mean (all within 5% today). Damage/s +and survival on their own trade against each other by design, so they're only held within ±50%: Zip is the glass cannon +(+44% damage/s, −36% survival), Luna the opposite. Difficulty orders how far the bot gets: Ollie reaches wave 25.9 on +Gentle, 15.5 on Normal and 10.5 on Tricky (12 seeds). + +## Accessibility + +- **Reduce motion** (Orbit-wide): no screen shake, no spark bursts, steady glows on the Dead Channel, a still flame, and the + NEW RECORD cheer stands still. +- **Reduce flashing** (Arcade Settings › Accessibility, **on by default**): no full-screen flashes; a hit only tints the + sprite, and the ship's moment of safety is steady see-through rather than blinking. With it off, losing a bar gives one + soft flash (18% white, 0.15 s) and the safe ship blinks gently. +- **Sound** goes through `ArcadeAudio`, so Orbit Quiet, night-quiet and Wind Down hold it down whatever is set. The pause + menu's Sound turns the game's effects on or off for this profile. Pausing pauses every cue still sounding. +- **Difficulty** Gentle / Normal / Tricky (Arcade Settings › Gameplay), per profile; a Kids profile starts on Gentle. +- **Auto-fire** (Arcade Settings › Gameplay, off by default): the ship fires on its own, no button held. +- Power-ups are named in words with their seconds left; pilots, bars and the boss's health are shapes and numbers as well + as colours. + +## Saves + +- Through `ArcadeStore`, per profile: the top 10 runs (points, detail "Wave n · Pilot"), the best wave (`level.bestWave`) and + the last pilot chosen (`level.pilot`). Reset Progress › level progress clears those two. +- **Every run is saved once, however it ends**: the signal lost, Retry, Back to Arcade, Exit from the pause menu, or the + screen going away mid-run (sleep timer, profile switch) through `RaidersRunBook` and the Stage C `RunTracker`. +- Arcade-wide choices added to the profile file: `choices.difficulty` (new, a string), `settings.autoFire`, + `settings.reduceFlashing`. Schema stays 1: older files read as before and older code ignores the new keys. + +## Performance (2 GB box) + +- Fixed 60 Hz simulation (`FixedStep`) apart from the screen's frames; a long frame is at most 5 ticks, and time paused or + hidden is thrown away. +- Pools made up front: 64 invaders, 40 player shots, 32 invader shots, 4 power-ups, 40 sparks (at most 141 sprites, under + 150; sparks at most 40). A full pool skips the spawn. +- **The simulation allocates nothing in steady play**: `RaidersBalanceTest` steps 10,000 ticks with the bot after a warm-up + and measures the thread's allocated bytes: **0**. The most sprites at once in that run was 49. +- Drawing: paths, strokes and the "999" text layout are made once (`RaidersArt`); the pilots' faces are drawn once into + 96 px bitmaps from the cast functions, because those build small lists as they draw. The field redraws each frame from a + frame counter without recomposing; the HUD numbers are separate states, so a kill recomposes only the score. Drawing + allocation was **not** measured (no device or emulator here). +- Pause stops the loop (`ArcadeGameLoop` gated), the simulation and its timers, and the sound (`ArcadeAudio.pauseAll`). + +## Code + +| File | What it holds | +|---|---| +| `arcade/raiders/RaidersSim.kt` | The rules: pools, waves (seeded), the Dead Channel, pilots, Overdrives, power-ups, scoring, `FixedStep`. No Android. | +| `arcade/raiders/RaidersControls.kt` | The remote in play (held moves, OK hold and repeat guard, ▲ once a press) and `RaidersRunBook` (every run saved once). | +| `arcade/raiders/RaidersArt.kt` | All the drawing: ships, invaders, badges, the Dead Channel, the beam, the signal. | +| `arcade/raiders/OrbiRaidersScreen.kt` | Title, play with its HUD, pause, result. | + +Changed in the framework: `ArcadeGames.kt` (the card is playable, a Sound effects setting), `ArcadePlay.kt` (difficulty, +auto-fire and reduce flashing for games that use them), `ArcadeStore.kt` (`choices`, `Difficulty`, the three readers), +`ArcadeAudio.kt` (`pauseAll`, `resumeAll`), `ArcadeHome.kt` (passes them in), `ArcadePages.kt` (Gameplay card with Difficulty +and Auto-fire; Reduce flashing). + +## Prototype only + +- One boss (The Dead Channel) for every fifth wave, a little tougher each time. +- Sound is the five existing `power_*.ogg` cues: a power-up caught, each pilot's Overdrive, the boss beaten. No shot, hit + or music sounds yet. +- The title has Play, How to Play and Back to Arcade; frame 10's High Scores and Settings buttons aren't there (both are on + the Arcade's own menu). +- The result card says "Saved to your high scores" rather than the profile's name. +- The game's result card comes after each boss and at the end of a run, not after every wave. +- No opening moment (the other games' host streaking in, `Moments.kt`): Orbi-Raiders opens straight on How to Play (first + time) or its title. + +## Known gaps + +- **Nothing has been seen running.** There is no emulator or AVD on this PC and no TV was to be used, so the screens, + focus order, feel and frame times are checked only by the compiler, the unit tests and reading the code against the + frames. The first look should be Paul's, on the box. +- Balance is a bot's balance. The real feel of the ship's acceleration with a held remote key, the auto-fire rate, the + Gentle setting for a child and the boss's warnings from the sofa all need a person. +- Frame 05's aim help, slower speed, hints, reduced impact sounds, high contrast, larger text and calm mode aren't built. +- The power-up sheet and the brief disagree on three power-ups (above). +- Per-profile Arcade saves still don't travel with Rooms' "Bring in" (as in Stage C).