Orbit Arcade Stage C: shared foundation, per-profile saves and the new Arcade home

- ArcadeStore: per-profile JSON (filesDir/arcade/<profileId>.json, schema 1) written
  through SafeWrite; top 10 runs per game, level progress, unlocks, settings,
  first-run flag and reset times. Missing or unreadable files start afresh.
- Household Records: one read-only snapshot of the old box-wide scores, never
  rewritten and linked to no profile. The old keys are only read.
- ArcadeGame registry (5 Orbit Originals, 8 Classics), ArcadeSession and Reset
  state machines, ArcadeInput (key map, OK hold-repeat guard), ArcadeAudio (one
  SoundPool + one MediaPlayer under Orbit Quiet / night-quiet / Wind Down),
  ArcadeGameLoop gated by pause, lifecycle and window focus.
- The eight Kotlin games wrapped with gameplay unchanged: every run is saved when
  it ends, including Leave; Block Drop and Blast Off ignore a held OK; Pairs and
  Patience get the shared pause; Reduce motion honoured by the Comet Trail
  crossfade and the Pairs flip.
- Arcade home, High Scores, How to Play, Arcade Settings and Reset Progress from
  the Stage B frames; Kids see only the games allowed for them.
- Family: Arcade for Kids (Off / Kids-suitable / Chosen games, behind the PIN),
  replacing the misleading "the games chosen for Kids" line.
- BumbleHive host: lifecycle pause/resume and a small bridge for profile,
  settings and runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-08 19:08:44 +00:00
