0.121.0 (versionCode 312): house High Scores across the rooms, Orbit Rush rise/dive you can see, the Originals row

- Scores ride the Rooms sync beside Continue watching: each room sends its people's own runs and
  counts; what arrives is kept as a read-only copy per room (arcade/rooms/<link>.json), merged only
  by adding (same run once, best 10, counts only up). No save file is ever written by a sync.
- A person's scores from every room show as theirs: cards, the best to beat, and the board, now
  "the whole house": Your best and House best with a name, and a house Top 10 with names
- Orbit Rush: shadow, size, an eased height and a coloured up/down marker with a time bar
- Originals row: room at both ends and above and below, a peek of the next card, eased
  scroll that keeps the focused card whole (a jump with Reduce motion)
- Tests: RoomScoresTest, Rush lift, the row's fit; 1,095 pass

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-09 12:57:11 +00:00
co-authored by Claude Opus 5.5
parent 70d03836e0
commit 86769e500b
12 changed files with 480 additions and 42 deletions
@@ -13,7 +13,7 @@ import java.util.Base64
* Rooms sync (Paul, 7 November 2026): rooms that have paired keep each other's family up to date on their own. Pairing (Add a
* room, Bring in from another room) leaves both TVs with a shared key; after that, while Orbit is open on both, they exchange
* what's changed every couple of minutes over the home Wi-Fi only: profiles (and removals), the PIN's salted hash, Continue
* watching and Taste. Everything is sealed with the pair's key (AES-GCM), dated, and merged, never overwritten: the same person
* watching, Taste and (9 November 2026) each person's Arcade scores. Everything is sealed with the pair's key (AES-GCM), dated, and merged, never overwritten: the same person
* by id with the newest change winning, Taste events by id, the latest place in a programme. Channels and schedules stay each
* room's own, and each room keeps its own unlock.
*/
@@ -79,6 +79,8 @@ internal object RoomSync {
}
return JSONObject().put("v", 1).put("room", Rooms.name).put("at", nowMs).put("nonce", java.util.UUID.randomUUID().toString()).put("since", sinceMs)
.put("profiles", Profiles.encode(Profiles.all)).put("tombs", JSONObject(Profiles.tombstones)).put("lock", AfterDarkLock.shared(context)).put("files", files)
// High Scores across the rooms (9 November 2026): each person's own scores. A room on an older build ignores this.
.put("arcade", runCatching { tv.orbit.classic.arcade.ArcadeRoomScores.outgoing(tv.orbit.classic.arcade.ArcadeRepo.get(context).ownFromDisk(Profiles.all.map { it.id })) }.getOrNull() ?: JSONObject())
}
/** Opens and checks a sealed message: the pair's key, a fresh time, a nonce not seen before. Null when it fails any of them. */
@@ -91,7 +93,7 @@ internal object RoomSync {
}
/** Takes in what a paired room sent: profiles and removals, the PIN, Continue watching and Taste, each merged. */
fun merge(context: Context, scheduleDir: File, o: JSONObject, nowMs: Long) {
fun merge(context: Context, scheduleDir: File, o: JSONObject, nowMs: Long, link: String = "") {
val there = runCatching { Profiles.decode(o.getString("profiles")) }.getOrNull()
val thereTombs = o.optJSONObject("tombs")?.let { t -> t.keys().asSequence().associateWith { t.getLong(it) } }.orEmpty()
if (there != null) {
@@ -102,6 +104,8 @@ internal object RoomSync {
o.optJSONObject("lock")?.let { AfterDarkLock.takeShared(context, it) }
o.optJSONObject("files")?.let { files -> runCatching { mergeFamilyFiles(scheduleDir, files, nowMs) } }
ContinueWatching.load(scheduleDir, Profiles.current?.id)
// That room's people's scores, kept as its own read-only copy: only ever added to, never written over a save.
o.optJSONObject("arcade")?.let { a -> runCatching { tv.orbit.classic.arcade.ArcadeRepo.get(context).roomScores.heard(link, tv.orbit.classic.arcade.ArcadeRoomScores.decode(a)) } }
}
/** The answering TV's side of /room/sync: returns the status and reply. */
@@ -110,7 +114,7 @@ internal object RoomSync {
val link = RoomLinks.of(req.optString("link"))?.takeIf { it.on } ?: return 404 to JSONObject()
if (from != null && from in ownAddresses()) return 409 to JSONObject()
val o = open(link, req.optString("sealed"), nowMs) ?: return 403 to JSONObject()
merge(context, scheduleDir, o, nowMs)
merge(context, scheduleDir, o, nowMs, link.id)
val reply = state(context, scheduleDir, o.optLong("since"), nowMs)
RoomLinks.synced(link.id, nowMs, from)
android.util.Log.i("OrbitRooms", "sync answered link=${link.id.take(4)}")
@@ -133,7 +137,7 @@ internal object RoomSync {
.getOrNull() ?: continue
if (status != 200) continue
val o = runCatching { open(link, JSONObject(text).getString("sealed"), System.currentTimeMillis()) }.getOrNull() ?: continue
merge(context, scheduleDir, o, System.currentTimeMillis())
merge(context, scheduleDir, o, System.currentTimeMillis(), link.id)
RoomLinks.synced(link.id, nowMs, address)
android.util.Log.i("OrbitRooms", "sync done link=${link.id.take(4)}")
break
@@ -1,5 +1,9 @@
package tv.orbit.classic.arcade
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.foundation.gestures.LocalBringIntoViewSpec
import androidx.compose.foundation.gestures.BringIntoViewSpec
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
@@ -94,6 +98,9 @@ internal fun OrbitArcade(modifier: Modifier, onPlaying: (Boolean) -> Unit, onExi
var data by remember(profile.id) { mutableStateOf(repo.store.load(profile.id)) }
val latestData by rememberUpdatedState(data)
val household = remember { repo.household }
// What's shown and what's to beat: this person's own scores with the other rooms' added in (never saved back).
val rooms = repo.roomScores.version
val shown = remember(data, rooms) { repo.combined(data) }
val visible = remember(profile) { arcadeVisible(profile) }
var page by remember { mutableStateOf(ArcadePage.Play) }
var playing by remember { mutableStateOf<ArcadeGame?>(null) }
@@ -133,7 +140,7 @@ internal fun OrbitArcade(modifier: Modifier, onPlaying: (Boolean) -> Unit, onExi
else -> {
val audio = remember(game) { ArcadeAudio(context) { AudioPrefs.of(latestData.settings) } }
DisposableEffect(audio) { audio.preloadKit(); onDispose { audio.release() } }
val play = ArcadePlay(game.id, profile.id, bestOf(record, game.scoreKind), audio, record.level, record.levelsResetMs,
val play = ArcadePlay(game.id, profile.id, bestOf(shown.game(game.id), 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)) } } },
@@ -144,7 +151,7 @@ internal fun OrbitArcade(modifier: Modifier, onPlaying: (Boolean) -> Unit, onExi
onLeave = { session = SessionState.Exited; playing = null },
difficulty = difficultyFor(data, profile.kind), autoFire = autoFireFor(data), reduceFlashing = reduceFlashingFor(data),
kept = record.kept, writeKept = { values -> update { d -> d.withGame(game.id) { it.copy(kept = it.kept + values) } } },
bests = scoreTableDefs(game.id, game.scoreKind).associate { t -> t.id to bestOf(data.game(t.id), t.kind) },
bests = scoreTableDefs(game.id, game.scoreKind).associate { t -> t.id to bestOf(shown.game(t.id), t.kind) },
kids = profile.kind == ProfileKind.Kids, playable = tv.orbit.classic.arcade.daily.playableIds(visible),
openGame = { id -> ArcadeGames.byId(id)?.let { next -> session = SessionState.Exited; playing = null; launch(next) } })
key(game.id) { game.Content(play) }
@@ -192,8 +199,9 @@ internal fun OrbitArcade(modifier: Modifier, onPlaying: (Boolean) -> Unit, onExi
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.Play -> GameShelves(visible, shown, pick, firstCard, kids = profile.kind == ProfileKind.Kids, onChosen = { chosen = it }, onPlay = ::launch, onMenu = { settingsFor = it })
ArcadePage.HighScores -> HighScoresPage(profile, visible, shown, household,
remember(shown, rooms) { Profiles.all.map { p -> p to if (p.id == profile.id) shown else repo.combined(repo.store.load(p.id)) } })
ArcadePage.HowTo -> HowToPage(visible)
ArcadePage.Settings -> ArcadeSettingsPage(profile, data, onChange = { key, on -> update { it.copy(settings = it.settings + (key to on)) } },
onChoice = { key, value -> update { it.copy(choices = it.choices + (key to value)) } }, onReset = { page = ArcadePage.Reset })
@@ -201,7 +209,7 @@ internal fun OrbitArcade(modifier: Modifier, onPlaying: (Boolean) -> Unit, onExi
}
}
}
if (page == ArcadePage.Play) chosen?.let { InfoPanel(it, data.game(it.id), household, note.takeIf { _ -> !it.launchable }) }
if (page == ArcadePage.Play) chosen?.let { InfoPanel(it, shown.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 -> listOfNotNull(Control("▲▼", "Choose a game"), Control("◀▶", "BumbleHive Normal / Hard").takeIf { visible.any { it.id == ArcadeGames.Hive.id } },
@@ -261,6 +269,7 @@ private fun OllieSays(line: String) {
}
/** Orbit Originals on top, the Classics below; only the games this profile can see, none greyed out. */
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
private fun GameShelves(visible: List<ArcadeGame>, data: ArcadeProfileData, pick: ArcadeGame?, firstCard: FocusRequester, kids: Boolean,
onChosen: (ArcadeGame) -> Unit, onPlay: (ArcadeGame) -> Unit, onMenu: (ArcadeGame) -> Unit) {
@@ -271,10 +280,19 @@ private fun GameShelves(visible: List<ArcadeGame>, data: ArcadeProfileData, pick
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
// Five cards fill the row; more than five (Quiz Night and the new games after it) scroll along it, each card the same
// width, the remote's focus bringing the next one into view.
if (originals.isNotEmpty()) BoxWithConstraints(Modifier.fillMaxWidth().height(170.dp)) {
val card = (maxWidth - 8.dp * 4) / 5
Row(Modifier.fillMaxSize().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
originals.forEach { g -> OriginalCard(g, data.game(g.id), Modifier.width(card).fillMaxHeight().then(if (g == start) Modifier.focusRequester(firstCard) else Modifier), onChosen, onPlay, onMenu) }
// Paul, 9 November 2026: the row "cuts either end off or clips". Now: room at both ends and above and below, so the
// focused card's grow and border never touch an edge; cards a little narrower than a fifth, so the next one always
// peeks in; and the remote's focus scrolls the row smoothly so the chosen card sits fully in view with a part of its
// neighbour showing (none needed at either end).
if (originals.isNotEmpty()) BoxWithConstraints(Modifier.fillMaxWidth().height(176.dp)) {
val edge = 12.dp; val gap = 10.dp
val many = originals.size > 5
val card = if (many) (maxWidth - edge * 2 - gap * 4) / 4.6f else (maxWidth - edge * 2 - gap * 4) / 5
val peek = with(LocalDensity.current) { (gap + card * .35f).toPx() }
CompositionLocalProvider(LocalBringIntoViewSpec provides remember(peek) { peekIntoView(peek) }) {
Row(Modifier.fillMaxSize().horizontalScroll(rememberScrollState()).padding(horizontal = edge, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(gap)) {
originals.forEach { g -> OriginalCard(g, data.game(g.id), Modifier.width(card).fillMaxHeight().then(if (g == start) Modifier.focusRequester(firstCard) else Modifier), onChosen, onPlay, onMenu) }
}
}
}
if (classics.isNotEmpty()) {
@@ -291,6 +309,28 @@ private fun GameShelves(visible: List<ArcadeGame>, data: ArcadeProfileData, pick
}
}
/**
* Scrolling the Originals row to a focused card: far enough that the whole card shows with [peek] pixels of the next one
* beside it, eased (Compose's own smooth scroll; a plain jump with Reduce motion). At either end the row simply stops.
*/
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
internal fun peekIntoView(peek: Float): BringIntoViewSpec = object : BringIntoViewSpec {
@Suppress("DEPRECATION", "OVERRIDE_DEPRECATION")
override val scrollAnimationSpec: androidx.compose.animation.core.AnimationSpec<Float>
get() = if (Motion.reduce) androidx.compose.animation.core.snap() else androidx.compose.animation.core.tween(360, easing = androidx.compose.animation.core.FastOutSlowInEasing)
override fun calculateScrollDistance(offset: Float, size: Float, containerSize: Float): Float = peekScroll(offset, size, containerSize, peek)
}
/** How far to scroll so an item from [offset] to [offset] + [size] shows whole with [peek] either side (0 when it already does). */
internal fun peekScroll(offset: Float, size: Float, containerSize: Float, peek: Float): Float {
val room = ((containerSize - size) / 2f).coerceAtLeast(0f).let { minOf(peek, it) }
return when {
offset < room -> offset - room
offset + size > containerSize - room -> offset + size - (containerSize - room)
else -> 0f
}
}
/** OK plays, Menu opens the game's own settings. */
private fun Modifier.gameKeys(game: ArcadeGame, onMenu: (ArcadeGame) -> Unit) = onPreviewKeyEvent { e ->
val n = e.nativeKeyEvent
@@ -38,22 +38,24 @@ private fun PageTitle(title: String, line: String) {
// ---------- High Scores (frame 04) ----------
@Composable
internal fun HighScoresPage(profile: Profile, visible: List<ArcadeGame>, data: ArcadeProfileData, household: Map<String, HouseholdRecord>) {
internal fun HighScoresPage(profile: Profile, visible: List<ArcadeGame>, data: ArcadeProfileData, household: Map<String, HouseholdRecord>,
house: List<Pair<Profile, ArcadeProfileData>> = listOf(profile to data)) {
var topTen by remember { mutableStateOf<ArcadeGame?>(null) }
// A game with modes (BumbleHive Hard, Star Chase Signal Run…) shows one table at a time, switched with ◀▶ on its row.
var tableIx by remember { mutableStateOf(emptyMap<String, Int>()) }
val now = remember { System.currentTimeMillis() }
PageTitle("HIGH SCORES", "${profile.name}, on this TV")
// The house board (Paul, 9 November 2026): everyone's scores, from every room, each kept on their own profile.
PageTitle("HIGH SCORES", "${profile.name} · the whole house, every room")
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) }
listOf("Your best" to 90, "House best" to 128, "Played" to 64).forEach { (t, w) -> Text(t, Modifier.width(w.dp), color = ArcadeColours.Muted, fontSize = 12.sp, maxLines = 1) }
}
visible.forEach { g ->
val defs = scoreTableDefs(g.id, g.scoreKind)
val ix = tableIx[g.id] ?: 0
ScoreRow(g, defs[ix], data.game(defs[ix].id), now, tableLabel = scoreTableLabel(g, ix), highlighted = ix > 0,
ScoreRow(g, defs[ix], data.game(defs[ix].id), now, houseTop(house, profile.id, defs[ix]).firstOrNull(), tableLabel = scoreTableLabel(g, ix), highlighted = ix > 0,
onSide = if (defs.size > 1) { side -> tableIx = tableIx + (g.id to Math.floorMod(ix + side, defs.size)) } else null) { topTen = g }
}
}
@@ -63,7 +65,7 @@ internal fun HighScoresPage(profile: Profile, visible: List<ArcadeGame>, data: A
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 -> val ix = tableIx[g.id] ?: 0; val def = scoreTableDefs(g.id, g.scoreKind)[ix]; TopTen(g, def, data.game(def.id), now, title = scoreTableTitle(g, ix), onClose = { topTen = null }) }
topTen?.let { g -> val ix = tableIx[g.id] ?: 0; val def = scoreTableDefs(g.id, g.scoreKind)[ix]; TopTen(g, def, houseTop(house, profile.id, def), now, title = scoreTableTitle(g, ix), onClose = { topTen = null }) }
}
/** Which High Scores table a game's row shows: its [ix]th (0 is the game's own). */
@@ -89,7 +91,7 @@ internal fun scoreTableTitle(game: ArcadeGame, hard: Boolean): String = scoreTab
private val rowHeight = 22.dp
@Composable
private fun ScoreRow(game: ArcadeGame, table: ScoreTable, record: GameRecord, now: Long, tableLabel: String? = null, highlighted: Boolean = false, onSide: ((Int) -> Unit)? = null, onOpen: () -> Unit) {
private fun ScoreRow(game: ArcadeGame, table: ScoreTable, record: GameRecord, now: Long, houseBest: HouseRun?, tableLabel: String? = null, highlighted: Boolean = false, onSide: ((Int) -> Unit)? = null, onOpen: () -> Unit) {
var focused by remember { mutableStateOf(false) }
val corner = RoundedCornerShape(6.dp)
val runs = rankRuns(record.runs, table.kind)
@@ -110,35 +112,33 @@ private fun ScoreRow(game: ArcadeGame, table: ScoreTable, record: GameRecord, no
Spacer(Modifier.weight(1f))
}
val best = bestOf(record, table.kind).takeIf { it > 0 }?.let(table.format)
if (best == null) Text(if (game.launchable) "Not played yet" else "Coming soon", Modifier.width(282.dp), color = ArcadeColours.Muted, fontSize = 12.sp)
val house = houseBest?.let { "${houseScore(table, it)} · ${if (it.mine) "You" else it.who}" }
if (best == null && house == 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 = table.kind == ScoreKind.Points || table.kind == ScoreKind.FewestMoves
Text(if (ranked) runs.getOrNull(1)?.let { table.format(it.score) }.orEmpty() else "", Modifier.width(64.dp), color = ArcadeColours.Muted, fontSize = 12.sp, maxLines = 1)
Text(if (ranked) runs.getOrNull(2)?.let { table.format(it.score) }.orEmpty() else "", Modifier.width(64.dp), color = ArcadeColours.Muted, fontSize = 12.sp, maxLines = 1)
Text(best ?: "—", Modifier.width(90.dp), color = if (best == null) ArcadeColours.Muted else ArcadeColours.Ink, fontSize = 13.sp, fontWeight = FontWeight.Bold, maxLines = 1)
Text(house.orEmpty(), Modifier.width(128.dp), color = if (houseBest?.mine == true) ArcadeColours.Yellow else ArcadeColours.Muted, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(playedLabel(record.lastPlayedMs, now), Modifier.width(64.dp), color = ArcadeColours.Muted, fontSize = 12.sp, maxLines = 1)
}
}
}
@Composable
private fun TopTen(game: ArcadeGame, table: ScoreTable, record: GameRecord, now: Long, title: String = "${game.title.uppercase()} · TOP 10", onClose: () -> Unit) {
private fun TopTen(game: ArcadeGame, table: ScoreTable, entries: List<HouseRun>, now: Long, title: String = "${game.title.uppercase()} · TOP 10", 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),
Column(Modifier.width(360.dp).background(ArcadeColours.PanelDeep, RoundedCornerShape(12.dp)).border(1.dp, ArcadeColours.Line, RoundedCornerShape(12.dp)).padding(16.dp),
verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(title, color = ArcadeColours.Ink, fontFamily = Anton, fontSize = 22.sp)
if (table.kind == ScoreKind.Wins || table.kind == ScoreKind.Solved) Text(formatScore(table.kind, record.count) + " in all", color = ArcadeColours.Yellow, fontSize = 14.sp, fontWeight = FontWeight.SemiBold)
val runs = rankRuns(record.runs, table.kind)
if (runs.isEmpty()) Text("Nothing saved yet.", color = ArcadeColours.Muted, fontSize = 13.sp)
runs.forEachIndexed { i, r ->
Row(Modifier.fillMaxWidth()) {
Text("The whole house, every room", color = ArcadeColours.Muted, fontSize = 12.sp)
if (entries.isEmpty()) Text("Nothing saved yet.", color = ArcadeColours.Muted, fontSize = 13.sp)
entries.forEachIndexed { i, e ->
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text("${i + 1}.", Modifier.width(26.dp), color = ArcadeColours.Muted, fontSize = 13.sp)
Text(when { table.id != game.id -> table.format(r.score); table.kind == ScoreKind.Wins -> "${r.score} moves"; table.kind == ScoreKind.Solved -> "${r.score} hearts left"; else -> table.format(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)
Text(if (e.mine) "You" else e.who, Modifier.width(84.dp), color = if (e.mine) ArcadeColours.Yellow else ArcadeColours.Ink, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(houseScore(table, e, long = true), Modifier.weight(1f), color = ArcadeColours.Ink, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1)
Text(listOfNotNull(e.run.detail.takeIf { !e.counted }, playedLabel(e.run.atMs, now)).joinToString(" · "), color = ArcadeColours.Muted, fontSize = 12.sp, maxLines = 1)
}
}
ArcadeButton("Close", Modifier.fillMaxWidth().padding(top = 6.dp).focusRequester(close), icon = "←", onClick = onClose)
@@ -146,6 +146,25 @@ private fun TopTen(game: ArcadeGame, table: ScoreTable, record: GameRecord, now:
}
}
/** One line of the house board: whose, whether it's the one looking, and the run (or, for won and solved counts, their total). */
internal data class HouseRun(val who: String, val mine: Boolean, val run: ArcadeRun, val counted: Boolean = false)
/**
* A table's house Top 10: every person's runs from every room, best first. Games counted by wins or solves rank people by
* their total instead, one line each.
*/
internal fun houseTop(house: List<Pair<Profile, ArcadeProfileData>>, me: String, table: ScoreTable): List<HouseRun> = when (table.kind) {
ScoreKind.Points, ScoreKind.FewestMoves -> house.flatMap { (p, d) -> d.game(table.id).runs.map { HouseRun(p.name, p.id == me, it) } }
.let { all -> val ranked = rankRuns(all.map { it.run }.distinct(), table.kind); ranked.mapNotNull { r -> all.firstOrNull { it.run == r } } }
.let { top -> if (top.size < TOP_RUNS) top else top.take(TOP_RUNS) }
ScoreKind.Wins, ScoreKind.Solved -> house.mapNotNull { (p, d) -> d.game(table.id).takeIf { it.count > 0 }?.let { g -> HouseRun(p.name, p.id == me, ArcadeRun(g.count, g.lastPlayedMs), counted = true) } }
.sortedWith(compareByDescending<HouseRun> { it.run.score }.thenBy { it.who }).take(TOP_RUNS)
}
/** A house line's number, as the table shows its scores (for a count: "12 won"). */
internal fun houseScore(table: ScoreTable, e: HouseRun, long: Boolean = false): String =
if (e.counted) formatScore(table.kind, e.run.score) else table.format(e.run.score) + if (long && table.kind == ScoreKind.FewestMoves && table.format(e.run.score) == "${e.run.score}") " moves" else ""
// ---------- How to Play ----------
@Composable
@@ -20,6 +20,17 @@ internal class ArcadeRepo private constructor(context: Context) {
runCatching { HouseholdRecords.snapshotIfAbsent(dir, { key -> legacy.all[key] }, System.currentTimeMillis()) }.getOrDefault(emptyMap())
}
/** What each paired room has sent of its people's scores (High Scores across the rooms). Read-only copies. */
val roomScores = RoomScoreCopies(dir)
/** A person's scores to show and to beat: their own here with the other rooms' added in. Never saved back. */
fun combined(own: ArcadeProfileData): ArcadeProfileData = ArcadeRoomScores.combined(own, roomScores.all())
/** Each person's own saved scores, read from disk for the Rooms sync (off the main thread; the screens keep their own copy). */
fun ownFromDisk(profileIds: List<String>): List<ArcadeProfileData> = profileIds.mapNotNull { id ->
store.file(id).takeIf { it.isFile }?.let { f -> runCatching { decodeArcade(f.readText(), id) }.getOrNull() }
}
/** 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)
@@ -0,0 +1,137 @@
package tv.orbit.classic.arcade
import org.json.JSONArray
import org.json.JSONObject
import tv.orbit.classic.writeSafely
import java.io.File
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
/**
* High Scores across the rooms (Paul, 9 November 2026: "the score for each game is stored per person but the highscore
* board is across the multiroom… like catch up its per user, like amelias score for all the games should be on her
* account"). Scores ride the Rooms sync that already carries Continue watching: every couple of minutes, over the home
* Wi-Fi, sealed with the pair's key.
*
* The rules, so a save can never be lost:
* - A room sends only its own people's scores, from their own Arcade files: never what another room sent it.
* - What arrives is kept apart, one read-only copy per paired room (filesDir/arcade/rooms/<link>.json). Nobody's own save
* file is ever written by a sync.
* - Merging only adds: runs from both copies are put together (the same run, by its score, time and detail, counted once)
* and the best [TOP_RUNS] kept; a games-won count only goes up.
* - Shown, a person's scores are their own here plus each other room's for them: one best, one Top 10, counts added room
* by room (each room counts only its own games, so a re-sync can't count anything twice).
* Game progress (levels, checkpoints, the day's puzzle) is not synced: it stays with the TV it was played on.
*/
internal data class RoomEntry(val runs: List<ArcadeRun> = emptyList(), val count: Int = 0)
/** One paired room's scores as last heard: person (profile id) to table id to their runs and count. */
internal typealias RoomPeople = Map<String, Map<String, RoomEntry>>
private const val MAX_PEOPLE = 12
private const val MAX_TABLES = 120
/** The kind each table keeps, for ranking what arrives: every game's own table and each of its modes'. */
internal fun kindOfTable(tableId: String): ScoreKind? {
ArcadeGames.all.forEach { g -> if (g.id == tableId) return g.scoreKind; modeTables[g.id]?.firstOrNull { it.id == tableId }?.let { return it.kind } }
return null
}
private fun safeId(s: String) = s.filter { it.isLetterOrDigit() || it == '-' || it == '_' }.take(40)
/** Runs from two places put together: the same run (score, time, detail) once, best first, the top [TOP_RUNS]. */
internal fun unionRuns(a: List<ArcadeRun>, b: List<ArcadeRun>, kind: ScoreKind?): List<ArcadeRun> {
val all = (a + b).distinctBy { Triple(it.score, it.atMs, it.detail) }
return if (kind != null) rankRuns(all, kind) else all.sortedByDescending { it.atMs }.take(TOP_RUNS)
}
internal object ArcadeRoomScores {
/** What this room sends: each person's own scores (runs and counts only: no levels, settings or progress). */
fun outgoing(own: List<ArcadeProfileData>): JSONObject = JSONObject().also { o ->
own.take(MAX_PEOPLE).forEach { data ->
val tables = JSONObject()
data.games.forEach { (id, g) ->
if (g.runs.isEmpty() && g.count == 0) return@forEach
tables.put(id, JSONObject().put("count", g.count).put("runs", JSONArray(g.runs.take(TOP_RUNS).map { r ->
JSONObject().put("score", r.score).put("at", r.atMs).also { if (r.detail != null) it.put("detail", r.detail.take(60)) } })))
}
if (tables.length() > 0) o.put(safeId(data.profileId), tables)
}
}
/** Reads what a room sent, bounded and cleaned: anything odd is left out, never fails the rest. */
fun decode(o: JSONObject?): RoomPeople {
if (o == null) return emptyMap()
return o.keys().asSequence().take(MAX_PEOPLE).mapNotNull { pid ->
val tables = o.optJSONObject(pid) ?: return@mapNotNull null
val id = safeId(pid).takeIf { it.isNotEmpty() } ?: return@mapNotNull null
id to tables.keys().asSequence().take(MAX_TABLES).mapNotNull { tid ->
val t = tables.optJSONObject(tid) ?: return@mapNotNull null
val runs = t.optJSONArray("runs")?.let { a -> (0 until minOf(a.length(), TOP_RUNS)).mapNotNull { i ->
a.optJSONObject(i)?.takeIf { it.has("score") && it.has("at") }?.let { r -> ArcadeRun(r.optInt("score"), r.optLong("at"), r.optString("detail").take(60).takeIf { r.has("detail") }) } } }.orEmpty()
safeId(tid).takeIf { it.isNotEmpty() }?.let { it to RoomEntry(runs, t.optInt("count").coerceIn(0, 1_000_000)) }
}.toMap()
}.toMap()
}
fun encode(people: RoomPeople): JSONObject = JSONObject().also { o ->
people.forEach { (pid, tables) -> o.put(pid, JSONObject().also { t -> tables.forEach { (tid, e) ->
t.put(tid, JSONObject().put("count", e.count).put("runs", JSONArray(e.runs.map { r -> JSONObject().put("score", r.score).put("at", r.atMs).also { if (r.detail != null) it.put("detail", r.detail) } })))
} }) }
}
/** What's kept from a room after it sends again: only ever more (runs added, the best kept; counts only up). */
fun merge(kept: RoomPeople, heard: RoomPeople): RoomPeople =
(kept.keys + heard.keys).associateWith { pid ->
val a = kept[pid].orEmpty(); val b = heard[pid].orEmpty()
(a.keys + b.keys).associateWith { tid ->
val x = a[tid] ?: RoomEntry(); val y = b[tid] ?: RoomEntry()
RoomEntry(unionRuns(x.runs, y.runs, kindOfTable(tid)), maxOf(x.count, y.count))
}
}
/** One person's scores to show: their own here, with each other room's added in. Their own file isn't changed. */
fun combined(own: ArcadeProfileData, rooms: Collection<RoomPeople>): ArcadeProfileData {
val theirs = rooms.mapNotNull { it[safeId(own.profileId)] }
if (theirs.isEmpty()) return own
val ids = own.games.keys + theirs.flatMap { it.keys }
return own.copy(games = ids.associateWith { id ->
val g = own.game(id); val more = theirs.mapNotNull { it[id] }
g.copy(runs = more.fold(g.runs) { runs, e -> unionRuns(runs, e.runs, kindOfTable(id)) }, count = g.count + more.sumOf { it.count })
})
}
}
/** The copies kept from each paired room, on disk under filesDir/arcade/rooms and in memory for the screens. */
internal class RoomScoreCopies(private val dir: File) {
private val rooms = HashMap<String, RoomPeople>()
private var loaded = false
/** Goes up each time a copy changes, so the High Scores redraw (snapshot state: safe to change from the sync thread). */
var version by androidx.compose.runtime.mutableIntStateOf(0)
private set
private fun file(link: String) = File(dir, "rooms/${safeId(link).ifEmpty { "room" }}.json")
@Synchronized fun all(): Collection<RoomPeople> {
if (!loaded) {
loaded = true
File(dir, "rooms").listFiles { f -> f.name.endsWith(".json") }?.forEach { f ->
runCatching { rooms[f.name.removeSuffix(".json")] = ArcadeRoomScores.decode(JSONObject(f.readText())) }
}
}
return rooms.values.toList()
}
/** A room's scores arrived: merged into its copy (only adding) and written safely. */
@Synchronized fun heard(link: String, people: RoomPeople) {
if (people.isEmpty()) return
all()
val key = safeId(link).ifEmpty { "room" }
val next = ArcadeRoomScores.merge(rooms[key].orEmpty(), people)
if (next == rooms[key]) return
rooms[key] = next
val f = file(key); f.parentFile?.mkdirs()
writeSafely(f, ArcadeRoomScores.encode(next).toString())
version++
}
}
@@ -197,6 +197,9 @@ private fun scaleAt(z: Float) = 1f / (1f + 4f * (z / FAR))
private fun DrawScope.yAt(s: Float) = size.height * HORIZON + (size.height * .9f - size.height * HORIZON) * (s - .2f) / .8f
private fun DrawScope.xAt(laneX: Float, s: Float) = size.width / 2 + (laneX - 1f) * LANE_W * size.width * s
/** The up/down marker's shape, made once and reused each frame (drawing runs on the one UI thread). */
private val markerPath = androidx.compose.ui.graphics.Path()
private fun DrawScope.drawRush(art: OrbiteroidsArt, s: RushSim, calm: Boolean, steady: Boolean) {
val w = size.width; val h = size.height
// Dashes rushing past on the lane lines (still with Reduce motion).
@@ -230,12 +233,37 @@ private fun DrawScope.drawRush(art: OrbiteroidsArt, s: RushSim, calm: Boolean, s
RKind.SHIELD -> { drawCircle(RColours.Shield, u * .18f, Offset(x, y - u * .3f)); drawCircle(Color.White, u * .18f, Offset(x, y - u * .3f), style = Stroke(u * .03f)) }
}
}
// Blaze's rocket: low when diving, high when rising, tinted for a moment when hit.
// Blaze's rocket (Paul, 9 November 2026: "harder to tell when you jump"). Up or down reads four ways at once: his
// shadow on the track (small and faint when he's risen, big and dark when he's dived), the rocket itself (bigger as he
// comes up towards you, smaller down low), how high he sits, and a marker in the colour of what it gets him past:
// yellow ▲ over a low satellite, cyan ▼ under a gate, with a bar for how long he stays there. Nothing flashes, and with
// Reduce motion he still moves (the shadow and marker don't depend on it).
val bx = xAt(s.laneX, 1f)
val by = h * .82f + when (s.height) { RHeight.RISE -> -h * .12f; RHeight.DIVE -> h * .06f; else -> 0f }
val k = h / 260f
if (s.shieldFor > 0f) drawCircle(RColours.Shield.copy(alpha = .3f), 34f * k, Offset(bx, by))
scale(k, k, Offset(bx, by)) { with(art) { ship(bx, by, 0f, s.hurtFor > 0f, if (calm) 1f else kotlin.math.sin(s.clock * 30f)) } }
val lift = s.lift
val ground = h * .88f
val by = h * .82f + if (lift >= 0f) -h * .16f * lift else -h * .07f * lift
val shadowW = 30f * k * (1f - .45f * lift.coerceAtLeast(0f) + .15f * (-lift).coerceAtLeast(0f))
drawOval(Color.Black.copy(alpha = .45f - .25f * lift.coerceAtLeast(0f) + .1f * (-lift).coerceAtLeast(0f)), Offset(bx - shadowW, ground - shadowW * .28f), Size(shadowW * 2f, shadowW * .56f))
val shipScale = k * (1f + .3f * lift.coerceAtLeast(0f) - .22f * (-lift).coerceAtLeast(0f))
if (s.shieldFor > 0f) drawCircle(RColours.Shield.copy(alpha = .3f), 34f * shipScale, Offset(bx, by))
scale(shipScale, shipScale, Offset(bx, by)) { with(art) { ship(bx, by, 0f, s.hurtFor > 0f, if (calm) 1f else kotlin.math.sin(s.clock * 30f)) } }
if (s.height != RHeight.LEVEL && s.heightFor > 0f) {
val up = s.height == RHeight.RISE
val c = RColours.warn(if (up) RKind.LOW else RKind.TALL)
val my = if (up) by - 40f * shipScale else by + 34f * shipScale
val a = 13f * k
val arrow = markerPath.apply {
reset()
if (up) { moveTo(bx, my - a); lineTo(bx + a, my); lineTo(bx - a, my) } else { moveTo(bx, my + a); lineTo(bx + a, my); lineTo(bx - a, my) }
close()
}
drawPath(arrow, c)
val left = (s.heightFor / RushSim.MOVE_TIME).coerceIn(0f, 1f)
val barY = if (up) my + 4f * k else my - 7f * k
drawRect(c.copy(alpha = .3f), Offset(bx - 16f * k, barY), Size(32f * k, 3f * k))
drawRect(c, Offset(bx - 16f * k, barY), Size(32f * k * left, 3f * k))
}
// The static storm behind, closer as he's hit: a band of grey along the bottom (dots still with Reduce motion).
val band = h * (.06f + .14f * (1f - s.storm))
drawRect(Brush.verticalGradient(listOf(Color.Transparent, Color(0xFF8D95AE).copy(alpha = .55f)), h - band, h), Offset(0f, h - band), Size(w, band))
@@ -31,6 +31,8 @@ internal class RushSim(var difficulty: Difficulty = Difficulty.Normal, seed: Lon
/** The lane he's in or heading for (0 left, 1 middle, 2 right), and where he's drawn, sliding between lanes. */
var lane = 1; var laneX = 1f
var height = RHeight.LEVEL; var heightFor = 0f
/** Where he's drawn up or down: 1 risen, -1 dived, 0 level, easing between so the move can be seen. */
var lift = 0f
var hull = HULL; var hurtFor = 0f
/** Orbit Shield: held until OK, then on for a while. */
var shieldHeld = false; var shieldFor = 0f
@@ -50,7 +52,7 @@ internal class RushSim(var difficulty: Difficulty = Difficulty.Normal, seed: Lon
fun newRun(d: Difficulty, seed: Long) {
difficulty = d; rnd = java.util.Random(seed)
lane = 1; laneX = 1f; height = RHeight.LEVEL; heightFor = 0f; hull = HULL; hurtFor = 0f; shieldHeld = false; shieldFor = 0f
lane = 1; laneX = 1f; height = RHeight.LEVEL; heightFor = 0f; lift = 0f; hull = HULL; hurtFor = 0f; shieldHeld = false; shieldFor = 0f
on.fill(false); distance = 0f; speed = START_SPEED * pace; stars = 0; dodged = 0; over = false; clock = 0f; spawnIn = 1.2f; storm = 1f; events = 0
}
@@ -74,6 +76,9 @@ internal class RushSim(var difficulty: Difficulty = Difficulty.Normal, seed: Lon
laneX += (lane - laneX) * minOf(1f, LANE_SNAP * dt)
if (kotlin.math.abs(lane - laneX) < .01f) laneX = lane.toFloat()
if (heightFor > 0f) { heightFor -= dt; if (heightFor <= 0f) height = RHeight.LEVEL }
val target = when (height) { RHeight.RISE -> 1f; RHeight.DIVE -> -1f; else -> 0f }
lift += (target - lift) * minOf(1f, LIFT_SNAP * dt)
if (kotlin.math.abs(target - lift) < .01f) lift = target
if (hurtFor > 0f) hurtFor -= dt
if (shieldFor > 0f) shieldFor -= dt
storm = minOf(1f, storm + dt * .02f)
@@ -130,6 +135,6 @@ internal class RushSim(var difficulty: Difficulty = Difficulty.Normal, seed: Lon
companion object {
const val MAX = 48; const val HULL = 3
const val START_SPEED = 46f; const val MAX_SPEED = 95f
const val LANE_SNAP = 22f; const val MOVE_TIME = .7f; const val HURT_TIME = 1f; const val SHIELD_TIME = 6f
const val LANE_SNAP = 22f; const val MOVE_TIME = .7f; const val HURT_TIME = 1f; const val SHIELD_TIME = 6f; const val LIFT_SNAP = 16f
}
}