From 86769e500b15870eba6238bfa51bf023f33649d4 Mon Sep 17 00:00:00 2001 From: Pauljd Date: Mon, 9 Nov 2026 12:57:11 +0000 Subject: [PATCH] 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/.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 --- android/app/build.gradle.kts | 4 +- .../main/java/tv/orbit/classic/RoomSync.kt | 12 +- .../tv/orbit/classic/arcade/ArcadeHome.kt | 58 ++++++-- .../tv/orbit/classic/arcade/ArcadePages.kt | 61 +++++--- .../tv/orbit/classic/arcade/ArcadeRepo.kt | 11 ++ .../orbit/classic/arcade/ArcadeRoomScores.kt | 137 ++++++++++++++++++ .../classic/arcade/rush/OrbitRushScreen.kt | 36 ++++- .../tv/orbit/classic/arcade/rush/RushSim.kt | 9 +- .../tv/orbit/classic/arcade/RoomScoresTest.kt | 109 ++++++++++++++ .../orbit/classic/arcade/TitleTextFitsTest.kt | 16 ++ .../orbit/classic/arcade/rush/RushSimTest.kt | 12 ++ docs/house-scores.md | 57 ++++++++ 12 files changed, 480 insertions(+), 42 deletions(-) create mode 100644 android/app/src/main/java/tv/orbit/classic/arcade/ArcadeRoomScores.kt create mode 100644 android/app/src/test/java/tv/orbit/classic/arcade/RoomScoresTest.kt create mode 100644 docs/house-scores.md diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 7082f91d..041e6400 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -9,8 +9,8 @@ android { applicationId = "tv.orbit.classic" minSdk = 26 targetSdk = 36 - versionCode = 311 - versionName = "0.120.0-sound-kit" + versionCode = 312 + versionName = "0.121.0-house-scores" } buildFeatures { compose = true } // The finished build for the TVs (Paul, 6 November 2026: the test build stuttered on the box). Not debuggable, so diff --git a/android/app/src/main/java/tv/orbit/classic/RoomSync.kt b/android/app/src/main/java/tv/orbit/classic/RoomSync.kt index 0df9e791..d4e259f9 100644 --- a/android/app/src/main/java/tv/orbit/classic/RoomSync.kt +++ b/android/app/src/main/java/tv/orbit/classic/RoomSync.kt @@ -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 diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeHome.kt b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeHome.kt index 971cce22..b3b3dbf9 100644 --- a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeHome.kt +++ b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeHome.kt @@ -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(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, 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, 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, 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 + 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 diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadePages.kt b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadePages.kt index 509489c0..cb31d1f0 100644 --- a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadePages.kt +++ b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadePages.kt @@ -38,22 +38,24 @@ private fun PageTitle(title: String, line: String) { // ---------- High Scores (frame 04) ---------- @Composable -internal fun HighScoresPage(profile: Profile, visible: List, data: ArcadeProfileData, household: Map) { +internal fun HighScoresPage(profile: Profile, visible: List, data: ArcadeProfileData, household: Map, + house: List> = listOf(profile to data)) { var topTen by remember { mutableStateOf(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()) } 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, 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, 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>, me: String, table: ScoreTable): List = 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 { 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 diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeRepo.kt b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeRepo.kt index 60141441..a6f24d33 100644 --- a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeRepo.kt +++ b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeRepo.kt @@ -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): List = 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) diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeRoomScores.kt b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeRoomScores.kt new file mode 100644 index 00000000..aba80d25 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeRoomScores.kt @@ -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/.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 = 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> + +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, b: List, kind: ScoreKind?): List { + 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): 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): 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() + 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 { + 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++ + } +} diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/rush/OrbitRushScreen.kt b/android/app/src/main/java/tv/orbit/classic/arcade/rush/OrbitRushScreen.kt index 4e5a7884..cb1db2a9 100644 --- a/android/app/src/main/java/tv/orbit/classic/arcade/rush/OrbitRushScreen.kt +++ b/android/app/src/main/java/tv/orbit/classic/arcade/rush/OrbitRushScreen.kt @@ -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)) diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/rush/RushSim.kt b/android/app/src/main/java/tv/orbit/classic/arcade/rush/RushSim.kt index 92bcb2a2..0fd7a948 100644 --- a/android/app/src/main/java/tv/orbit/classic/arcade/rush/RushSim.kt +++ b/android/app/src/main/java/tv/orbit/classic/arcade/rush/RushSim.kt @@ -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 } } diff --git a/android/app/src/test/java/tv/orbit/classic/arcade/RoomScoresTest.kt b/android/app/src/test/java/tv/orbit/classic/arcade/RoomScoresTest.kt new file mode 100644 index 00000000..c1f53c04 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/arcade/RoomScoresTest.kt @@ -0,0 +1,109 @@ +package tv.orbit.classic.arcade + +import org.json.JSONObject +import org.junit.Assert.* +import org.junit.Test +import tv.orbit.classic.Profile +import tv.orbit.classic.ProfileKind +import java.io.File +import java.nio.file.Files + +/** High Scores across the rooms: scores stay on the person who set them, merging only adds, and no save is written by a sync. */ +class RoomScoresTest { + private fun run(score: Int, at: Long, detail: String? = null) = ArcadeRun(score, at, detail) + private fun data(id: String, vararg games: Pair) = ArcadeProfileData(id, games.toMap()) + private fun wire(vararg people: ArcadeProfileData) = ArcadeRoomScores.decode(JSONObject(ArcadeRoomScores.outgoing(people.toList()).toString())) + + @Test fun aRoomSendsOnlyScoresAndTheyComeBackTheSame() { + val paul = data("grown", "OrbiRaiders" to GameRecord(listOf(run(5_000, 10, "Wave 7")), level = mapOf("story.Normal" to "10"), settings = mapOf("sounds" to true))) + val amelia = data("kids", "Pairs" to GameRecord(listOf(run(18, 20)), count = 0), "Patience" to GameRecord(count = 3)) + val heard = wire(paul, amelia) + assertEquals(listOf(run(5_000, 10, "Wave 7")), heard["grown"]!!["OrbiRaiders"]!!.runs) + assertEquals(3, heard["kids"]!!["Patience"]!!.count) + // Nothing but runs and counts goes: no level progress, no settings. + val text = ArcadeRoomScores.outgoing(listOf(paul)).toString() + assertFalse(text.contains("story") || text.contains("sounds")) + // Someone with nothing to show isn't sent. + assertTrue(wire(data("phveypj")).isEmpty()) + } + + @Test fun mergingOnlyEverAdds() { + val first = wire(data("kids", "Blocks" to GameRecord(listOf(run(900, 1), run(400, 2))), "Patience" to GameRecord(count = 4))) + // The other room later sends less (say its high scores were cleared): what was heard is kept. + val later = wire(data("kids", "Blocks" to GameRecord(listOf(run(300, 3))), "Patience" to GameRecord(count = 1))) + val kept = ArcadeRoomScores.merge(ArcadeRoomScores.merge(emptyMap(), first), later) + assertEquals(listOf(900, 400, 300), kept["kids"]!!["Blocks"]!!.runs.map { it.score }) + assertEquals(4, kept["kids"]!!["Patience"]!!.count) + // Hearing the same again changes nothing: the same run is counted once. + assertEquals(kept, ArcadeRoomScores.merge(kept, first)) + // Never more than the top ten kept. + val many = wire(data("kids", "Blocks" to GameRecord((1..15).map { run(it * 10, it.toLong()) }))) + assertEquals(TOP_RUNS, ArcadeRoomScores.merge(kept, many)["kids"]!!["Blocks"]!!.runs.size) + } + + @Test fun aPersonsScoresFromEveryRoomShowAsTheirs() { + val here = data("kids", "Blocks" to GameRecord(listOf(run(500, 5)), lastPlayedMs = 5), "Patience" to GameRecord(listOf(run(120, 6)), count = 2)) + val upstairs = wire(data("kids", "Blocks" to GameRecord(listOf(run(800, 7))), "Patience" to GameRecord(listOf(run(110, 8)), count = 3), "Snake" to GameRecord(listOf(run(40, 9)))), + data("grown", "OrbiRaiders" to GameRecord(listOf(run(9_999, 1))))) + val shown = ArcadeRoomScores.combined(here, listOf(upstairs)) + assertEquals(800, bestOf(shown.game("Blocks"), ScoreKind.Points)) + assertEquals(5, shown.game("Patience").count) // two won here, three upstairs + assertEquals(40, bestOf(shown.game("Snake"), ScoreKind.Points)) + // Paul's Orbi-Raiders stays Paul's: none of it shows on Amelia. + assertEquals(0, bestOf(shown.game("OrbiRaiders"), ScoreKind.Points)) + // What only lives here is left as it is. + assertEquals(5L, shown.game("Blocks").lastPlayedMs) + // No other rooms: the same object back. + assertSame(here, ArcadeRoomScores.combined(here, emptyList())) + } + + @Test fun anythingOddSentIsLeftOutNotFailed() { + val o = JSONObject("""{"kids":{"Blocks":{"runs":[{"score":5,"at":1},{"nope":1},"x"],"count":-4},"Bad":"x"},"../../etc":{"Snake":{"runs":[]}},"x":"y"}""") + val d = ArcadeRoomScores.decode(o) + assertEquals(listOf(run(5, 1)), d["kids"]!!["Blocks"]!!.runs) + assertEquals(0, d["kids"]!!["Blocks"]!!.count) + assertTrue(d.keys.all { k -> k.all { it.isLetterOrDigit() || it == '-' || it == '_' } }) + assertTrue(ArcadeRoomScores.decode(null).isEmpty()) + } + + @Test fun aSyncWritesOnlyItsOwnCopyNeverASave() { + val dir = Files.createTempDirectory("arcade").toFile() + val store = ArcadeStore(dir) + store.update("kids") { recordRun(it, "Blocks", ScoreKind.Points, RunEnd(500, true), 5) } + val save = File(dir, "kids.json").readBytes() + val copies = RoomScoreCopies(dir) + val v = copies.version + copies.heard("6734abcd", wire(data("kids", "Blocks" to GameRecord(listOf(run(800, 7)))))) + assertArrayEquals(save, File(dir, "kids.json").readBytes()) + assertTrue(File(dir, "rooms/6734abcd.json").isFile) + assertEquals(v + 1, copies.version) + // The same again: no change, no write. + copies.heard("6734abcd", wire(data("kids", "Blocks" to GameRecord(listOf(run(800, 7)))))) + assertEquals(v + 1, copies.version) + // A fresh start reads the copy back. + assertEquals(800, bestOf(ArcadeRoomScores.combined(store.load("kids"), RoomScoreCopies(dir).all()).game("Blocks"), ScoreKind.Points)) + dir.deleteRecursively() + } + + @Test fun theHouseBoardNamesWhoAndCountsWinsPerPerson() { + val paul = Profile("grown", "Paul", "", ProfileKind.Grown); val amelia = Profile("kids", "Amelia", "", ProfileKind.Kids) + val house = listOf(paul to data("grown", "Blocks" to GameRecord(listOf(run(700, 1), run(300, 2))), "Patience" to GameRecord(count = 2, lastPlayedMs = 3)), + amelia to data("kids", "Blocks" to GameRecord(listOf(run(900, 4))), "Patience" to GameRecord(count = 5, lastPlayedMs = 6))) + val blocks = houseTop(house, "grown", ScoreTable("Blocks", "Classic", ScoreKind.Points)) + assertEquals(listOf("Amelia" to 900, "Paul" to 700, "Paul" to 300), blocks.map { it.who to it.run.score }) + assertEquals(listOf(false, true, true), blocks.map { it.mine }) + val wins = houseTop(house, "grown", ScoreTable("Patience", "Classic", ScoreKind.Wins)) + assertEquals(listOf("Amelia" to 5, "Paul" to 2), wins.map { it.who to it.run.score }) + assertTrue(wins.all { it.counted }) + } + + @Test fun theOriginalsRowScrollsSoTheCardShowsWholeWithAPeek() { + val c = 1000f; val size = 200f; val peek = 80f + assertEquals(0f, peekScroll(300f, size, c, peek), 0f) // already well in view + assertEquals(100f, peekScroll(820f, size, c, peek), 0f) // off the right: in, with the next one peeking + assertEquals(-130f, peekScroll(-50f, size, c, peek), 0f) // off the left + assertEquals(30f, peekScroll(750f, size, c, peek), 0f) // whole, but no room for the peek yet + // A card wider than the room left for peeks still lands whole. + assertEquals(0f, peekScroll(100f, 800f, c, peek), 0f) + } +} diff --git a/android/app/src/test/java/tv/orbit/classic/arcade/TitleTextFitsTest.kt b/android/app/src/test/java/tv/orbit/classic/arcade/TitleTextFitsTest.kt index 7ff5d0df..969a17f9 100644 --- a/android/app/src/test/java/tv/orbit/classic/arcade/TitleTextFitsTest.kt +++ b/android/app/src/test/java/tv/orbit/classic/arcade/TitleTextFitsTest.kt @@ -105,6 +105,22 @@ class TitleTextFitsTest { } } + @Test fun theOriginalsRowNeverClipsAndEveryTitleFits() { + // The Arcade home on a TV is 960 by 540 dp at 720p and 1080p alike: 64 dp of margins, the 150 dp menu and a 10 dp gap + // leave the shelves 736 dp. Ten Originals scroll: 12 dp ends, 10 dp gaps, 4.6 cards across. + val shelf = 960.0 - 64 - 150 - 10 + val card = (shelf - 24 - 40) / 4.6 + // The focused card grows 4%: half of that each side must sit inside the 12 dp ends and the 8 dp above and below. + assertTrue(card * .02 <= 12); assertTrue((176 - 16) * .02 <= 8) + // At least four whole cards and a good part of the next always show. + assertTrue((shelf - 24 + 10) / (card + 10) in 4.4..4.8) + val anton = Font.createFont(Font.TRUETYPE_FONT, File("src/main/res/font/anton_regular.ttf")).deriveFont(17f * 1.3f) + for (g in ArcadeGames.originals) { + val name = g.title.uppercase() + assertTrue("$name: a word is too wide for ${"%.0f".format(card - 20)} dp", name.split(' ').all { width(anton, it) <= card - 20 }) + } + } + @Test fun nightShiftsWordsFit() { val anton = Font.createFont(Font.TRUETYPE_FONT, File("src/main/res/font/anton_regular.ttf")) // Each chapter card is a fifth of the row (896 dp less four 10 dp gaps), less 24 dp padding: every word of a name fits a line, at most two lines. diff --git a/android/app/src/test/java/tv/orbit/classic/arcade/rush/RushSimTest.kt b/android/app/src/test/java/tv/orbit/classic/arcade/rush/RushSimTest.kt index ac59156f..d7a2ca65 100644 --- a/android/app/src/test/java/tv/orbit/classic/arcade/rush/RushSimTest.kt +++ b/android/app/src/test/java/tv/orbit/classic/arcade/rush/RushSimTest.kt @@ -89,4 +89,16 @@ class RushSimTest { println("Orbit Rush: 10,000 ticks allocated $bytes bytes") assertTrue("allocated $bytes", bytes < 8 * 1024) } + + /** Paul: "harder to tell when you jump". The drawn height eases to fully up or down and back to level, so it can be seen. */ + @Test fun aRiseOrDiveShowsAndThenLevelsOut() { + val s = RushSim(seed = 3); s.newRun(tv.orbit.classic.arcade.Difficulty.Normal, 3) + s.rise(); repeat(12) { s.step() } + assertTrue("lift ${s.lift}", s.lift > .9f) + repeat(60) { s.step() } + assertEquals(0f, s.lift, 0f) + s.dive(); repeat(12) { s.step() } + assertTrue("lift ${s.lift}", s.lift < -.9f) + s.newRun(tv.orbit.classic.arcade.Difficulty.Normal, 4); assertEquals(0f, s.lift, 0f) + } } diff --git a/docs/house-scores.md b/docs/house-scores.md new file mode 100644 index 00000000..4ab30434 --- /dev/null +++ b/docs/house-scores.md @@ -0,0 +1,57 @@ +# 0.121.0 (versionCode 312): house High Scores, the Rush rise/dive, the Originals row + +Built on 0.120.0 (311, the sound kit). + +## 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… orbi raiders would stay on mine" + +- **Route.** Scores ride the existing Rooms sync, the one that carries Continue watching. It runs every 2 minutes while Orbit is open on both TVs, over the home Wi-Fi only, sealed with the pair's key (`RoomSync.state` / `merge`, key `"arcade"`). +- **What's sent.** Each person's own runs and games-won counts, read from their own Arcade file. Level progress, settings, checkpoints and the day's puzzle are not sent: game progress stays with the TV it was played on. +- **What's kept.** One read-only copy per paired room, in `filesDir/arcade/rooms/.json` (`RoomScoreCopies`). A sync never writes anyone's own save file, and `RoomScoresTest` checks that byte for byte. +- **Merging only adds.** + - Runs from each copy are put together, with the same run (score, time, detail) counted once, and the best 10 are kept. + - Counts only go up. + - If the other room clears a person's scores, what was already heard stays. +- **Shown.** A person's scores are their own here plus each other room's for them (`ArcadeRoomScores.combined`). This sets their best on the cards, the "best to beat" in a game, and the board. Games-won counts are added room by room, so a re-sync can't count anything twice. +- **The board.** " · the whole house, every room". + - Each row shows **Your best** and **House best · ** (shown as "You" when it's yours, in yellow). + - OK on a row opens the **house Top 10** with names. Counted games (Patience wins, Skydoku solves) rank people by their totals. + - Kids still see only their own games. Household Records stay read-only. +- **Mixed builds.** A TV on an older build ignores the new `"arcade"` key, so a mixed pair carries on syncing everything else. Each TV shows the other's scores once both run 312. No re-pairing is needed. + +## Orbit Rush: easier to tell when you jump + +Paul: "harder to tell when you jump". Up or down now reads four ways at once: + +1. **Shadow:** Blaze's shadow on the track is small and faint when he's risen, big and dark when he's dived. +2. **Size:** the rocket is bigger when risen and smaller when dived. +3. **Height:** he eases up or down (`RushSim.lift`) instead of jumping between heights. +4. **Marker:** an arrow in the colour of what the move gets him past (yellow ▲ over a low satellite, cyan ▼ under a gate), with a bar showing how long he stays there. + +Nothing flashes, and the marker and shadow work with Reduce motion too. The marker's shape is made once, not every frame. + +## The Originals row + +Paul: the row "could do with some work, cuts either end off or clips". + +- **Room to grow:** 12 dp at each end and 8 dp above and below, so the focused card's 4% grow and its border never touch an edge. +- **A peek of the next card:** with more than five Originals, cards are sized 4.6 across, so part of the next one always shows. +- **Scrolling:** focus scrolls the row with an eased 360 ms move (Compose, `peekIntoView` / `peekScroll`) so the chosen card sits whole with part of its neighbour beside it. With Reduce motion it's a plain jump, and the grow is off as before. +- **Sizes:** an Android TV lays out at 960 × 540 dp at both 720p and 1080p, so one size check covers both (`TitleTextFitsTest`). The Classics row has no grow, and its border sits inside each tile, so it doesn't clip. +- **EffectCraft:** I didn't use it. Compose's own easing was enough. + +## Checked + +- **Tests:** 1,095 run, 24 skipped, 0 failed. New: `RoomScoresTest` (7), a Rush rise and dive test, and a fit test for the Originals row. +- **Lint:** 88 warnings, none new. +- **APK:** `apks/orbit-tv-0.121.0-house-scores.apk`, sha256 `d8bf6f5a…eebe`. +- **Not yet seen on screen:** I've no emulator or screenshot tooling here, and no install was asked for. + +## What each TV needs + +- **Downstairs:** 311 → 312, using the usual routine. +- **Upstairs:** 293 → 312. That brings everything since 293 (the Classics family and modes, Night Shift, Orbiteroids, Quiz Night, Tangle, Codebreaker, Daily, Orbit Rush, the sound kit), using the same routine, with a snapshot and save checks. +- **After both:** within a couple of minutes of Orbit being open on both TVs, each person's scores show on the other TV.