co-authored by Claude Opus 5.5
parent 84b28b6f34
commit bdb0bcf0c0
25 changed files with 2232 additions and 457 deletions
@@ -1,5 +1,10 @@
package tv.orbit.classic
import tv.orbit.classic.arcade.ArcadePlay
import tv.orbit.classic.arcade.PauseWhenHidden
import tv.orbit.classic.arcade.RepeatGuard
import tv.orbit.classic.arcade.RunEnd
import tv.orbit.classic.arcade.rememberRun
import android.view.KeyEvent
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Canvas
@@ -171,17 +176,21 @@ private fun DrawScope.drawTrayPiece(p: BlastPiece, cell: Float) {
}
@Composable
internal fun BlastOffScreen(best: Int, onBest: (Int) -> Unit, onLeave: () -> Unit) {
val calm = LocalContext.current.let { context -> remember { OrbitSettings(context).reduceMotion } }
internal fun BlastOffScreen(play: ArcadePlay) {
val best = play.best
val calm = Motion.reduce
val random = remember { java.util.Random() }
var game by remember { mutableStateOf(BlastGame.start(random)) }
var paused by remember { mutableStateOf(false) }
val focus = remember { FocusRequester() }
val menuFocus = remember { FocusRequester() }
val windowFocused = LocalWindowInfo.current.isWindowFocused
LaunchedEffect(windowFocused) { if (!windowFocused && game.alive) paused = true }
// Holding OK places one shape, not one after another (audit finding 8).
val guard = remember { RepeatGuard() }
PauseWhenHidden(game.alive) { paused = true; guard.reset() }
LaunchedEffect(paused, game.alive) { if (paused || !game.alive) menuFocus.requestFocus() else focus.requestFocus() }
LaunchedEffect(game.alive) { if (!game.alive && game.score > best) onBest(game.score) }
// Every run is saved when it ends, however it ends (Arcade Stage C): game over, Leave, or the screen going away.
val run = rememberRun(play.onRunEnd) { RunEnd(game.score, finished = false) }
LaunchedEffect(game.alive) { if (game.alive) run.begin() else run.end(RunEnd(game.score, finished = true)) }
// Zip zooms past on a combo.
var zipAt by remember { mutableLongStateOf(-1L) }
var now by remember { mutableLongStateOf(0L) }
@@ -189,16 +198,18 @@ internal fun BlastOffScreen(best: Int, onBest: (Int) -> Unit, onLeave: () -> Uni
// The best as it stood while this game was played, so the new best still shows once it's been saved; Zip and Blaze cheer it.
val bestBefore = remember(game.alive) { best }
val newBest = game.score > bestBefore && game.score > 0
BackHandler { if (game.alive) paused = !paused else onLeave() }
BackHandler { if (game.alive) paused = !paused else play.onLeave() }
Row(Modifier.fillMaxSize().arcadeBackdrop().padding(20.dp).focusRequester(focus).focusable().onPreviewKeyEvent { event ->
val native = event.nativeKeyEvent
// Releases are always noted, so the guard knows OK was let go even if the game paused meanwhile.
if (native.action == KeyEvent.ACTION_UP) { guard.accept(native); return@onPreviewKeyEvent false }
if (native.action != KeyEvent.ACTION_DOWN || paused || !game.alive) return@onPreviewKeyEvent false
val next = when (native.keyCode) {
KeyEvent.KEYCODE_DPAD_LEFT -> game.move(-1, 0)
KeyEvent.KEYCODE_DPAD_RIGHT -> game.move(1, 0)
KeyEvent.KEYCODE_DPAD_UP -> game.move(0, -1)
KeyEvent.KEYCODE_DPAD_DOWN -> game.move(0, 1)
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER -> game.press(random).also { if (it.lastCleared >= 2 || it.streak >= 2) zipAt = System.currentTimeMillis() }
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER -> if (!guard.accept(native)) game else game.press(random).also { if (it.lastCleared >= 2 || it.streak >= 2) zipAt = System.currentTimeMillis() }
else -> null
}
if (next != null) game = next
@@ -247,7 +258,7 @@ internal fun BlastOffScreen(best: Int, onBest: (Int) -> Unit, onLeave: () -> Uni
if (!game.alive) game = BlastGame.start(random)
paused = false
})
OrbitButton("Leave the game", Modifier.width(200.dp), onClick = onLeave)
OrbitButton("Leave the game", Modifier.width(200.dp), onClick = play.onLeave)
}
}
}
@@ -1,5 +1,10 @@
package tv.orbit.classic
import tv.orbit.classic.arcade.ArcadePlay
import tv.orbit.classic.arcade.PauseWhenHidden
import tv.orbit.classic.arcade.RepeatGuard
import tv.orbit.classic.arcade.RunEnd
import tv.orbit.classic.arcade.rememberRun
import android.view.KeyEvent
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Canvas
@@ -157,32 +162,38 @@ private fun NextPiece(kind: Int, modifier: Modifier) = Canvas(modifier) {
}
@Composable
internal fun BlockDropScreen(best: Int, onBest: (Int) -> Unit, onLeave: () -> Unit) {
internal fun BlockDropScreen(play: ArcadePlay) {
val best = play.best
val random = remember { java.util.Random() }
var game by remember { mutableStateOf(BlockGame.start(random)) }
var paused by remember { mutableStateOf(false) }
val focus = remember { FocusRequester() }
val windowFocused = LocalWindowInfo.current.isWindowFocused
LaunchedEffect(windowFocused) { if (!windowFocused && game.alive) paused = true }
// Holding OK drops one piece, not one after another (audit finding 8).
val guard = remember { RepeatGuard() }
PauseWhenHidden(game.alive) { paused = true; guard.reset() }
LaunchedEffect(paused, game.alive) {
while (!paused && game.alive) { kotlinx.coroutines.delay(game.tickMs); game = game.fall(random = random) }
if (!game.alive && game.score > best) onBest(game.score)
}
// Every run is saved when it ends, however it ends (Arcade Stage C): game over, Leave, or the screen going away.
val run = rememberRun(play.onRunEnd) { RunEnd(game.score, finished = false, detail = "Level ${game.level}") }
LaunchedEffect(game.alive) { if (game.alive) run.begin() else run.end(RunEnd(game.score, finished = true, detail = "Level ${game.level}")) }
val menuFocus = remember { FocusRequester() }
LaunchedEffect(paused, game.alive) { if (paused || !game.alive) menuFocus.requestFocus() else focus.requestFocus() }
// The best as it stood while this game was played, so the new best still shows once it's been saved; Zip and Blaze cheer it.
val bestBefore = remember(game.alive) { best }
val newBest = game.score > bestBefore && game.score > 0
BackHandler { if (game.alive) paused = !paused else onLeave() }
BackHandler { if (game.alive) paused = !paused else play.onLeave() }
Row(Modifier.fillMaxSize().arcadeBackdrop().padding(20.dp).focusRequester(focus).focusable().onPreviewKeyEvent { event ->
val native = event.nativeKeyEvent
// Releases are always noted, so the guard knows OK was let go even if the game paused meanwhile.
if (native.action == KeyEvent.ACTION_UP) { guard.accept(native); return@onPreviewKeyEvent false }
if (native.action != KeyEvent.ACTION_DOWN || paused || !game.alive) return@onPreviewKeyEvent false
val next = when (native.keyCode) {
KeyEvent.KEYCODE_DPAD_LEFT -> game.move(-1)
KeyEvent.KEYCODE_DPAD_RIGHT -> game.move(1)
KeyEvent.KEYCODE_DPAD_UP -> game.turn()
KeyEvent.KEYCODE_DPAD_DOWN -> game.fall(pressed = true, random = random)
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER -> game.drop(random)
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER -> if (guard.accept(native)) game.drop(random) else game
else -> null
}
if (next != null) game = next
@@ -213,7 +224,7 @@ internal fun BlockDropScreen(best: Int, onBest: (Int) -> Unit, onLeave: () -> Un
if (!game.alive) game = BlockGame.start(random)
paused = false
})
OrbitButton("Leave the game", Modifier.width(200.dp), onClick = onLeave)
OrbitButton("Leave the game", Modifier.width(200.dp), onClick = play.onLeave)
}
}
Column(Modifier.width(130.dp).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
@@ -1,5 +1,11 @@
package tv.orbit.classic
import tv.orbit.classic.arcade.ArcadeGameLoop
import tv.orbit.classic.arcade.ArcadePlay
import tv.orbit.classic.arcade.PauseWhenHidden
import tv.orbit.classic.arcade.RunEnd
import tv.orbit.classic.arcade.loopRuns
import tv.orbit.classic.arcade.rememberRun
import android.view.KeyEvent
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Canvas
@@ -250,33 +256,29 @@ internal fun BrickField(game: BrickGame, modifier: Modifier) = Canvas(modifier)
}
@Composable
internal fun BrickBreakScreen(best: Int, onBest: (Int) -> Unit, onLeave: () -> Unit) {
internal fun BrickBreakScreen(play: ArcadePlay) {
val best = play.best
var game by remember { mutableStateOf(BrickGame.start()) }
val context = androidx.compose.ui.platform.LocalContext.current
val sfx = remember { BrickSounds(context) }
val settings = remember { OrbitSettings(context) }
var soundsOn by remember { mutableStateOf(settings.arcadeSounds) }
DisposableEffect(sfx) { onDispose { sfx.release() } }
var soundsOn by remember { mutableStateOf(play.setting("sounds")) }
LaunchedEffect(Unit) { play.audio.preload(*BrickPowerSounds.values.toIntArray()) }
var paused by remember { mutableStateOf(false) }
var held by remember { mutableIntStateOf(0) }
val focus = remember { FocusRequester() }
val windowFocused = LocalWindowInfo.current.isWindowFocused
LaunchedEffect(windowFocused) { if (!windowFocused && game.alive) paused = true }
LaunchedEffect(paused, game.alive) {
var last = withFrameNanos { it }
while (!paused && game.alive) {
val now = withFrameNanos { it }
game = game.step(((now - last) / 1e9f).coerceAtMost(.05f), held); last = now
if (game.sounds.isNotEmpty()) { if (soundsOn) game.sounds.forEach { sfx.play(it) }; game = game.copy(sounds = emptyList()) }
}
if (!game.alive && game.score > best) onBest(game.score)
PauseWhenHidden(game.alive) { paused = true }
// Every run is saved when it ends, however it ends (Arcade Stage C): game over, Leave, or the screen going away.
val run = rememberRun(play.onRunEnd) { RunEnd(game.score, finished = false, detail = "Wall ${game.level}") }
LaunchedEffect(game.alive) { if (game.alive) run.begin() else run.end(RunEnd(game.score, finished = true, detail = "Wall ${game.level}")) }
ArcadeGameLoop(loopRuns(paused, game.alive, shown = true)) { _, dt ->
if (paused || !game.alive) return@ArcadeGameLoop
game = game.step((dt / 1e9f).coerceAtMost(.05f), held)
if (game.sounds.isNotEmpty()) { game.sounds.forEach { power -> BrickPowerSounds[power]?.let { play.audio.cue(it, .7f, soundsOn) } }; game = game.copy(sounds = emptyList()) }
}
val menuFocus = remember { FocusRequester() }
LaunchedEffect(paused, game.alive) { if (paused || !game.alive) menuFocus.requestFocus() else focus.requestFocus() }
// The best as it stood while this game was played, so the new best still shows once it's been saved; Zip and Blaze cheer it.
val bestBefore = remember(game.alive) { best }
val newBest = game.score > bestBefore && game.score > 0
BackHandler { if (game.alive) paused = !paused else onLeave() }
BackHandler { if (game.alive) paused = !paused else play.onLeave() }
Row(Modifier.fillMaxSize().arcadeBackdrop().padding(20.dp).focusRequester(focus).focusable().onPreviewKeyEvent { event ->
val native = event.nativeKeyEvent
if (paused || !game.alive) return@onPreviewKeyEvent false
@@ -317,20 +319,13 @@ internal fun BrickBreakScreen(best: Int, onBest: (Int) -> Unit, onLeave: () -> U
if (!game.alive) game = BrickGame.start()
held = 0; paused = false
})
OrbitButton("Sounds: ${if (soundsOn) "On" else "Off"}", Modifier.width(200.dp), onClick = { soundsOn = !soundsOn; settings.arcadeSounds = soundsOn })
OrbitButton("Leave the game", Modifier.width(200.dp), onClick = onLeave)
OrbitButton("Sounds: ${if (soundsOn) "On" else "Off"}", Modifier.width(200.dp), onClick = { soundsOn = !soundsOn; play.setSetting("sounds", soundsOn) })
OrbitButton("Leave the game", Modifier.width(200.dp), onClick = play.onLeave)
}
}
}
}
/** Each power's short sound, made for Orbit (design/arcade/build-power-sounds.py); quiet, and only while a game plays. */
internal class BrickSounds(context: android.content.Context) {
private val pool = android.media.SoundPool.Builder().setMaxStreams(3)
.setAudioAttributes(android.media.AudioAttributes.Builder().setUsage(android.media.AudioAttributes.USAGE_GAME).setContentType(android.media.AudioAttributes.CONTENT_TYPE_SONIFICATION).build()).build()
private val ids = mapOf(BrickPower.DoubleLuna to R.raw.power_double_luna, BrickPower.BlazeRun to R.raw.power_blaze_run, BrickPower.DriftNet to R.raw.power_drift_net,
BrickPower.ZipSplit to R.raw.power_zip_split, BrickPower.WideOrbit to R.raw.power_wide_orbit).mapValues { (_, raw) -> pool.load(context, raw, 1) }
fun play(power: BrickPower) { ids[power]?.let { pool.play(it, .7f, .7f, 1, 0, 1f) } }
fun release() = pool.release()
}
/** Each power's short sound, made for Orbit (design/arcade/build-power-sounds.py); quiet, and played through the Arcade's one sound service. */
internal val BrickPowerSounds = mapOf(BrickPower.DoubleLuna to R.raw.power_double_luna, BrickPower.BlazeRun to R.raw.power_blaze_run, BrickPower.DriftNet to R.raw.power_drift_net,
BrickPower.ZipSplit to R.raw.power_zip_split, BrickPower.WideOrbit to R.raw.power_wide_orbit)
@@ -1,5 +1,11 @@
package tv.orbit.classic
import tv.orbit.classic.arcade.ArcadeGameLoop
import tv.orbit.classic.arcade.ArcadePlay
import tv.orbit.classic.arcade.PauseWhenHidden
import tv.orbit.classic.arcade.RunEnd
import tv.orbit.classic.arcade.loopRuns
import tv.orbit.classic.arcade.rememberRun
import android.view.KeyEvent
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Canvas
@@ -439,20 +445,21 @@ private class OrbSounds {
OrbEvent.Catch.name to tone(260, 500.0, 1200.0, .22), OrbEvent.Caught.name to tone(900, 720.0, 140.0, .22), OrbEvent.Cleared.name to tone(600, 520.0, 1040.0, .2))
}.getOrDefault(emptyMap())
private var flip = false
fun play(event: OrbEvent) {
/** Plays [event] at [level] (the Arcade's effects level under Orbit's quiet ceiling); nothing at 0. */
fun play(event: OrbEvent, level: Float = 1f) {
if (level <= 0f) return
val key = if (event == OrbEvent.Star) { flip = !flip; if (flip) "starA" else "starB" } else event.name
val track = tracks[key] ?: return
runCatching { track.stop(); track.reloadStaticData(); track.play() }
runCatching { track.setVolume(level); track.stop(); track.reloadStaticData(); track.play() }
}
fun release() = tracks.values.forEach { runCatching { it.release() } }
}
@Composable
internal fun OrbManScreen(best: Int, onBest: (Int) -> Unit, onLeave: () -> Unit) {
val context = LocalContext.current
val settings = remember { OrbitSettings(context) }
val calm = remember { settings.reduceMotion }
var soundOn by remember { mutableStateOf(settings.orbManSound) }
internal fun OrbManScreen(play: ArcadePlay) {
val best = play.best
val calm = Motion.reduce
var soundOn by remember { mutableStateOf(play.setting("sound")) }
val sounds = remember { OrbSounds() }
DisposableEffect(Unit) { onDispose { sounds.release() } }
val random = remember { java.util.Random() }
@@ -462,35 +469,33 @@ internal fun OrbManScreen(best: Int, onBest: (Int) -> Unit, onLeave: () -> Unit)
var clock by remember { mutableLongStateOf(0L) }
val focus = remember { FocusRequester() }
val menuFocus = remember { FocusRequester() }
val windowFocused = LocalWindowInfo.current.isWindowFocused
LaunchedEffect(windowFocused) { if (!windowFocused && game.alive) paused = true }
PauseWhenHidden(game.alive) { paused = true }
// Every run is saved when it ends, however it ends (Arcade Stage C): game over, Leave, or the screen going away.
val run = rememberRun(play.onRunEnd) { RunEnd(game.score, finished = false, detail = "Level ${game.level}") }
LaunchedEffect(game.alive) { if (game.alive) run.begin() else run.end(RunEnd(game.score, finished = true, detail = "Level ${game.level}")) }
// One frame clock: whole ticks move the game, what's left over places everyone smoothly in between.
LaunchedEffect(paused, game.alive) {
var last = -1L; var carry = 0L
while (!paused && game.alive) {
withFrameNanos { now ->
val ms = now / 1_000_000
if (last >= 0) carry += (ms - last).coerceAtMost(100)
last = ms
clock = ms
var g = game
while (carry >= ORB_TICK_MS) {
carry -= ORB_TICK_MS
g = g.step(random)
if (soundOn) g.events.forEach(sounds::play)
if (!g.alive) break
}
game = g
phase = carry.toFloat() / ORB_TICK_MS
}
var carry by remember { mutableLongStateOf(0L) }
ArcadeGameLoop(loopRuns(paused, game.alive, shown = true), onStart = { carry = 0L; phase = 0f }) { now, dt ->
if (paused || !game.alive) return@ArcadeGameLoop
val ms = now / 1_000_000
carry += (ms - (now - dt) / 1_000_000).coerceAtMost(100)
clock = ms
var g = game
val level = play.audio.effects(1f, soundOn)
while (carry >= ORB_TICK_MS) {
carry -= ORB_TICK_MS
g = g.step(random)
if (level > 0f) g.events.forEach { sounds.play(it, level) }
if (!g.alive) break
}
if (!game.alive && game.score > best) onBest(game.score)
game = g
phase = carry.toFloat() / ORB_TICK_MS
}
LaunchedEffect(paused, game.alive) { if (paused || !game.alive) menuFocus.requestFocus() else focus.requestFocus() }
// The best as it stood while this game was played, so the new best still shows once it's been saved; Zip and Blaze cheer it.
val bestBefore = remember(game.alive) { best }
val newBest = game.score > bestBefore && game.score > 0
BackHandler { if (game.alive) paused = !paused else onLeave() }
BackHandler { if (game.alive) paused = !paused else play.onLeave() }
// The power glow breathes gently; with Reduce motion on it holds steady.
val glow = if (!game.powered) 0f else if (calm) .7f else .55f + .25f * sin(clock / 400.0).toFloat()
Row(Modifier.fillMaxSize().arcadeBackdrop().padding(20.dp).focusRequester(focus).focusable().onPreviewKeyEvent { event ->
@@ -538,8 +543,8 @@ internal fun OrbManScreen(best: Int, onBest: (Int) -> Unit, onLeave: () -> Unit)
if (!game.alive) game = OrbGame.start()
paused = false
})
OrbitButton("Sound: ${if (soundOn) "On" else "Off"}", Modifier.width(200.dp), onClick = { soundOn = !soundOn; settings.orbManSound = soundOn })
OrbitButton("Leave the game", Modifier.width(200.dp), onClick = onLeave)
OrbitButton("Sound: ${if (soundOn) "On" else "Off"}", Modifier.width(200.dp), onClick = { soundOn = !soundOn; play.setSetting("sound", soundOn) })
OrbitButton("Leave the game", Modifier.width(200.dp), onClick = play.onLeave)
}
}
}
@@ -1,5 +1,13 @@
package tv.orbit.classic
import tv.orbit.classic.arcade.ArcadeGames
import tv.orbit.classic.arcade.ArcadePauseMenu
import tv.orbit.classic.arcade.ArcadePlay
import tv.orbit.classic.arcade.RunEnd
import tv.orbit.classic.arcade.SessionEvent
import tv.orbit.classic.arcade.SessionState
import tv.orbit.classic.arcade.reduceSession
import tv.orbit.classic.arcade.rememberRun
import android.view.KeyEvent
import androidx.activity.compose.BackHandler
import androidx.compose.animation.core.animateFloatAsState
@@ -75,7 +83,8 @@ private val Honey = Color(0xFFFFD84A)
@Composable
private fun PairsCard(channel: Int, up: Boolean, matched: Boolean, selected: Boolean, modifier: Modifier) {
val turn by animateFloatAsState(if (up) 1f else 0f, tween(260), label = "turn")
// Reduce motion: the card shows its face at once instead of turning over.
val turn by animateFloatAsState(if (up) 1f else 0f, tween(if (Motion.reduce) 0 else 260), label = "turn")
Box(modifier.graphicsLayer { rotationY = 180f * (1 - turn); cameraDistance = 12 * density }
.background(if (turn > .5f) Color(0xFF0B1B44) else NightPanel, RoundedCornerShape(8.dp))
.border(if (selected) 3.dp else 1.dp, if (selected) NightYellow else if (matched) Honey else NightBlue, RoundedCornerShape(8.dp)), contentAlignment = Alignment.Center) {
@@ -90,57 +99,76 @@ private fun PairsCard(channel: Int, up: Boolean, matched: Boolean, selected: Boo
}
@Composable
internal fun PairsScreen(best: Int, onBest: (Int) -> Unit, onLeave: () -> Unit) {
internal fun PairsScreen(play: ArcadePlay) {
val best = play.best
val random = remember { java.util.Random() }
var game by remember { mutableStateOf(PairsGame.deal(random)) }
val focus = remember { FocusRequester() }
val menuFocus = remember { FocusRequester() }
// The shared pause (Arcade Stage C): Back pauses instead of leaving at once.
var session by remember { mutableStateOf<SessionState>(SessionState.Play) }
LaunchedEffect(session) { if (session == SessionState.Exited) play.onLeave() else if (session == SessionState.Play && !game.done) runCatching { focus.requestFocus() } }
LaunchedEffect(game.waiting) { if (game.waiting) { delay(900); game = game.hide() } }
var newBest by remember { mutableStateOf(false) }
LaunchedEffect(game.done) { if (game.done) { newBest = best == 0 || game.moves < best; if (newBest) onBest(game.moves); menuFocus.requestFocus() } else focus.requestFocus() }
BackHandler(onBack = onLeave)
Row(Modifier.fillMaxSize().arcadeBackdrop().padding(20.dp).focusRequester(focus).focusable().onPreviewKeyEvent { event ->
val native = event.nativeKeyEvent
if (native.action != KeyEvent.ACTION_DOWN || game.done) return@onPreviewKeyEvent false
val next = when (native.keyCode) {
KeyEvent.KEYCODE_DPAD_LEFT -> game.moveCursor(-1, 0)
KeyEvent.KEYCODE_DPAD_RIGHT -> game.moveCursor(1, 0)
KeyEvent.KEYCODE_DPAD_UP -> game.moveCursor(0, -1)
KeyEvent.KEYCODE_DPAD_DOWN -> game.moveCursor(0, 1)
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER -> game.flip()
else -> null
}
if (next != null) game = next
next != null
}, horizontalArrangement = Arrangement.spacedBy(20.dp)) {
Column(Modifier.width(190.dp).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text("PAIRS", color = Honey, fontFamily = Marquee, fontSize = 40.sp)
Spacer(Modifier.height(10.dp))
Text("MOVES", color = NightMuted, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp)
Text(game.moves.toString(), color = Color.White, fontFamily = Marquee, fontSize = 36.sp)
Text("BEST", color = NightMuted, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp)
Text(if (best == 0) "–" else best.toString(), color = Color.White, fontFamily = Marquee, fontSize = 36.sp)
Text("PAIRS ${game.matched.size / 2} OF ${game.cards.size / 2}", color = NightMuted, fontSize = 13.sp, fontWeight = FontWeight.SemiBold)
Spacer(Modifier.weight(1f))
Text("◄►▲▼ Move OK Turn", color = NightMuted, fontSize = 13.sp)
Text("Back Leave", color = NightMuted, fontSize = 13.sp)
}
Box(Modifier.weight(1f).fillMaxHeight(), contentAlignment = Alignment.Center) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
for (row in 0 until PAIRS_ROWS) Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
for (col in 0 until PAIRS_COLUMNS) {
val i = row * PAIRS_COLUMNS + col
PairsCard(PairsChannels[game.cards[i]], i in game.matched || i in game.open, i in game.matched, i == game.cursor && !game.done, Modifier.width(120.dp).height(76.dp))
// A cleared board is saved for this profile; leaving part-way saves nothing (fewest moves only counts when it's done).
val run = rememberRun(play.onRunEnd) { RunEnd(game.moves, finished = game.done) }
LaunchedEffect(game.done) {
if (game.done) {
newBest = best == 0 || game.moves < best
run.end(RunEnd(game.moves, finished = true))
session = reduceSession(session, SessionEvent.Finish(RunEnd(game.moves, true), newBest))
menuFocus.requestFocus()
} else { run.begin(); focus.requestFocus() }
}
BackHandler(session == SessionState.Play || session is SessionState.Result) { session = reduceSession(session, SessionEvent.Back) }
Box(Modifier.fillMaxSize()) {
Row(Modifier.fillMaxSize().arcadeBackdrop().padding(20.dp).focusRequester(focus).focusable().onPreviewKeyEvent { event ->
val native = event.nativeKeyEvent
if (native.action != KeyEvent.ACTION_DOWN || game.done || session != SessionState.Play) return@onPreviewKeyEvent false
val next = when (native.keyCode) {
KeyEvent.KEYCODE_DPAD_LEFT -> game.moveCursor(-1, 0)
KeyEvent.KEYCODE_DPAD_RIGHT -> game.moveCursor(1, 0)
KeyEvent.KEYCODE_DPAD_UP -> game.moveCursor(0, -1)
KeyEvent.KEYCODE_DPAD_DOWN -> game.moveCursor(0, 1)
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER -> game.flip()
else -> null
}
if (next != null) game = next
next != null
}, horizontalArrangement = Arrangement.spacedBy(20.dp)) {
Column(Modifier.width(190.dp).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text("PAIRS", color = Honey, fontFamily = Marquee, fontSize = 40.sp)
Spacer(Modifier.height(10.dp))
Text("MOVES", color = NightMuted, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp)
Text(game.moves.toString(), color = Color.White, fontFamily = Marquee, fontSize = 36.sp)
Text("BEST", color = NightMuted, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp)
Text(if (best == 0) "–" else best.toString(), color = Color.White, fontFamily = Marquee, fontSize = 36.sp)
Text("PAIRS ${game.matched.size / 2} OF ${game.cards.size / 2}", color = NightMuted, fontSize = 13.sp, fontWeight = FontWeight.SemiBold)
Spacer(Modifier.weight(1f))
Text("◄►▲▼ Move OK Turn", color = NightMuted, fontSize = 13.sp)
Text("Back Pause", color = NightMuted, fontSize = 13.sp)
}
Box(Modifier.weight(1f).fillMaxHeight(), contentAlignment = Alignment.Center) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
for (row in 0 until PAIRS_ROWS) Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
for (col in 0 until PAIRS_COLUMNS) {
val i = row * PAIRS_COLUMNS + col
PairsCard(PairsChannels[game.cards[i]], i in game.matched || i in game.open, i in game.matched, i == game.cursor && !game.done, Modifier.width(120.dp).height(76.dp))
}
}
}
}
if (game.done) Column(Modifier.background(NightNavy, RoundedCornerShape(6.dp)).border(2.dp, Honey, RoundedCornerShape(6.dp)).padding(20.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("ALL PAIRED", color = Honey, fontFamily = Marquee, fontSize = 30.sp)
if (newBest) CastCheer()
Text(if (newBest) "New best: ${game.moves} moves" else "${game.moves} moves", color = Color.White, fontSize = 16.sp)
OrbitButton("Play again", Modifier.width(200.dp).focusRequester(menuFocus), onClick = { game = PairsGame.deal(random) })
OrbitButton("Leave the game", Modifier.width(200.dp), onClick = onLeave)
if (game.done) Column(Modifier.background(NightNavy, RoundedCornerShape(6.dp)).border(2.dp, Honey, RoundedCornerShape(6.dp)).padding(20.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("ALL PAIRED", color = Honey, fontFamily = Marquee, fontSize = 30.sp)
if (newBest) CastCheer()
Text(if (newBest) "New best: ${game.moves} moves" else "${game.moves} moves", color = Color.White, fontSize = 16.sp)
OrbitButton("Play again", Modifier.width(200.dp).focusRequester(menuFocus), onClick = { game = PairsGame.deal(random); session = reduceSession(session, SessionEvent.PlayAgain) })
OrbitButton("Leave the game", Modifier.width(200.dp), onClick = play.onLeave)
}
}
}
if (session is SessionState.Pause) ArcadePauseMenu(ArcadeGames.Pairs, "Pairs · ${game.moves} moves · ${game.matched.size / 2} of ${game.cards.size / 2} pairs",
onResume = { session = reduceSession(session, SessionEvent.Resume) },
onRestart = { run.end(RunEnd(game.moves, finished = false)); run.begin(); game = PairsGame.deal(random); session = reduceSession(session, SessionEvent.Restart) },
onExit = { session = reduceSession(session, SessionEvent.Exit) })
}
}
@@ -1,5 +1,13 @@
package tv.orbit.classic
import tv.orbit.classic.arcade.ArcadeGames
import tv.orbit.classic.arcade.ArcadePauseMenu
import tv.orbit.classic.arcade.ArcadePlay
import tv.orbit.classic.arcade.RunEnd
import tv.orbit.classic.arcade.SessionEvent
import tv.orbit.classic.arcade.SessionState
import tv.orbit.classic.arcade.reduceSession
import tv.orbit.classic.arcade.rememberRun
import android.view.KeyEvent
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
@@ -139,76 +147,96 @@ private fun CardFace(card: PlayingCard?, empty: String = "", modifier: Modifier
}
@Composable
internal fun PatienceScreen(wins: Int, onWin: () -> Unit, onLeave: () -> Unit) {
internal fun PatienceScreen(play: ArcadePlay) {
val wins = play.best
val random = remember { java.util.Random() }
var game by remember { mutableStateOf(PatienceGame.deal(random)) }
val focus = remember { FocusRequester() }
val menuFocus = remember { FocusRequester() }
LaunchedEffect(game.won) { if (game.won) { onWin(); menuFocus.requestFocus() } else focus.requestFocus() }
BackHandler { if (game.held != null) game = game.drop() else onLeave() }
Row(Modifier.fillMaxSize().background(Color(0xFF0A2A1F)).padding(16.dp).focusRequester(focus).focusable().onPreviewKeyEvent { event ->
val native = event.nativeKeyEvent
if (native.action != KeyEvent.ACTION_DOWN || game.won) return@onPreviewKeyEvent false
val next = when (native.keyCode) {
KeyEvent.KEYCODE_DPAD_LEFT -> game.steer(-1, 0)
KeyEvent.KEYCODE_DPAD_RIGHT -> game.steer(1, 0)
KeyEvent.KEYCODE_DPAD_UP -> game.steer(0, -1)
KeyEvent.KEYCODE_DPAD_DOWN -> game.steer(0, 1)
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER -> if (native.repeatCount > 0) null else game.press()
KeyEvent.KEYCODE_MENU, KeyEvent.KEYCODE_PROG_RED -> game.sendHome()
else -> null
}
if (next != null) game = next
next != null
}, horizontalArrangement = Arrangement.spacedBy(16.dp)) {
Column(Modifier.width(170.dp).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text("PATIENCE", color = Honey, fontFamily = Marquee, fontSize = 34.sp)
Spacer(Modifier.height(10.dp))
Text("MOVES", color = NightMuted, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp)
Text(game.moves.toString(), color = Color.White, fontFamily = Marquee, fontSize = 32.sp)
Text("GAMES WON", color = NightMuted, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp)
Text(wins.toString(), color = Color.White, fontFamily = Marquee, fontSize = 32.sp)
Spacer(Modifier.weight(1f))
Text("◄►▲▼ Point", color = NightMuted, fontSize = 13.sp)
Text("OK Pick up / put down", color = NightMuted, fontSize = 13.sp)
Text("▲▼ in a column: how many", color = NightMuted, fontSize = 13.sp)
Text("Back Put back / leave", color = NightMuted, fontSize = 13.sp)
Text("Menu Send a card home", color = NightMuted, fontSize = 13.sp)
}
Box(Modifier.weight(1f).fillMaxHeight()) {
Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
listOf(STOCK, WASTE, -1, 2, 3, 4, 5).forEach { i ->
if (i < 0) Spacer(Modifier.width(CardW)) else {
val pointed = game.pile == i; val holding = game.held?.first == i
CardFace(game.piles[i].lastOrNull()?.let { if (i == STOCK) it.copy(up = false) else it }, if (i == STOCK) "↺" else if (i in HOMES) "A" else "",
Modifier.border(if (pointed) 3.dp else 0.dp, if (holding) Honey else NightYellow, RoundedCornerShape(6.dp)))
// The shared pause (Arcade Stage C): Back puts a held card back, otherwise pauses instead of leaving at once.
var session by remember { mutableStateOf<SessionState>(SessionState.Play) }
LaunchedEffect(session) { if (session == SessionState.Exited) play.onLeave() else if (session == SessionState.Play && !game.won) runCatching { focus.requestFocus() } }
// A won game counts for this profile; leaving part-way counts nothing.
val run = rememberRun(play.onRunEnd) { RunEnd(game.moves, finished = game.won) }
LaunchedEffect(game.won) {
if (game.won) {
run.end(RunEnd(game.moves, finished = true))
session = reduceSession(session, SessionEvent.Finish(RunEnd(game.moves, true), newBest = false))
menuFocus.requestFocus()
} else { run.begin(); focus.requestFocus() }
}
BackHandler(session == SessionState.Play || session is SessionState.Result) {
if (session == SessionState.Play && game.held != null) game = game.drop() else session = reduceSession(session, SessionEvent.Back)
}
Box(Modifier.fillMaxSize()) {
Row(Modifier.fillMaxSize().background(Color(0xFF0A2A1F)).padding(16.dp).focusRequester(focus).focusable().onPreviewKeyEvent { event ->
val native = event.nativeKeyEvent
if (native.action != KeyEvent.ACTION_DOWN || game.won || session != SessionState.Play) return@onPreviewKeyEvent false
val next = when (native.keyCode) {
KeyEvent.KEYCODE_DPAD_LEFT -> game.steer(-1, 0)
KeyEvent.KEYCODE_DPAD_RIGHT -> game.steer(1, 0)
KeyEvent.KEYCODE_DPAD_UP -> game.steer(0, -1)
KeyEvent.KEYCODE_DPAD_DOWN -> game.steer(0, 1)
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER -> if (native.repeatCount > 0) null else game.press()
KeyEvent.KEYCODE_MENU, KeyEvent.KEYCODE_PROG_RED -> game.sendHome()
else -> null
}
if (next != null) game = next
next != null
}, horizontalArrangement = Arrangement.spacedBy(16.dp)) {
Column(Modifier.width(170.dp).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text("PATIENCE", color = Honey, fontFamily = Marquee, fontSize = 34.sp)
Spacer(Modifier.height(10.dp))
Text("MOVES", color = NightMuted, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp)
Text(game.moves.toString(), color = Color.White, fontFamily = Marquee, fontSize = 32.sp)
Text("GAMES WON", color = NightMuted, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp)
Text(wins.toString(), color = Color.White, fontFamily = Marquee, fontSize = 32.sp)
Spacer(Modifier.weight(1f))
Text("◄►▲▼ Point", color = NightMuted, fontSize = 13.sp)
Text("OK Pick up / put down", color = NightMuted, fontSize = 13.sp)
Text("▲▼ in a column: how many", color = NightMuted, fontSize = 13.sp)
Text("Back Put back / pause", color = NightMuted, fontSize = 13.sp)
Text("Menu Send a card home", color = NightMuted, fontSize = 13.sp)
}
Box(Modifier.weight(1f).fillMaxHeight()) {
Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
listOf(STOCK, WASTE, -1, 2, 3, 4, 5).forEach { i ->
if (i < 0) Spacer(Modifier.width(CardW)) else {
val pointed = game.pile == i; val holding = game.held?.first == i
CardFace(game.piles[i].lastOrNull()?.let { if (i == STOCK) it.copy(up = false) else it }, if (i == STOCK) "↺" else if (i in HOMES) "A" else "",
Modifier.border(if (pointed) 3.dp else 0.dp, if (holding) Honey else NightYellow, RoundedCornerShape(6.dp)))
}
}
}
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
for (c in COLUMNS) {
val cards = game.piles[c]
val pointed = game.pile == c
val chosen = if (game.held?.first == c) game.held!!.second else if (pointed) game.depth else 0
Box(Modifier.width(CardW).height(CardH + 22.dp * 12)) {
if (cards.isEmpty()) CardFace(null, "K", Modifier.border(if (pointed) 3.dp else 0.dp, NightYellow, RoundedCornerShape(6.dp)))
cards.forEachIndexed { n, card ->
val inRun = n >= cards.size - chosen
CardFace(card, modifier = Modifier.offset(y = (if (card.up) 22.dp else 12.dp) * n - offsetFix(cards, n))
.border(if (inRun) 3.dp else 0.dp, if (game.held?.first == c) Honey else NightYellow, RoundedCornerShape(6.dp)))
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
for (c in COLUMNS) {
val cards = game.piles[c]
val pointed = game.pile == c
val chosen = if (game.held?.first == c) game.held!!.second else if (pointed) game.depth else 0
Box(Modifier.width(CardW).height(CardH + 22.dp * 12)) {
if (cards.isEmpty()) CardFace(null, "K", Modifier.border(if (pointed) 3.dp else 0.dp, NightYellow, RoundedCornerShape(6.dp)))
cards.forEachIndexed { n, card ->
val inRun = n >= cards.size - chosen
CardFace(card, modifier = Modifier.offset(y = (if (card.up) 22.dp else 12.dp) * n - offsetFix(cards, n))
.border(if (inRun) 3.dp else 0.dp, if (game.held?.first == c) Honey else NightYellow, RoundedCornerShape(6.dp)))
}
}
}
}
}
}
if (game.won) Column(Modifier.align(Alignment.Center).background(NightNavy, RoundedCornerShape(6.dp)).border(2.dp, Honey, RoundedCornerShape(6.dp)).padding(20.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("WON!", color = Honey, fontFamily = Marquee, fontSize = 30.sp)
Text("In ${game.moves} moves", color = Color.White, fontSize = 16.sp)
OrbitButton("Deal again", Modifier.width(200.dp).focusRequester(menuFocus), onClick = { game = PatienceGame.deal(random) })
OrbitButton("Leave the game", Modifier.width(200.dp), onClick = onLeave)
if (game.won) Column(Modifier.align(Alignment.Center).background(NightNavy, RoundedCornerShape(6.dp)).border(2.dp, Honey, RoundedCornerShape(6.dp)).padding(20.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("WON!", color = Honey, fontFamily = Marquee, fontSize = 30.sp)
Text("In ${game.moves} moves", color = Color.White, fontSize = 16.sp)
OrbitButton("Deal again", Modifier.width(200.dp).focusRequester(menuFocus), onClick = { game = PatienceGame.deal(random); session = reduceSession(session, SessionEvent.PlayAgain) })
OrbitButton("Leave the game", Modifier.width(200.dp), onClick = play.onLeave)
}
}
}
if (session is SessionState.Pause) ArcadePauseMenu(ArcadeGames.Patience, "Patience · ${game.moves} moves",
onResume = { session = reduceSession(session, SessionEvent.Resume) },
onRestart = { run.end(RunEnd(game.moves, finished = false)); run.begin(); game = PatienceGame.deal(random); session = reduceSession(session, SessionEvent.Restart) },
onExit = { session = reduceSession(session, SessionEvent.Exit) })
}
}
@@ -1,5 +1,8 @@
package tv.orbit.classic
import tv.orbit.classic.arcade.ArcadePlay
import tv.orbit.classic.arcade.RunEnd
import tv.orbit.classic.arcade.rememberRun
import android.view.KeyEvent
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Canvas
@@ -180,17 +183,25 @@ internal fun DrawScope.drawSkyBoard(game: SkyGame, showCursor: Boolean = true) {
}
@Composable
internal fun SkydokuScreen(solved: Int, dailyDone: Boolean, onSolved: (daily: Boolean) -> Unit, onLeave: () -> Unit) {
internal fun SkydokuScreen(play: ArcadePlay) {
val solved = play.best
val random = remember { java.util.Random() }
val today = remember { java.time.LocalDate.now() }
val dailyDone = remember { play.level["daily"] == today.toString() }
var daily by remember { mutableStateOf(!dailyDone) }
var game by remember { mutableStateOf(SkyGame(if (!dailyDone) skyDaily(today) else skyMake(random))) }
var paused by remember { mutableStateOf(false) }
val focus = remember { FocusRequester() }
val menuFocus = remember { FocusRequester() }
LaunchedEffect(game.done) { if (game.done) onSolved(daily) }
// A solved puzzle counts for this profile; today's puzzle is then done for today (Arcade Stage C: per profile).
val run = rememberRun(play.onRunEnd) { RunEnd(game.hearts, finished = false) }
LaunchedEffect(game.done) {
if (!game.done) { run.begin(); return@LaunchedEffect }
if (daily) play.setLevel("daily", today.toString())
run.end(RunEnd(game.hearts, finished = true, detail = if (daily) "Today's puzzle" else null))
}
LaunchedEffect(paused, game.done, game.out) { if (paused || game.done || game.out) menuFocus.requestFocus() else focus.requestFocus() }
BackHandler { if (!game.done && !game.out) paused = !paused else onLeave() }
BackHandler { if (!game.done && !game.out) paused = !paused else play.onLeave() }
Row(Modifier.fillMaxSize().arcadeBackdrop().padding(20.dp).focusRequester(focus).focusable().onPreviewKeyEvent { event ->
val native = event.nativeKeyEvent
if (native.action != KeyEvent.ACTION_DOWN || paused || game.done || game.out) return@onPreviewKeyEvent false
@@ -246,7 +257,7 @@ internal fun SkydokuScreen(solved: Int, dailyDone: Boolean, onSolved: (daily: Bo
OrbitButton("New puzzle", Modifier.width(220.dp).then(if (game.done) Modifier.focusRequester(menuFocus) else Modifier), onClick = {
daily = false; game = SkyGame(skyMake(random)); paused = false
})
OrbitButton("Leave the game", Modifier.width(220.dp), onClick = onLeave)
OrbitButton("Leave the game", Modifier.width(220.dp), onClick = play.onLeave)
}
}
}
@@ -330,6 +330,8 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
val fullScreen = FullScreen.active
LaunchedEffect(fullScreen) { if (!fullScreen) now = System.currentTimeMillis(); while (true) { delay(1000); if (!FullScreen.active) now = System.currentTimeMillis() } }
LaunchedEffect(scheduledChannels) { windingDown = scheduledChannels[TOTS_NUMBER]?.stepIn?.let { it.endMs > System.currentTimeMillis() } == true }
// The Arcade keeps its sound under Wind Down's ceiling while it runs (Arcade Stage C).
LaunchedEffect(windingDown) { tv.orbit.classic.arcade.OrbitQuiet.windDown = windingDown }
fun smartLoop(programming: ChannelProgramming) = (extraChannels + listOfNotNull(channel, afterDarkChannel, toonamiChannel)).firstOrNull { it.number == programming.number }
LaunchedEffect(session != null) { if (session != null) onSignedIn() }
// Joined from another room: its server, so this TV only needs to sign in.
@@ -37,6 +37,7 @@ private sealed interface FamilyPage {
class Person(val id: String) : FamilyPage
class Add(val step: Int, val name: String, val kind: ProfileKind, val picture: String) : FamilyPage
class Picture(val id: String) : FamilyPage
class ArcadeKids(val id: String) : FamilyPage
object Lock : FamilyPage
}
@@ -54,7 +55,9 @@ internal fun FamilySettings(firstSwitch: FocusRequester, bedtime: @Composable ()
when (val p = page) {
FamilyPage.Home -> FamilyHome(firstSwitch, onOpen = { page = FamilyPage.Person(it) },
onAdd = { page = FamilyPage.Add(0, "", ProfileKind.Grown, "sil-pink") }, onLock = { page = FamilyPage.Lock }, bedtime, modifier)
is FamilyPage.Person -> PersonPage(p.id, onBack = { page = FamilyPage.Home }, onPicture = { page = FamilyPage.Picture(p.id) }, onChannels = { kidsChannelsFor = p.id }, modifier)
is FamilyPage.Person -> PersonPage(p.id, onBack = { page = FamilyPage.Home }, onPicture = { page = FamilyPage.Picture(p.id) }, onChannels = { kidsChannelsFor = p.id },
onArcade = { page = FamilyPage.ArcadeKids(p.id) }, modifier)
is FamilyPage.ArcadeKids -> ArcadeForKids(p.id, onBack = { page = FamilyPage.Person(p.id) }, modifier)
is FamilyPage.Add -> AddSomeone(p, onStep = { page = it }, onDone = { id -> page = FamilyPage.Person(id) }, onCancel = { page = FamilyPage.Home }, onChannels = { kidsChannelsFor = it }, modifier)
is FamilyPage.Picture -> PicturePicker(p.id, onDone = { page = FamilyPage.Person(p.id) }, modifier)
FamilyPage.Lock -> Column(modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) {
@@ -133,7 +136,7 @@ private fun HouseRow(title: String, detail: String, onClick: () -> Unit) {
/** One person's page: everything about them in one list. */
@Composable
private fun PersonPage(id: String, onBack: () -> Unit, onPicture: () -> Unit, onChannels: () -> Unit, modifier: Modifier) {
private fun PersonPage(id: String, onBack: () -> Unit, onPicture: () -> Unit, onChannels: () -> Unit, onArcade: () -> Unit, modifier: Modifier) {
val context = LocalContext.current
val p = Profiles.all.firstOrNull { it.id == id } ?: run { LaunchedEffect(Unit) { onBack() }; return }
var renaming by remember { mutableStateOf(false) }
@@ -165,8 +168,8 @@ private fun PersonPage(id: String, onBack: () -> Unit, onPicture: () -> Unit, on
}
if (p.kind == ProfileKind.Kids) {
PersonRow("Channels", "${p.channels.size} ticked", "Choose") { onChannels() }
PersonRow("Arcade", if (p.arcade) "On: the games chosen for Kids" else "Off", if (p.arcade) "Turn off" else "Turn on") {
Profiles.update(context, p.copy(arcade = !p.arcade)) }
// Says what Kids really sees (the Arcade audit: "the games chosen for Kids" promised a choice that didn't exist).
PersonRow("Arcade for Kids", arcadeForKidsLine(p), "Change") { onArcade() }
PersonRow("Drive-In", if (p.driveIn) "Family showings only, never The Late Show" else "Off", if (p.driveIn) "Turn off" else "Turn on") {
Profiles.update(context, p.copy(driveIn = !p.driveIn)) }
}
@@ -346,3 +349,65 @@ private fun KidsChannels(id: String, onDone: () -> Unit) {
}
}
}
/** The Arcade for Kids line on a Kids profile's page: exactly what it sees. */
internal fun arcadeForKidsLine(p: Profile): String {
val shown = tv.orbit.classic.arcade.arcadeVisible(p).filter { it.launchable }
return when (p.kidsArcade) {
KidsArcade.Off -> "Off: no Arcade for ${p.name}"
KidsArcade.KidsSuitable -> "Kids-suitable games: ${shown.size} to play"
KidsArcade.Chosen -> if (shown.isEmpty()) "Chosen games: none chosen yet, so no Arcade" else "Chosen games: ${shown.size} to play"
}
}
/**
* Family › a Kids profile › Arcade for Kids (Arcade Stage C): Off, the kids-suitable games, or games a grown-up chooses.
* Behind the grown-up PIN when one is set, checked by the same lock as everywhere else (without unlocking After Dark).
* Kids only ever see what's allowed here: other games are hidden, not greyed out.
*/
@Composable
private fun ArcadeForKids(id: String, onBack: () -> Unit, modifier: Modifier) {
val context = LocalContext.current
val p = Profiles.all.firstOrNull { it.id == id && it.kind == ProfileKind.Kids } ?: run { LaunchedEffect(Unit) { onBack() }; return }
var allowed by remember { mutableStateOf(!AfterDarkLock.pinSet) }
var problem by remember { mutableStateOf<String?>(null) }
if (!allowed) {
Box(modifier, contentAlignment = Alignment.Center) {
PinEntry("Enter the PIN to change ${p.name}'s Arcade", problem, onDone = { pin ->
if (AfterDarkLock.check(context, pin)) allowed = true else problem = AfterDarkLock.refusal(context)
}, onCancel = onBack)
}
return
}
BackHandler { onBack() }
val first = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { first.requestFocus() } }
val games = tv.orbit.classic.arcade.ArcadeGames.all
Column(modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("Arcade for ${p.name}", color = Ink, fontFamily = Anton, fontSize = 26.sp)
Text("${p.name} sees only the games allowed here; the rest are hidden, not greyed out. Their scores and progress are their own." +
if (!AfterDarkLock.pinSet) " Set a PIN in Family to keep this for grown-ups." else "", color = Muted, fontSize = 13.sp)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
KidsArcade.entries.forEachIndexed { i, m ->
OrbitButton(m.title, if (i == 0) Modifier.focusRequester(first) else Modifier, selected = p.kidsArcade == m) {
// Choosing for the first time starts from the kids-suitable games, to tick and untick from there.
val start = if (m == KidsArcade.Chosen && p.arcadeGames.isEmpty()) games.filter { it.kidsSuitable }.map { it.id }.toSet() else p.arcadeGames
Profiles.update(context, p.withKidsArcade(m, start))
}
}
}
Text(arcadeForKidsLine(p), color = Yellow, fontSize = 14.sp, fontWeight = FontWeight.SemiBold)
when (p.kidsArcade) {
KidsArcade.Off -> Text("The Arcade isn't in ${p.name}'s top bar.", color = Muted, fontSize = 13.sp)
KidsArcade.KidsSuitable -> Text(games.filter { it.kidsSuitable }.joinToString(", ") { it.title + if (it.launchable) "" else " (coming soon)" }, color = Ink, fontSize = 13.sp)
KidsArcade.Chosen -> LazyVerticalGrid(GridCells.Fixed(3), Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(6.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
items(games, key = { it.id }) { g ->
val on = g.id in p.arcadeGames
OrbitButton((if (on) "✓ " else " ") + g.title + if (g.launchable) "" else " (soon)", Modifier.fillMaxWidth(), selected = on) {
Profiles.update(context, p.withKidsArcade(KidsArcade.Chosen, if (on) p.arcadeGames - g.id else p.arcadeGames + g.id))
}
}
}
}
}
}
@@ -1,5 +1,7 @@
package tv.orbit.classic
import tv.orbit.classic.arcade.OrbitArcade
import tv.orbit.classic.arcade.arcadeOpenFor
import android.os.Bundle
import android.view.WindowManager
import androidx.activity.ComponentActivity
@@ -163,7 +165,8 @@ private fun OrbitApp() {
}
val picking = realChannelAvailable && restoreChecked && !chosen && Profiles.asks && !onboarding
val kidsDriveIn = profile?.kind != ProfileKind.Kids || profile.driveIn
val kidsArcade = profile?.kind != ProfileKind.Kids || profile.arcade
// Kids sees the Arcade only when Arcade for Kids leaves it some games (Family settings).
val kidsArcade = arcadeOpenFor(profile)
// Kids never reaches Settings, and only the parts of Orbit chosen for it.
LaunchedEffect(profile, section) {
if (Profiles.kids && realChannelAvailable && (section == "Connect Emby" || (section == "Drive-In" && !kidsDriveIn) || (section == "Arcade" && !kidsArcade))) section = "Home"
@@ -185,7 +188,7 @@ private fun OrbitApp() {
// Sections change at once (Paul, 6 November 2026: the slide stuttered on the box while the new screen was
// being built, between the guide, the channels and the Arcade).
Column(if (fullBleed) Modifier.fillMaxSize() else Modifier.fillMaxSize().padding(start = 36.dp, end = 36.dp, top = 56.dp, bottom = 16.dp)) {
if (section == "Arcade" && realChannelAvailable && chosen) OrbitArcade(Modifier.weight(1f), onPlaying = { playingGame = it })
if (section == "Arcade" && realChannelAvailable && chosen) OrbitArcade(Modifier.weight(1f), onPlaying = { playingGame = it }, onExit = { section = "Home" })
EmbyConnectionScreen(if (section == "Arcade") Modifier else Modifier.weight(1f), visible = section == "Connect Emby",
onboarding = onboarding, onSignedIn = { if (Onboarding.step == OnboardStep.SignIn) Onboarding.go(OnboardStep.Channels) },
mainGuide = section == "TV Guide" && realChannelAvailable && chosen,
@@ -43,7 +43,16 @@ import android.webkit.WebChromeClient
import android.webkit.WebViewClient
import android.webkit.WebView
import androidx.tv.material3.Text
import kotlinx.coroutines.delay
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import tv.orbit.classic.arcade.ArcadeFlags
import tv.orbit.classic.arcade.ArcadeGameLoop
import tv.orbit.classic.arcade.ArcadePlay
import tv.orbit.classic.arcade.PauseWhenHidden
import tv.orbit.classic.arcade.RunEnd
import tv.orbit.classic.arcade.loopRuns
import tv.orbit.classic.arcade.rememberRun
import kotlin.math.cos
import kotlin.math.sin
@@ -91,16 +100,6 @@ internal data class SnakeGame(val width: Int, val height: Int, val body: List<Sn
private val Marquee = FontFamily(Font(R.font.anton_regular))
private val Honey = Color(0xFFFFD84A)
private fun hexagon(center: Offset, radius: Float) = Path().apply {
for (i in 0..5) {
val angle = Math.toRadians(60.0 * i)
val x = center.x + radius * sin(angle).toFloat()
val y = center.y - radius * cos(angle).toFloat()
if (i == 0) moveTo(x, y) else lineTo(x, y)
}
close()
}
internal const val SNAKE_BACKDROPS = 4
/** A new backdrop every ten bites, going round. */
@@ -177,46 +176,43 @@ private fun SnakeField(game: SnakeGame, modifier: Modifier, before: List<SnakeCe
}
}
/** Runs until it's left. A reminder taking over the remote pauses it, so nobody loses a game to a pop-up. */
/** Runs until it's left. A reminder taking over the remote, or Orbit going out of sight, pauses it, so nobody loses a game to a pop-up. */
@Composable
private fun SnakeScreen(best: Int, onBest: (Int) -> Unit, onLeave: () -> Unit) {
internal fun SnakeScreen(play: ArcadePlay) {
val best = play.best
val random = remember { java.util.Random() }
var game by remember { mutableStateOf(SnakeGame.start(30, 22, random)) }
var before by remember { mutableStateOf<List<SnakeCell>?>(null) }
var progress by remember { mutableFloatStateOf(1f) }
var paused by remember { mutableStateOf(false) }
val focus = remember { FocusRequester() }
// Only the whole window losing focus counts: buttons coming and going move focus around too.
val windowFocused = LocalWindowInfo.current.isWindowFocused
LaunchedEffect(windowFocused) { if (!windowFocused && game.alive) paused = true }
PauseWhenHidden(game.alive) { paused = true }
// Every run is saved when it ends, however it ends (Arcade Stage C): game over, Leave, or the screen going away.
val run = rememberRun(play.onRunEnd) { RunEnd(game.score, finished = false) }
LaunchedEffect(game.alive) { if (game.alive) run.begin() else run.end(RunEnd(game.score, finished = true)) }
// Steps on the clock, drawn on every frame between them.
LaunchedEffect(paused, game.alive) {
var last = withFrameNanos { it }
while (!paused && game.alive) {
val time = withFrameNanos { it }
val tick = game.tickMs * 1_000_000f
if (time - last >= tick) {
last += tick.toLong()
before = game.body
game = game.step(random)
}
progress = ((time - last) / tick).coerceIn(0f, 1f)
var sinceStep by remember { mutableLongStateOf(0L) }
ArcadeGameLoop(loopRuns(paused, game.alive, shown = true), onStart = { sinceStep = 0L }) { _, dt ->
if (paused || !game.alive) return@ArcadeGameLoop
val tick = game.tickMs * 1_000_000L
sinceStep += dt
if (sinceStep >= tick) {
sinceStep -= tick
before = game.body
game = game.step(random)
}
if (!game.alive && game.score > best) onBest(game.score)
progress = (sinceStep.toFloat() / tick).coerceIn(0f, 1f)
}
val context = LocalContext.current
val settings = remember { OrbitSettings(context) }
var musicOn by remember { mutableStateOf(settings.snakeMusic) }
val music = remember { android.media.MediaPlayer.create(context, R.raw.snake_theme)?.apply { isLooping = true; setVolume(.5f, .5f) } }
DisposableEffect(music) { onDispose { music?.release() } }
var musicOn by remember { mutableStateOf(play.setting("music")) }
val playing = musicOn && !paused && game.alive
LaunchedEffect(playing) { if (playing) music?.start() else if (music?.isPlaying == true) music.pause() }
LaunchedEffect(playing) { play.audio.music(R.raw.snake_theme, playing, base = .5f, gameOn = musicOn) }
DisposableEffect(Unit) { onDispose { play.audio.stopMusic() } }
val menuFocus = remember { FocusRequester() }
LaunchedEffect(paused, game.alive) { if (paused || !game.alive) menuFocus.requestFocus() else focus.requestFocus() }
// The best as it stood while this game was played, so the new best still shows once it's been saved; Zip and Blaze cheer it.
val bestBefore = remember(game.alive) { best }
val newBest = game.score > bestBefore && game.score > 0
BackHandler { if (game.alive) paused = !paused else onLeave() }
BackHandler { if (game.alive) paused = !paused else play.onLeave() }
Row(Modifier.fillMaxSize().background(Navy).padding(20.dp).focusRequester(focus).focusable().onPreviewKeyEvent { event ->
val native = event.nativeKeyEvent
if (native.action != KeyEvent.ACTION_DOWN || paused || !game.alive) return@onPreviewKeyEvent false
@@ -242,7 +238,8 @@ private fun SnakeScreen(best: Int, onBest: (Int) -> Unit, onLeave: () -> Unit) {
Text("Back Pause", color = Muted, fontSize = 13.sp)
}
Box(Modifier.weight(1f).fillMaxHeight().background(Color(0xFF050E2A)).border(2.dp, Blue), contentAlignment = Alignment.Center) {
Crossfade(snakeBackdrop(game.score), animationSpec = tween(1500), label = "backdrop") { scene -> SnakeBackdrop(scene, Modifier.fillMaxSize()) }
// Reduce motion: the scene changes at once instead of a slow crossfade.
Crossfade(snakeBackdrop(game.score), animationSpec = tween(if (Motion.reduce) 0 else 1500), label = "backdrop") { scene -> SnakeBackdrop(scene, Modifier.fillMaxSize()) }
SnakeField(game, Modifier.fillMaxSize().padding(6.dp), before, progress)
if (paused || !game.alive) Column(Modifier.background(Navy, RoundedCornerShape(6.dp)).border(2.dp, Honey, RoundedCornerShape(6.dp)).padding(20.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(if (game.alive) "PAUSED" else "GAME OVER", color = Honey, fontFamily = Marquee, fontSize = 30.sp)
@@ -252,24 +249,60 @@ private fun SnakeScreen(best: Int, onBest: (Int) -> Unit, onLeave: () -> Unit) {
if (!game.alive) { game = SnakeGame.start(30, 22, random); before = null; progress = 1f }
paused = false
})
OrbitButton("Music: ${if (musicOn) "On" else "Off"}", Modifier.width(200.dp), onClick = { musicOn = !musicOn; settings.snakeMusic = musicOn })
OrbitButton("Leave the game", Modifier.width(200.dp), onClick = onLeave)
OrbitButton("Music: ${if (musicOn) "On" else "Off"}", Modifier.width(200.dp), onClick = { musicOn = !musicOn; play.setSetting("music", musicOn) })
OrbitButton("Leave the game", Modifier.width(200.dp), onClick = play.onLeave)
}
}
}
}
/** BumbleHive (once OrbitHive) runs as a small web page from inside the app, with no network, and handles the remote itself. */
@android.annotation.SuppressLint("SetJavaScriptEnabled")
/** What BumbleHive's page reads at start: who's playing, Reduce motion, how loud it may be, and the save switch. */
internal fun hiveConfig(play: ArcadePlay, reduceMotion: Boolean = Motion.reduce): String = org.json.JSONObject()
.put("profileId", play.profileId)
.put("reduceMotion", reduceMotion)
// The page's own sounds are multiplied by this: the profile's effects choice under Orbit's quiet ceiling.
.put("volume", play.audio.effects(1f).toDouble())
.put("migrate", ArcadeFlags.hiveProfileSaves)
.put("levelsResetAt", play.levelsResetMs)
.toString()
/**
* BumbleHive (once OrbitHive) runs as a small web page from inside the app, with no network, and handles the remote
* itself. Arcade Stage C adds a small bridge and changes none of its play: the page reads who's playing and their
* settings, tells the Arcade when a level starts, scores and ends (so its runs reach High Scores like every other game),
* and stops its timers and frame loop while Orbit is out of sight.
*/
@android.annotation.SuppressLint("SetJavaScriptEnabled", "JavascriptInterface")
@Composable
private fun OrbitHiveScreen(onLeave: () -> Unit) {
internal fun OrbitHiveScreen(play: ArcadePlay) {
var web by remember { mutableStateOf<WebView?>(null) }
val latest by rememberUpdatedState(play)
// No protected picture here, and leaving the window open to screenshots lets the game be checked on the box.
val activity = androidx.activity.compose.LocalActivity.current
androidx.compose.runtime.DisposableEffect(Unit) {
DisposableEffect(Unit) {
activity?.window?.clearFlags(android.view.WindowManager.LayoutParams.FLAG_SECURE)
onDispose { activity?.window?.addFlags(android.view.WindowManager.LayoutParams.FLAG_SECURE) }
}
// The level in play, so it's still saved if the page goes away mid-level (the sleep timer, Orbit closing).
var liveScore by remember { mutableIntStateOf(0) }
var liveLevel by remember { mutableIntStateOf(0) }
val run = rememberRun(play.onRunEnd) { RunEnd(liveScore, finished = false, detail = "Level $liveLevel") }
val lifecycle = LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle, web) {
val view = web
val observer = LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_PAUSE -> { view?.evaluateJavascript("window.orbitVisibility && window.orbitVisibility(false)", null); view?.onPause() }
Lifecycle.Event.ON_RESUME -> {
view?.onResume()
view?.evaluateJavascript("window.orbitConfig && window.orbitConfig(${org.json.JSONObject.quote(hiveConfig(latest))}); window.orbitVisibility && window.orbitVisibility(true)", null)
}
else -> {}
}
}
lifecycle.addObserver(observer)
onDispose { lifecycle.removeObserver(observer) }
}
BackHandler { web?.evaluateJavascript("window.orbitBack()", null) }
AndroidView(modifier = Modifier.fillMaxSize(), factory = { context ->
WebView(context).apply {
@@ -292,8 +325,13 @@ private fun OrbitHiveScreen(onLeave: () -> Unit) {
}
}
isFocusable = true; isFocusableInTouchMode = true
// Called from the page's own thread, so each goes back to the main one.
addJavascriptInterface(object {
@JavascriptInterface fun leave() { post { onLeave() } }
@JavascriptInterface fun leave() { post { latest.onLeave() } }
@JavascriptInterface fun config(): String = hiveConfig(latest)
@JavascriptInterface fun runStart(level: Int) { post { liveLevel = level; liveScore = 0; run.begin() } }
@JavascriptInterface fun runScore(score: Int) { post { liveScore = score } }
@JavascriptInterface fun runEnd(level: Int, score: Int, finished: Boolean) { post { liveScore = score; liveLevel = level; run.end(RunEnd(score, finished, "Level $level")) } }
}, "OrbitApp")
loadUrl("file:///android_asset/orbithive/index.html")
requestFocus()
@@ -301,229 +339,3 @@ private fun OrbitHiveScreen(onLeave: () -> Unit) {
}
}, onRelease = { it.destroy() })
}
private enum class ArcadeGame(val title: String, val tagline: String, val blurb: String) {
// Paul, 5 November 2026: the Tots mascot is Ollie, so the game is renamed around the mascot, and OrbitHive becomes BumbleHive after its bee.
OrbMan("Star Chase", "Maze chase starring Ollie", "Help Ollie clear the stars, and dodge Blaze, Zip, Drift and Luna."),
Blast("Blast Off", "Fit the shapes, clear the lines", "Fit three shapes at a time on the board; full rows and columns clear. No room left and it's over."),
Sky("Skydoku", "Find each of the cast a spot", "Put each of the cast in their colour: one per row and column, none touching. Three hearts, a puzzle every day."),
Hive("BumbleHive", "Link, match, clear the hive", "Help Bumble fire flowers into the honeycomb, and clear the hive before it reaches you."),
Snake("Comet Trail", "Snake, as Blaze's tail", "Help Blaze eat the stars: each one grows his tail. Don't hit the walls or your own trail."),
Blocks("Block Drop", "Drift's stacking game", "Turn and drop the falling blocks, and clear full rows before the stack reaches the top."),
Bricks("Brick Break", "Luna is the ball", "Keep the ball in play with your paddle and break every brick in the wall."),
Pairs("Pairs", "Match the cast and the channels", "Turn two cards at a time and find every pair of the cast and Orbit's channels, in as few moves as you can."),
Patience("Patience", "Solitaire, with Ollie on every card", "The classic card game: build each suit home from ace to king.")
}
/** The newest game, flagged as the arcade's pick. */
private val ArcadePick = ArcadeGame.OrbMan
/** Each game's little picture, for its card. */
private fun androidx.compose.ui.graphics.drawscope.DrawScope.gameIcon(game: ArcadeGame) {
val s = size.minDimension; val c = center
when (game) {
ArcadeGame.OrbMan -> drawOrbMascot(c, s * .28f)
ArcadeGame.Hive -> drawOrbBee(c + Offset(0f, s * .12f), s * .26f)
ArcadeGame.Blast -> { val b = s * .2f
listOf(Triple(-1f, -1f, 0), Triple(0f, -1f, 0), Triple(-1f, 0f, 0), Triple(0f, 0f, 1), Triple(1f, 0f, 1), Triple(0f, 1f, 2), Triple(1f, 1f, 3))
.forEach { (x, y, k) -> drawRoundRect(BlastColours[k], c + Offset(x * b - b / 2 + 1, y * b - b / 2 + 1), Size(b - 2, b - 2), androidx.compose.ui.geometry.CornerRadius(b * .2f)) } }
// All six of the cast, two rows of three.
ArcadeGame.Sky -> { val b = s * .3f
for (i in 0..5) { val at = c + Offset((i % 3 - 1f) * b * 1.05f, (i / 3 - .5f) * b * 1.05f); drawRoundRect(SkyColours[i].copy(alpha = .4f), at - Offset(b / 2, b / 2), Size(b, b), androidx.compose.ui.geometry.CornerRadius(b * .15f)); drawSkyFace(i, at, b * .4f) } }
// Each game's host from the cast (Paul, 6 November 2026).
ArcadeGame.Snake -> drawOrbChaser(c + Offset(s * .1f, 0f), s * .3f, OrbCharacter.Blaze, OrbDir.Right, false, false, false, 0f)
ArcadeGame.Blocks -> drawOrbChaser(c, s * .3f, OrbCharacter.Drift, OrbDir.Down, false, false, false, 0f)
ArcadeGame.Bricks -> drawOrbChaser(c, s * .3f, OrbCharacter.Luna, OrbDir.Down, false, false, false, 0f)
ArcadeGame.Pairs -> for (i in 0..1) {
val at = Offset(c.x - s * .36f + i * s * .38f, c.y - s * .3f)
drawRoundRect(Color(0xFF1E3E8C), at, Size(s * .34f, s * .5f), androidx.compose.ui.geometry.CornerRadius(s * .04f))
drawRoundRect(Ink, at, Size(s * .34f, s * .5f), androidx.compose.ui.geometry.CornerRadius(s * .04f), style = Stroke(s * .03f))
drawCircle(Color(0xFFFFD84A), s * .08f, at + Offset(s * .17f, s * .25f))
}
ArcadeGame.Patience -> for (i in 0..2) withTransform({ rotate(-18f + i * 18f, c + Offset(0f, s * .3f)) }) {
val at = Offset(c.x - s * .15f, c.y - s * .32f)
drawRoundRect(Color(0xFFF4F6FB), at, Size(s * .3f, s * .44f), androidx.compose.ui.geometry.CornerRadius(s * .04f))
drawRoundRect(Navy, at, Size(s * .3f, s * .44f), androidx.compose.ui.geometry.CornerRadius(s * .04f), style = Stroke(s * .02f))
if (i == 2) drawCircle(Navy, s * .06f, at + Offset(s * .15f, s * .2f))
}
}
}
/** A game on the right: its picture, name and line, focused as on What's On (navy inside a gold ring). */
@Composable
private fun GameCard(game: ArcadeGame, modifier: Modifier, focus: FocusRequester?, up: FocusRequester?, onFocus: () -> Unit, onPlay: () -> Unit) {
var focused by remember { mutableStateOf(false) }
val corner = RoundedCornerShape(8.dp)
Row(modifier.then(if (focus != null) Modifier.focusRequester(focus) else Modifier).focusProperties { if (up != null) this.up = up }
.onFocusChanged { focused = it.isFocused; if (it.isFocused) onFocus() }
.background(if (focused) Navy else Panel, corner).border(if (focused) 3.dp else 1.dp, if (focused) Yellow else Blue, corner)
.clickable(onClick = onPlay).padding(horizontal = 10.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Canvas(Modifier.logoPlate().size(34.dp)) { gameIcon(game) }
Box(Modifier.width(1.dp).fillMaxHeight(.7f).background(Muted.copy(alpha = .4f)))
Column(verticalArrangement = Arrangement.spacedBy(1.dp)) {
Text(game.title.uppercase().takeIf { game == ArcadeGame.OrbMan } ?: game.title, color = Ink, fontFamily = Marquee, fontSize = 17.sp, lineHeight = 20.sp, maxLines = 1)
Text(game.tagline, color = Muted, fontSize = 11.sp, lineHeight = 14.sp, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)
}
}
}
/** The arcade (Paul, 5 November 2026, from his reference): the chosen game large on the left, every game as a card on the right, and what you played last. */
@Composable
internal fun OrbitArcade(modifier: Modifier, onPlaying: (Boolean) -> Unit) {
val context = LocalContext.current
val settings = remember { OrbitSettings(context).also(ArcadeLook::load) }
var best by remember { mutableIntStateOf(settings.snakeBest) }
var blockBest by remember { mutableIntStateOf(settings.blockDropBest) }
var brickBest by remember { mutableIntStateOf(settings.brickBreakBest) }
var pairsBest by remember { mutableIntStateOf(settings.pairsBest) }
var patienceWins by remember { mutableIntStateOf(settings.patienceWins) }
var orbBest by remember { mutableIntStateOf(settings.orbManBest) }
var blastBest by remember { mutableIntStateOf(settings.blastBest) }
var skySolved by remember { mutableIntStateOf(settings.skydokuSolved) }
var recent by remember { mutableStateOf(settings.recentGames.mapNotNull { name -> ArcadeGame.entries.firstOrNull { it.name == name } }) }
var playing by remember { mutableStateOf<ArcadeGame?>(null) }
var chosen by remember { mutableStateOf(ArcadeGame.OrbMan) }
// Each game opens with its host streaking in (design/motion), then the game itself.
var opening by remember { mutableStateOf<ArcadeGame?>(null) }
fun play(game: ArcadeGame) {
recent = (listOf(game) + recent.filter { it != game }).take(6)
settings.recentGames = recent.map { it.name }
if (Moment.forGame(game.name) != null) opening = game else playing = game
}
DisposableEffect(playing, opening) { onPlaying(playing != null || opening != null); onDispose { onPlaying(false) } }
opening?.let { game -> MomentClip(Moment.forGame(game.name)!!) { opening = null; playing = game }; return }
when (playing) {
ArcadeGame.OrbMan -> { OrbManScreen(orbBest, onBest = { orbBest = it; settings.orbManBest = it }, onLeave = { playing = null }); return }
ArcadeGame.Snake -> { SnakeScreen(best, onBest = { best = it; settings.snakeBest = it }, onLeave = { playing = null }); return }
ArcadeGame.Hive -> { OrbitHiveScreen(onLeave = { playing = null }); return }
ArcadeGame.Blast -> { BlastOffScreen(blastBest, onBest = { blastBest = it; settings.blastBest = it }, onLeave = { playing = null }); return }
ArcadeGame.Sky -> { SkydokuScreen(skySolved, settings.skydokuDaily == java.time.LocalDate.now().toString(), onSolved = { daily ->
skySolved += 1; settings.skydokuSolved = skySolved; if (daily) settings.skydokuDaily = java.time.LocalDate.now().toString() }, onLeave = { playing = null }); return }
ArcadeGame.Pairs -> { PairsScreen(pairsBest, onBest = { pairsBest = it; settings.pairsBest = it }, onLeave = { playing = null }); return }
ArcadeGame.Patience -> { PatienceScreen(patienceWins, onWin = { patienceWins += 1; settings.patienceWins = patienceWins }, onLeave = { playing = null }); return }
ArcadeGame.Bricks -> { BrickBreakScreen(brickBest, onBest = { brickBest = it; settings.brickBreakBest = it }, onLeave = { playing = null }); return }
ArcadeGame.Blocks -> { BlockDropScreen(blockBest, onBest = { blockBest = it; settings.blockDropBest = it }, onLeave = { playing = null }); return }
null -> {}
}
fun bestLine(game: ArcadeGame): String? = when (game) {
ArcadeGame.OrbMan -> orbBest.takeIf { it > 0 }?.let { "%,d".format(it) }
ArcadeGame.Snake -> best.takeIf { it > 0 }?.let { "%,d".format(it) }
ArcadeGame.Blocks -> blockBest.takeIf { it > 0 }?.let { "%,d".format(it) }
ArcadeGame.Bricks -> brickBest.takeIf { it > 0 }?.let { "%,d".format(it) }
ArcadeGame.Pairs -> pairsBest.takeIf { it > 0 }?.let { "$it moves" }
ArcadeGame.Patience -> patienceWins.takeIf { it > 0 }?.let { "$it won" }
ArcadeGame.Hive -> null
ArcadeGame.Blast -> blastBest.takeIf { it > 0 }?.let { "%,d".format(it) }
ArcadeGame.Sky -> skySolved.takeIf { it > 0 }?.let { "$it solved" }
}
val first = remember { FocusRequester() }
LaunchedEffect(Unit) { first.requestFocus() }
val nav = LocalNavFocus.current
val preview = remember { SnakeGame(16, 9, listOf(SnakeCell(9, 4), SnakeCell(8, 4), SnakeCell(7, 4), SnakeCell(6, 4), SnakeCell(6, 5), SnakeCell(5, 5), SnakeCell(4, 5)), SnakeDirection.Right, SnakeDirection.Right, SnakeCell(12, 4)) }
val blockPreview = remember {
val board = List(BLOCK_ROWS) { y -> IntArray(BLOCK_COLUMNS) { x -> if (y >= 16 && (x + y) % 9 != 0) 1 + (x * 3 + y) % 7 else 0 } }
BlockGame(board, BlockPiece(2, 1, 4, 9), 0, emptyList())
}
val brickPreview = remember { BrickGame.start().copy(bricks = bricksFor(2), ballX = 180f, ballY = 150f, paddleX = 150f) }
val orbPreview = remember {
val g = OrbGame.start()
val chasers = g.chasers.mapIndexed { i, c -> val p = listOf(OrbPos(5, 1), OrbPos(17, 3), OrbPos(14, 11), OrbPos(3, 8))[i]; c.copy(mover = OrbMover(p, p, OrbDir.Left), out = true) }
g.copy(player = OrbMover(OrbPos(9, 8), OrbPos(9, 8), OrbDir.Right), chasers = chasers, stars = g.stars.filter { it.y != 3 || it.x > 9 }.toSet(), readyLeft = 0)
}
val blastPreview = remember {
val rows = listOf("..##....", "..##....", ".....###", "#....###", "##..####", "###.####", "####.###", "#######.")
BlastGame(rows.mapIndexed { y, row -> row.mapIndexed { x, ch -> if (ch == '#') 1 + (x * 2 + y * 3) % BlastColours.size else 0 } }, BlastGame.deal(java.util.Random(3)), 0, 0, 0)
}
val skyPreview = remember { val p = skyMake(java.util.Random(8)); SkyGame(p, placed = setOf(p.answer[1] + SKY_SIZE, p.answer[4] + 4 * SKY_SIZE)) }
var clock by remember { mutableLongStateOf(0L) }
LaunchedEffect(chosen) { if (chosen == ArcadeGame.OrbMan) while (true) { withFrameNanos { clock = it / 1_000_000 } } }
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(16.dp)) {
// The chosen game, large.
Column(Modifier.weight(1.05f).fillMaxHeight().background(Brush.verticalGradient(listOf(Blue, Panel)), RoundedCornerShape(10.dp)).padding(14.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
Column {
if (chosen == ArcadePick) Text("ARCADE PICK", Modifier.background(Yellow, RoundedCornerShape(4.dp)).padding(horizontal = 8.dp, vertical = 2.dp), color = OnAccent, fontSize = 11.sp, fontWeight = FontWeight.Bold)
Text(chosen.title.uppercase(), color = Ink, fontFamily = Marquee, fontSize = 36.sp, maxLines = 1)
}
Box(Modifier.width(1.dp).height(40.dp).background(Muted.copy(alpha = .5f)))
Text(chosen.tagline, color = Ink, fontSize = 14.sp, maxLines = 2)
}
Box(Modifier.fillMaxWidth().weight(1f).background(Color(0xFF050E2A), RoundedCornerShape(8.dp)).border(2.dp, Color(0xFF3D63FF), RoundedCornerShape(8.dp)).padding(6.dp)) {
when (chosen) {
ArcadeGame.OrbMan -> Canvas(Modifier.fillMaxSize()) { drawOrbField(orbPreview, timeMs = clock) }
ArcadeGame.Snake -> SnakeField(preview, Modifier.fillMaxSize())
ArcadeGame.Blocks -> BlockField(blockPreview, Modifier.fillMaxSize().padding(4.dp))
ArcadeGame.Bricks -> BrickField(brickPreview, Modifier.fillMaxSize().padding(4.dp))
ArcadeGame.Pairs, ArcadeGame.Patience -> Canvas(Modifier.fillMaxSize().padding(14.dp)) {
// A spread of cards: face down for Pairs, a dealt column for Patience.
val w = size.width / 8; val h = w * 1.36f
for (i in 0 until 7) {
val down = chosen == ArcadeGame.Pairs && i % 3 != 1
val at = Offset(i * w * 1.12f, if (chosen == ArcadeGame.Patience) i * h * .22f else (i % 2) * h * .6f)
drawRoundRect(if (down) Panel else Color(0xFFF4F6FB), at, Size(w, h), androidx.compose.ui.geometry.CornerRadius(w * .1f))
drawRoundRect(if (down) Blue else BlockColours[i % BlockColours.size], at, Size(w, h), androidx.compose.ui.geometry.CornerRadius(w * .1f), style = Stroke(w * .05f))
}
}
ArcadeGame.Blast -> Canvas(Modifier.fillMaxSize().padding(6.dp)) { drawBlastBoard(blastPreview, showPiece = false) }
ArcadeGame.Sky -> Canvas(Modifier.fillMaxSize().padding(10.dp)) { drawSkyBoard(skyPreview, showCursor = false) }
ArcadeGame.Hive -> Canvas(Modifier.fillMaxSize()) {
val colours = listOf(Color(0xFFE53935), Color(0xFF1E66D0), Color(0xFF2E9D3A), Color(0xFFF4F4F4), Color(0xFFF5A623), Color(0xFF8E44AD))
val r = size.height / 9
for (row in 0..3) for (col in 0 until (size.width / (r * 1.8f)).toInt()) {
val at = Offset(r + col * r * 1.8f + (row % 2) * r * .9f, r + row * r * 1.56f)
drawPath(hexagon(at, r * .92f), colours[(col * 3 + row * 5 + col * row) % colours.size])
}
}
}
}
Text(chosen.blurb, color = Ink, fontSize = 14.sp, maxLines = 2)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
bestLine(chosen)?.let { Text(if (chosen == ArcadeGame.Patience) "Games: " else "Your best: ", color = Ink, fontSize = 15.sp); Text(it, color = Yellow, fontFamily = Marquee, fontSize = 20.sp) }
?: Text("New to you", color = Muted, fontSize = 15.sp)
Box(Modifier.width(1.dp).height(24.dp).background(Muted.copy(alpha = .5f)))
Text("OK Play", Modifier.background(Yellow, RoundedCornerShape(5.dp)).padding(horizontal = 12.dp, vertical = 3.dp), color = OnAccent, fontSize = 15.sp, fontWeight = FontWeight.Bold)
}
}
// Every game, two to a row, then what you played last.
Column(Modifier.weight(1f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
ArcadeGame.entries.chunked(2).forEachIndexed { row, pair ->
// Tall enough for the name and its line in full (Paul, 5 November 2026: the line was clipped at 48).
Row(Modifier.fillMaxWidth().height(56.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
pair.forEachIndexed { i, game ->
GameCard(game, Modifier.weight(1f).fillMaxHeight(), if (row == 0 && i == 0) first else null, if (row == 0) nav else null, { chosen = game }, { play(game) })
}
if (pair.size == 1) Spacer(Modifier.weight(1f))
}
}
if (recent.isNotEmpty()) {
Spacer(Modifier.height(2.dp))
Box(Modifier.fillMaxWidth().height(1.dp).background(Muted.copy(alpha = .3f)))
Text("RECENTLY PLAYED", color = Ink, fontFamily = Marquee, fontSize = 16.sp)
Row(Modifier.fillMaxWidth().height(46.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
recent.take(3).forEach { game ->
var focused by remember { mutableStateOf(false) }
val corner = RoundedCornerShape(8.dp)
Row(Modifier.weight(1f).fillMaxHeight().onFocusChanged { focused = it.isFocused; if (it.isFocused) chosen = game }
.background(if (focused) Navy else Panel, corner).border(if (focused) 3.dp else 0.dp, if (focused) Yellow else Color.Transparent, corner)
.clickable { play(game) }.padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Canvas(Modifier.logoPlate().size(30.dp)) { gameIcon(game) }
Column {
Text(game.title, color = Ink, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1)
Text(bestLine(game)?.let { "Your best: $it" } ?: "Played recently", color = Muted, fontSize = 10.sp, maxLines = 1)
}
}
}
repeat(3 - minOf(3, recent.size)) { Spacer(Modifier.weight(1f)) }
}
}
}
}
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text("◄►▲▼ Choose OK Play Back Main menu", Modifier.weight(1f), color = Muted, fontSize = 11.sp)
// One backdrop behind every game (Paul, 6 November 2026): OK goes to the next.
OrbitButton("Backdrop: ${ArcadeLook.backdrop.title}", Modifier.width(220.dp), centred = true) { ArcadeLook.next(settings) }
}
}
}
@@ -41,11 +41,26 @@ import org.json.JSONObject
*/
internal enum class ProfileKind { Grown, Kids }
/**
* Family › Arcade for Kids (Arcade Stage C, 8 November 2026): no Arcade, the games marked kids-suitable, or only the games
* a grown-up chose for this Kids profile. Grown-up profiles always see every game.
*/
internal enum class KidsArcade(val title: String) { Off("Off"), KidsSuitable("Kids-suitable games"), Chosen("Chosen games") }
internal data class Profile(val id: String, val name: String, val picture: String, val kind: ProfileKind,
/** Kids only: the channels it sees. */
val channels: Set<Int> = emptySet(), val arcade: Boolean = true, val driveIn: Boolean = false,
/** When it last changed, so paired rooms keep the newest (Rooms sync, 7 November 2026). 0 for a profile never changed. */
val updatedMs: Long = 0)
val updatedMs: Long = 0,
/** Kids only: Arcade for Kids, or null for a profile saved before it existed (then [arcade] decides). */
val arcadeMode: KidsArcade? = null,
/** Kids only, with [KidsArcade.Chosen]: the games chosen for it, by Arcade game id. */
val arcadeGames: Set<String> = emptySet()) {
/** Arcade for Kids as it applies: older profiles had only on (the kids-suitable games) or off. */
val kidsArcade: KidsArcade get() = arcadeMode ?: if (arcade) KidsArcade.KidsSuitable else KidsArcade.Off
/** Arcade for Kids changed; [arcade] follows it, so rooms on an older Orbit still read on or off correctly. */
fun withKidsArcade(mode: KidsArcade, games: Set<String> = arcadeGames) = copy(arcadeMode = mode, arcade = mode != KidsArcade.Off, arcadeGames = games)
}
/** Kids' channels to start with, from the approved design: Tots, Junior, Wonder, PixelZ, ToonZ, Heroes, Rewind, Vortex, Terra, Wild. */
internal val KidsStartChannels = setOf(TOTS_NUMBER, 611, 612, 613, 605, 602, 604, VORTEX_NUMBER, 201, 203)
@@ -135,6 +150,7 @@ internal object Profiles {
fun encode(list: List<Profile>) = JSONArray(list.map { p ->
JSONObject().put("id", p.id).put("name", p.name).put("picture", p.picture).put("kind", p.kind.name)
.put("channels", JSONArray(p.channels.sorted())).put("arcade", p.arcade).put("driveIn", p.driveIn).put("u", p.updatedMs)
.also { o -> p.arcadeMode?.let { o.put("arcadeMode", it.name) }; if (p.arcadeGames.isNotEmpty()) o.put("arcadeGames", JSONArray(p.arcadeGames.sorted())) }
}).toString()
fun decode(text: String): List<Profile> {
val a = JSONArray(text)
@@ -142,7 +158,9 @@ internal object Profiles {
val o = a.getJSONObject(i); val ch = o.optJSONArray("channels")
// "Grown-ups" became "Adult" (Paul, 6 November 2026): a profile saved under the old name takes the new one.
Profile(o.getString("id"), o.getString("name").let { if (it == "Grown-ups") "Adult" else it }, o.getString("picture"), ProfileKind.valueOf(o.getString("kind")),
ch?.let { c -> (0 until c.length()).map { c.getInt(it) }.toSet() }.orEmpty(), o.optBoolean("arcade", true), o.optBoolean("driveIn", false), o.optLong("u"))
ch?.let { c -> (0 until c.length()).map { c.getInt(it) }.toSet() }.orEmpty(), o.optBoolean("arcade", true), o.optBoolean("driveIn", false), o.optLong("u"),
o.optString("arcadeMode").let { m -> KidsArcade.entries.firstOrNull { it.name == m } },
o.optJSONArray("arcadeGames")?.let { g -> (0 until g.length()).mapNotNull { g.optString(it).takeIf { s -> s.isNotEmpty() } }.toSet() }.orEmpty())
}.takeIf { list -> list.any { it.kind == ProfileKind.Grown } } ?: DefaultProfiles
}
}
@@ -0,0 +1,130 @@
package tv.orbit.classic.arcade
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.graphics.drawscope.withTransform
import tv.orbit.classic.BlastColours
import tv.orbit.classic.OrbCharacter
import tv.orbit.classic.OrbDir
import tv.orbit.classic.SkyColours
import tv.orbit.classic.drawNightCap
import tv.orbit.classic.drawNiteOwl
import tv.orbit.classic.drawOrbBee
import tv.orbit.classic.drawOrbChaser
import tv.orbit.classic.drawOrbMascot
import tv.orbit.classic.drawSkyFace
import kotlin.math.cos
import kotlin.math.sin
/** A flat-topped hexagon, for the hive and the honeycomb behind the cards. */
internal fun hexPath(center: Offset, radius: Float) = Path().apply {
for (i in 0..5) {
val a = Math.toRadians(60.0 * i)
val x = center.x + radius * sin(a).toFloat()
val y = center.y - radius * cos(a).toFloat()
if (i == 0) moveTo(x, y) else lineTo(x, y)
}
close()
}
/** A game's host from the cast, small, for icons and the High Scores rows. */
internal fun DrawScope.drawMascot(mascot: Mascot, c: Offset, r: Float) = when (mascot) {
Mascot.Ollie -> drawOrbMascot(c, r * .9f)
Mascot.Blaze -> drawOrbChaser(c, r, OrbCharacter.Blaze, OrbDir.Right, false, false, false, 0f)
Mascot.Zip -> drawOrbChaser(c, r, OrbCharacter.Zip, OrbDir.Down, false, false, false, 0f)
Mascot.Drift -> drawOrbChaser(c, r, OrbCharacter.Drift, OrbDir.Down, false, false, false, 0f)
Mascot.Luna -> drawOrbChaser(c, r, OrbCharacter.Luna, OrbDir.Down, false, false, false, 0f)
Mascot.Bumble -> drawOrbBee(c + Offset(0f, r * .2f), r * .9f)
Mascot.NiteOwl -> drawNiteOwl(c, r)
}
/** Each Classic's little picture, for its tile (the old Arcade menu's icons, unchanged). */
internal fun DrawScope.gameIcon(game: ArcadeGame) {
val s = size.minDimension; val c = center
when (game.id) {
ArcadeGames.OrbMan.id -> drawOrbMascot(c, s * .28f)
ArcadeGames.Hive.id -> drawOrbBee(c + Offset(0f, s * .12f), s * .26f)
ArcadeGames.Blast.id -> { val b = s * .2f
listOf(Triple(-1f, -1f, 0), Triple(0f, -1f, 0), Triple(-1f, 0f, 0), Triple(0f, 0f, 1), Triple(1f, 0f, 1), Triple(0f, 1f, 2), Triple(1f, 1f, 3))
.forEach { (x, y, k) -> drawRoundRect(BlastColours[k], c + Offset(x * b - b / 2 + 1, y * b - b / 2 + 1), Size(b - 2, b - 2), CornerRadius(b * .2f)) } }
// All six of the cast, two rows of three.
ArcadeGames.Sky.id -> { val b = s * .3f
for (i in 0..5) { val at = c + Offset((i % 3 - 1f) * b * 1.05f, (i / 3 - .5f) * b * 1.05f); drawRoundRect(SkyColours[i].copy(alpha = .4f), at - Offset(b / 2, b / 2), Size(b, b), CornerRadius(b * .15f)); drawSkyFace(i, at, b * .4f) } }
ArcadeGames.Snake.id -> drawOrbChaser(c + Offset(s * .1f, 0f), s * .3f, OrbCharacter.Blaze, OrbDir.Right, false, false, false, 0f)
ArcadeGames.Blocks.id -> drawOrbChaser(c, s * .3f, OrbCharacter.Drift, OrbDir.Down, false, false, false, 0f)
ArcadeGames.Bricks.id -> drawOrbChaser(c, s * .3f, OrbCharacter.Luna, OrbDir.Down, false, false, false, 0f)
ArcadeGames.Pairs.id -> for (i in 0..1) {
val at = Offset(c.x - s * .36f + i * s * .38f, c.y - s * .3f)
drawRoundRect(Color(0xFF1E3E8C), at, Size(s * .34f, s * .5f), CornerRadius(s * .04f))
drawRoundRect(ArcadeColours.Ink, at, Size(s * .34f, s * .5f), CornerRadius(s * .04f), style = Stroke(s * .03f))
drawCircle(Color(0xFFFFD84A), s * .08f, at + Offset(s * .17f, s * .25f))
}
ArcadeGames.Patience.id -> for (i in 0..2) withTransform({ rotate(-18f + i * 18f, c + Offset(0f, s * .3f)) }) {
val at = Offset(c.x - s * .15f, c.y - s * .32f)
drawRoundRect(Color(0xFFF4F6FB), at, Size(s * .3f, s * .44f), CornerRadius(s * .04f))
drawRoundRect(ArcadeColours.Night, at, Size(s * .3f, s * .44f), CornerRadius(s * .04f), style = Stroke(s * .02f))
if (i == 2) drawCircle(ArcadeColours.Night, s * .06f, at + Offset(s * .15f, s * .2f))
}
else -> drawMascot(game.mascot, c, s * .3f)
}
}
private val HiveColours = listOf(Color(0xFFFF8A3D), Color(0xFFFF4FA3), Color(0xFF6EDCAA), Color(0xFF35D6F2), Color(0xFFA77BFF), Color(0xFFFFD84A))
/** The art at the top of an Orbit Original's card: its host in a small scene, drawn from the cast, still. */
internal fun DrawScope.originalArt(game: ArcadeGame) {
val w = size.width; val h = size.height
drawRect(Brush.verticalGradient(listOf(Color(0xFF0A1740), Color(0xFF16245A))))
val stars = java.util.Random(game.id.hashCode().toLong())
repeat(18) { drawCircle(Color.White.copy(alpha = .3f + stars.nextFloat() * .5f), .8f + stars.nextFloat() * 1.2f, Offset(stars.nextFloat() * w, stars.nextFloat() * h)) }
when (game.id) {
ArcadeGames.OrbiRaiders.id -> {
// Ollie's rocket below a row of glitchy invaders.
for (i in 0..2) { val at = Offset(w * (.25f + i * .25f), h * .22f); drawRoundRect(listOf(Color(0xFF6C4BD8), Color(0xFF4C7DFF), Color(0xFFFF4FA3))[i], at - Offset(h * .08f, h * .07f), Size(h * .16f, h * .14f), CornerRadius(h * .03f)) }
val base = Offset(w * .5f, h * .78f)
val body = Path().apply { moveTo(base.x, base.y - h * .42f); quadraticBezierTo(base.x + h * .14f, base.y - h * .2f, base.x + h * .1f, base.y); lineTo(base.x - h * .1f, base.y); quadraticBezierTo(base.x - h * .14f, base.y - h * .2f, base.x, base.y - h * .42f); close() }
drawPath(body, Color(0xFFF4F6FB))
drawCircle(Color(0xFFFFD84A), h * .09f, base - Offset(0f, h * .22f))
drawOrbMascot(base - Offset(0f, h * .22f), h * .06f)
drawCircle(Color(0xFFFF8A3D), h * .05f, base + Offset(0f, h * .06f))
}
ArcadeGames.ChannelChaos.id -> {
// Ollie between four little screens, each in its channel's colour.
listOf(Offset(.2f, .3f) to Color(0xFFFF4FA3), Offset(.8f, .3f) to Color(0xFFF4F6FB), Offset(.2f, .78f) to Color(0xFF6EDCAA), Offset(.8f, .78f) to Color(0xFFA77BFF)).forEach { (p, col) ->
val at = Offset(w * p.x, h * p.y)
drawRoundRect(col, at - Offset(h * .14f, h * .1f), Size(h * .28f, h * .2f), CornerRadius(h * .03f))
drawRoundRect(ArcadeColours.Night.copy(alpha = .5f), at - Offset(h * .1f, h * .06f), Size(h * .2f, h * .12f), CornerRadius(h * .02f))
}
drawOrbMascot(Offset(w * .5f, h * .55f), h * .2f)
}
ArcadeGames.Hive.id -> {
val r = h * .14f
for (row in 0..1) for (col in 0..7) {
val at = Offset(r + col * r * 1.75f + (row % 2) * r * .87f, r * .9f + row * r * 1.5f)
drawPath(hexPath(at, r * .95f), HiveColours[(col + row * 3) % HiveColours.size])
}
drawOrbBee(Offset(w * .5f, h * .66f), h * .2f)
}
ArcadeGames.NightShift.id -> {
drawCircle(Color(0xFFE8E6FF), h * .1f, Offset(w * .82f, h * .2f))
drawCircle(Color(0xFF16245A), h * .1f, Offset(w * .86f, h * .17f))
drawRect(Color(0xFF1C2C6E), Offset(0f, h * .82f), Size(w, h * .18f))
drawNiteOwl(Offset(w * .45f, h * .55f), h * .28f)
drawNightCap(Offset(w * .14f, h * .26f), h * .08f)
}
ArcadeGames.Orbiteroids.id -> {
drawCircle(Color(0xFF8A93A8), h * .08f, Offset(w * .15f, h * .2f))
drawCircle(Color(0xFF8A93A8), h * .1f, Offset(w * .85f, h * .72f))
drawCircle(Color(0xFF6C7488), h * .05f, Offset(w * .78f, h * .2f))
withTransform({ rotate(35f, Offset(w * .5f, h * .5f)) }) { drawOrbChaser(Offset(w * .5f, h * .5f), h * .2f, OrbCharacter.Zip, OrbDir.Up, false, false, false, 0f) }
}
else -> drawMascot(game.mascot, center, h * .3f)
}
}
@@ -0,0 +1,101 @@
package tv.orbit.classic.arcade
import android.content.Context
import android.media.AudioAttributes
import android.media.MediaPlayer
import android.media.SoundPool
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import tv.orbit.classic.OrbitSettings
import tv.orbit.classic.identQuietNow
import tv.orbit.classic.identVolume
/** Arcade-wide sound choices for one profile (Arcade Settings › Audio). */
internal data class AudioPrefs(val music: Boolean = true, val effects: Boolean = true, val muteAll: Boolean = false) {
companion object {
fun of(settings: Map<String, Boolean>) = AudioPrefs(settings["music"] ?: true, settings["effects"] ?: true, settings["muteAll"] ?: false)
}
}
/** Wind Down on Tots (the step-in plan) is running; set by the screen that starts and stops it. */
internal object OrbitQuiet {
var windDown by mutableStateOf(false)
}
/** How loud the Arcade may be while Wind Down is on: well under Orbit's quiet ident level. */
internal const val WIND_DOWN_CEILING = .25f
/**
* Orbit's own quiet settings are a ceiling the Arcade can't go over (frame 05: "Orbit Quiet and Wind Down always win").
* Quiet ident sound, or night-quiet late at night, holds the Arcade to the soft ident level; Wind Down holds it lower still.
*/
internal fun arcadeCeiling(identQuiet: Boolean, windDown: Boolean): Float =
minOf(if (identQuiet) identVolume(true) else 1f, if (windDown) WIND_DOWN_CEILING else 1f)
internal fun musicLevel(base: Float, prefs: AudioPrefs, gameOn: Boolean, ceiling: Float): Float =
if (prefs.muteAll || !prefs.music || !gameOn) 0f else (base * ceiling).coerceIn(0f, 1f)
internal fun effectsLevel(base: Float, prefs: AudioPrefs, gameOn: Boolean, ceiling: Float): Float =
if (prefs.muteAll || !prefs.effects || !gameOn) 0f else (base * ceiling).coerceIn(0f, 1f)
/**
* The Arcade's one sound service: short cues through one SoundPool and music through one MediaPlayer, both released when
* the game closes. [prefs] gives the profile's choices as they are now; the ceiling is read fresh on every play.
*/
internal class ArcadeAudio(private val context: Context, private val prefs: () -> AudioPrefs) {
private val settings = OrbitSettings(context)
private var pool: SoundPool? = null
private val sounds = HashMap<Int, Int>()
private var player: MediaPlayer? = null
private var playerRes = 0
private var musicBase = .5f
private var released = false
fun ceiling(): Float = arcadeCeiling(identQuietNow(settings), OrbitQuiet.windDown)
fun effects(base: Float, gameOn: Boolean = true) = effectsLevel(base, prefs(), gameOn, ceiling())
fun music(base: Float, gameOn: Boolean = true) = musicLevel(base, prefs(), gameOn, ceiling())
private fun pool(): SoundPool? {
if (released) return null
return pool ?: runCatching {
SoundPool.Builder().setMaxStreams(3).setAudioAttributes(AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build()).build()
}.getOrNull().also { pool = it }
}
/** Loads cues ahead, so the first play isn't late. */
fun preload(vararg raw: Int) { val p = pool() ?: return; raw.forEach { r -> if (r !in sounds) sounds[r] = p.load(context, r, 1) } }
/** Plays a short cue at [base] volume, under the ceiling; nothing when effects are off or muted. */
fun cue(raw: Int, base: Float = .7f, gameOn: Boolean = true) {
val level = effects(base, gameOn)
if (level <= 0f) return
val p = pool() ?: return
val id = sounds.getOrPut(raw) { p.load(context, raw, 1) }
runCatching { p.play(id, level, level, 1, 0, 1f) }
}
/** Starts or pauses the one music track; [playing] is whether the game wants it now. */
fun music(raw: Int, playing: Boolean, base: Float = .5f, gameOn: Boolean = true) {
if (released) return
musicBase = base
val level = music(base, gameOn)
if (!playing || level <= 0f) { runCatching { if (player?.isPlaying == true) player?.pause() }; return }
if (player == null || playerRes != raw) {
runCatching { player?.release() }
player = runCatching { MediaPlayer.create(context, raw)?.apply { isLooping = true } }.getOrNull()
playerRes = raw
}
runCatching { player?.setVolume(level, level); if (player?.isPlaying != true) player?.start() }
}
fun stopMusic() { runCatching { if (player?.isPlaying == true) player?.pause() } }
fun release() {
released = true
runCatching { player?.release() }; player = null
runCatching { pool?.release() }; pool = null
sounds.clear()
}
}
@@ -0,0 +1,13 @@
package tv.orbit.classic.arcade
/**
* Switches for Arcade work that isn't turned on yet. Both are off in every build until Paul says otherwise.
*/
internal object ArcadeFlags {
/**
* BumbleHive saves per profile (orbithive-save-v1:<profileId>), with the old box-wide save offered as a copy any
* profile can continue from. Off: BumbleHive keeps its one box-wide save exactly as before. The old save is only ever
* read by the profile-save path, never written or removed. See docs/arcade-stage-c.md, "BumbleHive saves".
*/
@Volatile var hiveProfileSaves = false
}
@@ -0,0 +1,149 @@
package tv.orbit.classic.arcade
import androidx.compose.runtime.Composable
import tv.orbit.classic.BlastOffScreen
import tv.orbit.classic.BlockDropScreen
import tv.orbit.classic.BrickBreakScreen
import tv.orbit.classic.KidsArcade
import tv.orbit.classic.OrbManScreen
import tv.orbit.classic.OrbitHiveScreen
import tv.orbit.classic.PairsScreen
import tv.orbit.classic.PatienceScreen
import tv.orbit.classic.Profile
import tv.orbit.classic.ProfileKind
import tv.orbit.classic.SkydokuScreen
import tv.orbit.classic.SnakeScreen
/** Who hosts a game, drawn from the cast library ([tv.orbit.classic.drawOrbMascot] and friends). */
internal enum class Mascot { Ollie, Blaze, Zip, Drift, Luna, Bumble, NiteOwl }
/** One remote key and what it does, for How to Play and the info panel. */
internal data class Control(val keys: String, val action: String)
/** A per-game on/off choice, saved per profile. [legacyKey] is the old box-wide key it starts from, read only. */
internal data class GameSetting(val key: String, val title: String, val default: Boolean = true, val legacyKey: String? = null)
/**
* A game in the Orbit Arcade. The Classics wrap the existing games unchanged; the Orbit Originals that aren't built yet
* are cards only ([launchable] false, "Coming soon").
*/
internal interface ArcadeGame {
val id: String
val title: String
val tagline: String
val blurb: String
val mascot: Mascot
/** Shown to Kids profiles whose Arcade for Kids is "Kids-suitable games". */
val kidsSuitable: Boolean
/** An Orbit Original (the top row) rather than a Classic. */
val original: Boolean
val launchable: Boolean
val scoreKind: ScoreKind
/** Keeps level progress that Reset can clear. */
val keepsLevels: Boolean
/** The old "orbit_settings" key whose value became this game's Household Record. */
val legacyRecordKey: String?
val controls: List<Control>
val settings: List<GameSetting>
/** One line under How to Play: what the game is about. */
val goal: String
@Composable
fun Content(play: ArcadePlay)
}
private class GameDef(
override val id: String, override val title: String, override val tagline: String, override val blurb: String, override val mascot: Mascot,
override val kidsSuitable: Boolean, override val original: Boolean, override val launchable: Boolean, override val scoreKind: ScoreKind,
override val keepsLevels: Boolean, override val legacyRecordKey: String?, override val controls: List<Control>, override val goal: String,
override val settings: List<GameSetting> = emptyList(),
private val content: @Composable (ArcadePlay) -> Unit = {},
) : ArcadeGame {
@Composable
override fun Content(play: ArcadePlay) = content(play)
}
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.
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.")
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.")
val Hive: ArcadeGame = GameDef("Hive", "BumbleHive", "Link, match, clear the hive", "Help Bumble fire flowers and clear the hive.", Mascot.Bumble,
kidsSuitable = true, original = true, launchable = true, ScoreKind.Points, keepsLevels = true, legacyRecordKey = null,
listOf(Control("◀▶", "Aim"), Control("OK", "Fire a flower"), Control("▼", "Swap flower"), Control("▲", "Honeybomb"), BackPause),
"Join three or more of a colour to clear them, before the hive reaches Bumble.") { OrbitHiveScreen(it) }
val NightShift: ArcadeGame = GameDef("NightShift", "Nite Owl's Night Shift", "Route the starlight", "Turn the beams and guide each lost star home.", Mascot.NiteOwl,
kidsSuitable = true, original = true, launchable = false, ScoreKind.FewestMoves, keepsLevels = true, legacyRecordKey = null,
listOf(Control("◀▶▲▼", "Hop"), Control("OK", "Turn a beam"), BackPause), "No timer and no fail: just Nite Owl's par.")
val Orbiteroids: ArcadeGame = GameDef("Orbiteroids", "Orbiteroids", "Zip clears the sky", "Fly Zip through the debris and keep the sky clear.", Mascot.Zip,
kidsSuitable = true, original = true, launchable = false, ScoreKind.Points, keepsLevels = false, legacyRecordKey = null,
listOf(Control("◀▶", "Turn"), Control("▲", "Thrust"), Control("OK", "Fire"), BackPause), "Clear each sector, and watch your hull.")
// Classics: the eight Kotlin games, unchanged, each in a thin wrapper.
val OrbMan: ArcadeGame = GameDef("OrbMan", "Star Chase", "Maze chase starring Ollie", "Help Ollie clear the stars, and dodge Blaze, Zip, Drift and Luna.", Mascot.Ollie,
kidsSuitable = true, original = false, launchable = true, ScoreKind.Points, keepsLevels = false, legacyRecordKey = "orb_man_best",
listOf(Control("◀▶▲▼", "Steer Ollie"), Control("OK", "Pause"), BackPause), "Clear every star; a power hexagon turns the chase round.",
listOf(GameSetting("sound", "Sound", legacyKey = "orb_man_sound"))) { OrbManScreen(it) }
val Blast: ArcadeGame = GameDef("Blast", "Blast Off", "Fit the shapes, clear the lines", "Fit three shapes at a time; full rows and columns clear.", Mascot.Zip,
kidsSuitable = false, original = false, launchable = true, ScoreKind.Points, keepsLevels = false, legacyRecordKey = "blast_best",
listOf(Control("◀▶▲▼", "Move the shape"), Control("OK", "Place it"), Control("▼", "Off the board: choose another"), BackPause), "No room left for any shape and it's over.") { BlastOffScreen(it) }
val Sky: ArcadeGame = GameDef("Sky", "Skydoku", "Find each of the cast a spot", "Put each of the cast in their colour: one per row and column, none touching.", Mascot.Luna,
kidsSuitable = false, original = false, launchable = true, ScoreKind.Solved, keepsLevels = true, legacyRecordKey = "skydoku_solved",
listOf(Control("◀▶▲▼", "Move"), Control("OK", "Place"), BackPause), "Three hearts, and a new puzzle every day.") { SkydokuScreen(it) }
val Snake: ArcadeGame = GameDef("Snake", "Comet Trail", "Snake, as Blaze's tail", "Help Blaze eat the stars. Each one grows his tail.", Mascot.Blaze,
kidsSuitable = true, original = false, launchable = true, ScoreKind.Points, keepsLevels = false, legacyRecordKey = "snake_best",
listOf(Control("◀▶▲▼", "Steer Blaze"), BackPause), "Don't hit the walls or your own trail.",
listOf(GameSetting("music", "Music", legacyKey = "snake_music"))) { SnakeScreen(it) }
val Blocks: ArcadeGame = GameDef("Blocks", "Block Drop", "Drift's stacking game", "Turn and drop the blocks, and clear full rows.", Mascot.Drift,
kidsSuitable = true, original = false, launchable = true, ScoreKind.Points, keepsLevels = false, legacyRecordKey = "block_drop_best",
listOf(Control("◀▶", "Move"), Control("▲", "Turn"), Control("▼", "Down"), Control("OK", "Drop"), BackPause), "Clear rows before the stack reaches the top.") { BlockDropScreen(it) }
val Bricks: ArcadeGame = GameDef("Bricks", "Brick Break", "Luna is the ball", "Keep Luna in play and break every brick in the wall.", Mascot.Luna,
kidsSuitable = true, original = false, launchable = true, ScoreKind.Points, keepsLevels = false, legacyRecordKey = "brick_break_best",
listOf(Control("◀▶", "Hold to move"), Control("OK", "Launch"), BackPause), "Catch the gold stars for powers.",
listOf(GameSetting("sounds", "Power sounds", legacyKey = "arcade_sounds"))) { BrickBreakScreen(it) }
val Pairs: ArcadeGame = GameDef("Pairs", "Pairs", "Match the cast and the channels", "Find every pair of the cast and Orbit's channels.", Mascot.Ollie,
kidsSuitable = true, original = false, launchable = true, ScoreKind.FewestMoves, keepsLevels = false, legacyRecordKey = "pairs_best",
listOf(Control("◀▶▲▼", "Move"), Control("OK", "Turn a card"), BackPause), "In as few moves as you can.") { PairsScreen(it) }
val Patience: ArcadeGame = GameDef("Patience", "Patience", "Solitaire, with Ollie on every card", "Build each suit home from ace to king.", Mascot.Ollie,
kidsSuitable = true, original = false, launchable = true, ScoreKind.Wins, keepsLevels = false, legacyRecordKey = "patience_wins",
listOf(Control("◀▶▲▼", "Point"), Control("OK", "Pick up / put down"), Control("▲▼", "In a column: how many"), Control("Menu", "Send a card home"), Control("Back", "Put back / pause")),
"Klondike, one card at a time.") { PatienceScreen(it) }
val originals = listOf(OrbiRaiders, ChannelChaos, Hive, NightShift, Orbiteroids)
val classics = listOf(OrbMan, Blast, Sky, Snake, Blocks, Bricks, Pairs, Patience)
val all = originals + classics
fun byId(id: String): ArcadeGame? = all.firstOrNull { it.id == id }
}
/**
* The games a profile sees. Grown-ups see everything. Kids see nothing when Arcade for Kids is off, the kids-suitable
* games, or only the games chosen for them; games they can't play are hidden, never greyed out.
*/
internal fun arcadeVisible(profile: Profile?, games: List<ArcadeGame> = ArcadeGames.all): List<ArcadeGame> {
if (profile == null || profile.kind != ProfileKind.Kids) return games
return when (profile.kidsArcade) {
KidsArcade.Off -> emptyList()
KidsArcade.KidsSuitable -> games.filter { it.kidsSuitable }
KidsArcade.Chosen -> games.filter { it.id in profile.arcadeGames }
}
}
/** Whether the Arcade belongs in the top bar for this profile at all. */
internal fun arcadeOpenFor(profile: Profile?) = arcadeVisible(profile).isNotEmpty()
/** The Arcade's pick: Star Chase when this profile can play it, otherwise the first game they can. */
internal fun arcadePick(visible: List<ArcadeGame>): ArcadeGame? = visible.firstOrNull { it.id == ArcadeGames.OrbMan.id } ?: visible.firstOrNull { it.launchable }
/** Recently played, newest first, keeping only games this profile can still see and play. */
internal fun recentVisible(recent: List<String>, visible: List<ArcadeGame>): List<ArcadeGame> =
recent.mapNotNull { id -> visible.firstOrNull { it.id == id && it.launchable } }
/** High Scores lists the games this profile can see that can be played (a coming-soon card has none yet). */
internal fun highScoreGames(visible: List<ArcadeGame>) = visible.filter { it.launchable } + visible.filter { !it.launchable }
@@ -0,0 +1,382 @@
package tv.orbit.classic.arcade
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
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.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
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.ArcadeLook
import tv.orbit.classic.Moment
import tv.orbit.classic.MomentClip
import tv.orbit.classic.Motion
import tv.orbit.classic.OrbitSettings
import tv.orbit.classic.Profile
import tv.orbit.classic.ProfileAvatar
import tv.orbit.classic.ProfileKind
import tv.orbit.classic.Profiles
import tv.orbit.classic.R
import tv.orbit.classic.cachedPainter
import tv.orbit.classic.drawOrbMascot
/** The Arcade's pages, from the menu on the left (frames 01-05). */
internal enum class ArcadePage(val title: String, val icon: String) {
Play("Play Games", "🎮"), HighScores("High Scores", "🏆"), HowTo("How to Play", "?"), Settings("Settings", "⚙"), Reset("Reset Progress", "↻")
}
// ---------- words and numbers, kept screen-free so they're tested ----------
/** A game's headline number as it reads: points with thousands, moves, games won or puzzles solved. */
internal fun formatScore(kind: ScoreKind, value: Int): String = when (kind) {
ScoreKind.Points -> "%,d".format(value)
ScoreKind.FewestMoves -> "$value moves"
ScoreKind.Wins -> "$value won"
ScoreKind.Solved -> "$value solved"
}
/** The profile's best for [game], or null before there is one. */
internal fun bestLine(game: ArcadeGame, record: GameRecord): String? = bestOf(record, game.scoreKind).takeIf { it > 0 }?.let { formatScore(game.scoreKind, it) }
/** The Household Record for [game], read-only and nameless, or null when there was none from before profiles. */
internal fun householdLine(game: ArcadeGame, records: Map<String, HouseholdRecord>): String? =
game.legacyRecordKey?.let { records[it] }?.number?.takeIf { it > 0 }?.let { formatScore(game.scoreKind, it) }
/** When a game was last played: Today, Yesterday, the day of the week within a week, else the date. */
internal fun playedLabel(atMs: Long, nowMs: Long, zone: java.time.ZoneId = java.time.ZoneId.systemDefault()): String {
if (atMs <= 0) return ""
val day = java.time.Instant.ofEpochMilli(atMs).atZone(zone).toLocalDate()
val today = java.time.Instant.ofEpochMilli(nowMs).atZone(zone).toLocalDate()
val days = java.time.temporal.ChronoUnit.DAYS.between(day, today)
return when {
days <= 0L -> "Today"
days == 1L -> "Yesterday"
days < 7L -> day.dayOfWeek.getDisplayName(java.time.format.TextStyle.SHORT, java.util.Locale.UK)
else -> "${day.dayOfMonth} ${day.month.getDisplayName(java.time.format.TextStyle.SHORT, java.util.Locale.UK)}"
}
}
// ---------- the Arcade ----------
/**
* Orbit Arcade (Stage C, from the approved Stage B frames): Orbit Originals on top, the Classics shelf below, the menu
* on the left and the chosen game's panel along the bottom. Everything here belongs to whoever's watching: their own
* scores, settings and progress, with the old box-wide scores shown read-only as Household Records.
*/
@Composable
internal fun OrbitArcade(modifier: Modifier, onPlaying: (Boolean) -> Unit, onExit: () -> Unit) {
val context = LocalContext.current
val profile = Profiles.current ?: return
val repo = remember { ArcadeRepo.get(context) }
remember { ArcadeLook.load(OrbitSettings(context)) }
var data by remember(profile.id) { mutableStateOf(repo.store.load(profile.id)) }
val latestData by rememberUpdatedState(data)
val household = remember { repo.household }
val visible = remember(profile) { arcadeVisible(profile) }
var page by remember { mutableStateOf(ArcadePage.Play) }
var playing by remember { mutableStateOf<ArcadeGame?>(null) }
var opening by remember { mutableStateOf<ArcadeGame?>(null) }
var session by remember { mutableStateOf<SessionState>(SessionState.Exited) }
var settingsFor by remember { mutableStateOf<ArcadeGame?>(null) }
var note by remember { mutableStateOf<String?>(null) }
// The whole Arcade is full screen (frame 01 has its own top and "Back to Orbit TV"), so Orbit's bar steps aside.
DisposableEffect(Unit) { onPlaying(true); onDispose { onPlaying(false) } }
fun update(change: (ArcadeProfileData) -> ArcadeProfileData) { data = repo.store.update(profile.id, change) }
fun start(game: ArcadeGame) { playing = game; session = sessionStart(data.game(game.id)) }
fun launch(game: ArcadeGame) {
if (!game.launchable) { note = "${game.title} is coming soon to the Arcade."; return }
if (game !in visible) return
note = null
update { markPlayed(it, game.id, System.currentTimeMillis()) }
if (Moment.forGame(game.id) != null) opening = game else start(game)
}
// Each game opens with its host streaking in (design/motion), then its How to Play the first time, then the game.
opening?.let { game -> MomentClip(Moment.forGame(game.id)!!) { opening = null; start(game) }; return }
playing?.let { game ->
val record = data.game(game.id)
when (session) {
SessionState.Title -> {
HowToPlayCard(game, firstRun = !record.firstRunSeen, everyTime = record.howToEveryTime,
onEveryTime = { on -> update { d -> d.withGame(game.id) { it.copy(howToEveryTime = on) } } },
onPlay = { update { d -> d.withGame(game.id) { it.copy(firstRunSeen = true) } }; session = reduceSession(session, SessionEvent.Start) },
onBack = { session = reduceSession(session, SessionEvent.Back); playing = null })
return
}
SessionState.Exited -> LaunchedEffect(Unit) { playing = null }
else -> {
val audio = remember(game) { ArcadeAudio(context) { AudioPrefs.of(latestData.settings) } }
DisposableEffect(audio) { onDispose { audio.release() } }
val play = ArcadePlay(game.id, profile.id, bestOf(record, game.scoreKind), audio, record.level, record.levelsResetMs,
readSetting = { key -> game.settings.firstOrNull { it.key == key }?.let { settingFor(latestData.game(game.id), it, repo::legacyFlag) } ?: true },
writeSetting = { key, on -> update { d -> d.withGame(game.id) { it.copy(settings = it.settings + (key to on)) } } },
writeLevel = { key, value -> update { d -> d.withGame(game.id) { it.copy(level = it.level + (key to value)) } } },
onRunEnd = { end -> update { recordRun(it, game.id, game.scoreKind, end, System.currentTimeMillis()) } },
onLeave = { session = SessionState.Exited; playing = null })
key(game.id) { game.Content(play) }
return
}
}
}
val pick = remember(visible) { arcadePick(visible) }
val recent = recentVisible(data.recent, visible)
var chosen by remember { mutableStateOf(recent.firstOrNull() ?: pick ?: visible.firstOrNull()) }
val firstCard = remember { FocusRequester() }
val menuFocus = remember { FocusRequester() }
LaunchedEffect(page) { runCatching { if (page == ArcadePage.Play && visible.isNotEmpty()) firstCard.requestFocus() else menuFocus.requestFocus() } }
Box(modifier.fillMaxSize().background(Brush.linearGradient(listOf(Color(0xFF071632), Color(0xFF0E1F52), Color(0xFF2A1760))))) {
ArcadeSkyDots()
Column(Modifier.fillMaxSize().padding(start = 32.dp, end = 32.dp, top = 16.dp, bottom = 12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
// The menu on the left.
Column(Modifier.width(150.dp).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Image(cachedPainter(R.drawable.orbit_arcade_logo), "Orbit Arcade", Modifier.height(44.dp).width(132.dp).padding(bottom = 4.dp))
Spacer(Modifier.height(6.dp))
ArcadePage.entries.forEach { p ->
MenuItem(p.title, p.icon, selected = page == p, Modifier.then(if (p == page) Modifier.focusRequester(menuFocus) else Modifier),
caption = if (p == ArcadePage.Reset && profile.kind == ProfileKind.Kids) "${profile.name}'s progress only" else null) { page = p }
}
MenuItem("Back to Orbit TV", "←", selected = false, onClick = onExit)
Spacer(Modifier.weight(1f))
if (page == ArcadePage.Play) OllieSays(when {
note != null -> "Soon!"
recent.isNotEmpty() -> "Another go?"
else -> "Pick a game!"
})
}
Column(Modifier.weight(1f).fillMaxHeight()) {
Row(Modifier.fillMaxWidth().height(36.dp), verticalAlignment = Alignment.CenterVertically) {
if (page == ArcadePage.Play) {
val originals = visible.count { it.original }
if (originals > 0) { Text("Orbit Originals", color = ArcadeColours.Ink, fontSize = 16.sp, fontWeight = FontWeight.SemiBold); Spacer(Modifier.width(8.dp)); Text("$originals games, made for Orbit", color = ArcadeColours.Muted, fontSize = 13.sp) }
}
Spacer(Modifier.weight(1f))
PlayingAs(profile)
}
when (page) {
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.Reset -> ResetPage(profile, visible, data, onReset = { id, action -> update { applyReset(it, id, action, System.currentTimeMillis()) } })
}
}
}
if (page == ArcadePage.Play) chosen?.let { InfoPanel(it, data.game(it.id), household, note.takeIf { _ -> !it.launchable }) }
KeyFooter(when (page) {
ArcadePage.Play -> listOf(Control("◀▶▲▼", "Browse"), Control("OK", "Play"), Control("Menu", "Game settings"), Control("Back", "Orbit TV"))
ArcadePage.HighScores -> listOf(Control("▲▼", "Choose a game"), Control("OK", "See top 10"), Control("Back", "Orbit TV"))
else -> listOf(Control("▲▼", "Choose"), Control("OK", "Select"), Control("Back", "Orbit TV"))
}, note = if (profile.kind == ProfileKind.Kids && page == ArcadePage.Play) "Kids profile: only Kids games are shown" else null)
}
settingsFor?.let { game -> GameSettingsSheet(game, data.game(game.id), repo::legacyFlag,
onSetting = { key, on -> update { d -> d.withGame(game.id) { it.copy(settings = it.settings + (key to on)) } } },
onEveryTime = { on -> update { d -> d.withGame(game.id) { it.copy(howToEveryTime = on) } } },
onClose = { settingsFor = null }) }
}
}
/** A still field of stars behind the Arcade, drawn once. */
@Composable
private fun ArcadeSkyDots() {
Canvas(Modifier.fillMaxSize()) {
val stars = java.util.Random(11)
repeat(90) { drawCircle(Color.White.copy(alpha = .15f + stars.nextFloat() * .45f), .7f + stars.nextFloat() * 1.3f, Offset(stars.nextFloat() * size.width, stars.nextFloat() * size.height)) }
}
}
@Composable
private fun PlayingAs(profile: Profile) {
Row(Modifier.background(ArcadeColours.PanelDeep, RoundedCornerShape(20.dp)).border(1.dp, ArcadeColours.Line, RoundedCornerShape(20.dp)).padding(horizontal = 10.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
ProfileAvatar(profile.picture, 22.dp)
Text("Playing as ${profile.name}", color = ArcadeColours.Ink, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, maxLines = 1)
if (profile.kind == ProfileKind.Kids) Text("KIDS", Modifier.background(ArcadeColours.Green, RoundedCornerShape(10.dp)).padding(horizontal = 8.dp), color = ArcadeColours.Night, fontSize = 13.sp, fontWeight = FontWeight.Bold)
}
}
@Composable
private fun MenuItem(title: String, icon: String, selected: Boolean, modifier: Modifier = Modifier, caption: String? = null, onClick: () -> Unit) {
var focused by remember { mutableStateOf(false) }
val corner = RoundedCornerShape(8.dp)
Row(modifier.fillMaxWidth().heightIn(min = 30.dp).onFocusChanged { focused = it.isFocused }
.background(if (focused || selected) ArcadeColours.FocusFill else ArcadeColours.Panel.copy(alpha = .6f), corner)
.border(if (focused) 3.dp else if (selected) 1.dp else 0.dp, if (focused) ArcadeColours.Yellow else ArcadeColours.Line, corner)
.clickable(onClick = onClick).padding(horizontal = 10.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (selected) Box(Modifier.width(3.dp).height(18.dp).background(ArcadeColours.Cyan, RoundedCornerShape(2.dp)))
Text(icon, color = ArcadeColours.Ink, fontSize = 13.sp, modifier = Modifier.width(18.dp))
Column {
Text(title, color = ArcadeColours.Ink, fontSize = 14.sp, fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal, maxLines = 1)
if (caption != null) Text(caption, color = ArcadeColours.Muted, fontSize = 11.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
@Composable
private fun OllieSays(line: String) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Canvas(Modifier.size(44.dp)) { drawOrbMascot(center, size.minDimension * .3f) }
Text(line, Modifier.background(ArcadeColours.Ink, RoundedCornerShape(12.dp)).padding(horizontal = 10.dp, vertical = 5.dp), color = ArcadeColours.Night, fontSize = 13.sp, fontWeight = FontWeight.SemiBold)
}
}
/** Orbit Originals on top, the Classics below; only the games this profile can see, none greyed out. */
@Composable
private fun GameShelves(visible: List<ArcadeGame>, data: ArcadeProfileData, pick: ArcadeGame?, firstCard: FocusRequester, kids: Boolean,
onChosen: (ArcadeGame) -> Unit, onPlay: (ArcadeGame) -> Unit, onMenu: (ArcadeGame) -> Unit) {
val originals = visible.filter { it.original }
val classics = visible.filter { !it.original }
// Focus starts on the game played last, else the Arcade's pick.
val start = recentVisible(data.recent, visible).firstOrNull() ?: pick ?: visible.firstOrNull()
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (originals.isNotEmpty()) Row(Modifier.fillMaxWidth().height(170.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
originals.forEach { g -> OriginalCard(g, data.game(g.id), Modifier.weight(1f).fillMaxHeight().then(if (g == start) Modifier.focusRequester(firstCard) else Modifier), onChosen, onPlay, onMenu) }
repeat(5 - originals.size) { Spacer(Modifier.weight(1f)) }
}
if (classics.isNotEmpty()) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text("Classics", color = ArcadeColours.Ink, fontSize = 16.sp, fontWeight = FontWeight.SemiBold)
Text("${classics.size} games" + if (kids) ", Kids picks" else "", color = ArcadeColours.Muted, fontSize = 13.sp)
}
Row(Modifier.fillMaxWidth().height(64.dp), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
classics.forEach { g -> ClassicTile(g, g == pick, Modifier.weight(1f).fillMaxHeight().then(if (g == start) Modifier.focusRequester(firstCard) else Modifier), onChosen, onPlay, onMenu) }
repeat(8 - classics.size) { Spacer(Modifier.weight(1f)) }
}
}
if (visible.isEmpty()) Text("No games are chosen for this profile yet. A grown-up can choose them in Settings › Family.", color = ArcadeColours.Muted, fontSize = 15.sp)
}
}
/** OK plays, Menu opens the game's own settings. */
private fun Modifier.gameKeys(game: ArcadeGame, onMenu: (ArcadeGame) -> Unit) = onPreviewKeyEvent { e ->
val n = e.nativeKeyEvent
if (arcadeKey(n.keyCode) == ArcadeKey.Menu && game.launchable) { if (n.action == android.view.KeyEvent.ACTION_UP) onMenu(game); true } else false
}
@Composable
private fun OriginalCard(game: ArcadeGame, record: GameRecord, modifier: Modifier, onChosen: (ArcadeGame) -> Unit, onPlay: (ArcadeGame) -> Unit, onMenu: (ArcadeGame) -> Unit) {
var focused by remember { mutableStateOf(false) }
val corner = RoundedCornerShape(10.dp)
// The focused card grows a little (frame 01); with Reduce motion it doesn't.
val grow = if (focused && !Motion.reduce) 1.04f else 1f
Column(modifier.graphicsLayer { scaleX = grow; scaleY = grow }.onFocusChanged { focused = it.isFocused; if (it.isFocused) onChosen(game) }.gameKeys(game, onMenu)
.clip(corner).background(if (focused) ArcadeColours.FocusFill else ArcadeColours.Panel, corner).border(if (focused) 3.dp else 1.dp, if (focused) ArcadeColours.Yellow else ArcadeColours.Line, corner)
.clickable { onPlay(game) }) {
Canvas(Modifier.fillMaxWidth().weight(1f)) { originalArt(game) }
Column(Modifier.fillMaxWidth().height(70.dp).padding(horizontal = 10.dp, vertical = 6.dp)) {
Text(game.title.uppercase(), color = ArcadeColours.Ink, fontFamily = Anton, fontSize = 17.sp, lineHeight = 19.sp, maxLines = 2, overflow = TextOverflow.Ellipsis)
Spacer(Modifier.weight(1f))
when {
!game.launchable -> Text("COMING SOON", Modifier.background(ArcadeColours.Pink, RoundedCornerShape(10.dp)).padding(horizontal = 8.dp), color = ArcadeColours.Ink, fontSize = 12.sp, fontWeight = FontWeight.Bold)
else -> bestLine(game, record)?.let { Row { Text("Your best ", color = ArcadeColours.Muted, fontSize = 13.sp); Text(it, color = ArcadeColours.Ink, fontSize = 13.sp, fontWeight = FontWeight.Bold) } }
?: Text("New to you", color = ArcadeColours.Muted, fontSize = 13.sp)
}
}
}
}
@Composable
private fun ClassicTile(game: ArcadeGame, isPick: Boolean, modifier: Modifier, onChosen: (ArcadeGame) -> Unit, onPlay: (ArcadeGame) -> Unit, onMenu: (ArcadeGame) -> Unit) {
var focused by remember { mutableStateOf(false) }
val corner = RoundedCornerShape(8.dp)
Box(modifier.onFocusChanged { focused = it.isFocused; if (it.isFocused) onChosen(game) }.gameKeys(game, onMenu)
.background(if (focused) ArcadeColours.FocusFill else ArcadeColours.Panel, corner).border(if (focused) 3.dp else 1.dp, if (focused) ArcadeColours.Yellow else ArcadeColours.Line, corner)
.clickable { onPlay(game) }.padding(4.dp)) {
Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
Canvas(Modifier.size(30.dp)) { gameIcon(game) }
Text(game.title, color = ArcadeColours.Ink, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
if (isPick) Text("PICK", Modifier.align(Alignment.TopEnd).background(ArcadeColours.Yellow, RoundedCornerShape(4.dp)).padding(horizontal = 3.dp), color = ArcadeColours.Night, fontSize = 9.sp, fontWeight = FontWeight.Bold)
}
}
/** The chosen game along the bottom: what it is, its keys, your top 3 and the Household record. */
@Composable
private fun InfoPanel(game: ArcadeGame, record: GameRecord, household: Map<String, HouseholdRecord>, note: String?) {
Row(Modifier.fillMaxWidth().height(76.dp).background(ArcadeColours.PanelDeep.copy(alpha = .9f), RoundedCornerShape(10.dp)).border(1.dp, ArcadeColours.Line, RoundedCornerShape(10.dp))
.padding(horizontal = 12.dp, vertical = 6.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Text(game.title.uppercase(), color = ArcadeColours.Ink, fontFamily = Anton, fontSize = 20.sp, maxLines = 1)
Text(note ?: game.blurb, color = ArcadeColours.Muted, fontSize = 13.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) {
game.controls.take(5).forEach { c -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { KeyCap(c.keys); Text(c.action, color = ArcadeColours.Ink, fontSize = 12.sp, maxLines = 1) } }
}
}
Box(Modifier.width(1.dp).fillMaxHeight().background(ArcadeColours.Line))
Column(Modifier.width(92.dp)) {
Text("Your top 3", color = ArcadeColours.Muted, fontSize = 12.sp)
val top = topThree(game, record)
if (top.isEmpty()) Text(if (game.launchable) "Not played yet" else "Coming soon", color = ArcadeColours.Muted, fontSize = 12.sp)
top.forEachIndexed { i, t -> Text("${i + 1}. $t", color = ArcadeColours.Ink, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, maxLines = 1) }
}
Column(Modifier.width(150.dp).background(ArcadeColours.Night.copy(alpha = .6f), RoundedCornerShape(8.dp)).border(1.dp, ArcadeColours.Line, RoundedCornerShape(8.dp)).padding(horizontal = 8.dp, vertical = 4.dp)) {
Row { Text("🔒 Household record · ", color = ArcadeColours.Muted, fontSize = 11.sp); Text("read-only", color = ArcadeColours.Cyan, fontSize = 11.sp) }
val h = householdLine(game, household)
Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Text(h ?: "—", color = ArcadeColours.Ink, fontFamily = Anton, fontSize = 20.sp)
Text(if (h != null) "from before profiles" else "none from before profiles", color = ArcadeColours.Muted, fontSize = 11.sp, maxLines = 1)
}
}
}
}
/** The profile's top three for the info panel: scores or moves; for won or solved games, the count. */
internal fun topThree(game: ArcadeGame, record: GameRecord): List<String> = when (game.scoreKind) {
ScoreKind.Points, ScoreKind.FewestMoves -> rankRuns(record.runs, game.scoreKind).take(3).map { formatScore(game.scoreKind, it.score) }
ScoreKind.Wins, ScoreKind.Solved -> if (record.count > 0) listOf(formatScore(game.scoreKind, record.count)) else emptyList()
}
/** Menu on a game: its own settings (frame 05's per-game half), and whether How to Play shows every time. */
@Composable
private fun GameSettingsSheet(game: ArcadeGame, record: GameRecord, legacy: (String, Boolean) -> Boolean, onSetting: (String, Boolean) -> Unit, onEveryTime: (Boolean) -> Unit, onClose: () -> Unit) {
var howTo by remember { mutableStateOf(false) }
if (howTo) { HowToPlayCard(game, firstRun = false, everyTime = null, onEveryTime = {}, onPlay = { howTo = false }, onBack = { howTo = false }); return }
val first = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { first.requestFocus() } }
androidx.activity.compose.BackHandler(onBack = onClose)
ArcadeScrim {
Column(Modifier.width(300.dp).background(ArcadeColours.PanelDeep, RoundedCornerShape(12.dp)).border(1.dp, ArcadeColours.Line, RoundedCornerShape(12.dp)).padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("${game.title.uppercase()} SETTINGS", color = ArcadeColours.Ink, fontFamily = Anton, fontSize = 22.sp)
Text("Saved for whoever's playing, on this TV.", color = ArcadeColours.Muted, fontSize = 12.sp)
var firstUsed = false
game.settings.forEach { s ->
val on = settingFor(record, s, legacy)
val m = if (!firstUsed) { firstUsed = true; Modifier.fillMaxWidth().focusRequester(first) } else Modifier.fillMaxWidth()
ArcadeButton(s.title, m, detail = if (on) "On" else "Off", onClick = { onSetting(s.key, !on) })
}
ArcadeButton("Show How to Play every time", if (!firstUsed) Modifier.fillMaxWidth().focusRequester(first) else Modifier.fillMaxWidth(), detail = if (record.howToEveryTime) "On" else "Off", onClick = { onEveryTime(!record.howToEveryTime) })
ArcadeButton("How to Play", Modifier.fillMaxWidth(), icon = "?", onClick = { howTo = true })
ArcadeButton("Done", Modifier.fillMaxWidth(), icon = "←", onClick = onClose)
}
}
}
/** Something to focus when a page has nothing else (so Back and the menu still work). */
@Composable
internal fun FocusAnchor(modifier: Modifier = Modifier) = Box(modifier.size(1.dp).focusable())
@@ -0,0 +1,44 @@
package tv.orbit.classic.arcade
import android.view.KeyEvent
/** The remote, as the Arcade sees it. */
internal enum class ArcadeKey { Up, Down, Left, Right, Ok, Back, Menu, PlayPause, Other }
internal fun arcadeKey(keyCode: Int): ArcadeKey = when (keyCode) {
KeyEvent.KEYCODE_DPAD_UP -> ArcadeKey.Up
KeyEvent.KEYCODE_DPAD_DOWN -> ArcadeKey.Down
KeyEvent.KEYCODE_DPAD_LEFT -> ArcadeKey.Left
KeyEvent.KEYCODE_DPAD_RIGHT -> ArcadeKey.Right
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER, KeyEvent.KEYCODE_BUTTON_A -> ArcadeKey.Ok
KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_ESCAPE, KeyEvent.KEYCODE_BUTTON_B -> ArcadeKey.Back
KeyEvent.KEYCODE_MENU, KeyEvent.KEYCODE_SETTINGS -> ArcadeKey.Menu
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, KeyEvent.KEYCODE_MEDIA_PAUSE, KeyEvent.KEYCODE_BUTTON_START -> ArcadeKey.PlayPause
else -> ArcadeKey.Other
}
/** What a key means in play: Back (and play/pause) always pause, never leave. */
internal fun pausesGame(key: ArcadeKey) = key == ArcadeKey.Back || key == ArcadeKey.PlayPause
/**
* Holding a button on the remote repeats it. For moves that's wanted, but for one-shot actions (Block Drop's hard drop,
* Blast Off's place) a held OK would drop or place again and again (audit finding 8). The guard lets a one-shot key act
* once per press: a repeat, or a second "down" without a release in between (some remotes send that), is ignored.
*/
internal class RepeatGuard(private val oneShot: Set<ArcadeKey> = setOf(ArcadeKey.Ok)) {
private val held = HashSet<ArcadeKey>()
/** True when this key event should act. [down] is ACTION_DOWN; ups are never acted on, only noted. */
fun accept(key: ArcadeKey, down: Boolean, repeatCount: Int): Boolean {
if (!down) { held.remove(key); return false }
if (key !in oneShot) return true
if (repeatCount > 0 || key in held) return false
held.add(key)
return true
}
fun accept(event: KeyEvent): Boolean = accept(arcadeKey(event.keyCode), event.action == KeyEvent.ACTION_DOWN, event.repeatCount)
/** The window lost focus, so a release may never arrive: forget what's held. */
fun reset() = held.clear()
}
@@ -0,0 +1,271 @@
package tv.orbit.classic.arcade
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.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.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
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.ArcadeLook
import tv.orbit.classic.Motion
import tv.orbit.classic.OrbitSettings
import tv.orbit.classic.Profile
import tv.orbit.classic.ProfileKind
@Composable
private fun PageTitle(title: String, line: String) {
Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(bottom = 8.dp)) {
Text(title, color = ArcadeColours.Ink, fontFamily = Anton, fontSize = 28.sp)
Text(line, color = ArcadeColours.Muted, fontSize = 14.sp, modifier = Modifier.padding(bottom = 4.dp))
}
}
// ---------- High Scores (frame 04) ----------
@Composable
internal fun HighScoresPage(profile: Profile, visible: List<ArcadeGame>, data: ArcadeProfileData, household: Map<String, HouseholdRecord>) {
var topTen by remember { mutableStateOf<ArcadeGame?>(null) }
val now = remember { System.currentTimeMillis() }
PageTitle("HIGH SCORES", "${profile.name}, on this TV")
Row(Modifier.fillMaxSize(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Column(Modifier.weight(1f).fillMaxHeight().background(ArcadeColours.PanelDeep.copy(alpha = .85f), RoundedCornerShape(10.dp)).border(1.dp, ArcadeColours.Line, RoundedCornerShape(10.dp)).padding(8.dp)) {
Row(Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 2.dp)) {
Text("Game", Modifier.weight(1f), color = ArcadeColours.Muted, fontSize = 12.sp)
listOf("Your best" to 90, "2nd" to 64, "3rd" to 64, "Played" to 64).forEach { (t, w) -> Text(t, Modifier.width(w.dp), color = ArcadeColours.Muted, fontSize = 12.sp, maxLines = 1) }
}
visible.forEach { g -> ScoreRow(g, data.game(g.id), now) { topTen = g } }
}
Column(Modifier.width(150.dp).fillMaxHeight().background(ArcadeColours.PanelDeep.copy(alpha = .85f), RoundedCornerShape(10.dp)).border(1.dp, ArcadeColours.Line, RoundedCornerShape(10.dp)).padding(8.dp)) {
Text("🔒 Household Records", color = ArcadeColours.Cyan, fontSize = 13.sp, fontWeight = FontWeight.SemiBold)
Text("From before profiles · read-only", color = ArcadeColours.Muted, fontSize = 11.sp)
visible.forEach { g -> Text(householdLine(g, household) ?: "—", Modifier.fillMaxWidth().height(rowHeight).padding(top = 3.dp), color = ArcadeColours.Ink, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, textAlign = androidx.compose.ui.text.style.TextAlign.End) }
}
}
topTen?.let { g -> TopTen(g, data.game(g.id), now, onClose = { topTen = null }) }
}
private val rowHeight = 22.dp
@Composable
private fun ScoreRow(game: ArcadeGame, record: GameRecord, now: Long, onOpen: () -> Unit) {
var focused by remember { mutableStateOf(false) }
val corner = RoundedCornerShape(6.dp)
val runs = rankRuns(record.runs, game.scoreKind)
Row(Modifier.fillMaxWidth().height(rowHeight).onFocusChanged { focused = it.isFocused }.background(if (focused) ArcadeColours.FocusFill else ArcadeColours.Panel.copy(alpha = .35f), corner)
.border(if (focused) 2.dp else 0.dp, if (focused) ArcadeColours.Yellow else ArcadeColours.Panel, corner).clickable(onClick = onOpen).padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically) {
Canvas(Modifier.size(16.dp)) { drawMascot(game.mascot, center, size.minDimension * .4f) }
Spacer(Modifier.width(6.dp))
Text(game.title, Modifier.weight(1f), color = ArcadeColours.Ink, fontSize = 13.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
val best = bestLine(game, record)
if (best == null) Text(if (game.launchable) "Not played yet" else "Coming soon", Modifier.width(282.dp), color = ArcadeColours.Muted, fontSize = 12.sp)
else {
Text(best, Modifier.width(90.dp), color = ArcadeColours.Ink, fontSize = 13.sp, fontWeight = FontWeight.Bold, maxLines = 1)
val ranked = game.scoreKind == ScoreKind.Points || game.scoreKind == ScoreKind.FewestMoves
Text(if (ranked) runs.getOrNull(1)?.let { formatScore(game.scoreKind, it.score) }.orEmpty() else "", Modifier.width(64.dp), color = ArcadeColours.Muted, fontSize = 12.sp, maxLines = 1)
Text(if (ranked) runs.getOrNull(2)?.let { formatScore(game.scoreKind, it.score) }.orEmpty() else "", Modifier.width(64.dp), color = ArcadeColours.Muted, fontSize = 12.sp, maxLines = 1)
Text(playedLabel(record.lastPlayedMs, now), Modifier.width(64.dp), color = ArcadeColours.Muted, fontSize = 12.sp, maxLines = 1)
}
}
}
@Composable
private fun TopTen(game: ArcadeGame, record: GameRecord, now: Long, onClose: () -> Unit) {
val close = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { close.requestFocus() } }
BackHandler(onBack = onClose)
ArcadeScrim {
Column(Modifier.width(320.dp).background(ArcadeColours.PanelDeep, RoundedCornerShape(12.dp)).border(1.dp, ArcadeColours.Line, RoundedCornerShape(12.dp)).padding(16.dp),
verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text("${game.title.uppercase()} · TOP 10", color = ArcadeColours.Ink, fontFamily = Anton, fontSize = 22.sp)
if (game.scoreKind == ScoreKind.Wins || game.scoreKind == ScoreKind.Solved) Text(formatScore(game.scoreKind, record.count) + " in all", color = ArcadeColours.Yellow, fontSize = 14.sp, fontWeight = FontWeight.SemiBold)
val runs = rankRuns(record.runs, game.scoreKind)
if (runs.isEmpty()) Text("Nothing saved yet.", color = ArcadeColours.Muted, fontSize = 13.sp)
runs.forEachIndexed { i, r ->
Row(Modifier.fillMaxWidth()) {
Text("${i + 1}.", Modifier.width(26.dp), color = ArcadeColours.Muted, fontSize = 13.sp)
Text(when (game.scoreKind) { ScoreKind.Wins -> "${r.score} moves"; ScoreKind.Solved -> "${r.score} hearts left"; else -> formatScore(game.scoreKind, r.score) },
Modifier.weight(1f), color = ArcadeColours.Ink, fontSize = 13.sp, fontWeight = FontWeight.SemiBold)
Text(listOfNotNull(r.detail, playedLabel(r.atMs, now)).joinToString(" · "), color = ArcadeColours.Muted, fontSize = 12.sp)
}
}
ArcadeButton("Close", Modifier.fillMaxWidth().padding(top = 6.dp).focusRequester(close), icon = "←", onClick = onClose)
}
}
}
// ---------- How to Play ----------
@Composable
internal fun HowToPage(visible: List<ArcadeGame>) {
var open by remember { mutableStateOf<ArcadeGame?>(null) }
var shown by remember { mutableStateOf(visible.firstOrNull { it.launchable }) }
PageTitle("HOW TO PLAY", "Every game's keys on the remote")
Row(Modifier.fillMaxSize(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
Column(Modifier.width(220.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
visible.filter { it.launchable }.forEach { g ->
ArcadeButton(g.title, Modifier.fillMaxWidth().onFocusChanged { if (it.isFocused) shown = g }, height = 26.dp, onClick = { open = g })
}
}
shown?.let { g ->
Column(Modifier.weight(1f).background(ArcadeColours.PanelDeep.copy(alpha = .85f), RoundedCornerShape(10.dp)).border(1.dp, ArcadeColours.Line, RoundedCornerShape(10.dp)).padding(14.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(g.title.uppercase(), color = ArcadeColours.Ink, fontFamily = Anton, fontSize = 22.sp)
Text(g.blurb, color = ArcadeColours.Muted, fontSize = 13.sp)
g.controls.forEach { c -> Row(verticalAlignment = Alignment.CenterVertically) { Box(Modifier.width(96.dp)) { KeyCap(c.keys) }; Text(c.action, color = ArcadeColours.Ink, fontSize = 14.sp) } }
Text(g.goal, color = ArcadeColours.Muted, fontSize = 13.sp)
}
}
}
open?.let { g -> HowToPlayCard(g, firstRun = false, everyTime = null, onEveryTime = {}, onPlay = { open = null }, onBack = { open = null }) }
}
// ---------- Arcade Settings (frame 05) ----------
@Composable
private fun ToggleRow(title: String, on: Boolean, modifier: Modifier = Modifier, detail: String? = null, onClick: () -> 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 = onClick).padding(horizontal = 10.dp, vertical = 3.dp),
verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text(title, color = ArcadeColours.Ink, fontSize = 14.sp)
if (detail != null) Text(detail, color = ArcadeColours.Muted, fontSize = 11.sp)
}
Text(if (on) "On" else "Off", color = if (on) ArcadeColours.Ink else ArcadeColours.Muted, fontSize = 13.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.Normal)
Spacer(Modifier.width(8.dp))
Box(Modifier.size(36.dp, 18.dp).background(if (on) ArcadeColours.Cyan else ArcadeColours.Night, RoundedCornerShape(9.dp)).border(1.dp, ArcadeColours.Line, RoundedCornerShape(9.dp)).padding(2.dp),
contentAlignment = if (on) Alignment.CenterEnd else Alignment.CenterStart) {
Box(Modifier.size(14.dp).background(ArcadeColours.Ink, RoundedCornerShape(7.dp)))
}
}
}
@Composable
private fun SettingsCard(title: String, icon: String, modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) {
Column(modifier.fillMaxWidth().background(ArcadeColours.PanelDeep.copy(alpha = .85f), RoundedCornerShape(10.dp)).border(1.dp, ArcadeColours.Line, RoundedCornerShape(10.dp)).padding(8.dp),
verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text("$icon $title", color = ArcadeColours.Ink, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.padding(start = 4.dp, bottom = 2.dp))
content()
}
}
/**
* 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).
*/
@Composable
internal fun ArcadeSettingsPage(profile: Profile, data: ArcadeProfileData, onChange: (String, Boolean) -> Unit, onReset: () -> Unit) {
val context = LocalContext.current
val settings = remember { OrbitSettings(context) }
val audio = AudioPrefs.of(data.settings)
PageTitle("ARCADE SETTINGS", "For ${profile.name}, every game in the Arcade")
Row(Modifier.fillMaxSize(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {
SettingsCard("Audio", "🔊") {
ToggleRow("Music", audio.music) { onChange("music", !audio.music) }
ToggleRow("Effects", audio.effects) { onChange("effects", !audio.effects) }
ToggleRow("Mute all", audio.muteAll) { onChange("muteAll", !audio.muteAll) }
Column(Modifier.fillMaxWidth().background(ArcadeColours.Panel, RoundedCornerShape(8.dp)).padding(8.dp)) {
Text("Orbit Quiet and Wind Down always win", color = ArcadeColours.Ink, fontSize = 13.sp, fontWeight = FontWeight.SemiBold)
Text("They turn the Arcade down, whatever is set here.", color = ArcadeColours.Muted, fontSize = 12.sp)
}
}
SettingsCard("Progress", "↻") {
Row(Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 3.dp)) {
Text("Saved for ${profile.name} on this TV", Modifier.weight(1f), color = ArcadeColours.Ink, fontSize = 14.sp)
Text("✓", color = ArcadeColours.Cyan, fontSize = 14.sp)
}
ArcadeButton("Restart, reset or clear", Modifier.fillMaxWidth(), detail = "4 choices ›", height = 26.dp, onClick = onReset)
}
}
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {
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
}
}
SettingsCard("Look", "★") {
var look by remember { mutableStateOf(ArcadeLook.backdrop) }
ArcadeButton("Backdrop", Modifier.fillMaxWidth(), detail = look.title, height = 26.dp, onClick = { ArcadeLook.next(settings); look = ArcadeLook.backdrop })
Text("Behind every game, for everyone on this TV.", color = ArcadeColours.Muted, fontSize = 11.sp, modifier = Modifier.padding(start = 10.dp))
}
}
}
}
// ---------- Reset Progress (frame 22) ----------
/** What each action would clear, in plain words, or why it can't be used here. */
internal fun resetDetail(action: ResetAction, game: ArcadeGame, who: String, allowed: Boolean): String = when {
action == ResetAction.RestartLevel -> if (allowed) "Starts this level again." else "From a game's pause menu, while you play."
!allowed && action == ResetAction.ResetLevelProgress -> if (game.id == ArcadeGames.Hive.id) "BumbleHive's levels are one save for the whole TV for now." else "${game.title} keeps no levels."
action == ResetAction.ResetLevelProgress -> "$who's levels and unlocks for ${game.title} go back to the start."
action == ResetAction.ClearHighScores -> "$who's top scores for this game go."
else -> "$who's choices for ${game.title} go back to how they started."
}
@Composable
internal fun ResetPage(profile: Profile, visible: List<ArcadeGame>, data: ArcadeProfileData, onReset: (String, ResetAction) -> Unit) {
var state by remember { mutableStateOf(ResetState()) }
val games = visible.filter { it.launchable }
val game = state.gameId?.let { id -> games.firstOrNull { it.id == id } }
fun allowed(a: ResetAction) = game != null && resetAllowed(a, game, profile.id, data.profileId, inGame = false)
LaunchedEffect(state.done) { state.done?.let { action -> game?.let { onReset(it.id, action) }; state = state.copy(done = null) } }
PageTitle("RESET PROGRESS", if (profile.kind == ProfileKind.Kids) "${profile.name}'s progress only" else "${profile.name}'s own progress. Nobody else's changes.")
if (game == null) {
val first = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { first.requestFocus() } }
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text("Choose a game", color = ArcadeColours.Muted, fontSize = 13.sp)
games.chunked(2).forEachIndexed { r, pair ->
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
pair.forEachIndexed { i, g ->
ArcadeButton(g.title, Modifier.weight(1f).then(if (r == 0 && i == 0) Modifier.focusRequester(first) else Modifier), height = 28.dp,
detail = bestLine(g, data.game(g.id)) ?: "Nothing saved", onClick = { state = reduceReset(state, ResetEvent.ChooseGame(g.id), ::allowed) })
}
if (pair.size == 1) Spacer(Modifier.weight(1f))
}
}
}
return
}
BackHandler(state.confirming == null) { state = reduceReset(state, ResetEvent.Back, ::allowed) }
val first = remember { FocusRequester() }
LaunchedEffect(game.id, state.confirming) { if (state.confirming == null) runCatching { first.requestFocus() } }
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(game.title.uppercase(), color = ArcadeColours.Ink, fontFamily = Anton, fontSize = 20.sp)
ResetAction.entries.forEachIndexed { i, a ->
val ok = allowed(a)
ArcadeButton(a.title, Modifier.fillMaxWidth().then(if (i == 1) Modifier.focusRequester(first) else Modifier), detail = resetDetail(a, game, profile.name, ok),
height = 34.dp, enabled = ok, onClick = { state = reduceReset(state, ResetEvent.Choose(a), ::allowed) })
}
ArcadeButton("Choose another game", Modifier.width(220.dp), icon = "←", height = 28.dp, onClick = { state = reduceReset(state, ResetEvent.Back, ::allowed) })
}
state.confirming?.let { action ->
val (icon, title, confirm) = when (action) {
ResetAction.ClearHighScores -> Triple("🏆", "Clear ${game.title} high scores for ${profile.name}?", "Clear")
ResetAction.ResetLevelProgress -> Triple("↻", "Reset ${game.title} levels for ${profile.name}?", "Reset")
ResetAction.ResetSettings -> Triple("⚙", "Reset ${game.title} settings for ${profile.name}?", "Reset")
ResetAction.RestartLevel -> Triple("↻", "Restart this level?", "Restart")
}
ArcadeConfirm(icon, title, resetDetail(action, game, profile.name, true) + " This can't be undone.", confirm,
onCancel = { state = reduceReset(state, ResetEvent.Cancel, ::allowed) },
onConfirm = { state = reduceReset(reduceReset(state, ResetEvent.Toggle, ::allowed), ResetEvent.Press, ::allowed) })
}
}
@@ -0,0 +1,59 @@
package tv.orbit.classic.arcade
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
/**
* What a game gets from the Arcade while it's played: the profile's best so far, the shared sound service, its own
* settings, and where to report a run's end. The games keep their own rules; this is all they share.
*/
internal class ArcadePlay(
val gameId: String,
val profileId: String,
/** The profile's headline number for this game: best points, fewest moves (0 = none yet), or games won / solved. */
val best: Int,
val audio: ArcadeAudio,
/** Today's Skydoku already solved by this profile, and the like: the game's level progress. */
val level: Map<String, String>,
/** When this profile last reset the game's level progress (BumbleHive clears its own save from this). */
val levelsResetMs: Long,
private val readSetting: (String) -> Boolean,
private val writeSetting: (String, Boolean) -> Unit,
private val writeLevel: (String, String) -> Unit,
val onRunEnd: (RunEnd) -> Unit,
val onLeave: () -> Unit,
) {
fun setting(key: String) = readSetting(key)
fun setSetting(key: String, on: Boolean) = writeSetting(key, on)
fun setLevel(key: String, value: String) = writeLevel(key, value)
}
/**
* Makes sure each run is reported exactly once: when the game ends it, when the player leaves, or when the screen goes
* away mid-run for any other reason (the sleep timer, switching profile, Orbit closing).
*/
internal class RunTracker(private val report: (RunEnd) -> Unit) {
var open = false
private set
fun begin() { open = true }
fun end(run: RunEnd) {
if (!open) return
open = false
report(run)
}
}
/** A [RunTracker] that also reports the run in progress ([inProgress]) if the game's screen is taken away mid-run. */
@Composable
internal fun rememberRun(onRunEnd: (RunEnd) -> Unit, inProgress: () -> RunEnd): RunTracker {
val report by rememberUpdatedState(onRunEnd)
val live by rememberUpdatedState(inProgress)
val tracker = remember { RunTracker { report(it) } }
DisposableEffect(tracker) { onDispose { tracker.end(live()) } }
return tracker
}
@@ -0,0 +1,34 @@
package tv.orbit.classic.arcade
import android.content.Context
import java.io.File
import java.util.concurrent.Executors
/**
* The Arcade's saves for this box: per-profile files and the Household Records, under filesDir/arcade. Disk writes go
* to one background thread in order; the screens use the in-memory copy straight away.
*/
internal class ArcadeRepo private constructor(context: Context) {
private val app = context.applicationContext
val dir = File(app.filesDir, "arcade")
private val writer = Executors.newSingleThreadExecutor { r -> Thread(r, "arcade-saves").apply { isDaemon = true } }
val store = ArcadeStore(dir, write = { writer.execute(it) }, log = { android.util.Log.w("OrbitArcade", it) })
private val legacy = app.getSharedPreferences("orbit_settings", Context.MODE_PRIVATE)
/** Household Records: the one-time snapshot of the old box-wide scores, taken now if it hasn't been. */
val household: Map<String, HouseholdRecord> by lazy {
runCatching { HouseholdRecords.snapshotIfAbsent(dir, { key -> legacy.all[key] }, System.currentTimeMillis()) }.getOrDefault(emptyMap())
}
/** An old box-wide on/off (Comet Trail's music and the like), read only, as a profile's starting choice. */
fun legacyFlag(key: String, default: Boolean) = runCatching { legacy.getBoolean(key, default) }.getOrDefault(default)
companion object {
@Volatile private var made: ArcadeRepo? = null
fun get(context: Context): ArcadeRepo = made ?: synchronized(this) { made ?: ArcadeRepo(context).also { made = it } }
}
}
/** A game setting for a profile: what they chose, else the old box-wide choice it started from, else its default. */
internal fun settingFor(record: GameRecord, setting: GameSetting, legacy: (String, Boolean) -> Boolean): Boolean =
record.settings[setting.key] ?: setting.legacyKey?.let { legacy(it, setting.default) } ?: setting.default
@@ -0,0 +1,119 @@
package tv.orbit.classic.arcade
/**
* One game being played, from its title (the How to Play card on a first run) to leaving it. Screen-free, so every
* move is tested. The real-time Classics keep their own pause and game-over panels for now (Stage C changes no gameplay);
* the Arcade host, Pairs and Patience run on this.
*/
internal sealed interface SessionState {
/** The title: the How to Play card, shown before the first run or every time when asked for. */
data object Title : SessionState
data object Play : SessionState
/** Paused, optionally showing How to Play over the pause menu. */
data class Pause(val howTo: Boolean = false) : SessionState
data class Result(val end: RunEnd, val newBest: Boolean) : SessionState
data object Exited : SessionState
}
internal sealed interface SessionEvent {
/** OK on the title, or a game opened with nothing to show first. */
data object Start : SessionEvent
/** The remote's Back: pause in play, resume from pause, close How to Play, leave from the title or a result. */
data object Back : SessionEvent
data object Resume : SessionEvent
data object HowTo : SessionEvent
data object Restart : SessionEvent
data class Finish(val end: RunEnd, val newBest: Boolean) : SessionEvent
data object PlayAgain : SessionEvent
data object Exit : SessionEvent
/** The window or the app went away mid-game. */
data object Hidden : SessionEvent
}
/** The first state for a game: its How to Play card the first time (or every time, when asked), otherwise straight into play. */
internal fun sessionStart(record: GameRecord): SessionState = if (!record.firstRunSeen || record.howToEveryTime) SessionState.Title else SessionState.Play
internal fun reduceSession(state: SessionState, event: SessionEvent): SessionState = when (state) {
SessionState.Title -> when (event) {
SessionEvent.Start -> SessionState.Play
SessionEvent.Back, SessionEvent.Exit -> SessionState.Exited
else -> state
}
SessionState.Play -> when (event) {
SessionEvent.Back, SessionEvent.Hidden -> SessionState.Pause()
is SessionEvent.Finish -> SessionState.Result(event.end, event.newBest)
SessionEvent.Restart -> SessionState.Play
SessionEvent.Exit -> SessionState.Exited
else -> state
}
is SessionState.Pause -> when (event) {
SessionEvent.Back -> if (state.howTo) SessionState.Pause() else SessionState.Play
SessionEvent.Resume -> SessionState.Play
SessionEvent.HowTo -> SessionState.Pause(howTo = true)
SessionEvent.Restart -> SessionState.Play
SessionEvent.Exit -> SessionState.Exited
// A game can't finish while paused; it stays paused.
else -> state
}
is SessionState.Result -> when (event) {
SessionEvent.PlayAgain, SessionEvent.Restart, SessionEvent.Start -> SessionState.Play
SessionEvent.Back, SessionEvent.Exit -> SessionState.Exited
else -> state
}
SessionState.Exited -> state
}
/** Whether the game's own loop may run: only in play. */
internal val SessionState.running get() = this == SessionState.Play
// ---------- Reset Progress ----------
/**
* The shared Reset screen (frame 22): a game, then one of four separate actions, each with its own confirmation where
* Cancel is chosen first. Nothing is reset until the confirm button itself is pressed.
*/
internal data class ResetState(val gameId: String? = null, val confirming: ResetAction? = null, val focusOnConfirm: Boolean = false, val done: ResetAction? = null)
internal sealed interface ResetEvent {
data class ChooseGame(val id: String) : ResetEvent
data class Choose(val action: ResetAction) : ResetEvent
/** Left and right in the confirm dialog: between Cancel and the action. */
data object Toggle : ResetEvent
data object Cancel : ResetEvent
/** OK on whichever button has focus. */
data object Press : ResetEvent
data object Back : ResetEvent
}
internal fun reduceReset(state: ResetState, event: ResetEvent, allowed: (ResetAction) -> Boolean): ResetState = when {
state.confirming != null -> when (event) {
ResetEvent.Toggle -> state.copy(focusOnConfirm = !state.focusOnConfirm)
ResetEvent.Cancel, ResetEvent.Back -> state.copy(confirming = null, focusOnConfirm = false)
ResetEvent.Press -> if (state.focusOnConfirm) state.copy(confirming = null, focusOnConfirm = false, done = state.confirming) else state.copy(confirming = null, focusOnConfirm = false)
else -> state
}
else -> when (event) {
is ResetEvent.ChooseGame -> ResetState(gameId = event.id)
// Cancel is always what has focus first.
is ResetEvent.Choose -> if (state.gameId != null && allowed(event.action)) state.copy(confirming = event.action, focusOnConfirm = false, done = null) else state
ResetEvent.Back -> if (state.gameId != null) ResetState() else state
else -> state
}
}
/**
* Who may reset what. Everyone resets only their own Arcade data (Household Records are never reset by anyone); a Kids
* profile can never reach anyone else's. Restart level only means something inside a game, and level progress only where
* a game keeps it.
*/
internal fun resetAllowed(action: ResetAction, game: ArcadeGame, actorId: String, ownerId: String, inGame: Boolean,
hiveProfileSaves: Boolean = ArcadeFlags.hiveProfileSaves): Boolean {
if (actorId != ownerId) return false
return when (action) {
ResetAction.RestartLevel -> inGame
// BumbleHive's levels are one save for the whole TV until profile saves are switched on, and that is never reset.
ResetAction.ResetLevelProgress -> game.keepsLevels && (game.id != ArcadeGames.Hive.id || hiveProfileSaves)
ResetAction.ClearHighScores -> game.launchable
ResetAction.ResetSettings -> game.launchable
}
}
@@ -0,0 +1,202 @@
package tv.orbit.classic.arcade
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.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
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.drawOrbMascot
/**
* The Arcade's own look (Stage B frames): always its night sky, whatever Orbit look is chosen, like the games. Yellow is
* only ever on what the remote has focus on. Sizes are the 1080p frames' pixels halved (the box draws 960×540 dp).
*/
internal object ArcadeColours {
val Night = Color(0xFF071632)
val Panel = Color(0xFF13306B)
val PanelDeep = Color(0xFF0C1F4A)
val Line = Color(0xFF3D63B8)
val FocusFill = Color(0xFF2556A8)
val Ink = Color(0xFFF4F6FB)
val Muted = Color(0xFFB4C0DA)
val Yellow = Color(0xFFFFDE59)
val Cyan = Color(0xFF35D6F2)
val Pink = Color(0xFFFF4FA3)
val Red = Color(0xFFFF6B6B)
val DangerFill = Color(0xFF3A1424)
val Green = Color(0xFF6EDCAA)
}
/** A remote key, drawn as a key cap. */
@Composable
internal fun KeyCap(keys: String, modifier: Modifier = Modifier, size: TextUnit = 13.sp) {
Text(keys, modifier.background(ArcadeColours.PanelDeep, RoundedCornerShape(5.dp)).border(1.dp, ArcadeColours.Muted.copy(alpha = .7f), RoundedCornerShape(5.dp))
.padding(horizontal = 6.dp, vertical = 1.dp), color = ArcadeColours.Ink, fontSize = size, fontWeight = FontWeight.SemiBold, maxLines = 1)
}
/** The footer's remote keys, as on every frame. */
@Composable
internal fun KeyFooter(keys: List<Control>, modifier: Modifier = Modifier, note: String? = null) {
Column(modifier.fillMaxWidth()) {
Box(Modifier.fillMaxWidth().height(1.dp).background(ArcadeColours.Line.copy(alpha = .6f)))
Row(Modifier.fillMaxWidth().padding(top = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp)) {
keys.forEach { c -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { KeyCap(c.keys); Text(c.action, color = ArcadeColours.Muted, fontSize = 13.sp) } }
if (note != null) { Spacer(Modifier.weight(1f)); Text(note, color = ArcadeColours.Muted, fontSize = 13.sp) }
}
}
}
/** A button in the Arcade's style: a yellow ring and a lighter fill when focused; [danger] for a reset's confirm. */
@Composable
internal fun ArcadeButton(label: String, modifier: Modifier = Modifier, icon: String? = null, detail: String? = null, primary: Boolean = false, danger: Boolean = false,
height: Dp = 30.dp, enabled: Boolean = true, onClick: () -> Unit) {
var focused by remember { mutableStateOf(false) }
val corner = RoundedCornerShape(8.dp)
val fill = when { danger -> ArcadeColours.DangerFill; focused || primary -> ArcadeColours.FocusFill; else -> ArcadeColours.Panel }
val edge = when { focused -> ArcadeColours.Yellow; danger -> ArcadeColours.Red; else -> ArcadeColours.Line }
Row(modifier.height(height).onFocusChanged { focused = it.isFocused }.background(fill, corner).border(if (focused) 3.dp else 1.dp, edge, corner)
.clickable(enabled = enabled, onClick = onClick).padding(horizontal = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (icon != null) Text(icon, color = if (danger) ArcadeColours.Red else ArcadeColours.Ink, fontSize = 14.sp, fontWeight = FontWeight.Bold)
Text(label, Modifier.weight(1f, fill = false), color = if (enabled) (if (danger && !focused) Color(0xFFFFC2C2) else ArcadeColours.Ink) else ArcadeColours.Muted,
fontSize = 14.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (detail != null) { Spacer(Modifier.weight(1f)); Text(detail, color = ArcadeColours.Muted, fontSize = 12.sp, maxLines = 1) }
}
}
/**
* A dimmed whole screen behind a dialog, so no half-covered words show round it. It's a window of its own, over
* everything; its Back goes to the dialog's own handler, never straight out.
*/
@Composable
internal fun ArcadeScrim(content: @Composable BoxScope.() -> Unit) {
androidx.compose.ui.window.Dialog(onDismissRequest = {}, properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false,
dismissOnBackPress = false, dismissOnClickOutside = false, decorFitsSystemWindows = false)) {
Box(Modifier.fillMaxSize().background(ArcadeColours.Night.copy(alpha = .9f)), contentAlignment = Alignment.Center, content = content)
}
}
/**
* The shared pause menu (frame 20): Resume first, then Restart Level, How to Play, an optional sound line, and Exit to
* Arcade. Back resumes; with How to Play open, Back closes it.
*/
@Composable
internal fun ArcadePauseMenu(game: ArcadeGame, line: String, onResume: () -> Unit, onRestart: () -> Unit, onExit: () -> Unit,
sound: String? = null, onSound: (() -> Unit)? = null) {
var howTo by remember { mutableStateOf(false) }
if (howTo) { HowToPlayCard(game, firstRun = false, everyTime = null, onEveryTime = {}, onPlay = { howTo = false }, onBack = { howTo = false }); return }
val first = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { first.requestFocus() } }
BackHandler(onBack = onResume)
ArcadeScrim {
Column(Modifier.width(210.dp).background(ArcadeColours.PanelDeep, RoundedCornerShape(12.dp)).border(1.dp, ArcadeColours.Line, RoundedCornerShape(12.dp)).padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("PAUSED", color = ArcadeColours.Ink, fontFamily = Anton, fontSize = 30.sp)
Text(line, color = ArcadeColours.Muted, fontSize = 13.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
Spacer(Modifier.height(2.dp))
ArcadeButton("Resume", Modifier.fillMaxWidth().focusRequester(first), icon = "▶", onClick = onResume)
ArcadeButton("Restart Level", Modifier.fillMaxWidth(), icon = "↻", onClick = onRestart)
ArcadeButton("How to Play", Modifier.fillMaxWidth(), icon = "?", onClick = { howTo = true })
if (sound != null && onSound != null) ArcadeButton("Sound", Modifier.fillMaxWidth(), icon = "♪", detail = sound, onClick = onSound)
ArcadeButton("Exit to Arcade", Modifier.fillMaxWidth(), icon = "←", onClick = onExit)
}
KeyFooter(listOf(Control("▲▼", "Choose"), Control("OK", "Select"), Control("Back", "Resume")), Modifier.align(Alignment.BottomStart).padding(start = 32.dp, end = 32.dp, bottom = 16.dp))
}
}
/**
* How to Play (frame 23): the remote with the game's keys, shown before a first game and from any pause menu. [everyTime]
* is null when the card was opened from a menu (there's no "show this every time" to choose there).
*/
@Composable
internal fun HowToPlayCard(game: ArcadeGame, firstRun: Boolean, everyTime: Boolean?, onEveryTime: (Boolean) -> Unit, onPlay: () -> Unit, onBack: () -> Unit) {
val first = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { first.requestFocus() } }
BackHandler(onBack = onBack)
ArcadeScrim {
Row(Modifier.padding(horizontal = 52.dp, vertical = 30.dp).fillMaxWidth().background(ArcadeColours.PanelDeep, RoundedCornerShape(14.dp))
.border(1.dp, ArcadeColours.Line, RoundedCornerShape(14.dp)).padding(24.dp), horizontalArrangement = Arrangement.spacedBy(28.dp)) {
// A plain drawing of the remote, its ring lit.
Canvas(Modifier.width(76.dp).height(210.dp)) {
val w = size.width; val h = size.height
drawRoundRect(Color(0xFF1B2A4E), size = size, cornerRadius = androidx.compose.ui.geometry.CornerRadius(w * .45f))
drawCircle(ArcadeColours.Red, w * .05f, Offset(w / 2, h * .1f))
drawCircle(ArcadeColours.Cyan, w * .4f, Offset(w / 2, h * .34f), style = Stroke(w * .05f))
drawCircle(ArcadeColours.Cyan.copy(alpha = .25f), w * .18f, Offset(w / 2, h * .34f))
drawCircle(ArcadeColours.Cyan, w * .14f, Offset(w * .3f, h * .58f), style = Stroke(w * .03f))
drawCircle(ArcadeColours.Cyan, w * .14f, Offset(w * .7f, h * .58f), style = Stroke(w * .03f))
drawRoundRect(Color(0xFF2A3A62), Offset(w * .35f, h * .72f), androidx.compose.ui.geometry.Size(w * .3f, h * .2f), androidx.compose.ui.geometry.CornerRadius(w * .15f))
}
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(if (firstRun) "FIRST GAME? HERE'S HOW" else "HOW TO PLAY", color = ArcadeColours.Muted, fontSize = 13.sp, letterSpacing = 3.sp)
Text("HOW TO PLAY ${game.title.uppercase()}", color = ArcadeColours.Ink, fontFamily = Anton, fontSize = 28.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
game.controls.forEach { c ->
Row(verticalAlignment = Alignment.CenterVertically) {
Box(Modifier.width(96.dp)) { KeyCap(c.keys, size = 14.sp) }
Text(c.action, color = ArcadeColours.Ink, fontSize = 15.sp)
}
}
Text(game.goal, color = ArcadeColours.Muted, fontSize = 13.sp)
Spacer(Modifier.weight(1f))
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
ArcadeButton(if (everyTime != null) "Got it, let's play" else "Back to the game", Modifier.width(150.dp).focusRequester(first), icon = "▶", primary = true, onClick = onPlay)
if (everyTime != null) ArcadeButton(if (everyTime) "☑ Show this every time" else "☐ Show this every time", Modifier.width(190.dp), onClick = { onEveryTime(!everyTime) })
}
}
Column(Modifier.align(Alignment.Bottom), horizontalAlignment = Alignment.CenterHorizontally) {
Text("You've got this!", Modifier.background(ArcadeColours.Ink, RoundedCornerShape(10.dp)).padding(horizontal = 10.dp, vertical = 6.dp),
color = ArcadeColours.Night, fontSize = 13.sp, fontWeight = FontWeight.SemiBold)
Canvas(Modifier.size(64.dp)) { drawOrbMascot(center, size.minDimension * .34f) }
}
}
KeyFooter(listOf(Control("◀▶", "Choose"), Control("OK", "Select"), Control("Back", if (everyTime != null) "Back to the Arcade" else "Back")),
Modifier.align(Alignment.BottomStart).padding(start = 32.dp, end = 32.dp, bottom = 10.dp))
}
}
/**
* A reset's confirmation (frame 22): what goes, that Household Records don't, and Cancel chosen first. Left and right
* move between the two buttons; nothing happens until the red one is pressed.
*/
@Composable
internal fun ArcadeConfirm(icon: String, title: String, detail: String, confirm: String, onCancel: () -> Unit, onConfirm: () -> Unit) {
val cancel = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { cancel.requestFocus() } }
BackHandler(onBack = onCancel)
ArcadeScrim {
Column(Modifier.width(306.dp).background(ArcadeColours.PanelDeep, RoundedCornerShape(12.dp)).border(1.dp, ArcadeColours.Line, RoundedCornerShape(12.dp)).padding(18.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) {
Box(Modifier.size(28.dp).background(ArcadeColours.Panel, CircleShape), contentAlignment = Alignment.Center) { Text(icon, color = ArcadeColours.Ink, fontSize = 14.sp) }
Text(title, color = ArcadeColours.Ink, fontSize = 17.sp, fontWeight = FontWeight.SemiBold)
}
Text("🔒 Household Records are not affected.", color = ArcadeColours.Cyan, fontSize = 14.sp)
Text(detail, color = ArcadeColours.Muted, fontSize = 12.sp)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
ArcadeButton("Cancel", Modifier.weight(1f).focusRequester(cancel), icon = "←", primary = true, onClick = onCancel)
ArcadeButton(confirm, Modifier.weight(1f), danger = true, onClick = onConfirm)
}
}
KeyFooter(listOf(Control("◀▶", "Choose"), Control("OK", "Select"), Control("Back", "Cancel")), Modifier.align(Alignment.BottomStart).padding(start = 32.dp, end = 32.dp, bottom = 16.dp),
note = "Cancel is chosen first")
}
}
@@ -0,0 +1,230 @@
package tv.orbit.classic.arcade
import org.json.JSONArray
import org.json.JSONObject
import tv.orbit.classic.writeSafely
import java.io.File
/**
* Orbit Arcade saves (Stage C, 8 November 2026). Each profile has its own small file, filesDir/arcade/<profileId>.json,
* written whole through [writeSafely] (temp file, flush, rename), so a power cut leaves the old file or the new one.
* It is bounded: the top [TOP_RUNS] runs per game, a few counters, level progress, unlocks, settings and when each was
* last reset. A missing or unreadable file never reaches the screen as an error: the Arcade starts from empty, and an
* unreadable file is kept beside it (".unreadable") rather than silently thrown away.
*/
internal const val ARCADE_SCHEMA = 1
internal const val TOP_RUNS = 10
/** How a game's result ranks: more points, fewer moves, or a count of games won or puzzles solved. */
internal enum class ScoreKind { Points, FewestMoves, Wins, Solved }
/** One finished (or left) run, as the High Scores keep it. */
internal data class ArcadeRun(val score: Int, val atMs: Long, val detail: String? = null)
/** How a run ended: [finished] when the game itself ended it (game over, cleared, won), false when the player left. */
internal data class RunEnd(val score: Int, val finished: Boolean, val detail: String? = null)
internal data class GameRecord(
val runs: List<ArcadeRun> = emptyList(),
/** Games won (Patience) or puzzles solved (Skydoku). */
val count: Int = 0,
/** Level progress, game by game (Skydoku: the day today's puzzle was solved). */
val level: Map<String, String> = emptyMap(),
val unlocks: Set<String> = emptySet(),
val settings: Map<String, Boolean> = emptyMap(),
/** The How to Play card has been seen once, so it isn't shown again unless asked for. */
val firstRunSeen: Boolean = false,
val howToEveryTime: Boolean = false,
val lastPlayedMs: Long = 0,
val scoresResetMs: Long = 0,
val levelsResetMs: Long = 0,
val settingsResetMs: Long = 0,
)
internal data class ArcadeProfileData(
val profileId: String,
val games: Map<String, GameRecord> = emptyMap(),
/** Arcade-wide choices for this profile: music, effects, mute all. */
val settings: Map<String, Boolean> = emptyMap(),
/** Games by id, most recently played first. */
val recent: List<String> = emptyList(),
) {
fun game(id: String) = games[id] ?: GameRecord()
fun withGame(id: String, change: (GameRecord) -> GameRecord) = copy(games = games + (id to change(game(id))))
}
/** The runs worth keeping, best first: most points, fewest moves, or (won/solved games) fewest moves and most hearts. */
internal fun rankRuns(runs: List<ArcadeRun>, kind: ScoreKind): List<ArcadeRun> = when (kind) {
ScoreKind.Points, ScoreKind.Solved -> runs.sortedWith(compareByDescending<ArcadeRun> { it.score }.thenBy { it.atMs })
ScoreKind.FewestMoves, ScoreKind.Wins -> runs.sortedWith(compareBy<ArcadeRun> { it.score }.thenBy { it.atMs })
}.take(TOP_RUNS)
/** The headline number for a game: best points, fewest moves (0 before the first clear), or how many won or solved. */
internal fun bestOf(record: GameRecord, kind: ScoreKind): Int = when (kind) {
ScoreKind.Points -> record.runs.maxOfOrNull { it.score } ?: 0
ScoreKind.FewestMoves -> record.runs.minOfOrNull { it.score } ?: 0
ScoreKind.Wins, ScoreKind.Solved -> record.count
}
/**
* A run has ended. Points count whenever they were scored, even if the player left mid-game (the audit: a record run was
* thrown away by Leave). Moves, wins and solves count only when the game was actually finished.
*/
internal fun recordRun(data: ArcadeProfileData, gameId: String, kind: ScoreKind, end: RunEnd, nowMs: Long): ArcadeProfileData = data.withGame(gameId) { g ->
val played = g.copy(lastPlayedMs = nowMs)
val run = ArcadeRun(end.score, nowMs, end.detail)
when (kind) {
ScoreKind.Points -> if (end.score > 0) played.copy(runs = rankRuns(g.runs + run, kind)) else played
ScoreKind.FewestMoves -> if (end.finished && end.score > 0) played.copy(runs = rankRuns(g.runs + run, kind)) else played
ScoreKind.Wins, ScoreKind.Solved -> if (end.finished) played.copy(count = g.count + 1, runs = rankRuns(g.runs + run, kind)) else played
}
}
internal fun markPlayed(data: ArcadeProfileData, gameId: String, nowMs: Long): ArcadeProfileData =
data.withGame(gameId) { it.copy(lastPlayedMs = nowMs) }.copy(recent = (listOf(gameId) + data.recent.filter { it != gameId }).take(6))
/** The four things the Reset screen can do, each confirmed on its own. */
internal enum class ResetAction(val title: String) {
RestartLevel("Restart level"), ResetLevelProgress("Reset level progress"), ClearHighScores("Clear high scores"), ResetSettings("Reset settings")
}
/** Applies a reset to one game for one profile. Restart level changes nothing saved: the game restarts its level. */
internal fun applyReset(data: ArcadeProfileData, gameId: String, action: ResetAction, nowMs: Long): ArcadeProfileData = when (action) {
ResetAction.RestartLevel -> data
ResetAction.ResetLevelProgress -> data.withGame(gameId) { it.copy(level = emptyMap(), unlocks = emptySet(), levelsResetMs = nowMs) }
ResetAction.ClearHighScores -> data.withGame(gameId) { it.copy(runs = emptyList(), count = 0, scoresResetMs = nowMs) }
ResetAction.ResetSettings -> data.withGame(gameId) { it.copy(settings = emptyMap(), howToEveryTime = false, settingsResetMs = nowMs) }
}
// ---------- JSON ----------
internal fun encodeArcade(data: ArcadeProfileData): String = JSONObject()
.put("schema", ARCADE_SCHEMA)
.put("profileId", data.profileId)
.put("settings", JSONObject(data.settings as Map<*, *>))
.put("recent", JSONArray(data.recent))
.put("games", JSONObject().also { games ->
data.games.toSortedMap().forEach { (id, g) ->
games.put(id, JSONObject()
.put("runs", JSONArray(g.runs.map { r -> JSONObject().put("score", r.score).put("at", r.atMs).also { if (r.detail != null) it.put("detail", r.detail) } }))
.put("count", g.count)
.put("level", JSONObject(g.level as Map<*, *>))
.put("unlocks", JSONArray(g.unlocks.sorted()))
.put("settings", JSONObject(g.settings as Map<*, *>))
.put("firstRunSeen", g.firstRunSeen)
.put("howToEveryTime", g.howToEveryTime)
.put("lastPlayed", g.lastPlayedMs)
.put("resets", JSONObject().put("scores", g.scoresResetMs).put("levels", g.levelsResetMs).put("settings", g.settingsResetMs)))
}
}).toString()
/** Reads a profile's file text. Anything it can't make sense of is left out rather than failing the whole file; null when it isn't a save at all. */
internal fun decodeArcade(text: String, profileId: String): ArcadeProfileData? {
val o = runCatching { JSONObject(text) }.getOrNull() ?: return null
if (o.optInt("schema", -1) < 1) return null
fun bools(j: JSONObject?) = j?.keys()?.asSequence()?.mapNotNull { k -> (j.opt(k) as? Boolean)?.let { k to it } }?.toMap().orEmpty()
fun strings(j: JSONArray?) = j?.let { a -> (0 until a.length()).mapNotNull { a.opt(it) as? String } }.orEmpty()
val games = o.optJSONObject("games")?.let { gs ->
gs.keys().asSequence().mapNotNull { id ->
val g = gs.optJSONObject(id) ?: return@mapNotNull null
val runs = g.optJSONArray("runs")?.let { a ->
(0 until a.length()).mapNotNull { i -> a.optJSONObject(i)?.takeIf { it.has("score") }?.let { r -> ArcadeRun(r.optInt("score"), r.optLong("at"), r.optString("detail").takeIf { r.has("detail") }) } }
}.orEmpty().take(TOP_RUNS)
val resets = g.optJSONObject("resets")
id to GameRecord(runs, g.optInt("count").coerceAtLeast(0),
g.optJSONObject("level")?.let { l -> l.keys().asSequence().mapNotNull { k -> (l.opt(k) as? String)?.let { k to it } }.toMap() }.orEmpty(),
strings(g.optJSONArray("unlocks")).toSet(), bools(g.optJSONObject("settings")), g.optBoolean("firstRunSeen"), g.optBoolean("howToEveryTime"),
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))
}
/** A profile id as a file name: letters, digits, '-' and '_' only, and never the household file's name. */
internal fun arcadeFileName(profileId: String): String {
val safe = profileId.filter { it.isLetterOrDigit() || it == '-' || it == '_' }.take(40).ifEmpty { "unknown" }
return (if (safe == HOUSEHOLD_NAME) "p-$safe" else safe) + ".json"
}
/**
* The saves on disk. Reads and writes go through here; [write] runs the actual disk write, so the app can keep it off
* the main thread while tests write at once. The in-memory copy is what the screens use.
*/
internal class ArcadeStore(private val dir: File, private val write: (Runnable) -> Unit = { it.run() }, private val log: (String) -> Unit = {}) {
private val cache = HashMap<String, ArcadeProfileData>()
fun file(profileId: String) = File(dir, arcadeFileName(profileId))
@Synchronized
fun load(profileId: String): ArcadeProfileData = cache.getOrPut(profileId) {
val f = file(profileId)
val text = runCatching { if (f.isFile) f.readText() else null }.getOrNull()
when {
text == null -> ArcadeProfileData(profileId)
else -> decodeArcade(text, profileId) ?: run {
// Kept for a look later, never read again; the Arcade starts afresh for this profile.
runCatching { f.copyTo(File(dir, f.name + ".unreadable"), overwrite = true) }
log("arcade save for $profileId unreadable, starting afresh")
ArcadeProfileData(profileId)
}
}
}
@Synchronized
fun update(profileId: String, change: (ArcadeProfileData) -> ArcadeProfileData): ArcadeProfileData {
val next = change(load(profileId)).copy(profileId = profileId)
cache[profileId] = next
val text = encodeArcade(next)
val f = file(profileId)
write(Runnable { runCatching { writeSafely(f, text) }.onFailure { log("arcade save for $profileId failed: ${it.message}") } })
return next
}
/** Forgets the in-memory copy, so the next load reads the disk (tests, and a profile removed). */
@Synchronized
fun forget(profileId: String) { cache.remove(profileId) }
}
// ---------- Household Records ----------
internal const val HOUSEHOLD_NAME = "household-records"
/** The old box-wide keys in "orbit_settings", from before profiles. Read once into Household Records and never changed. */
internal val LegacyRecordKeys = listOf("snake_best", "block_drop_best", "brick_break_best", "pairs_best", "patience_wins", "orb_man_best", "blast_best", "skydoku_solved", "skydoku_daily")
internal data class HouseholdRecord(val key: String, val number: Int?, val text: String?, val source: String, val copiedAtMs: Long)
/**
* Household Records: one read-only snapshot of the old box-wide scores, taken the first time the new Arcade opens. It
* belongs to no profile, shows no name, and is never written again: once the file exists it is only ever read, even if
* it can't be (then the records simply show as empty).
*/
internal object HouseholdRecords {
fun file(dir: File) = File(dir, "$HOUSEHOLD_NAME.json")
/** Takes the snapshot if there isn't one yet. [legacy] reads a key's value (Int, String, or null when unset). */
fun snapshotIfAbsent(dir: File, legacy: (String) -> Any?, nowMs: Long): Map<String, HouseholdRecord> {
val f = file(dir)
if (f.exists()) return load(dir)
val records = LegacyRecordKeys.mapNotNull { key ->
when (val v = legacy(key)) {
is Int -> HouseholdRecord(key, v, null, "orbit_settings/$key", nowMs)
is String -> v.takeIf { it.isNotBlank() }?.let { HouseholdRecord(key, null, it, "orbit_settings/$key", nowMs) }
else -> null
}
}.associateBy { it.key }
val json = JSONObject().put("schema", ARCADE_SCHEMA).put("copiedAt", nowMs).put("readOnly", true).put("records", JSONObject().also { o ->
records.values.forEach { r -> o.put(r.key, JSONObject().put("source", r.source).put("copiedAt", r.copiedAtMs).also { j -> if (r.number != null) j.put("value", r.number) else j.put("text", r.text) }) }
})
runCatching { writeSafely(f, json.toString()) }
return records
}
fun load(dir: File): Map<String, HouseholdRecord> = runCatching {
val o = JSONObject(file(dir).readText()).getJSONObject("records")
o.keys().asSequence().mapNotNull { key ->
val r = o.optJSONObject(key) ?: return@mapNotNull null
HouseholdRecord(key, if (r.has("value")) r.optInt("value") else null, r.optString("text").takeIf { r.has("text") }, r.optString("source"), r.optLong("copiedAt"))
}.associateBy { it.key }
}.getOrDefault(emptyMap())
}
@@ -0,0 +1,52 @@
package tv.orbit.classic.arcade
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.platform.LocalWindowInfo
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.currentStateAsState
import kotlinx.coroutines.isActive
/** A game's loop runs only in play, while the game is going, and while the Arcade is on screen with the remote's focus. */
internal fun loopRuns(paused: Boolean, alive: Boolean, shown: Boolean) = !paused && alive && shown
/** The Arcade is on screen (the app is resumed) and its window has the remote (no reminder or dialog on top). */
@Composable
internal fun rememberArcadeShown(): Boolean {
val focused = LocalWindowInfo.current.isWindowFocused
val state by LocalLifecycleOwner.current.lifecycle.currentStateAsState()
return focused && state.isAtLeast(Lifecycle.State.RESUMED)
}
/** Pauses a running game when the Arcade goes out of sight or loses the remote, so nobody loses a game to a pop-up. */
@Composable
internal fun PauseWhenHidden(alive: Boolean, pause: () -> Unit) {
val shown = rememberArcadeShown()
val latest by rememberUpdatedState(pause)
LaunchedEffect(shown) { if (!shown && alive) latest() }
}
/**
* The shared frame loop: [onFrame] gets each frame's time and the time since the previous one, from the second frame of
* each run (the first only sets the clock, so time spent paused or hidden never arrives as one big step). [onStart] runs
* each time the loop starts or starts again.
*/
@Composable
internal fun ArcadeGameLoop(running: Boolean, onStart: () -> Unit = {}, onFrame: (frameNanos: Long, dtNanos: Long) -> Unit) {
val shown = rememberArcadeShown()
val frame by rememberUpdatedState(onFrame)
val start by rememberUpdatedState(onStart)
val go = running && shown
LaunchedEffect(go) {
if (!go) return@LaunchedEffect
start()
var last = withFrameNanos { it }
while (isActive) {
withFrameNanos { now -> frame(now, now - last); last = now }
}
}
}