diff --git a/.gitignore b/.gitignore index d85c9d15..4bb40b93 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ android/local.properties android/**/build/ server/node_modules/ server/dist/ +android/.kotlin/ diff --git a/android/app/src/main/java/tv/orbit/classic/OrbitArcade.kt b/android/app/src/main/java/tv/orbit/classic/OrbitArcade.kt index cd5db17e..f9dc4c3b 100644 --- a/android/app/src/main/java/tv/orbit/classic/OrbitArcade.kt +++ b/android/app/src/main/java/tv/orbit/classic/OrbitArcade.kt @@ -36,17 +36,7 @@ import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp -import androidx.compose.ui.viewinterop.AndroidView -import android.webkit.ConsoleMessage -import android.webkit.JavascriptInterface -import android.webkit.WebChromeClient -import android.webkit.WebViewClient -import android.webkit.WebView import androidx.tv.material3.Text -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.LifecycleEventObserver -import androidx.lifecycle.compose.LocalLifecycleOwner -import tv.orbit.classic.arcade.ArcadeFlags import tv.orbit.classic.arcade.ArcadeGameLoop import tv.orbit.classic.arcade.ArcadePlay import tv.orbit.classic.arcade.PauseWhenHidden @@ -255,87 +245,3 @@ internal fun SnakeScreen(play: ArcadePlay) { } } } - -/** What BumbleHive's page reads at start: who's playing, Reduce motion, how loud it may be, and the save switch. */ -internal fun hiveConfig(play: ArcadePlay, reduceMotion: Boolean = Motion.reduce): String = org.json.JSONObject() - .put("profileId", play.profileId) - .put("reduceMotion", reduceMotion) - // The page's own sounds are multiplied by this: the profile's effects choice under Orbit's quiet ceiling. - .put("volume", play.audio.effects(1f).toDouble()) - .put("migrate", ArcadeFlags.hiveProfileSaves) - .put("levelsResetAt", play.levelsResetMs) - .toString() - -/** - * BumbleHive (once OrbitHive) runs as a small web page from inside the app, with no network, and handles the remote - * itself. Arcade Stage C adds a small bridge and changes none of its play: the page reads who's playing and their - * settings, tells the Arcade when a level starts, scores and ends (so its runs reach High Scores like every other game), - * and stops its timers and frame loop while Orbit is out of sight. - */ -@android.annotation.SuppressLint("SetJavaScriptEnabled", "JavascriptInterface") -@Composable -internal fun OrbitHiveScreen(play: ArcadePlay) { - var web by remember { mutableStateOf(null) } - val latest by rememberUpdatedState(play) - // No protected picture here, and leaving the window open to screenshots lets the game be checked on the box. - val activity = androidx.activity.compose.LocalActivity.current - DisposableEffect(Unit) { - activity?.window?.clearFlags(android.view.WindowManager.LayoutParams.FLAG_SECURE) - onDispose { activity?.window?.addFlags(android.view.WindowManager.LayoutParams.FLAG_SECURE) } - } - // The level in play, so it's still saved if the page goes away mid-level (the sleep timer, Orbit closing). - var liveScore by remember { mutableIntStateOf(0) } - var liveLevel by remember { mutableIntStateOf(0) } - val run = rememberRun(play.onRunEnd) { RunEnd(liveScore, finished = false, detail = "Level $liveLevel") } - val lifecycle = LocalLifecycleOwner.current.lifecycle - DisposableEffect(lifecycle, web) { - val view = web - val observer = LifecycleEventObserver { _, event -> - when (event) { - Lifecycle.Event.ON_PAUSE -> { view?.evaluateJavascript("window.orbitVisibility && window.orbitVisibility(false)", null); view?.onPause() } - Lifecycle.Event.ON_RESUME -> { - view?.onResume() - view?.evaluateJavascript("window.orbitConfig && window.orbitConfig(${org.json.JSONObject.quote(hiveConfig(latest))}); window.orbitVisibility && window.orbitVisibility(true)", null) - } - else -> {} - } - } - lifecycle.addObserver(observer) - onDispose { lifecycle.removeObserver(observer) } - } - BackHandler { web?.evaluateJavascript("window.orbitBack()", null) } - AndroidView(modifier = Modifier.fillMaxSize(), factory = { context -> - WebView(context).apply { - setBackgroundColor(android.graphics.Color.rgb(7, 22, 50)) - settings.javaScriptEnabled = true - settings.domStorageEnabled = true - settings.allowFileAccess = true - settings.mediaPlaybackRequiresUserGesture = false - // The page is the app's own and asks for nothing outside it. Its problems go to the log. - webChromeClient = object : WebChromeClient() { - override fun onConsoleMessage(message: ConsoleMessage): Boolean { - android.util.Log.i("OrbitHive", "${message.messageLevel()} ${message.message()} line ${message.lineNumber()}") - return true - } - } - webViewClient = object : WebViewClient() { - override fun onPageFinished(view: WebView, url: String) { android.util.Log.i("OrbitHive", "loaded size=${view.width}x${view.height}") } - override fun onReceivedError(view: WebView, request: android.webkit.WebResourceRequest, error: android.webkit.WebResourceError) { - android.util.Log.w("OrbitHive", "failed ${request.url.lastPathSegment}: ${error.description}") - } - } - isFocusable = true; isFocusableInTouchMode = true - // Called from the page's own thread, so each goes back to the main one. - addJavascriptInterface(object { - @JavascriptInterface fun leave() { post { latest.onLeave() } } - @JavascriptInterface fun config(): String = hiveConfig(latest) - @JavascriptInterface fun runStart(level: Int) { post { liveLevel = level; liveScore = 0; run.begin() } } - @JavascriptInterface fun runScore(score: Int) { post { liveScore = score } } - @JavascriptInterface fun runEnd(level: Int, score: Int, finished: Boolean) { post { liveScore = score; liveLevel = level; run.end(RunEnd(score, finished, "Level $level")) } } - }, "OrbitApp") - loadUrl("file:///android_asset/orbithive/index.html") - requestFocus() - web = this - } - }, onRelease = { it.destroy() }) -} diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeAudio.kt b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeAudio.kt index b5de2942..c44f9449 100644 --- a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeAudio.kt +++ b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeAudio.kt @@ -47,6 +47,7 @@ internal class ArcadeAudio(private val context: Context, private val prefs: () - private val settings = OrbitSettings(context) private var pool: SoundPool? = null private val sounds = HashMap() + private val fileSounds = HashMap() private var player: MediaPlayer? = null private var playerRes = 0 private var musicBase = .5f @@ -59,7 +60,7 @@ internal class ArcadeAudio(private val context: Context, private val prefs: () - private fun pool(): SoundPool? { if (released) return null return pool ?: runCatching { - SoundPool.Builder().setMaxStreams(3).setAudioAttributes(AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_GAME) + SoundPool.Builder().setMaxStreams(4).setAudioAttributes(AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_GAME) .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build()).build() }.getOrNull().also { pool = it } } @@ -76,6 +77,18 @@ internal class ArcadeAudio(private val context: Context, private val prefs: () - runCatching { p.play(id, level, level, 1, 0, 1f) } } + /** Loads sound files ahead (BumbleHive's tones, written once into the cache). */ + fun preloadFiles(vararg paths: String) { val p = pool() ?: return; paths.forEach { f -> if (f !in fileSounds) fileSounds[f] = p.load(f, 1) } } + + /** Plays a short sound file at [base] volume, under the ceiling, like [cue]. */ + fun cueFile(path: String, base: Float = .7f, gameOn: Boolean = true) { + val level = effects(base, gameOn) + if (level <= 0f) return + val p = pool() ?: return + val id = fileSounds[path] ?: p.load(path, 1).also { fileSounds[path] = it } + runCatching { p.play(id, level, level, 1, 0, 1f) } + } + /** Starts or pauses the one music track; [playing] is whether the game wants it now. */ fun music(raw: Int, playing: Boolean, base: Float = .5f, gameOn: Boolean = true) { if (released) return @@ -101,6 +114,6 @@ internal class ArcadeAudio(private val context: Context, private val prefs: () - released = true runCatching { player?.release() }; player = null runCatching { pool?.release() }; pool = null - sounds.clear() + sounds.clear(); fileSounds.clear() } } diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeFlags.kt b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeFlags.kt deleted file mode 100644 index 5280f10c..00000000 --- a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeFlags.kt +++ /dev/null @@ -1,13 +0,0 @@ -package tv.orbit.classic.arcade - -/** - * Switches for Arcade work that isn't turned on yet. Both are off in every build until Paul says otherwise. - */ -internal object ArcadeFlags { - /** - * BumbleHive saves per profile (orbithive-save-v1:), with the old box-wide save offered as a copy any - * profile can continue from. Off: BumbleHive keeps its one box-wide save exactly as before. The old save is only ever - * read by the profile-save path, never written or removed. See docs/arcade-stage-c.md, "BumbleHive saves". - */ - @Volatile var hiveProfileSaves = false -} diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeGames.kt b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeGames.kt index 074bf56a..e701e1b9 100644 --- a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeGames.kt +++ b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeGames.kt @@ -6,7 +6,6 @@ import tv.orbit.classic.BlockDropScreen import tv.orbit.classic.BrickBreakScreen import tv.orbit.classic.KidsArcade import tv.orbit.classic.OrbManScreen -import tv.orbit.classic.OrbitHiveScreen import tv.orbit.classic.PairsScreen import tv.orbit.classic.PatienceScreen import tv.orbit.classic.Profile @@ -80,7 +79,10 @@ internal object ArcadeGames { val Hive: ArcadeGame = GameDef("Hive", "BumbleHive", "Link, match, clear the hive", "Help Bumble fire flowers and clear the hive.", Mascot.Bumble, kidsSuitable = true, original = true, launchable = true, ScoreKind.Points, keepsLevels = true, legacyRecordKey = null, listOf(Control("◀▶", "Aim"), Control("OK", "Fire a flower"), Control("▼", "Swap flower"), Control("▲", "Honeybomb"), BackPause), - "Join three or more of a colour to clear them, before the hive reaches Bumble.") { OrbitHiveScreen(it) } + "Join three or more of a colour to clear them, before the hive reaches Bumble.", + listOf(GameSetting("sound", "Sound"), GameSetting("guide", "Guide line"), GameSetting("classicSkin", "Classic skin", default = false))) { + tv.orbit.classic.arcade.hive.BumbleHiveScreen(it) + } val NightShift: ArcadeGame = GameDef("NightShift", "Nite Owl's Night Shift", "Route the starlight", "Turn the beams and guide each lost star home.", Mascot.NiteOwl, kidsSuitable = true, original = true, launchable = false, ScoreKind.FewestMoves, keepsLevels = true, legacyRecordKey = null, listOf(Control("◀▶▲▼", "Hop"), Control("OK", "Turn a beam"), BackPause), "No timer and no fail: just Nite Owl's par.") 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 7c1849db..0d022ba5 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 @@ -134,7 +134,8 @@ internal fun OrbitArcade(modifier: Modifier, onPlaying: (Boolean) -> Unit, onExi writeLevel = { key, value -> update { d -> d.withGame(game.id) { it.copy(level = it.level + (key to value)) } } }, onRunEnd = { end -> update { recordRun(it, game.id, game.scoreKind, end, System.currentTimeMillis()) } }, onLeave = { session = SessionState.Exited; playing = null }, - difficulty = difficultyFor(data, profile.kind), autoFire = autoFireFor(data), reduceFlashing = reduceFlashingFor(data)) + 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) } } }) key(game.id) { game.Content(play) } return } 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 c7f795ea..bc6d1b1f 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 @@ -242,7 +242,7 @@ private fun DifficultyRow(chosen: Difficulty, onNext: () -> Unit) { /** What each action would clear, in plain words, or why it can't be used here. */ internal fun resetDetail(action: ResetAction, game: ArcadeGame, who: String, allowed: Boolean): String = when { action == ResetAction.RestartLevel -> if (allowed) "Starts this level again." else "From a game's pause menu, while you play." - !allowed && action == ResetAction.ResetLevelProgress -> if (game.id == ArcadeGames.Hive.id) "BumbleHive's levels are one save for the whole TV for now." else "${game.title} keeps no levels." + !allowed && action == ResetAction.ResetLevelProgress -> "${game.title} keeps no levels." action == ResetAction.ResetLevelProgress -> "$who's levels and unlocks for ${game.title} go back to the start." action == ResetAction.ClearHighScores -> "$who's top scores for this game go." else -> "$who's choices for ${game.title} go back to how they started." diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadePlay.kt b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadePlay.kt index ea95ca3f..09ff69d5 100644 --- a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadePlay.kt +++ b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadePlay.kt @@ -29,10 +29,15 @@ internal class ArcadePlay( val difficulty: Difficulty = Difficulty.Normal, val autoFire: Boolean = false, val reduceFlashing: Boolean = true, + /** What the game keeps through a level reset ([GameRecord.kept]), and where it writes it. */ + val kept: Map = emptyMap(), + private val writeKept: (Map) -> Unit = {}, ) { fun setting(key: String) = readSetting(key) fun setSetting(key: String, on: Boolean) = writeSetting(key, on) fun setLevel(key: String, value: String) = writeLevel(key, value) + /** Merges these into the kept values. */ + fun setKept(values: Map) = writeKept(values) } /** diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeSession.kt b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeSession.kt index d9dbd1ff..b77d8e20 100644 --- a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeSession.kt +++ b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeSession.kt @@ -106,13 +106,12 @@ internal fun reduceReset(state: ResetState, event: ResetEvent, allowed: (ResetAc * profile can never reach anyone else's. Restart level only means something inside a game, and level progress only where * a game keeps it. */ -internal fun resetAllowed(action: ResetAction, game: ArcadeGame, actorId: String, ownerId: String, inGame: Boolean, - hiveProfileSaves: Boolean = ArcadeFlags.hiveProfileSaves): Boolean { +internal fun resetAllowed(action: ResetAction, game: ArcadeGame, actorId: String, ownerId: String, inGame: Boolean): Boolean { if (actorId != ownerId) return false return when (action) { ResetAction.RestartLevel -> inGame - // BumbleHive's levels are one save for the whole TV until profile saves are switched on, and that is never reset. - ResetAction.ResetLevelProgress -> game.keepsLevels && (game.id != ArcadeGames.Hive.id || hiveProfileSaves) + // BumbleHive's levels are per profile since the native game (its Household save is never reset). + ResetAction.ResetLevelProgress -> game.keepsLevels ResetAction.ClearHighScores -> game.launchable ResetAction.ResetSettings -> game.launchable } diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeStore.kt b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeStore.kt index 253694d9..3cf31e8b 100644 --- a/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeStore.kt +++ b/android/app/src/main/java/tv/orbit/classic/arcade/ArcadeStore.kt @@ -39,6 +39,8 @@ internal data class GameRecord( val scoresResetMs: Long = 0, val levelsResetMs: Long = 0, val settingsResetMs: Long = 0, + /** What a game keeps through "Reset level progress" (BumbleHive: Honeybombs, the daily spin, Normal or Hard). */ + val kept: Map = emptyMap(), ) internal data class ArcadeProfileData( @@ -117,7 +119,8 @@ internal fun encodeArcade(data: ArcadeProfileData): String = JSONObject() .put("firstRunSeen", g.firstRunSeen) .put("howToEveryTime", g.howToEveryTime) .put("lastPlayed", g.lastPlayedMs) - .put("resets", JSONObject().put("scores", g.scoresResetMs).put("levels", g.levelsResetMs).put("settings", g.settingsResetMs))) + .put("resets", JSONObject().put("scores", g.scoresResetMs).put("levels", g.levelsResetMs).put("settings", g.settingsResetMs)) + .also { if (g.kept.isNotEmpty()) it.put("kept", JSONObject(g.kept as Map<*, *>)) }) } }).toString() @@ -137,7 +140,8 @@ internal fun decodeArcade(text: String, profileId: String): ArcadeProfileData? { id to GameRecord(runs, g.optInt("count").coerceAtLeast(0), g.optJSONObject("level")?.let { l -> l.keys().asSequence().mapNotNull { k -> (l.opt(k) as? String)?.let { k to it } }.toMap() }.orEmpty(), strings(g.optJSONArray("unlocks")).toSet(), bools(g.optJSONObject("settings")), g.optBoolean("firstRunSeen"), g.optBoolean("howToEveryTime"), - g.optLong("lastPlayed"), resets?.optLong("scores") ?: 0, resets?.optLong("levels") ?: 0, resets?.optLong("settings") ?: 0) + g.optLong("lastPlayed"), resets?.optLong("scores") ?: 0, resets?.optLong("levels") ?: 0, resets?.optLong("settings") ?: 0, + g.optJSONObject("kept")?.let { l -> l.keys().asSequence().mapNotNull { k -> (l.opt(k) as? String)?.let { k to it } }.toMap() }.orEmpty()) }.toMap() }.orEmpty() val choices = o.optJSONObject("choices")?.let { c -> c.keys().asSequence().mapNotNull { k -> (c.opt(k) as? String)?.let { k to it } }.toMap() }.orEmpty() diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/hive/BumbleHiveScreen.kt b/android/app/src/main/java/tv/orbit/classic/arcade/hive/BumbleHiveScreen.kt new file mode 100644 index 00000000..d901913b --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/arcade/hive/BumbleHiveScreen.kt @@ -0,0 +1,284 @@ +package tv.orbit.classic.arcade.hive + +import android.view.KeyEvent +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.focusable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.drawscope.drawIntoCanvas +import androidx.compose.ui.graphics.nativeCanvas +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.ui.viewinterop.AndroidView +import androidx.tv.material3.Text +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext +import tv.orbit.classic.Anton +import tv.orbit.classic.Motion +import tv.orbit.classic.arcade.ArcadeButton +import tv.orbit.classic.arcade.ArcadeColours +import tv.orbit.classic.arcade.ArcadeGameLoop +import tv.orbit.classic.arcade.ArcadeGames +import tv.orbit.classic.arcade.ArcadePauseMenu +import tv.orbit.classic.arcade.ArcadePlay +import tv.orbit.classic.arcade.ArcadeRepo +import tv.orbit.classic.arcade.Control +import tv.orbit.classic.arcade.KeyFooter +import tv.orbit.classic.arcade.PauseWhenHidden +import tv.orbit.classic.arcade.RunEnd +import tv.orbit.classic.arcade.rememberRun +import java.io.File +import java.util.concurrent.atomic.AtomicBoolean + +/** game.js ran at the screen's frame rate; the port runs its rules on a fixed 60 Hz step, at most five steps a frame. */ +internal class HiveClock { + private var acc = 0.0 + fun ticks(dtNanos: Long): Int { + acc += (dtNanos / 1e9).coerceIn(0.0, 0.1) + var n = 0 + while (acc >= STEP && n < MAX) { acc -= STEP; n++ } + if (n == MAX) acc = 0.0 + return n + } + fun reset() { acc = 0.0 } + companion object { const val STEP = 1.0 / 60; const val MAX = 5 } +} + +/** The remote as game.js read it: arrows, OK (and the pad's A and R2), Back, ▼/▲ also on the pad's X/Y, and Menu or play/pause to pause. */ +internal fun hiveKey(keyCode: Int): HiveKey? = when (keyCode) { + KeyEvent.KEYCODE_DPAD_LEFT -> HiveKey.Left + KeyEvent.KEYCODE_DPAD_RIGHT -> HiveKey.Right + KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_BUTTON_Y, KeyEvent.KEYCODE_B -> HiveKey.Up + KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_BUTTON_X, KeyEvent.KEYCODE_S -> HiveKey.Down + KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER, KeyEvent.KEYCODE_SPACE, KeyEvent.KEYCODE_BUTTON_A, KeyEvent.KEYCODE_BUTTON_R2 -> HiveKey.Ok + KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, KeyEvent.KEYCODE_MEDIA_PAUSE, KeyEvent.KEYCODE_MENU, KeyEvent.KEYCODE_BUTTON_START, KeyEvent.KEYCODE_P -> HiveKey.Pause + else -> null +} + +/** + * Writes the save through the Arcade (per profile, ArcadeStore), only what changed since the last write. Normal and Hard + * progress go in the game's level progress, Honeybombs, the daily spin, the mode and the Household answer in what a level + * reset keeps, and skin, guide line and sound in its settings. + */ +internal class HiveSaver(private val play: () -> ArcadePlay) { + private var normal: String? = null + private var hard: String? = null + private var kept: Map? = null + private val flags = HashMap() + + fun prime(save: HiveSaveData) { normal = save.normal.encode(); hard = save.hard.encode(); kept = keptOf(save); flags[HiveKeys.GUIDE] = save.guide; flags[HiveKeys.SOUND] = save.sound; flags[HiveKeys.CLASSIC] = !save.skinOrbit } + + fun write(save: HiveSaveData) { + val p = play() + save.normal.encode().let { if (it != normal) { normal = it; p.setLevel(HiveKeys.NORMAL, it) } } + save.hard.encode().let { if (it != hard) { hard = it; p.setLevel(HiveKeys.HARD, it) } } + keptOf(save).let { if (it != kept) { kept = it; p.setKept(it) } } + flag(p, HiveKeys.GUIDE, save.guide); flag(p, HiveKeys.SOUND, save.sound); flag(p, HiveKeys.CLASSIC, !save.skinOrbit) + } + + private fun flag(p: ArcadePlay, key: String, on: Boolean) { if (flags[key] != on) { flags[key] = on; p.setSetting(key, on) } } + + private fun keptOf(s: HiveSaveData) = buildMap { + put(HiveKeys.BOMBS, s.bombs.toString()); put(HiveKeys.LAST_SPIN, s.lastSpin); put(HiveKeys.MODE, s.mode.key) + s.household?.let { put(HiveKeys.HOUSEHOLD, it) } + } +} + +/** + * BumbleHive, native (8 November 2026), replacing the WebView game. Plays exactly as assets/orbithive/game.js did (Normal), + * or Hard; the Arcade's shared pause menu, How to Play and a result card in the Arcade's style; every level reported to + * High Scores; saves per profile. The first time it opens on a TV, the old WebView save is read once into a read-only + * Household save any profile can continue from as a copy ([HiveLegacy]). + */ +@Composable +internal fun BumbleHiveScreen(play: ArcadePlay) { + val game = ArcadeGames.Hive + val context = LocalContext.current + val latestPlay by rememberUpdatedState(play) + val dir = remember { ArcadeRepo.get(context).dir } + var snapshot by remember { mutableStateOf(HiveLegacy.load(dir)) } + var importing by remember { mutableStateOf(HiveLegacy.needsImport(dir)) } + + var liveLevel by remember { mutableIntStateOf(0) } + var liveScore by remember { mutableIntStateOf(0) } + var liveMode by remember { mutableStateOf(HiveMode.Normal) } + fun detail(level: Int, mode: HiveMode) = if (mode == HiveMode.Hard) "Level $level · Hard" else "Level $level" + val run = rememberRun(play.onRunEnd) { RunEnd(liveScore, finished = false, detail = detail(liveLevel, liveMode)) } + val tones = remember { arrayOfNulls(Sfx.COUNT) } + val save = remember { readHiveSave(play.level, play.kept, play::setting) } + val saver = remember { HiveSaver { latestPlay }.also { it.prime(save) } } + val simRef = remember { arrayOfNulls(1) } + val host = remember { + object : HiveHost { + override fun sound(id: Int) { val f = tones[id] ?: return; latestPlay.audio.cueFile(f, 1f, save.sound) } + override fun persist() = saver.write(save) + override fun runStart(level: Int) { liveLevel = level; liveScore = 0; liveMode = simRef[0]?.mode ?: HiveMode.Normal; run.begin() } + override fun runEnd(level: Int, score: Int, finished: Boolean) { liveScore = score; run.end(RunEnd(score, finished, detail(level, simRef[0]?.mode ?: HiveMode.Normal))) } + override fun leave() = latestPlay.onLeave() + } + } + val sim = remember { HiveSim(save, host, legacy = snapshot?.save).also { simRef[0] = it } } + sim.calm = Motion.reduce + var screen by remember { mutableStateOf(sim.screen) } + val tick = remember { mutableLongStateOf(0L) } + val clock = remember { HiveClock() } + val font = remember { runCatching { android.graphics.Typeface.createFromAsset(context.assets, "orbithive/barlow-semibold.ttf") }.getOrDefault(android.graphics.Typeface.DEFAULT_BOLD) } + val art = remember { HiveArt(font) } + DisposableEffect(Unit) { onDispose { art.release() } } + fun sync() { + // Paused however it happened (Back, Menu, the window losing the remote): every sound stops where it is. + if (sim.screen == HiveScreen.Pause && screen != HiveScreen.Pause) latestPlay.audio.pauseAll() + screen = sim.screen; liveScore = sim.score + } + + // The tones are written once into the cache, then loaded ahead of play. + LaunchedEffect(Unit) { + val files = withContext(Dispatchers.IO) { runCatching { HiveTones.files(File(context.cacheDir, "bumblehive-tones")) }.getOrNull() } + files?.forEachIndexed { i, f -> if (f.isFile) tones[i] = f.path } + latestPlay.audio.preloadFiles(*tones.filterNotNull().toTypedArray()) + } + + PauseWhenHidden(alive = screen == HiveScreen.Play) { sim.pause(); sync() } + ArcadeGameLoop(running = screen != HiveScreen.Pause, onStart = { clock.reset() }) { _, dt -> + val n = clock.ticks(dt) + for (i in 0 until n) sim.update(HiveClock.STEP) + tick.longValue++ + if (sim.screen != screen || sim.score != liveScore) sync() + } + + val focus = remember { FocusRequester() } + val overlay = screen == HiveScreen.Pause || screen == HiveScreen.Win || screen == HiveScreen.Lose + LaunchedEffect(overlay) { if (!overlay) runCatching { focus.requestFocus() } } + BackHandler(enabled = !overlay) { sim.action(HiveKey.Back); sync() } + + Box(Modifier.fillMaxSize().background(ArcadeColours.Night).focusRequester(focus).focusable().onPreviewKeyEvent { e -> + if (overlay) return@onPreviewKeyEvent false + val n = e.nativeKeyEvent + val k = hiveKey(n.keyCode) ?: return@onPreviewKeyEvent false + sim.key(k, n.action == KeyEvent.ACTION_DOWN, n.repeatCount > 0) + sync() + true + }) { + Canvas(Modifier.fillMaxSize()) { + tick.longValue // redraw every frame, without recomposing + drawIntoCanvas { art.draw(it.nativeCanvas, size.width.toInt(), size.height.toInt(), sim) } + } + when (screen) { + HiveScreen.Win, HiveScreen.Lose -> HiveResultCard(sim, onAct = { it(); sync() }) + else -> {} + } + } + if (screen == HiveScreen.Pause) { + val modeWord = if (sim.mode == HiveMode.Hard) " · Hard" else "" + ArcadePauseMenu(game, "BumbleHive · Level ${sim.level}$modeWord · ${"%,d".format(sim.score)}", + onResume = { sim.resume(); latestPlay.audio.resumeAll(); sync() }, + onRestart = { sim.replay(); latestPlay.audio.resumeAll(); sync() }, + onExit = { sim.closeRun(); latestPlay.onLeave() }, + sound = if (save.sound) "On" else "Off", onSound = { save.sound = !save.sound; saver.write(save); sync() }) + } + // The one-time read of the old WebView save, out of sight; the game plays meanwhile. + if (importing) HiveLegacyImport(dir) { snap -> + importing = false + if (snap != null) { + snapshot = snap + sim.legacy = snap.save + if (sim.screen == HiveScreen.Title) { sim.setScreen(HiveScreen.Title); sync() } + } + } +} + +/** The result card, in the Arcade's style: "Hive full!" with its stars, or "Swarmed!", and game.js's three choices. */ +@Composable +private fun HiveResultCard(sim: HiveSim, onAct: (() -> Unit) -> Unit) { + val first = remember { FocusRequester() } + LaunchedEffect(Unit) { runCatching { first.requestFocus() } } + BackHandler { onAct { sim.toLevels() } } + val won = sim.screen == HiveScreen.Win + Box(Modifier.fillMaxSize().background(ArcadeColours.Night.copy(alpha = .6f)), contentAlignment = Alignment.Center) { + Column(Modifier.width(420.dp).background(ArcadeColours.PanelDeep, RoundedCornerShape(14.dp)).border(1.dp, ArcadeColours.Line, RoundedCornerShape(14.dp)).padding(20.dp), + horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text("BUMBLEHIVE · LEVEL ${sim.level}${if (sim.mode == HiveMode.Hard) " · HARD" else ""}", color = ArcadeColours.Muted, fontSize = 13.sp, letterSpacing = 3.sp) + Text(if (won) "HIVE FULL!" else "SWARMED!", color = if (won) ArcadeColours.Yellow else androidx.compose.ui.graphics.Color(0xFFFF8A65), fontFamily = Anton, fontSize = 44.sp) + if (won) Text("★".repeat(sim.stars) + "☆".repeat(3 - sim.stars), color = ArcadeColours.Yellow, fontSize = 40.sp) + else Text("The flowers reached your bee.", color = ArcadeColours.Ink, fontSize = 15.sp) + Text("Score ${"%,d".format(sim.score)}", color = ArcadeColours.Ink, fontSize = 20.sp, fontWeight = FontWeight.SemiBold) + Spacer(Modifier.height(6.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + if (won) { + ArcadeButton("Next Level", Modifier.width(120.dp).focusRequester(first), icon = "▶", primary = true, height = 34.dp, onClick = { onAct { sim.nextLevel() } }) + ArcadeButton("Replay", Modifier.width(110.dp), icon = "↻", height = 34.dp, onClick = { onAct { sim.replay() } }) + ArcadeButton("Levels", Modifier.width(110.dp), height = 34.dp, onClick = { onAct { sim.toLevels() } }) + } else { + ArcadeButton("Try Again", Modifier.width(120.dp).focusRequester(first), icon = "↻", primary = true, height = 34.dp, onClick = { onAct { sim.replay() } }) + ArcadeButton("Levels", Modifier.width(110.dp), height = 34.dp, onClick = { onAct { sim.toLevels() } }) + ArcadeButton("Menu", Modifier.width(110.dp), height = 34.dp, onClick = { onAct { sim.toMenu() } }) + } + } + } + KeyFooter(listOf(Control("◀▶", "Choose"), Control("OK", "Select"), Control("Back", "Levels")), Modifier.align(Alignment.BottomStart).padding(start = 24.dp, end = 24.dp, bottom = 10.dp)) + } +} + +/** + * The old save's one read: a WebView with the old game's settings, out of sight (1 dp, see-through, never focused), + * loading the old game's own URL so its localStorage is the same. The game's scripts are swapped for empty ones on the + * way in, so nothing of the old game runs; [HiveLegacy.READ_SCRIPT] only reads. The WebView is destroyed as soon as it + * has answered, or after [HiveLegacy.TIMEOUT_MS]. It is the only WebView BumbleHive ever makes. + */ +@android.annotation.SuppressLint("SetJavaScriptEnabled") +@Composable +private fun HiveLegacyImport(dir: File, onDone: (HiveLegacy.Snapshot?) -> Unit) { + val done by rememberUpdatedState(onDone) + var reading by remember { mutableStateOf(false) } + var finished by remember { mutableStateOf(false) } + val answer = remember { arrayOfNulls<(String?) -> Unit>(1) } + val once = remember { AtomicBoolean(false) } + fun reply(raw: String?) { if (once.compareAndSet(false, true)) answer[0]?.invoke(raw) } + LaunchedEffect(Unit) { + HiveLegacy.importOnce(dir, System::currentTimeMillis, read = { cb -> answer[0] = cb; reading = true }) { snap -> finished = true; done(snap) } + } + LaunchedEffect(reading) { if (reading) { delay(HiveLegacy.TIMEOUT_MS); reply(null) } } + if (!reading || finished) return + AndroidView(modifier = Modifier.size(1.dp).alpha(0f), factory = { ctx -> + runCatching { + android.webkit.WebView(ctx).apply { + isFocusable = false; isFocusableInTouchMode = false + // The old game's settings, so the storage is found where it was. + settings.javaScriptEnabled = true + settings.domStorageEnabled = true + settings.allowFileAccess = true + webViewClient = object : android.webkit.WebViewClient() { + override fun shouldInterceptRequest(view: android.webkit.WebView, request: android.webkit.WebResourceRequest): android.webkit.WebResourceResponse? { + val path = request.url.toString() + return if (path.endsWith("/orbithive/game.js") || path.endsWith("/orbithive/hive-save.js")) + android.webkit.WebResourceResponse("text/javascript", "utf-8", java.io.ByteArrayInputStream(ByteArray(0))) else null + } + override fun onPageFinished(view: android.webkit.WebView, url: String) { + if (url == HiveLegacy.ORIGIN_URL) view.evaluateJavascript(HiveLegacy.READ_SCRIPT) { raw -> reply(raw) } + } + override fun onReceivedError(view: android.webkit.WebView, request: android.webkit.WebResourceRequest, error: android.webkit.WebResourceError) { + if (request.isForMainFrame) reply(null) + } + } + loadUrl(HiveLegacy.ORIGIN_URL) + } as android.view.View + }.getOrElse { + android.util.Log.w("BumbleHive", "no WebView for the save import: ${it.message}") + android.os.Handler(android.os.Looper.getMainLooper()).post { reply(null) } + android.view.View(ctx) + } + }, onRelease = { (it as? android.webkit.WebView)?.destroy() }) +} diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/hive/HiveArt.kt b/android/app/src/main/java/tv/orbit/classic/arcade/hive/HiveArt.kt new file mode 100644 index 00000000..1ed28fc0 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/arcade/hive/HiveArt.kt @@ -0,0 +1,608 @@ +package tv.orbit.classic.arcade.hive + +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.DashPathEffect +import android.graphics.LinearGradient +import android.graphics.Paint +import android.graphics.Path +import android.graphics.RadialGradient +import android.graphics.RectF +import android.graphics.Shader +import android.graphics.Typeface +import kotlin.math.PI +import kotlin.math.ceil +import kotlin.math.cos +import kotlin.math.max +import kotlin.math.min +import kotlin.math.round +import kotlin.math.sin + +private fun rgba(r: Int, g: Int, b: Int, a: Double) = android.graphics.Color.argb((a * 255).toInt().coerceIn(0, 255), r, g, b) +private fun hex(v: Long) = v.toInt() +private const val NAVY = 0xFF14213D.toInt() +private const val HONEY = 0xFFFFD84A.toInt() +private const val DEG = 180.0 / PI + +/** A number shown as text, rebuilt only when the number changes, so a steady frame makes no new strings. */ +private class Label(private val make: (Int) -> String) { + private var v = Int.MIN_VALUE + private var s = "" + operator fun get(value: Int): String { if (value != v) { v = value; s = make(value) }; return s } +} + +/** + * BumbleHive's drawing, game.js's render() moved to android.graphics on the Compose Canvas's native canvas, in the same + * 1280×720 units scaled to the screen. The flowers are six small bitmaps made once per screen size (as game.js pre-drew + * them); the honeycomb, hills, bee and button shapes are paths made once; gradients are made once (the lid's when it + * moves). Nothing is created on a steady frame. + */ +internal class HiveArt(private val font: Typeface) { + private val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL } + private val line = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE } + private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply { typeface = font; style = Paint.Style.FILL } + private val textEdge = Paint(Paint.ANTI_ALIAS_FLAG).apply { typeface = font; style = Paint.Style.STROKE; strokeJoin = Paint.Join.ROUND } + private val bmp = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG) + private val rect = RectF() + private val fm = Paint.FontMetrics() + + private var scale = 1f + private var ox = 0f + private var oy = 0f + private var spriteScale = -1f + private var sprites: Array? = null + + // ---------- made once ---------- + private val hexPath = Path() + private val comb = Path().also { p -> + for (r in -1 until 16) for (c in 0 until 12) { + val x = Hive.FX + Hive.R + c * Hive.D + (if (kotlin.math.abs(r) % 2 != 0) Hive.R else 0.0) + val y = Hive.TOP0 + Hive.R + r * Hive.RH + addHex(p, x, y, Hive.R + 1) + } + } + private val bombHex = Path().also { addHex(it, 0.0, 0.0, Hive.R) } + private val hills1 = Path().apply { moveTo(0f, 560f); quadTo(250f, 480f, 520f, 560f); quadTo(800f, 640f, 1280f, 520f); lineTo(1280f, 720f); lineTo(0f, 720f); close() } + private val hills2 = Path().apply { moveTo(0f, 640f); quadTo(400f, 590f, 760f, 650f); quadTo(1000f, 690f, 1280f, 620f); lineTo(1280f, 720f); lineTo(0f, 720f); close() } + private val ray = Path().apply { moveTo(0f, 0f); lineTo(1400f, -110f); lineTo(1400f, 110f); close() } + private val pendulum = Path().apply { moveTo(-16f, 8f); lineTo(0f, -70f); lineTo(16f, 8f) } + private val antennae = Path().apply { moveTo(-6f, -22f); quadTo(-9f, -34f, -15f, -37f); moveTo(6f, -22f); quadTo(9f, -34f, 15f, -37f) } + private val antennaTips = Path().also { p -> + for (hx in intArrayOf(-15, 15)) { + for (k in 0 until 6) { val a = PI / 6 + k * PI / 3; val px = (hx + cos(a) * 4.5).toFloat(); val py = (-38 + sin(a) * 4.5).toFloat(); if (k == 0) p.moveTo(px, py) else p.lineTo(px, py) } + p.close() + } + } + private val beeBody = Path().apply { addCircle(0f, 0f, 24f, Path.Direction.CW) } + private val wheelSeg = Path() + private val guide = Path() + private val guidePts = DoubleArray(128) + private var guideAngle = Double.NaN + private var guideTop = Double.NaN + private var guideVersion = -1 + private val deadlineDash = DashPathEffect(floatArrayOf(10f, 8f), 0f) + private val guideDash = Array(16) { DashPathEffect(floatArrayOf(4f, 12f), it.toFloat()) } + + private val space = LinearGradient(0f, 0f, 1280f, 720f, intArrayOf(hex(0xFF040A1E), hex(0xFF0B1538), hex(0xFF2A1760)), floatArrayOf(0f, .6f, 1f), Shader.TileMode.CLAMP) + private val nebula = RadialGradient(1080f, 180f, 460f, intArrayOf(rgba(160, 80, 255, .22), rgba(160, 80, 255, .22), rgba(160, 80, 255, 0.0)), floatArrayOf(0f, 20f / 460f, 1f), Shader.TileMode.CLAMP) + private val day = LinearGradient(0f, 0f, 0f, 720f, intArrayOf(hex(0xFF3D8FD6), hex(0xFF8FD0F5), hex(0xFFBFE6F7)), floatArrayOf(0f, .7f, 1f), Shader.TileMode.CLAMP) + private val wood = LinearGradient((Hive.FX - 26).toFloat(), 0f, (Hive.FX2 + 26).toFloat(), 0f, intArrayOf(hex(0xFF9B6531), hex(0xFFC48848), hex(0xFF9B6531)), floatArrayOf(0f, .5f, 1f), Shader.TileMode.CLAMP) + private var lid: Shader? = null + private var lidTop = Double.NaN + private val stars = Array(150) { i -> floatArrayOf(((i * 397) % 1280).toFloat(), ((i * 211) % 720).toFloat(), .6f + (i % 4) * .5f, i * .7f) } + private val dots = Array(26) { i -> floatArrayOf(((i * 97) % 1280).toFloat(), (600 + (i * 53) % 100).toFloat()) } + private val dotColours = intArrayOf(hex(0xFFFFD54A), hex(0xFFFFFFFF), hex(0xFFE57373)) + private var buttonsFor: List? = null + + // ---------- words ---------- + private val starWords = Array(4) { "★".repeat(it) + "☆".repeat(3 - it) } + private val dropMarks = Array(9) { "▼".repeat(it) } + private val scoreText = Label { it.toString().padStart(6, '0') } + private val swapsText = Label { "⇅ $it" } + private val bombsText = Label { "×$it" } + private val levelText = Label { "LEVEL $it" } + private val dropsText = Label { "Drops: $it" } + private val bestText = Label { "Best: $it" } + private val bannerText = Label { if (it == HiveSim.BANNER_NO_BOMBS) "No Honeybombs left" else "Level $it" } + private val prizeText = Label { "$it" } + private val wonText = Label { "You won $it Honeybomb${if (it > 1) "s" else ""}!" } + private val fxWords = arrayOfNulls(Fx.CAP) + private val fxWordValue = IntArray(Fx.CAP) { Int.MIN_VALUE } + private var infoKey = -1L + private var infoLine = "" + private var pageKey = -1L + private var pageLine = "" + private var householdKey = -1 + private var householdLine = "" + + private fun addHex(p: Path, x: Double, y: Double, r: Double) { + for (i in 0 until 6) { + val a = PI / 6 + i * PI / 3 + val px = (x + cos(a) * r).toFloat(); val py = (y + sin(a) * r).toFloat() + if (i == 0) p.moveTo(px, py) else p.lineTo(px, py) + } + p.close() + } + + // ---------- the frame ---------- + + /** Draws [sim] filling [w]×[h] pixels, letterboxed like game.js. [t] is the sim's clock, for the twinkles. */ + fun draw(c: Canvas, w: Int, h: Int, sim: HiveSim) { + scale = min(w / Hive.W.toFloat(), h / Hive.H.toFloat()) + ox = (w - Hive.W.toFloat() * scale) / 2; oy = (h - Hive.H.toFloat() * scale) / 2 + if (scale != spriteScale) makeSprites() + fill.shader = null + fill.color = hex(0xFF3D7FB8) + c.drawRect(0f, 0f, w.toFloat(), h.toFloat(), fill) + c.save() + c.translate(ox, oy); c.scale(scale, scale) + c.clipRect(0f, 0f, 1280f, 720f) + when (sim.screen) { + HiveScreen.Title -> drawTitle(c, sim) + HiveScreen.Levels -> drawLevels(c, sim) + HiveScreen.Help -> drawHelp(c, sim) + HiveScreen.Daily -> drawWheel(c, sim) + HiveScreen.Household -> drawHousehold(c, sim) + else -> { + val shake = sim.shakeT() + c.save() + if (shake >= 0 && !sim.calm) c.translate(0f, (sin(shake * 60) * 4 * (1 - shake / 0.3)).toFloat()) + drawSky(c, sim) + drawHive(c, sim) + drawGrid(c, sim) + if (sim.shotOn) { if (sim.shotBomb) drawBomb(c, sim.shotX, sim.shotY, 1.0) else drawFlower(c, sim.shotX, sim.shotY, sim.shotColour) } + drawLauncher(c, sim) + drawEffects(c, sim) + drawHud(c, sim) + c.restore() + } + } + c.restore() + } + + private fun makeSprites() { + spriteScale = scale + sprites?.forEach { it.recycle() } + val size = ceil(Hive.D * max(scale.toDouble(), 0.5) * 1.1).toInt() + sprites = Array(6) { i -> + Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).also { b -> + val g = Canvas(b) + val k = (size / (Hive.D * 1.1)).toFloat() + g.translate(size / 2f, size / 2f); g.scale(k, k) + drawFlowerShape(g, Hive.R.toFloat(), i) + } + } + } + + private fun drawFlowerShape(g: Canvas, r: Float, colour: Int) { + val p = Paint(Paint.ANTI_ALIAS_FLAG) + p.color = rgba(0, 0, 0, .25); g.drawCircle(2f, 3f, r * .98f, p) + for (i in 0 until 6) { + val a = i / 6.0 * PI * 2 + PI / 6 + val px = (cos(a) * r * .5).toFloat(); val py = (sin(a) * r * .5).toFloat() + p.color = hex(Hive.DARK[colour]); g.drawCircle(px, py, r * .5f, p) + p.color = hex(Hive.PETAL[colour]); g.drawCircle(px * .96f, py * .96f, r * .44f, p) + } + p.color = rgba(255, 255, 255, .35); g.drawCircle(-r * .25f, -r * .35f, r * .2f, p) + // game.js: a radial gradient from a point up and left of centre out to the edge of the middle. + p.shader = RadialGradient(-r * .06f, -r * .06f, r * .4f, hex(0xFFFFF3A0), hex(0xFFF2B400), Shader.TileMode.CLAMP) + g.drawCircle(0f, 0f, r * .36f, p) + p.shader = null; p.style = Paint.Style.STROKE; p.strokeWidth = 1.5f; p.color = rgba(120, 70, 0, .5) + g.drawCircle(0f, 0f, r * .36f, p) + } + + private fun drawFlower(c: Canvas, x: Double, y: Double, colour: Int, s: Double = 1.0, alpha: Double = 1.0, rot: Double = 0.0) { + val sp = sprites?.getOrNull(colour) ?: return + val size = (Hive.D * 1.1 * s).toFloat() + c.save() + c.translate(x.toFloat(), y.toFloat()) + if (rot != 0.0) c.rotate((rot * DEG).toFloat()) + bmp.alpha = (alpha * 255).toInt().coerceIn(0, 255) + rect.set(-size / 2, -size / 2, size / 2, size / 2) + c.drawBitmap(sp, null, rect, bmp) + c.restore() + } + + // ---------- text ---------- + + private fun words(c: Canvas, s: String, x: Double, y: Double, size: Float, colour: Int, align: Paint.Align = Paint.Align.CENTER, edge: Int = 0, alpha: Float = 1f) { + text.textSize = size; text.textAlign = align; text.color = colour + if (alpha < 1f) text.alpha = (text.alpha * alpha).toInt() + if (edge != 0) { + textEdge.textSize = size; textEdge.textAlign = align; textEdge.strokeWidth = size / 6; textEdge.color = edge + if (alpha < 1f) textEdge.alpha = (textEdge.alpha * alpha).toInt() + c.drawText(s, x.toFloat(), y.toFloat(), textEdge) + } + c.drawText(s, x.toFloat(), y.toFloat(), text) + } + + private fun panel(c: Canvas, x: Float, y: Float, w: Float, h: Float) { + rect.set(x, y, x + w, y + h) + fill.shader = null; fill.color = rgba(70, 40, 15, .82); c.drawRoundRect(rect, 16f, 16f, fill) + line.pathEffect = null; line.strokeWidth = 3f; line.color = hex(0xFFF2A900); c.drawRoundRect(rect, 16f, 16f, line) + } + + private fun roundFill(c: Canvas, x: Double, y: Double, w: Double, h: Double, r: Double, colour: Int) { + rect.set(x.toFloat(), y.toFloat(), (x + w).toFloat(), (y + h).toFloat()) + fill.shader = null; fill.color = colour + c.drawRoundRect(rect, r.toFloat(), r.toFloat(), fill) + } + + // ---------- skies ---------- + + private fun drawSky(c: Canvas, sim: HiveSim) { if (sim.save.skinOrbit) drawSpace(c, sim) else drawDay(c, sim) } + + /** The Orbit skin: deep space, a ringed planet and a slow twinkle, kept dark so the flowers stand out. */ + private fun drawSpace(c: Canvas, sim: HiveSim) { + fill.shader = space; c.drawRect(0f, 0f, 1280f, 720f, fill) + fill.shader = nebula; c.drawRect(0f, 0f, 1280f, 720f, fill) + fill.shader = null + c.save(); c.translate(1130f, 620f); c.rotate((-0.24 * DEG).toFloat()) + line.pathEffect = null; line.color = rgba(255, 216, 74, .4); line.strokeWidth = 7f + rect.set(-215f, -44f, 215f, 44f) + c.drawArc(rect, 180f, 180f, false, line) + c.rotate((0.24 * DEG).toFloat()) + // game.js's planet gradient sits in untranslated units, so on screen the planet is its outer colour throughout. + fill.color = hex(0xFF1A1650); c.drawCircle(0f, 0f, 120f, fill) + c.rotate((-0.24 * DEG).toFloat()) + rect.set(-215f, -44f, 215f, 44f) + c.drawArc(rect, 0f, 180f, false, line) + c.restore() + fill.color = hex(0xFFC9D4E8); c.drawCircle(150f, 140f, 34f, fill) + fill.color = hex(0xFFAAB6CC); c.drawCircle(140f, 130f, 7f, fill); c.drawCircle(163f, 150f, 5f, fill) + val t = sim.time + for (s in stars) { + fill.color = rgba(255, 255, 255, if (sim.calm) 0.5 else 0.35 + 0.35 * sin(t * 1.4 + s[3])) + c.drawCircle(s[0], s[1], s[2], fill) + } + } + + /** The Classic skin: a summer sky, hills and a smiling sun. */ + private fun drawDay(c: Canvas, sim: HiveSim) { + fill.shader = day; c.drawRect(0f, 0f, 1280f, 720f, fill); fill.shader = null + fill.color = hex(0xFF6CBF43); c.drawPath(hills1, fill) + fill.color = hex(0xFF4F9E32); c.drawPath(hills2, fill) + for (i in dots.indices) { fill.color = dotColours[i % 3]; c.drawCircle(dots[i][0], dots[i][1], 5f, fill) } + // Turning sun rays (still under Reduce motion). + c.save(); c.translate(170f, 120f) + c.rotate(if (sim.calm) 0f else (sim.time * 0.05 * DEG).toFloat()) + fill.color = rgba(255, 246, 201, .28) + for (i in 0 until 14) { c.rotate((360.0 / 14).toFloat()); c.drawPath(ray, fill) } + c.restore() + fill.color = hex(0xFFFFD54A); c.drawCircle(170f, 120f, 62f, fill) + fill.color = hex(0xFFF2A900); c.drawCircle(150f, 112f, 6f, fill); c.drawCircle(190f, 112f, 6f, fill) + line.pathEffect = null; line.color = hex(0xFFF2A900); line.strokeWidth = 4f + rect.set(148f, 106f, 192f, 150f); c.drawArc(rect, 36f, 108f, false, line) + } + + // ---------- the hive ---------- + + private fun drawHive(c: Canvas, sim: HiveSim) { + val fx = Hive.FX.toFloat(); val fx2 = Hive.FX2.toFloat(); val fw = Hive.FW.toFloat(); val top = sim.top.toFloat() + // Wooden frame. + rect.set(fx - 26, 8f, fx - 26 + fw + 52, 8f + 668); fill.shader = null; fill.color = hex(0xFF7A4A22); c.drawRoundRect(rect, 18f, 18f, fill) + rect.set(fx - 20, 14f, fx - 20 + fw + 40, 14f + 656); fill.shader = wood; c.drawRoundRect(rect, 14f, 14f, fill); fill.shader = null + // Honeycomb interior. + fill.color = hex(0xFF1D1209); c.drawRect(fx, 58f, fx + fw, 58f + 602, fill) + c.save(); c.clipRect(fx, 58f, fx + fw, 58f + 602) + fill.color = hex(0xFF2A1A0E); c.drawPath(comb, fill) + line.pathEffect = null; line.color = hex(0xFF4A2F16); line.strokeWidth = 2f; c.drawPath(comb, line) + c.restore() + // Lid that pushes down. + if (sim.top != lidTop) { lidTop = sim.top; lid = LinearGradient(0f, 14f, 0f, top, hex(0xFFB77B3E), hex(0xFF8A5A2B), Shader.TileMode.CLAMP) } + fill.shader = lid; c.drawRect(fx - 6, 14f, fx - 6 + fw + 12, top, fill); fill.shader = null + fill.color = hex(0xFF6D4220); c.drawRect(fx - 6, top - 6, fx - 6 + fw + 12, top, fill) + line.color = rgba(0, 0, 0, .18); line.strokeWidth = 2f + var y = 30f + while (y < top - 8) { c.drawLine(fx, y, fx2, y, line); y += 18f } + if (sim.top - Hive.TOP0 > 0) words(c, dropMarks[min(sim.drops, 8)], 640.0, sim.top - 14, 18f, rgba(255, 255, 255, .18)) + // Launcher line. + line.color = rgba(255, 213, 74, .35); line.strokeWidth = 2f; line.pathEffect = deadlineDash + c.drawLine(fx, Hive.DEADLINE.toFloat(), fx2, Hive.DEADLINE.toFloat(), line) + line.pathEffect = null + } + + private fun drawGrid(c: Canvas, sim: HiveSim) { + for (r in 0 until Hive.MAXROWS) { + val y = Hive.cellY(r, sim.top) + for (col in 0 until Hive.cellsIn(r)) { + val v = sim.grid[r, col] + if (v >= 0) drawFlower(c, Hive.cellX(r, col), y, v) + } + } + } + + private fun drawLauncher(c: Canvas, sim: HiveSim) { + if (sim.save.guide && !sim.shotOn) { + if (sim.angle != guideAngle || sim.top != guideTop || sim.grid.version != guideVersion) { + guideAngle = sim.angle; guideTop = sim.top; guideVersion = sim.grid.version + val n = sim.guidePoints(guidePts) + guide.reset(); guide.moveTo(guidePts[0].toFloat(), guidePts[1].toFloat()) + for (i in 1 until n) guide.lineTo(guidePts[i * 2].toFloat(), guidePts[i * 2 + 1].toFloat()) + } + line.color = rgba(255, 240, 180, .75); line.strokeWidth = 3f + val phase = if (sim.calm) 0 else (((-sim.time * 40) % 16 + 16) % 16).toInt().coerceIn(0, 15) + line.pathEffect = guideDash[phase] + c.drawPath(guide, line) + line.pathEffect = null + } + // Pendulum launcher. + c.save() + c.translate(Hive.LAUNCH_X.toFloat(), Hive.LAUNCH_Y.toFloat()); c.rotate((sim.angle * DEG).toFloat()) + line.color = hex(0xFFE8A33A); line.strokeWidth = 5f; line.strokeJoin = Paint.Join.ROUND + c.drawPath(pendulum, line) + line.strokeJoin = Paint.Join.MITER + fill.shader = null; fill.color = hex(0xFFFFD54A); c.drawCircle(0f, -70f, 5f, fill) + c.restore() + if (!sim.shotOn) { + if (sim.bombArmed) drawBomb(c, Hive.LAUNCH_X, Hive.LAUNCH_Y - 28, if (sim.calm) 1.05 else 1 + sin(sim.time * 8) * 0.05) + else drawFlower(c, Hive.LAUNCH_X, Hive.LAUNCH_Y - 28, sim.current) + } + drawBee(c, Hive.LAUNCH_X - 92, Hive.LAUNCH_Y - 8 + (if (sim.calm) 0.0 else sin(sim.time * 3) * 4), 1.15, sim.angle * 0.3, sim.time) + } + + private fun drawBomb(c: Canvas, x: Double, y: Double, s: Double) { + c.save() + c.translate(x.toFloat(), y.toFloat()); c.scale(s.toFloat(), s.toFloat()) + fill.shader = null; fill.color = hex(0xFFF2A900); c.drawPath(bombHex, fill) + line.pathEffect = null; line.color = hex(0xFF7A4400); line.strokeWidth = 3f; c.drawPath(bombHex, line) + text.textSize = 22f; text.textAlign = Paint.Align.CENTER; text.color = hex(0xFF7A4400) + text.getFontMetrics(fm) + c.drawText("✸", 0f, 1f - (fm.ascent + fm.descent) / 2, text) + c.restore() + } + + /** + * Bumble, drawn to the Orbit cast's model sheet (design/arcade/orbit-cast.md): flat colours with one soft highlight, no + * outline, round white eyes with navy pupils, no mouth; honey body, two navy stripes, pale wings, hexagon-tipped antennae. + */ + private fun drawBee(c: Canvas, x: Double, y: Double, s: Double, tilt: Double, time: Double) { + c.save() + c.translate(x.toFloat(), y.toFloat()); c.scale(s.toFloat(), s.toFloat()); c.rotate((tilt * DEG).toFloat()) + val flap = sin(time * 30) * 0.25 + fill.shader = null; fill.color = rgba(232, 240, 255, .8) + c.save(); c.rotate(((-0.45 + flap) * DEG).toFloat()); rect.set(-28f, -32f, 2f, -12f); c.drawOval(rect, fill); c.restore() + c.save(); c.rotate(((0.45 - flap) * DEG).toFloat()); rect.set(-2f, -32f, 28f, -12f); c.drawOval(rect, fill); c.restore() + line.pathEffect = null; line.color = NAVY; line.strokeWidth = 2.5f; line.strokeCap = Paint.Cap.ROUND + c.drawPath(antennae, line) + line.strokeCap = Paint.Cap.BUTT + fill.color = HONEY; c.drawPath(antennaTips, fill) + c.drawCircle(0f, 0f, 24f, fill) + c.save(); c.clipPath(beeBody) + fill.color = NAVY; c.drawRect(-26f, 6f, 26f, 12f, fill); c.drawRect(-26f, 16f, 26f, 22f, fill) + c.restore() + fill.color = rgba(255, 255, 255, .3); c.drawCircle(-9f, -11f, 7f, fill) + fill.color = hex(0xFFFFFFFF); c.drawCircle(-8f, -4f, 6.2f, fill); c.drawCircle(8f, -4f, 6.2f, fill) + fill.color = NAVY; c.drawCircle(-6.5f, -4f, 3.1f, fill); c.drawCircle(9.5f, -4f, 3.1f, fill) + c.restore() + } + + private fun drawEffects(c: Canvas, sim: HiveSim) { + for (i in 0 until sim.fxCount) { + val t = sim.fxT[i]; val x = sim.fxX[i]; val y = sim.fxY[i] + when (sim.fxType[i]) { + Fx.POP -> { + val k = t / 0.35 + drawFlower(c, x, y, sim.fxColour[i], 1 + k * 0.8, 1 - k) + fill.shader = null; fill.color = hex(Hive.PETAL[sim.fxColour[i]]); fill.alpha = ((1 - k) * 255).toInt().coerceIn(0, 255) + for (j in 0 until 6) { + val a = j / 6.0 * PI * 2 + c.drawCircle((x + cos(a) * k * 50).toFloat(), (y + sin(a) * k * 50).toFloat(), (6 * (1 - k)).toFloat().coerceAtLeast(0f), fill) + } + } + Fx.FALL -> drawFlower(c, x, y, sim.fxColour[i], 1.0, 1.0, sim.fxRot[i]) + Fx.TEXT -> { + val v = sim.fxColour[i] + if (fxWordValue[i] != v || fxWords[i] == null) { fxWordValue[i] = v; fxWords[i] = "+$v" } + words(c, fxWords[i]!!, x, y - t * 60, 30f, hex(0xFFFFD54A), edge = hex(0xFF7A4400), alpha = (1 - t / 0.9).toFloat().coerceIn(0f, 1f)) + } + Fx.RING -> { + line.pathEffect = null; line.color = rgba(255, 213, 74, (1 - t / 0.5).coerceIn(0.0, 1.0)); line.strokeWidth = 10f + c.drawCircle(x.toFloat(), y.toFloat(), (20 + t * 300).toFloat(), line) + } + } + } + } + + private fun drawHud(c: Canvas, sim: HiveSim) { + val fx = Hive.FX; val fx2 = Hive.FX2 + // Bottom bar. + roundFill(c, fx - 20, 668.0, Hive.FW + 40, 46.0, 10.0, hex(0xFFA86D34)) + roundFill(c, 640.0 - 90, 676.0, 180.0, 32.0, 6.0, hex(0xFF2A1A0E)) + words(c, scoreText[sim.score], 640.0, 701.0, 24f, hex(0xFFFFFFFF)) + // Next flower. + words(c, "NEXT", fx + 14, 699.0, 15f, hex(0xFFFFF3C4), Paint.Align.LEFT) + drawFlower(c, fx + 86, 691.0, sim.next, 0.62) + // Swap and Honeybomb counters. + roundFill(c, fx2 - 196, 674.0, 92.0, 34.0, 8.0, rgba(0, 0, 0, .25)) + roundFill(c, fx2 - 98, 674.0, 92.0, 34.0, 8.0, rgba(0, 0, 0, .25)) + words(c, swapsText[sim.swaps], fx2 - 150, 699.0, 18f, hex(0xFFFFFFFF)) + c.save(); c.translate((fx2 - 78).toFloat(), 691f); c.scale(.5f, .5f); drawBomb(c, 0.0, 0.0, if (sim.bombArmed) 1.2 else 1.0); c.restore() + words(c, bombsText[sim.save.bombs], fx2 - 38, 699.0, 18f, if (sim.bombArmed) hex(0xFFFFD54A) else hex(0xFFFFFFFF)) + + // Left panel: level, stars challenge, panic bar. + panel(c, 80f, 200f, 250f, 330f) + if (sim.mode == HiveMode.Hard) words(c, "HARD MODE", 205.0, 222.0, 15f, hex(0xFFFF8A65)) + words(c, levelText[sim.level], 205.0, 248.0, 30f, hex(0xFFFFD54A), edge = hex(0xFF7A4400)) + words(c, starWords[sim.starsFor(sim.drops)], 205.0, 292.0, 30f, hex(0xFFFFD54A)) + words(c, "Star challenge: clear before", 205.0, 322.0, 14f, hex(0xFFFFF3C4)) + words(c, "the ceiling drops twice", 205.0, 340.0, 14f, hex(0xFFFFF3C4)) + words(c, "CEILING", 205.0, 380.0, 16f, hex(0xFFFFFFFF)) + roundFill(c, 110.0, 394.0, 190.0, 30.0, 15.0, hex(0xFF2A1A0E)) + val pc = sim.panic + val bar = when { + pc > 0.8 -> if (sim.calm || (sim.time * 8).toInt() % 2 != 0) hex(0xFFE53935) else hex(0xFFFF7043) + pc > 0.55 -> hex(0xFFF5A623) + else -> hex(0xFF7CC242) + } + roundFill(c, 114.0, 398.0, max(22.0, 182 * pc), 22.0, 11.0, bar) + words(c, dropsText[sim.drops], 205.0, 460.0, 18f, hex(0xFFFFFFFF)) + words(c, bestText[sim.progress.best[sim.level]], 205.0, 494.0, 18f, hex(0xFFFFFFFF)) + + // Right panel: remote help. + panel(c, 950f, 200f, 250f, 330f) + words(c, "REMOTE", 1075.0, 244.0, 22f, hex(0xFFFFD54A), edge = hex(0xFF7A4400)) + for (i in REMOTE.indices) { + roundFill(c, 972.0, 268.0 + i * 50, 76.0, 34.0, 8.0, rgba(255, 255, 255, .14)) + words(c, REMOTE[i][0], 1010.0, 292.0 + i * 50, 16f, hex(0xFFFFFFFF)) + words(c, REMOTE[i][1], 1062.0, 292.0 + i * 50, 17f, hex(0xFFFFF3C4), Paint.Align.LEFT) + } + // Pause button (game.js drew it for touch). + roundFill(c, 1176.0, 16.0, 84.0, 48.0, 12.0, rgba(0, 0, 0, .25)) + words(c, "II", 1218.0, 50.0, 26f, hex(0xFFFFFFFF)) + + if (sim.bannerT > 0) { + val a = min(1.0, sim.bannerT).toFloat() + words(c, bannerText[sim.banner], 640.0, 360.0, 54f, hex(0xFFFFD54A), edge = hex(0xFF7A4400), alpha = a) + } + } + + // ---------- menus ---------- + + /** Orbit's focus ring: its yellow, with a thin navy edge each side so it reads on the amber buttons (frame 61). */ + private fun ringStroke(width: Float, navy: Boolean) { + line.pathEffect = null + if (navy) { line.strokeWidth = width + 4; line.color = NAVY } else { line.strokeWidth = width; line.color = hex(0xFFFFDE59) } + } + + private fun drawButtons(c: Canvas, sim: HiveSim) { + val list = sim.buttons + if (list !== buttonsFor) { + buttonsFor = list + buttonShadesOn = Array(list.size) { i -> list[i].let { b -> if (b.hex || b.round) null else LinearGradient(0f, b.y.toFloat(), 0f, (b.y + b.h).toFloat(), hex(0xFFFFD27A), hex(0xFFF7A823), Shader.TileMode.CLAMP) } } + buttonShadesOff = Array(list.size) { i -> list[i].let { b -> if (b.hex || b.round) null else LinearGradient(0f, b.y.toFloat(), 0f, (b.y + b.h).toFloat(), hex(0xFFFBBF47), hex(0xFFE08C10), Shader.TileMode.CLAMP) } } + } + for (i in list.indices) { + val b = list[i] + val on = i == sim.focus + if (b.hex) { + val locked = b.level > sim.progress.unlocked + val cx = b.x + b.w / 2; val cy = b.y + b.h / 2 - 8 + hexPath.reset(); addHex(hexPath, cx, cy, if (on) 44.0 else 40.0) + fill.shader = null; fill.color = if (locked) hex(0xFF9EA7AD) else hex(0xFFF7A823); c.drawPath(hexPath, fill) + if (on) { ringStroke(6f, true); c.drawPath(hexPath, line); ringStroke(6f, false); c.drawPath(hexPath, line) } + else { line.strokeWidth = 3f; line.color = if (locked) hex(0xFF59636A) else hex(0xFFA35A00); c.drawPath(hexPath, line) } + words(c, if (locked) "🔒" else b.label, cx, cy + 10, if (locked) 22f else 28f, hex(0xFFFFFFFF), edge = if (locked) 0 else hex(0xFFA35A00)) + if (!locked) words(c, starWords[sim.progress.stars[b.level].coerceIn(0, 3)], cx, cy + 50, 18f, hex(0xFFFFD54A), edge = hex(0xFF7A4400)) + } else if (b.round) { + val cx = (b.x + b.w / 2).toFloat(); val cy = (b.y + b.h / 2).toFloat(); val r = (b.w / 2).toFloat() + fill.shader = null; fill.color = if (on) hex(0xFFFFD54A) else hex(0xFFF7A823); c.drawCircle(cx, cy, r, fill) + if (on) { ringStroke(6f, true); c.drawCircle(cx, cy, r, line); ringStroke(6f, false); c.drawCircle(cx, cy, r, line) } + else { line.strokeWidth = 3f; line.color = hex(0xFFA35A00); c.drawCircle(cx, cy, r, line) } + words(c, b.label, b.x + b.w / 2, b.y + b.h / 2 + 12, 32f, hex(0xFFFFFFFF), edge = hex(0xFFA35A00)) + } else { + rect.set(b.x.toFloat(), b.y.toFloat(), (b.x + b.w).toFloat(), (b.y + b.h).toFloat()) + val rr = (b.h / 2).toFloat() + fill.shader = if (on) buttonShadesOn[i] else buttonShadesOff[i] + if (on) fill.setShadowLayer(24f, 0f, 0f, rgba(255, 255, 255, .9)) + c.drawRoundRect(rect, rr, rr, fill) + fill.clearShadowLayer(); fill.shader = null + if (on) { ringStroke(5f, true); c.drawRoundRect(rect, rr, rr, line); ringStroke(5f, false); c.drawRoundRect(rect, rr, rr, line) } + else { line.strokeWidth = 3f; line.color = hex(0xFFA35A00); c.drawRoundRect(rect, rr, rr, line) } + if (b.glow) { + line.color = hex(0xFFFFFFFF); line.strokeWidth = 2f + line.alpha = ((if (sim.calm) 0.6 else 0.5 + sin(sim.time * 5) * 0.3) * 255).toInt().coerceIn(0, 255) + rect.set((b.x - 6).toFloat(), (b.y - 6).toFloat(), (b.x + b.w + 6).toFloat(), (b.y + b.h + 6).toFloat()) + c.drawRoundRect(rect, rr + 6, rr + 6, line) + } + words(c, b.label, b.x + b.w / 2, b.y + b.h / 2 + b.h * 0.15, round(b.h * 0.4).toFloat(), hex(0xFFFFFFFF), edge = hex(0xFFA35A00)) + } + } + } + + private var buttonShadesOn: Array = emptyArray() + private var buttonShadesOff: Array = emptyArray() + + private fun drawTitle(c: Canvas, sim: HiveSim) { + drawSky(c, sim) + val t = sim.time + val bob = if (sim.calm) 0.0 else sin(t * 2) * 6 + words(c, "Bumble", 640.0, 150 + bob, 110f, hex(0xFFFFC21A), edge = hex(0xFF8A4B00)) + words(c, "Hive", 640.0, 260 + bob, 110f, hex(0xFFFFC21A), edge = hex(0xFF8A4B00)) + drawBee(c, 900.0, 210 + (if (sim.calm) 0.0 else sin(t * 3) * 10), 2.4, if (sim.calm) 0.0 else sin(t) * 0.1, t) + for (i in 0 until 5) drawFlower(c, 250.0 + i * 40, 620 + (if (sim.calm) 0.0 else sin(t * 2 + i) * 4), i % 5) + // Inside the TV-safe area (5% in from each edge: above y 684). + val key = (sim.save.bombs.toLong() shl 20) or (sim.progress.unlocked.toLong() shl 2) or sim.mode.ordinal.toLong() + if (key != infoKey) { + infoKey = key + infoLine = "Honeybombs: ${sim.save.bombs} • Levels unlocked: ${sim.progress.unlocked}/${Hive.LEVELS}" + if (sim.mode == HiveMode.Hard) " • Hard mode" else "" + } + words(c, infoLine, 640.0, 672.0, 18f, hex(0xFFFFFFFF), edge = rgba(0, 0, 0, .35)) + drawButtons(c, sim) + } + + private fun drawLevels(c: Canvas, sim: HiveSim) { + drawSky(c, sim) + words(c, if (sim.mode == HiveMode.Hard) "Level Select · Hard" else "Level Select", 640.0, 100.0, 64f, hex(0xFFFFC21A), edge = hex(0xFF8A4B00)) + val p = sim.progress + val total = p.totalStars() + val key = (p.page.toLong() shl 32) or total.toLong() + if (key != pageKey) { pageKey = key; pageLine = "Page ${p.page + 1} of ${Hive.LEVELS / Hive.PER_PAGE} • ★ $total" } + words(c, pageLine, 640.0, 140.0, 20f, hex(0xFFFFFFFF), edge = rgba(0, 0, 0, .35)) + drawButtons(c, sim) + } + + private fun drawHelp(c: Canvas, sim: HiveSim) { + drawSky(c, sim) + panel(c, 220f, 40f, 840f, 500f) + words(c, "How to play", 640.0, 100.0, 46f, hex(0xFFFFD54A), edge = hex(0xFF7A4400)) + for (i in HELP.indices) words(c, HELP[i], 640.0, 160.0 + i * 44, 21f, hex(0xFFFFFFFF)) + drawButtons(c, sim) + } + + private fun drawWheel(c: Canvas, sim: HiveSim) { + drawSky(c, sim) + words(c, "Bumble’s Daily Bonus", 640.0, 82.0, 56f, hex(0xFFFFC21A), edge = hex(0xFF8A4B00)) + words(c, "A free spin for Honeybombs. Once a day, just for fun.", 640.0, 118.0, 20f, hex(0xFFFFFFFF), edge = rgba(0, 0, 0, .35)) + val cx = 640f; val cy = 350f; val r = 190f + val seg = HiveSim.PRIZES.size + c.save(); c.translate(cx, cy); c.rotate((sim.wheelAngle * DEG).toFloat()) + rect.set(-r, -r, r, r) + for (i in 0 until seg) { + wheelSeg.reset(); wheelSeg.moveTo(0f, 0f); wheelSeg.arcTo(rect, i * 360f / seg, 360f / seg); wheelSeg.close() + fill.shader = null; fill.color = if (i % 2 != 0) hex(0xFFF7A823) else hex(0xFFFFD54A); c.drawPath(wheelSeg, fill) + line.pathEffect = null; line.color = hex(0xFFA35A00); line.strokeWidth = 3f; c.drawPath(wheelSeg, line) + c.save(); c.rotate(((i + 0.5) / seg * 360).toFloat()) + words(c, prizeText[HiveSim.PRIZES[i]], r * 0.68, 12.0, 36f, hex(0xFFFFFFFF), edge = hex(0xFFA35A00)) + c.restore() + } + c.restore() + fill.color = hex(0xFFA35A00); c.drawCircle(cx, cy, 34f, fill) + drawBomb(c, cx.toDouble(), cy.toDouble(), 0.9) + wheelSeg.reset(); wheelSeg.moveTo(cx - 18, cy - r - 24); wheelSeg.lineTo(cx + 18, cy - r - 24); wheelSeg.lineTo(cx, cy - r + 14); wheelSeg.close() + fill.color = hex(0xFFE53935); c.drawPath(wheelSeg, fill) + if (sim.wheelSpun) words(c, wonText[sim.wheelPrize], 640.0, 590.0, 34f, hex(0xFFFFFFFF), edge = hex(0xFF7A4400)) + else words(c, "Skip it any time. Nothing is lost if you don’t spin.", 640.0, 588.0, 22f, hex(0xFFFFFFFF), edge = rgba(0, 0, 0, .35)) + drawButtons(c, sim) + } + + /** This TV's BumbleHive from before profiles, offered as a copy to continue from. */ + private fun drawHousehold(c: Canvas, sim: HiveSim) { + drawSky(c, sim) + panel(c, 240f, 120f, 800f, 480f) + words(c, "Carry on from this TV’s hive?", 640.0, 200.0, 44f, hex(0xFFFFD54A), edge = hex(0xFF7A4400)) + val n = sim.legacy?.progress?.unlocked ?: 1 + if (n != householdKey) { householdKey = n; householdLine = "BumbleHive was played on this TV before profiles: $n of ${Hive.LEVELS} levels unlocked." } + words(c, householdLine, 640.0, 280.0, 22f, hex(0xFFFFFFFF)) + words(c, "Continue from a copy of it, or start fresh. Either way, that save stays as it is", 640.0, 330.0, 22f, hex(0xFFFFFFFF)) + words(c, "for anyone else who wants it.", 640.0, 362.0, 22f, hex(0xFFFFFFFF)) + drawButtons(c, sim) + } + + fun release() { sprites?.forEach { it.recycle() }; sprites = null; spriteScale = -1f } + + companion object { + private val REMOTE = arrayOf(arrayOf("◀ ▶", "Aim"), arrayOf("OK", "Fire"), arrayOf("▼", "Swap flower"), arrayOf("▲", "Honeybomb"), arrayOf("BACK", "Pause")) + val HELP = arrayOf( + "Your bee fires flowers into the honeycomb.", + "Join three or more of the same colour to burst them.", + "Flowers that lose their hold on the ceiling fall away for big bonus points.", + "The ceiling bar fills over time. When it is full, the ceiling pushes down a row.", + "Clear every flower to win. If they reach the dashed line, you are swarmed!", + "Finish before the ceiling drops twice for three stars.", + "Remote: ◀ ▶ aim, OK fires, ▼ swaps your flower, ▲ arms a Honeybomb, BACK pauses.", + "Change the skin below: Orbit or Classic.", + "Hard mode (on the title): a quicker ceiling, 3 swaps, new colours sooner.", + ) + } +} diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/hive/HiveLegacy.kt b/android/app/src/main/java/tv/orbit/classic/arcade/hive/HiveLegacy.kt new file mode 100644 index 00000000..b3e9c5a9 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/arcade/hive/HiveLegacy.kt @@ -0,0 +1,91 @@ +package tv.orbit.classic.arcade.hive + +import org.json.JSONObject +import org.json.JSONTokener +import tv.orbit.classic.writeSafely +import java.io.File + +/** + * The one-time carry-over of the WebView game's progress (8 November 2026). + * + * The old BumbleHive kept its save in the WebView's localStorage under 'orbithive-save-v1', for the page + * file:///android_asset/orbithive/index.html (OrbitHiveScreen, loadUrl). The first time the native game opens, a short-lived, + * invisible WebView with the old one's settings loads that same URL, so it has the same origin and so the same storage, and + * runs [READ_SCRIPT], which only reads. The answer is written once to filesDir/arcade/household-bumblehive-legacy.json and + * the WebView is destroyed. That file is never written again; the localStorage key and the WebView's data folder are + * never written, cleared or deleted. A failed read (no WebView, a timeout, storage unreadable) writes nothing, so it's + * tried again next time, and the game plays meanwhile. + */ +internal object HiveLegacy { + const val KEY = "orbithive-save-v1" + /** Exactly the URL the old game loaded, so localStorage is the same origin's. */ + const val ORIGIN_URL = "file:///android_asset/orbithive/index.html" + const val FILE = "household-bumblehive-legacy.json" + const val TIMEOUT_MS = 10_000L + + // READ_SCRIPT_BEGIN + /** Reads the old save (and any per-profile copies the old game made) and returns them as JSON text. Reads only. */ + const val READ_SCRIPT = """(function () { + try { + var k = 'orbithive-save-v1', s = window.localStorage, v = s.getItem(k), o = {}; + for (var i = 0; i < s.length; i++) { var n = s.key(i); if (n && n.indexOf(k + ':') === 0) o[n] = s.getItem(n); } + return JSON.stringify({ ok: true, present: v !== null, value: v, profiles: o }); + } catch (e) { return JSON.stringify({ ok: false, error: String(e) }); } +})()""" + // READ_SCRIPT_END + + /** What the read found: the old save's text exactly as stored (null when there was none). */ + class Found(val present: Boolean, val value: String?, val profiles: Map) + + /** The snapshot on disk. [save] is null when there was nothing, or nothing game.js could have read. */ + class Snapshot(val present: Boolean, val value: String?, val copiedAtMs: Long) { + val save: LegacyHiveSave? by lazy { LegacyHiveSave.parse(value) } + } + + fun file(dir: File) = File(dir, FILE) + fun needsImport(dir: File) = !file(dir).exists() + + /** + * evaluateJavascript's answer (the script's string, JSON-quoted) as a [Found], or null for anything else: a failure the + * script caught, no answer, or nonsense. Null is a failed read and is tried again next time. + */ + fun parseAnswer(raw: String?): Found? = runCatching { + val text = JSONTokener(raw ?: return null).nextValue() as? String ?: return null + val o = JSONObject(text) + if (!o.optBoolean("ok")) return null + val present = o.optBoolean("present") + val value = if (present && !o.isNull("value")) o.getString("value") else null + val profiles = o.optJSONObject("profiles")?.let { p -> p.keys().asSequence().mapNotNull { k -> (p.opt(k) as? String)?.let { k to it } }.toMap() }.orEmpty() + Found(present && value != null, value, profiles) + }.getOrNull() + + /** Writes the snapshot, only if there isn't one yet (it is never replaced). True when one is on disk afterwards. */ + @Synchronized + fun record(dir: File, found: Found, nowMs: Long): Boolean { + val f = file(dir) + if (f.exists()) return true + dir.mkdirs() + val json = JSONObject().put("schema", 1).put("readOnly", true).put("source", "localStorage/$KEY").put("origin", ORIGIN_URL) + .put("copiedAt", nowMs).put("present", found.present).put("value", found.value ?: JSONObject.NULL) + .put("profiles", JSONObject(found.profiles as Map<*, *>)) + return runCatching { writeSafely(f, json.toString()); true }.getOrDefault(false) + } + + /** The snapshot, or null when there is none yet or it can't be read (then no Household save is offered). */ + fun load(dir: File): Snapshot? = runCatching { + val o = JSONObject(file(dir).readText()) + Snapshot(o.optBoolean("present"), if (o.isNull("value")) null else o.optString("value"), o.optLong("copiedAt")) + }.getOrNull() + + /** + * The import, given a [read] that asks the old storage and calls back with evaluateJavascript's answer (null on any + * failure). Runs the read only when there's no snapshot yet; [done] gets the snapshot, or null when the read failed. + */ + fun importOnce(dir: File, nowMs: () -> Long, read: ((String?) -> Unit) -> Unit, done: (Snapshot?) -> Unit) { + if (!needsImport(dir)) { done(load(dir)); return } + read { raw -> + val found = parseAnswer(raw) + done(if (found != null && record(dir, found, nowMs())) load(dir) else null) + } + } +} diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/hive/HiveRules.kt b/android/app/src/main/java/tv/orbit/classic/arcade/hive/HiveRules.kt new file mode 100644 index 00000000..df04e5cf --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/arcade/hive/HiveRules.kt @@ -0,0 +1,228 @@ +package tv.orbit.classic.arcade.hive + +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.min +import kotlin.math.sqrt + +/** + * BumbleHive's rules, ported from assets/orbithive/game.js (the WebView game it replaces) number for number. Everything + * here is plain arithmetic on doubles, as in JavaScript, so the 200 levels come out cell for cell the same; the parity + * test (BumbleHiveParityTest) checks them all against game.js run under Node. + */ +internal object Hive { + const val W = 1280.0 + const val H = 720.0 + const val R = 24.0 + const val D = R * 2 + val RH = R * sqrt(3.0) + const val COLS = 11 + const val MAXROWS = 18 + const val CELLS = COLS * MAXROWS + const val FX = W / 2 - (COLS * D) / 2 + const val FW = COLS * D + const val FX2 = FX + FW + const val TOP0 = 64.0 + const val LAUNCH_X = W / 2 + const val LAUNCH_Y = 632.0 + const val DEADLINE = 592.0 + const val SHOT_SPEED = 1500.0 + const val LEVELS = 200 + const val PER_PAGE = 20 + const val MAX_ANGLE = 1.38 + + /** The six flowers: petal and its darker edge. */ + val PETAL = longArrayOf(0xFFE53935, 0xFF1E66D0, 0xFF2E9D3A, 0xFFF4F4F4, 0xFFF5A623, 0xFF8E44AD) + val DARK = longArrayOf(0xFF9E1B1B, 0xFF123F82, 0xFF1B5E20, 0xFF9E9E9E, 0xFFA35A00, 0xFF4A235A) + val NAMES = arrayOf("red", "blue", "green", "white", "orange", "purple") + + fun cellsIn(r: Int) = if (r % 2 != 0) COLS - 1 else COLS + fun idx(r: Int, c: Int) = r * COLS + c + fun cellX(r: Int, c: Int) = FX + R + c * D + (if (r % 2 != 0) R else 0.0) + fun cellY(r: Int, top: Double) = top + R + r * RH + fun clampAngle(a: Double) = max(-MAX_ANGLE, min(MAX_ANGLE, a)) +} + +/** Normal is the original game exactly. Hard (Paul, 8 November 2026): a quicker ceiling, fewer swaps, colours sooner. */ +internal enum class HiveMode(val title: String, val key: String) { + Normal("Normal", "normal"), Hard("Hard", "hard"); + + val swaps get() = if (this == Hard) 3 else 5 + /** Levels between each new colour (still at most six). */ + val colourEvery get() = if (this == Hard) 10 else 15 +} + +internal class LevelInfo(val colours: Int, val rows: Int, val shape: Int, val panic: Double) + +/** game.js rng(seed): a 32-bit LCG. All the products stay below 2^53, so JavaScript's doubles and these longs agree. */ +internal class HiveRng(seed: Int) { + private var s: Long = ((seed.toLong() * 2654435761L) and 0xFFFFFFFFL).let { if (it == 0L) 1L else it } + fun next(): Double { s = (s * 1664525L + 1013904223L) and 0xFFFFFFFFL; return s / 4294967296.0 } +} + +internal object HiveLevels { + const val SHAPES = 12 + private val HEART = arrayOf("01100110", "11111111", "11111111", "01111110", "00111100", "00011000") + + fun info(n: Int, mode: HiveMode = HiveMode.Normal): LevelInfo { + val colours = min(6, 3 + (n - 1) / mode.colourEvery) + val rows = min(10, 4 + (n - 1) / 8 + (if (n % 3 == 0) 1 else 0)) + val shape = if (n <= 3) 0 else (n * 7) % SHAPES + val normal = max(7.0, 20.0 - ((n - 1) / 120.0) * 13.0) // seconds until the ceiling pushes down + val panic = if (mode == HiveMode.Hard) max(5.0, normal * 0.6) else normal + return LevelInfo(colours, rows, shape, panic) + } + + /** The twelve shapes a level's flowers are laid out in (game.js SHAPES). */ + fun inShape(shape: Int, r: Int, c: Int, n: Int): Boolean = when (shape) { + 0 -> true + 1 -> { val w = Hive.cellsIn(r); c >= r / 2 && c < w - r / 2 } + 2 -> { + val row = HEART[min(r, 5)] + val w = Hive.cellsIn(r) + val x = Math.round(((c + (if (r % 2 != 0) 0.5 else 0.0)) / (w - (if (r % 2 != 0) 0 else 1))) * 7).toInt() + r < 6 && row[x] == '1' + } + 3 -> r % 3 != 2 + 4 -> c % 3 != 1 + 5 -> ((r shr 1) + (c shr 1)) % 2 == 0 + 6 -> c < 3 || c > Hive.cellsIn(r) - 4 || r < 2 + 7 -> { val w = Hive.cellsIn(r); r < 2 || c == 0 || c == w - 1 || r == n - 1 || (r > 3 && abs(c - (w - 1) / 2.0) < 1.6) } + 8 -> abs(c - (Hive.cellsIn(r) - 1) / 2.0) <= min(r, n - 1 - r) + 1 + 9 -> (r + c) % 4 != 3 + 10 -> c < 2 || c > Hive.cellsIn(r) - 3 || (r >= n / 2 - 1 && r <= n / 2) + 11 -> abs(((c + r) % 6) - 3) > 0 + else -> false + } + + /** game.js buildLevel(n), into [grid]. Hard uses the same layout and the same random draws, with more colours sooner. */ + fun build(n: Int, mode: HiveMode, grid: HiveGrid): LevelInfo { + val info = info(n, mode) + val rand = HiveRng(n * 7919 + 13) + grid.clear() + var count = 0 + for (r in 0 until info.rows) { + for (c in 0 until Hive.cellsIn(r)) { + if (!inShape(info.shape, r, c, info.rows)) continue + var col = (rand.next() * info.colours).toInt() + // Clump colours a little so there are matches to find. + if (rand.next() < 0.45) { + val left = if (c > 0) grid[r, c - 1] else -1 + val up = if (r > 0) grid[r - 1, min(c, Hive.cellsIn(r - 1) - 1)] else -1 + if (left >= 0 && rand.next() < 0.6) col = left else if (up >= 0) col = up + } + grid[r, c] = col + count++ + } + } + if (count < 8) for (r in 0 until 3) for (c in 0 until Hive.cellsIn(r)) grid[r, c] = (rand.next() * info.colours).toInt() + // Keep only flowers that hang from the ceiling. + grid.pruneLoose() + return info + } +} + +/** + * The honeycomb: 18 rows of 11 and 10 cells, -1 for empty. Its searches (what hangs from the ceiling, a colour's cluster) + * use buffers made once, so play never allocates. + */ +internal class HiveGrid { + val cells = IntArray(Hive.CELLS) { -1 } + private val seen = BooleanArray(Hive.CELLS) + private val stack = IntArray(Hive.CELLS * 6) + private val nb = IntArray(12) + /** The last cluster found by [cluster], as cell indexes. */ + val found = IntArray(Hive.CELLS) + /** Bumped on every change, so the guide line knows when to look again. */ + var version = 0; private set + + operator fun get(r: Int, c: Int) = cells[Hive.idx(r, c)] + operator fun set(r: Int, c: Int, v: Int) { cells[Hive.idx(r, c)] = v; version++ } + fun clear() { cells.fill(-1); version++ } + fun copyFrom(o: HiveGrid) { o.cells.copyInto(cells); version++ } + + /** game.js neighbours(r, c), in its order, into [out] as (row, col) pairs; returns how many. */ + fun neighbours(r: Int, c: Int, out: IntArray): Int { + var n = 0 + if (r % 2 == 1) { + n = add(out, n, r - 1, c); n = add(out, n, r - 1, c + 1); n = add(out, n, r, c - 1) + n = add(out, n, r, c + 1); n = add(out, n, r + 1, c); n = add(out, n, r + 1, c + 1) + } else { + n = add(out, n, r - 1, c - 1); n = add(out, n, r - 1, c); n = add(out, n, r, c - 1) + n = add(out, n, r, c + 1); n = add(out, n, r + 1, c - 1); n = add(out, n, r + 1, c) + } + return n + } + + private fun add(out: IntArray, n: Int, a: Int, b: Int): Int { + if (a < 0 || a >= Hive.MAXROWS || b < 0 || b >= Hive.cellsIn(a)) return n + out[n * 2] = a; out[n * 2 + 1] = b + return n + 1 + } + + fun supported(r: Int, c: Int): Boolean { + if (r == 0) return true + val n = neighbours(r, c, nb) + for (i in 0 until n) if (get(nb[i * 2], nb[i * 2 + 1]) >= 0) return true + return false + } + + /** game.js attachedSet: marks in [hanging] every flower joined to the top row. */ + fun attached(hanging: BooleanArray = seen): BooleanArray { + hanging.fill(false) + var sp = 0 + for (c in 0 until Hive.cellsIn(0)) if (get(0, c) >= 0) { hanging[Hive.idx(0, c)] = true; stack[sp++] = Hive.idx(0, c) } + while (sp > 0) { + val i = stack[--sp] + val n = neighbours(i / Hive.COLS, i % Hive.COLS, nb) + for (k in 0 until n) { + val j = Hive.idx(nb[k * 2], nb[k * 2 + 1]) + if (!hanging[j] && cells[j] >= 0) { hanging[j] = true; stack[sp++] = j } + } + } + return hanging + } + + /** Removes every flower no longer hanging from the ceiling (used when a level is built). */ + fun pruneLoose() { + val keep = attached() + for (i in 0 until Hive.CELLS) if (cells[i] >= 0 && !keep[i]) cells[i] = -1 + version++ + } + + /** game.js cluster(g, r, c): the same-colour group joined to (r, c), into [found]; returns its size. */ + fun cluster(r: Int, c: Int): Int { + val col = get(r, c) + seen.fill(false) + val start = Hive.idx(r, c) + seen[start] = true + var count = 0; var sp = 0 + found[count++] = start; stack[sp++] = start + while (sp > 0) { + val i = stack[--sp] + val n = neighbours(i / Hive.COLS, i % Hive.COLS, nb) + for (k in 0 until n) { + val j = Hive.idx(nb[k * 2], nb[k * 2 + 1]) + if (!seen[j] && cells[j] == col) { seen[j] = true; found[count++] = j; stack[sp++] = j } + } + } + return count + } + + fun flowerCount(): Int { var n = 0; for (v in cells) if (v >= 0) n++; return n } + + /** game.js coloursLeft: the colours still in the hive, in the order the scan first meets them, into [out]. */ + fun coloursLeft(out: IntArray): Int { + var n = 0 + for (r in 0 until Hive.MAXROWS) for (c in 0 until Hive.cellsIn(r)) { + val v = get(r, c) + if (v < 0) continue + var have = false + for (k in 0 until n) if (out[k] == v) { have = true; break } + if (!have) out[n++] = v + } + return n + } + + fun has(colour: Int): Boolean { for (v in cells) if (v == colour) return true; return false } +} diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/hive/HiveSave.kt b/android/app/src/main/java/tv/orbit/classic/arcade/hive/HiveSave.kt new file mode 100644 index 00000000..e45ff7fa --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/arcade/hive/HiveSave.kt @@ -0,0 +1,150 @@ +package tv.orbit.classic.arcade.hive + +import org.json.JSONObject + +/** + * One mode's level progress: what's unlocked, the stars and best score per level, and the Level Select page. Normal and + * Hard each have one, and neither ever touches the other. + */ +internal class HiveProgress { + var unlocked = 1 + val stars = IntArray(Hive.LEVELS + 1) + val best = IntArray(Hive.LEVELS + 1) + var page = 0 + + fun totalStars(): Int { var n = 0; for (s in stars) n += s; return n } + fun hasProgress() = unlocked > 1 || stars.any { it > 0 } || best.any { it > 0 } + + fun copyFrom(o: HiveProgress) { unlocked = o.unlocked; o.stars.copyInto(stars); o.best.copyInto(best); page = o.page } + fun reset() { unlocked = 1; stars.fill(0); best.fill(0); page = 0 } + + fun encode(): String = JSONObject().put("unlocked", unlocked).put("page", page) + .put("stars", levelMap(stars)).put("best", levelMap(best)).toString() + + companion object { + private fun levelMap(a: IntArray) = JSONObject().also { o -> for (n in 1..Hive.LEVELS) if (a[n] > 0) o.put(n.toString(), a[n]) } + + /** Reads what [encode] wrote, or a save from game.js (the same fields); anything odd is left out rather than failing. */ + fun decode(o: JSONObject?): HiveProgress { + val p = HiveProgress() + if (o == null) return p + p.unlocked = number(o.opt("unlocked"))?.toInt()?.coerceIn(1, Hive.LEVELS) ?: 1 + p.page = number(o.opt("page"))?.toInt()?.coerceIn(0, Hive.LEVELS / Hive.PER_PAGE - 1) ?: 0 + readLevels(o.optJSONObject("stars"), p.stars, 3) + readLevels(o.optJSONObject("best"), p.best, Int.MAX_VALUE) + return p + } + + fun decode(text: String?): HiveProgress = decode(text?.let { runCatching { JSONObject(it) }.getOrNull() }) + + private fun readLevels(o: JSONObject?, into: IntArray, maxValue: Int) { + if (o == null) return + for (k in o.keys()) { + val n = k.toIntOrNull() ?: continue + if (n !in 1..Hive.LEVELS) continue + val v = number(o.opt(k))?.toLong() ?: continue + if (v > 0) into[n] = v.coerceAtMost(maxValue.toLong()).toInt() + } + } + + /** JavaScript's Number(x) for the values a save can hold: numbers, and numbers written as text. */ + fun number(v: Any?): Double? = when (v) { + is Number -> v.toDouble().takeIf { it.isFinite() } + is String -> v.trim().toDoubleOrNull()?.takeIf { it.isFinite() } + else -> null + } + } +} + +/** + * Everything BumbleHive keeps for one profile. Progress is per mode; Honeybombs, the daily spin, the chosen mode and the + * game's own choices (skin, guide line, sound) are the profile's, whichever mode they play. + */ +internal class HiveSaveData { + val normal = HiveProgress() + val hard = HiveProgress() + var bombs = 2 + var lastSpin = "" + var guide = true + var sound = true + var skinOrbit = true + var mode = HiveMode.Normal + /** null until this profile has answered the Household save offer: "copied" or "fresh". */ + var household: String? = null + + fun progress(m: HiveMode) = if (m == HiveMode.Hard) hard else normal +} + +/** The old box-wide save from the WebView game (localStorage 'orbithive-save-v1'), as game.js's save object. */ +internal class LegacyHiveSave(val progress: HiveProgress, val bombs: Int, val lastSpin: String, val guide: Boolean, val sound: Boolean, val skinOrbit: Boolean) { + val hasProgress get() = progress.hasProgress() + + companion object { + /** game.js's own reading: its defaults with the save laid over them. Null when the text isn't a save at all. */ + fun parse(text: String?): LegacyHiveSave? { + if (text.isNullOrBlank()) return null + val o = runCatching { JSONObject(text) }.getOrNull() ?: return null + return LegacyHiveSave(HiveProgress.decode(o), HiveProgress.number(o.opt("bombs"))?.toInt()?.coerceIn(0, 9999) ?: 2, + o.opt("lastSpin") as? String ?: "", o.opt("guide") as? Boolean ?: true, o.opt("sound") as? Boolean ?: true, + (o.opt("skin") as? String ?: "orbit") == "orbit") + } + } +} + +/** Where a profile's BumbleHive lives in its Arcade save (GameRecord level, kept and settings). */ +internal object HiveKeys { + const val NORMAL = "normal" + const val HARD = "hard" + const val BOMBS = "bombs" + const val LAST_SPIN = "lastSpin" + const val MODE = "mode" + const val HOUSEHOLD = "household" + const val GUIDE = "guide" + const val SOUND = "sound" + const val CLASSIC = "classicSkin" +} + +/** + * Reads a profile's BumbleHive from its Arcade save. [level] is cleared by "Reset level progress" (both modes start + * again); [kept] survives it, as game.js kept Honeybombs and choices through a reset; [setting] reads the game settings. + */ +internal fun readHiveSave(level: Map, kept: Map, setting: (String) -> Boolean): HiveSaveData { + val s = HiveSaveData() + s.normal.copyFrom(HiveProgress.decode(level[HiveKeys.NORMAL])) + s.hard.copyFrom(HiveProgress.decode(level[HiveKeys.HARD])) + s.bombs = kept[HiveKeys.BOMBS]?.toIntOrNull()?.coerceAtLeast(0) ?: 2 + s.lastSpin = kept[HiveKeys.LAST_SPIN] ?: "" + s.mode = if (kept[HiveKeys.MODE] == HiveMode.Hard.key) HiveMode.Hard else HiveMode.Normal + s.household = kept[HiveKeys.HOUSEHOLD] + s.guide = setting(HiveKeys.GUIDE) + s.sound = setting(HiveKeys.SOUND) + s.skinOrbit = !setting(HiveKeys.CLASSIC) + return s +} + +/** + * Continue from the Household save: a copy of it becomes this profile's Normal progress. The snapshot itself is never + * changed, and Hard is never touched (it starts at level 1). A profile that has already played a little (the offer can + * wait until it's answered) keeps the best of both: the furthest level, and each level's stars and best score. Its + * Honeybombs are the larger number. A profile that hasn't played takes the old save's choices (skin, guide, sound) and + * daily spin too, as game.js's copy did. + */ +internal fun adoptHousehold(save: HiveSaveData, legacy: LegacyHiveSave) { + val fresh = !save.normal.hasProgress() + val p = save.normal; val l = legacy.progress + p.unlocked = maxOf(p.unlocked, l.unlocked) + for (n in 1..Hive.LEVELS) { p.stars[n] = maxOf(p.stars[n], l.stars[n]); p.best[n] = maxOf(p.best[n], l.best[n]) } + if (fresh) p.page = l.page + save.bombs = maxOf(save.bombs, legacy.bombs) + if (fresh) { + save.lastSpin = legacy.lastSpin + save.guide = legacy.guide + save.sound = legacy.sound + save.skinOrbit = legacy.skinOrbit + } + save.household = "copied" +} + +/** Whether to ask this profile about the Household save: there's one with progress, and they haven't answered yet. */ +internal fun offerHousehold(save: HiveSaveData, legacy: LegacyHiveSave?) = + save.household == null && legacy != null && legacy.hasProgress diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/hive/HiveSim.kt b/android/app/src/main/java/tv/orbit/classic/arcade/hive/HiveSim.kt new file mode 100644 index 00000000..d507fd0f --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/arcade/hive/HiveSim.kt @@ -0,0 +1,669 @@ +package tv.orbit.classic.arcade.hive + +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.ceil +import kotlin.math.floor +import kotlin.math.max +import kotlin.math.min + +/** BumbleHive's sounds: the same beeps game.js made, rendered once as short tones ([HiveTones]). */ +internal object Sfx { + const val SHOOT = 0 + const val STICK = 1 + /** POP1 + n - 1 for n flowers, up to five notes. */ + const val POP1 = 2 + const val DROP = 7 + const val MOVE = 8 + const val LID = 9 + const val WIN = 10 + const val LOSE = 11 + const val BOOM = 12 + const val WALL = 13 + const val TICK = 14 + const val COUNT = 15 +} + +/** game.js's screens. Pause, Win and Lose are drawn by the Arcade's shared cards over the frozen hive. */ +internal enum class HiveScreen { Title, Levels, Help, Daily, Household, Play, Pause, Win, Lose } + +/** What a menu button does. */ +internal enum class HiveAct { Play, Mode, Levels, Help, Daily, Level, PagePrev, PageNext, Menu, Skin, Guide, Sound, HelpBack, Spin, NotToday, Collect, Continue, Fresh } + +/** A menu button, in game.js's 1280×720 units. */ +internal class HiveButton(val label: String, val x: Double, val y: Double, val w: Double, val h: Double, val act: HiveAct, + val hex: Boolean = false, val round: Boolean = false, val glow: Boolean = false, val level: Int = 0) + +/** The remote, as game.js's keyAction saw it. */ +internal enum class HiveKey { Left, Right, Up, Down, Ok, Back, Pause } + +/** What the game tells the screen: sounds, saving, runs for High Scores, leaving. */ +internal interface HiveHost { + fun sound(id: Int) {} + fun persist() {} + fun runStart(level: Int) {} + fun runEnd(level: Int, score: Int, finished: Boolean) {} + fun leave() {} + /** The day as game.js's today(): the UTC date, yyyy-mm-dd. */ + fun today(): String = java.time.LocalDate.now(java.time.ZoneOffset.UTC).toString() +} + +/** The effects game.js drew: a burst, a falling flower, a bonus, the Honeybomb's ring and the ceiling's shake. */ +internal object Fx { + const val POP = 0 + const val FALL = 1 + const val TEXT = 2 + const val RING = 3 + const val SHAKE = 4 + const val CAP = 640 +} + +/** + * BumbleHive, the whole game with no screen in it: game.js's state and rules, its menus and focus, its Daily Bonus and + * its saves, ported line for line. Time comes in through [update] in fixed steps; nothing here allocates once a level is + * under way (effects, shot and searches all live in arrays made up front). + */ +internal class HiveSim(val save: HiveSaveData, private val host: HiveHost, seed: Long = System.nanoTime(), + /** The Household save on offer (game.js's household screen), if any. */ + var legacy: LegacyHiveSave? = null) { + private val random = java.util.Random(seed) + /** Reduce motion: no shake, no bobbing or pulsing, and the daily wheel stops on its result at once. */ + var calm = false + + // ---------- the level ---------- + var mode = save.mode; private set + var level = 1; private set + val grid = HiveGrid() + var info = HiveLevels.info(1); private set + var top = Hive.TOP0; private set + var angle = 0.0 + var current = 0 + var next = 0 + var score = 0; private set + var panic = 0.0; private set + var drops = 0; private set + var swaps = 5; private set + var bombArmed = false + var time = 0.0; private set + var bannerT = 0.0; private set + /** The banner: a level number, or [BANNER_NO_BOMBS]. */ + var banner = 1; private set + var stars = 0; private set + + // ---------- the shot ---------- + var shotOn = false; private set + var shotX = 0.0; private set + var shotY = 0.0; private set + var shotVx = 0.0; private set + var shotVy = 0.0; private set + var shotColour = 0; private set + var shotBomb = false; private set + + // ---------- effects, oldest first ---------- + val fxType = IntArray(Fx.CAP) + val fxX = DoubleArray(Fx.CAP) + val fxY = DoubleArray(Fx.CAP) + val fxVx = DoubleArray(Fx.CAP) + val fxVy = DoubleArray(Fx.CAP) + val fxRot = DoubleArray(Fx.CAP) + val fxVr = DoubleArray(Fx.CAP) + /** A flower's colour, or a bonus's points. */ + val fxColour = IntArray(Fx.CAP) + val fxT = DoubleArray(Fx.CAP) + var fxCount = 0; private set + + // ---------- menus ---------- + var screen = HiveScreen.Title; private set + var focus = 0; private set + var buttons: List = emptyList(); private set + var wheelAngle = 0.0; private set + var wheelSpeed = 0.0; private set + var wheelPrize = 0; private set + var wheelSpun = false; private set + var runOpen = false; private set + private var heldLeft = false + private var heldRight = false + private var heldTime = 0.0 + private val colours = IntArray(6) + + val progress get() = save.progress(mode) + + init { + info = HiveLevels.build(1, mode, grid) + setScreen(HiveScreen.Title) + } + + // ---------- runs ---------- + + private fun endRun(finished: Boolean) { if (!runOpen) return; runOpen = false; host.runEnd(level, score, finished) } + + /** The player left mid-level: the run is saved as left, not finished. */ + fun closeRun() = endRun(false) + + fun startLevel(n: Int) { + endRun(false) + info = HiveLevels.build(n, mode, grid) + level = n; top = Hive.TOP0; angle = 0.0; shotOn = false; fxCount = 0 + score = 0; panic = 0.0; drops = 0; swaps = mode.swaps; bombArmed = false; time = 0.0; banner = n; bannerT = 1.6 + current = randomColour() + next = randomColour() + setScreen(HiveScreen.Play) + runOpen = true + host.runStart(n) + } + + private fun randomColour(): Int { + val n = grid.coloursLeft(colours) + return if (n > 0) colours[(random.nextDouble() * n).toInt()] else (random.nextDouble() * 3).toInt() + } + + // ---------- shooting ---------- + + fun fire() { + if (shotOn || screen != HiveScreen.Play) return + val a = angle + shotOn = true; shotX = Hive.LAUNCH_X; shotY = Hive.LAUNCH_Y - 28 + shotVx = StrictMath.sin(a) * Hive.SHOT_SPEED; shotVy = -StrictMath.cos(a) * Hive.SHOT_SPEED + shotColour = current; shotBomb = bombArmed + if (bombArmed) { bombArmed = false; save.bombs = max(0, save.bombs - 1); host.persist() } + current = next + next = randomColour() + host.sound(Sfx.SHOOT) + } + + fun swap() { + if (screen != HiveScreen.Play || shotOn || swaps <= 0) return + val t = current; current = next; next = t + swaps-- + host.sound(Sfx.MOVE) + } + + fun toggleBomb() { + if (screen != HiveScreen.Play || shotOn) return + if (!bombArmed && save.bombs <= 0) { banner = BANNER_NO_BOMBS; bannerT = 1.2; return } + bombArmed = !bombArmed + host.sound(Sfx.MOVE) + } + + private fun hitsFlower(x: Double, y: Double): Boolean { + val hitR = (Hive.D - 6) * (Hive.D - 6) + for (r in 0 until Hive.MAXROWS) { + val cy = Hive.cellY(r, top) + for (c in 0 until Hive.cellsIn(r)) { + if (grid[r, c] < 0) continue + val dx = Hive.cellX(r, c) - x + val dy = cy - y + if (dx * dx + dy * dy < hitR) return true + } + } + return false + } + + private fun updateShot(dt: Double) { + if (!shotOn) return + var dist = Hive.SHOT_SPEED * dt + while (dist > 0 && shotOn) { + val step = min(dist, 6.0) + dist -= step + val k = step / Hive.SHOT_SPEED + shotX += shotVx * k + shotY += shotVy * k + if (shotX < Hive.FX + Hive.R) { shotX = Hive.FX + Hive.R + (Hive.FX + Hive.R - shotX); shotVx = abs(shotVx); host.sound(Sfx.WALL) } + if (shotX > Hive.FX2 - Hive.R) { shotX = Hive.FX2 - Hive.R - (shotX - (Hive.FX2 - Hive.R)); shotVx = -abs(shotVx); host.sound(Sfx.WALL) } + if (shotY - Hive.R <= top) { land(); return } + if (hitsFlower(shotX, shotY)) { land(); return } + } + } + + private fun land() { + shotOn = false + // Choose the nearest free cell that touches the ceiling or another flower. + var bestR = -1 + var bestC = -1 + var bestD = Double.POSITIVE_INFINITY + val approxR = Math.round((shotY - top - Hive.R) / Hive.RH).toInt() + for (r in max(0, approxR - 1)..min(Hive.MAXROWS - 1, approxR + 1)) { + for (c in 0 until Hive.cellsIn(r)) { + if (grid[r, c] >= 0) continue + if (!grid.supported(r, c)) continue + val dx = Hive.cellX(r, c) - shotX + val dy = Hive.cellY(r, top) - shotY + val d = dx * dx + dy * dy + if (d < bestD) { bestD = d; bestR = r; bestC = c } + } + } + if (bestR < 0) { bestR = 0; bestC = max(0, min(Hive.COLS - 1, Math.round((shotX - Hive.FX - Hive.R) / Hive.D).toInt())) } + val r = bestR + val c = bestC + grid[r, c] = shotColour + host.sound(Sfx.STICK) + + var popped = 0 + val cells = grid.found + if (shotBomb) { + val cx = Hive.cellX(r, c) + val cy = Hive.cellY(r, top) + val reach = (Hive.D * 2.1) * (Hive.D * 2.1) + for (a in 0 until Hive.MAXROWS) for (b in 0 until Hive.cellsIn(a)) { + if (grid[a, b] < 0) continue + val dx = Hive.cellX(a, b) - cx + val dy = Hive.cellY(a, top) - cy + if (dx * dx + dy * dy <= reach) cells[popped++] = Hive.idx(a, b) + } + host.sound(Sfx.BOOM) + addFx(Fx.RING, cx, cy, 0) + } else { + val group = grid.cluster(r, c) + if (group >= 3) popped = group + } + if (popped > 0) { + for (i in 0 until popped) { + val a = cells[i] / Hive.COLS + val b = cells[i] % Hive.COLS + addFx(Fx.POP, Hive.cellX(a, b), Hive.cellY(a, top), grid[a, b]) + grid[a, b] = -1 + } + score += popped * 10 + host.sound(Sfx.POP1 + min(popped, 5) - 1) + // Anything no longer hanging from the ceiling falls away. + val keep = grid.attached() + var fallen = 0 + for (a in 0 until Hive.MAXROWS) for (b in 0 until Hive.cellsIn(a)) { + if (grid[a, b] >= 0 && !keep[Hive.idx(a, b)]) { + val i = addFx(Fx.FALL, Hive.cellX(a, b), Hive.cellY(a, top), grid[a, b]) + val vx = (random.nextDouble() - 0.5) * 160 + val vy = -120 - random.nextDouble() * 120 + val vr = (random.nextDouble() - 0.5) * 8 + if (i >= 0) { fxVx[i] = vx; fxVy[i] = vy; fxVr[i] = vr } + grid[a, b] = -1 + fallen++ + } + } + if (fallen > 0) { + val bonus = 20 * fallen * fallen + score += bonus + addFx(Fx.TEXT, shotX, shotY, bonus) + host.sound(Sfx.DROP) + } + } + if (grid.flowerCount() == 0) { win(); return } + checkBreach() + if (!grid.has(current)) current = randomColour() + if (!grid.has(next)) next = randomColour() + } + + private fun checkBreach() { + var breached = false + for (r in 0 until Hive.MAXROWS) for (c in 0 until Hive.cellsIn(r)) { + if (grid[r, c] >= 0 && Hive.cellY(r, top) + Hive.R > Hive.DEADLINE) breached = true + } + if (breached) lose() + } + + /** Three stars when the ceiling dropped at most once, two for up to three, else one. */ + fun starsFor(drops: Int) = if (drops <= 1) 3 else if (drops <= 3) 2 else 1 + + private fun win() { + score += 1000 + Math.round((1 - panic) * 500).toInt() + stars = starsFor(drops) + val p = progress + p.stars[level] = max(p.stars[level], stars) + p.best[level] = max(p.best[level], score) + p.unlocked = max(p.unlocked, min(Hive.LEVELS, level + 1)) + host.persist() + host.sound(Sfx.WIN) + endRun(true) + setScreen(HiveScreen.Win) + } + + private fun lose() { + host.sound(Sfx.LOSE) + endRun(true) + setScreen(HiveScreen.Lose) + } + + // ---------- effects ---------- + + /** Adds an effect at the end (oldest first, as drawn); its pool place, or -1 when it's full (it's only for show). */ + private fun addFx(type: Int, x: Double, y: Double, colour: Int): Int { + if (fxCount >= Fx.CAP) return -1 + val i = fxCount++ + fxType[i] = type; fxX[i] = x; fxY[i] = y; fxColour[i] = colour; fxT[i] = 0.0 + fxVx[i] = 0.0; fxVy[i] = 0.0; fxRot[i] = 0.0; fxVr[i] = 0.0 + return i + } + + private fun lifeOf(type: Int): Double = when (type) { + Fx.TEXT -> 0.9 + Fx.RING -> 0.5 + Fx.SHAKE -> 0.3 + else -> 0.35 + } + + private fun updateEffects(dt: Double) { + var w = 0 + for (i in 0 until fxCount) { + fxT[i] += dt + val type = fxType[i] + if (type == Fx.FALL) { + fxVy[i] += 1400 * dt + fxX[i] += fxVx[i] * dt + fxY[i] += fxVy[i] * dt + fxRot[i] += fxVr[i] * dt + } + val keep = if (type == Fx.FALL) fxY[i] < Hive.H + 60 else fxT[i] < lifeOf(type) + if (!keep) continue + if (w != i) { + fxType[w] = type; fxX[w] = fxX[i]; fxY[w] = fxY[i]; fxVx[w] = fxVx[i]; fxVy[w] = fxVy[i] + fxRot[w] = fxRot[i]; fxVr[w] = fxVr[i]; fxColour[w] = fxColour[i]; fxT[w] = fxT[i] + } + w++ + } + fxCount = w + } + + /** The ceiling's shake right now, for drawing: its time, or -1. */ + fun shakeT(): Double { + for (i in 0 until fxCount) if (fxType[i] == Fx.SHAKE) return fxT[i] + return -1.0 + } + + // ---------- time ---------- + + /** game.js update(dt). */ + fun update(dt: Double) { + time += dt + if (screen == HiveScreen.Daily) updateWheel(dt) + if (screen != HiveScreen.Play) { updateEffects(dt); return } + // Aim with weight: slow at first, faster the longer the button is held. + val dir = (if (heldRight) 1 else 0) - (if (heldLeft) 1 else 0) + if (dir != 0) { + heldTime += dt + val speed = 0.45 + min(1.0, heldTime / 0.7) * 1.35 + angle = Hive.clampAngle(angle + dir * speed * dt) + } else heldTime = 0.0 + + updateShot(dt) + if (screen != HiveScreen.Play) return + + // Panic bar: when it fills, the ceiling pushes down one row. + panic += dt / info.panic + if (panic >= 1) { + panic = 0.0 + top += Hive.RH + drops++ + addFx(Fx.SHAKE, 0.0, 0.0, 0) + host.sound(Sfx.LID) + checkBreach() + } + if (bannerT > 0) bannerT -= dt + updateEffects(dt) + } + + // ---------- the guide line ---------- + + /** game.js guidePoints(): the aim's path, bounces and all, into [out] as x, y pairs; returns how many points. */ + fun guidePoints(out: DoubleArray): Int { + val cap = out.size / 2 + var x = Hive.LAUNCH_X + var y = Hive.LAUNCH_Y - 28 + out[0] = x; out[1] = y + var n = 1 + var vx = StrictMath.sin(angle) + val vy = -StrictMath.cos(angle) + for (i in 0 until 700) { + x += vx * 4 + y += vy * 4 + if (x < Hive.FX + Hive.R) { x = Hive.FX + Hive.R; vx = -vx; if (n < cap - 1) { out[n * 2] = x; out[n * 2 + 1] = y; n++ } } + if (x > Hive.FX2 - Hive.R) { x = Hive.FX2 - Hive.R; vx = -vx; if (n < cap - 1) { out[n * 2] = x; out[n * 2 + 1] = y; n++ } } + if (y - Hive.R <= top) break + if (hitsFlower(x, y)) break + } + out[n * 2] = x; out[n * 2 + 1] = y + return n + 1 + } + + // ---------- menus ---------- + + private fun titleButtons(): List { + val list = ArrayList(5) + list.add(HiveButton("PLAY", 520.0, 330.0, 240.0, 64.0, HiveAct.Play)) + // Hard mode (Paul, 8 November 2026): chosen here, beside Play; each mode keeps its own levels. + list.add(HiveButton("MODE: " + mode.title.uppercase(), 790.0, 330.0, 240.0, 64.0, HiveAct.Mode)) + list.add(HiveButton("LEVELS", 520.0, 410.0, 240.0, 64.0, HiveAct.Levels)) + list.add(HiveButton("HELP & SETTINGS", 520.0, 490.0, 240.0, 64.0, HiveAct.Help)) + if (save.lastSpin != host.today()) list.add(HiveButton("DAILY BONUS", 520.0, 570.0, 240.0, 64.0, HiveAct.Daily, glow = true)) + return list + } + + private fun levelButtons(): List { + val list = ArrayList(Hive.PER_PAGE + 3) + val page = progress.page + for (i in 0 until Hive.PER_PAGE) { + val n = page * Hive.PER_PAGE + i + 1 + if (n > Hive.LEVELS) break + val col = i % 5 + val row = i / 5 + val x = 400.0 + col * 110 + (if (row % 2 != 0) 55 else 0) - 27 + list.add(HiveButton(n.toString(), x, 170.0 + row * 100, 100.0, 92.0, HiveAct.Level, hex = true, level = n)) + } + list.add(HiveButton("◀", 260.0, 330.0, 80.0, 80.0, HiveAct.PagePrev, round = true)) + list.add(HiveButton("▶", 940.0, 330.0, 80.0, 80.0, HiveAct.PageNext, round = true)) + list.add(HiveButton("BACK", 540.0, 600.0, 200.0, 56.0, HiveAct.Menu)) + return list + } + + private fun helpButtons(): List = listOf( + HiveButton(if (save.skinOrbit) "SKIN: ORBIT" else "SKIN: CLASSIC", 210.0, 560.0, 260.0, 56.0, HiveAct.Skin), + HiveButton(if (save.guide) "GUIDE LINE: ON" else "GUIDE LINE: OFF", 510.0, 560.0, 260.0, 56.0, HiveAct.Guide), + HiveButton(if (save.sound) "SOUND: ON" else "SOUND: OFF", 810.0, 560.0, 260.0, 56.0, HiveAct.Sound), + HiveButton("BACK", 540.0, 632.0, 200.0, 56.0, HiveAct.HelpBack)) + + /** Bumble's Daily Bonus: free, once a day, and "Not today" keeps today's spin for later. */ + private fun dailyButtons(): List = when { + wheelSpun -> listOf(HiveButton("COLLECT", 520.0, 610.0, 240.0, 60.0, HiveAct.Collect)) + wheelSpeed > 0 -> emptyList() + else -> listOf(HiveButton("SPIN", 390.0, 610.0, 240.0, 60.0, HiveAct.Spin), HiveButton("NOT TODAY", 650.0, 610.0, 240.0, 60.0, HiveAct.NotToday)) + } + + private fun buttonsFor(s: HiveScreen): List = when (s) { + HiveScreen.Title -> titleButtons() + HiveScreen.Levels -> levelButtons() + HiveScreen.Help -> helpButtons() + HiveScreen.Daily -> dailyButtons() + HiveScreen.Household -> listOf(HiveButton("CONTINUE FROM IT", 330.0, 520.0, 300.0, 64.0, HiveAct.Continue), HiveButton("START FRESH", 650.0, 520.0, 300.0, 64.0, HiveAct.Fresh)) + else -> emptyList() + } + + private fun refreshButtons() { + buttons = buttonsFor(screen) + focus = min(focus, max(0, buttons.size - 1)) + } + + fun setScreen(to: HiveScreen) { + // Leaving a level for the menus ends its run. + if (runOpen && (to == HiveScreen.Title || to == HiveScreen.Levels)) endRun(false) + // Until it's answered, the Household question comes before the title (it may have arrived after the game opened). + val s = if (to == HiveScreen.Title && offerHousehold(save, legacy)) HiveScreen.Household else to + screen = s + buttons = buttonsFor(s) + focus = 0 + if (s == HiveScreen.Levels) { + val want = min(progress.unlocked, Hive.LEVELS) + val i = buttons.indexOfFirst { it.level == want } + if (i >= 0) focus = i else { + progress.page = (want - 1) / Hive.PER_PAGE + buttons = buttonsFor(s) + focus = max(0, buttons.indexOfFirst { it.level == want }) + } + } + } + + private fun moveFocus(dx: Int, dy: Int) { + if (buttons.isEmpty()) return + val cur = buttons[focus] + val cx = cur.x + cur.w / 2 + val cy = cur.y + cur.h / 2 + var best = -1 + var bestScore = Double.POSITIVE_INFINITY + for (i in buttons.indices) { + if (i == focus) continue + val b = buttons[i] + val bx = b.x + b.w / 2 - cx + val by = b.y + b.h / 2 - cy + val along = bx * dx + by * dy + if (along <= 4) continue + val across = abs(bx * dy - by * dx) + val score = along + across * 2.2 + if (score < bestScore) { bestScore = score; best = i } + } + if (best >= 0) { focus = best; host.sound(Sfx.MOVE) } + } + + /** Presses the focused button. */ + fun press() { buttons.getOrNull(focus)?.let { act(it) } } + + fun act(b: HiveButton) { + when (b.act) { + HiveAct.Play -> startLevel(min(progress.unlocked, Hive.LEVELS)) + HiveAct.Mode -> { + mode = if (mode == HiveMode.Normal) HiveMode.Hard else HiveMode.Normal + save.mode = mode + host.persist() + refreshButtons() + } + HiveAct.Levels -> setScreen(HiveScreen.Levels) + HiveAct.Help -> setScreen(HiveScreen.Help) + HiveAct.Daily -> { wheelSpeed = 0.0; wheelPrize = 0; wheelSpun = false; setScreen(HiveScreen.Daily) } + HiveAct.Level -> if (b.level <= progress.unlocked) startLevel(b.level) else host.sound(Sfx.LOSE) + HiveAct.PagePrev -> { progress.page = max(0, progress.page - 1); host.persist(); refreshButtons() } + HiveAct.PageNext -> { + progress.page = min(ceil(Hive.LEVELS / Hive.PER_PAGE.toDouble()).toInt() - 1, progress.page + 1) + host.persist() + refreshButtons() + } + HiveAct.Menu, HiveAct.NotToday, HiveAct.Collect, HiveAct.HelpBack -> setScreen(HiveScreen.Title) + HiveAct.Skin -> { save.skinOrbit = !save.skinOrbit; host.persist(); refreshButtons() } + HiveAct.Guide -> { save.guide = !save.guide; host.persist(); refreshButtons() } + HiveAct.Sound -> { save.sound = !save.sound; host.persist(); refreshButtons() } + HiveAct.Spin -> spinWheel() + HiveAct.Continue -> { + val l = legacy + if (l != null) adoptHousehold(save, l) + host.persist() + setScreen(HiveScreen.Title) + } + HiveAct.Fresh -> { save.household = "fresh"; host.persist(); setScreen(HiveScreen.Title) } + } + } + + // ---------- the result cards (drawn by the Arcade, acting here) ---------- + + fun nextLevel() = startLevel(min(Hive.LEVELS, level + 1)) + fun replay() = startLevel(level) + fun toLevels() = setScreen(HiveScreen.Levels) + fun toMenu() = setScreen(HiveScreen.Title) + + // ---------- pause ---------- + + fun pause() { if (screen == HiveScreen.Play) { releaseKeys(); setScreen(HiveScreen.Pause) } } + fun resume() { if (screen == HiveScreen.Pause) setScreen(HiveScreen.Play) } + + // ---------- Bumble's Daily Bonus ---------- + + private fun spinWheel() { + if (wheelSpeed > 0 || wheelSpun) return + host.sound(Sfx.SHOOT) + // Reduce motion: no spinning, the wheel simply shows where it stopped. + if (calm) { wheelAngle += random.nextDouble() * PI * 2; finishSpin(); return } + wheelSpeed = 14 + random.nextDouble() * 6 + refreshButtons() + } + + private fun updateWheel(dt: Double) { + if (wheelSpeed <= 0) return + wheelAngle += wheelSpeed * dt + wheelSpeed = max(0.0, wheelSpeed - 6 * dt) + val now = floor(wheelAngle * 8 / (PI * 2)) + val before = floor((wheelAngle - wheelSpeed * dt) * 8 / (PI * 2)) + if (now != before) host.sound(Sfx.TICK) + if (wheelSpeed == 0.0) finishSpin() + } + + private fun finishSpin() { + val seg = PRIZES.size + // The pointer sits at the top of the wheel; find which segment is under it. + val a = (((-PI / 2 - wheelAngle) % (PI * 2)) + PI * 2) % (PI * 2) + val i = floor(a / ((PI * 2) / seg)).toInt() % seg + wheelPrize = PRIZES[i] + wheelSpun = true + save.bombs += wheelPrize + save.lastSpin = host.today() + host.persist() + host.sound(Sfx.WIN) + refreshButtons() + } + + // ---------- the remote ---------- + + /** game.js's keydown and keyup. [repeat] is the remote's own repeat of a held key. */ + fun key(k: HiveKey, down: Boolean, repeat: Boolean) { + if (!down) { + if (k == HiveKey.Left) heldLeft = false + if (k == HiveKey.Right) heldRight = false + return + } + if (k == HiveKey.Pause) { + if (screen == HiveScreen.Play) pause() else if (screen == HiveScreen.Pause) resume() + return + } + if (screen == HiveScreen.Play && (k == HiveKey.Left || k == HiveKey.Right)) { + val held = if (k == HiveKey.Left) heldLeft else heldRight + if (!held) { + if (k == HiveKey.Left) heldLeft = true else heldRight = true + heldTime = 0.0 + angle += (if (k == HiveKey.Left) -1 else 1) * 0.012 + } + return + } + if (repeat && k == HiveKey.Ok) return + action(k) + } + + /** game.js onAction. Back on the title (or the Household question) leaves the game. */ + fun action(k: HiveKey) { + if (screen == HiveScreen.Play) { + when (k) { + HiveKey.Ok -> fire() + HiveKey.Down -> swap() + HiveKey.Up -> toggleBomb() + HiveKey.Back -> pause() + else -> {} + } + return + } + when (k) { + HiveKey.Left -> moveFocus(-1, 0) + HiveKey.Right -> moveFocus(1, 0) + HiveKey.Up -> moveFocus(0, -1) + HiveKey.Down -> moveFocus(0, 1) + HiveKey.Ok -> press() + HiveKey.Back -> when (screen) { + HiveScreen.Pause -> resume() + HiveScreen.Help, HiveScreen.Levels, HiveScreen.Daily -> setScreen(HiveScreen.Title) + HiveScreen.Household, HiveScreen.Title -> host.leave() + HiveScreen.Win, HiveScreen.Lose -> setScreen(HiveScreen.Levels) + else -> {} + } + else -> {} + } + } + + /** The window lost the remote: nothing stays held. */ + fun releaseKeys() { heldLeft = false; heldRight = false } + + companion object { + val PRIZES = intArrayOf(1, 2, 1, 3, 1, 2, 1, 5) + const val BANNER_NO_BOMBS = -1 + } +} diff --git a/android/app/src/main/java/tv/orbit/classic/arcade/hive/HiveTones.kt b/android/app/src/main/java/tv/orbit/classic/arcade/hive/HiveTones.kt new file mode 100644 index 00000000..353eb898 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/arcade/hive/HiveTones.kt @@ -0,0 +1,91 @@ +package tv.orbit.classic.arcade.hive + +import java.io.File +import kotlin.math.PI +import kotlin.math.floor +import kotlin.math.max +import kotlin.math.pow +import kotlin.math.sin + +/** + * game.js's beeps (Web Audio oscillators with a falling gain and an optional slide), rendered once into short WAV files so + * they play through the Arcade's one SoundPool, under its quiet ceiling, like every other game's cues. Each is the same + * note, length, wave, level and slide as before; the notes game.js spaced out with setTimeout are mixed into one file. + */ +internal object HiveTones { + const val RATE = 22050 + + enum class Wave { Sine, Triangle, Square, Sawtooth } + + /** beep(freq, dur, type, vol, slide), starting [at] seconds into the sound. */ + class Beep(val at: Double, val freq: Double, val dur: Double, val wave: Wave, val vol: Double, val slide: Double = 0.0) + + /** game.js's sfx table, by [Sfx] id. */ + fun beeps(id: Int): List = when (id) { + Sfx.SHOOT -> listOf(Beep(0.0, 520.0, 0.12, Wave.Triangle, 0.06, 300.0)) + Sfx.STICK -> listOf(Beep(0.0, 220.0, 0.08, Wave.Sine, 0.06)) + in Sfx.POP1 until Sfx.POP1 + 5 -> (0..id - Sfx.POP1).map { i -> Beep(i * 0.045, 600.0 + i * 120, 0.1, Wave.Sine, 0.05) } + Sfx.DROP -> listOf(Beep(0.0, 400.0, 0.35, Wave.Triangle, 0.05, -300.0)) + Sfx.MOVE -> listOf(Beep(0.0, 880.0, 0.04, Wave.Square, 0.02)) + Sfx.LID -> listOf(Beep(0.0, 110.0, 0.4, Wave.Sawtooth, 0.05, -40.0)) + Sfx.WIN -> listOf(523.0, 659.0, 784.0, 1047.0).mapIndexed { i, f -> Beep(i * 0.12, f, 0.18, Wave.Triangle, 0.06) } + Sfx.LOSE -> listOf(392.0, 330.0, 262.0, 196.0).mapIndexed { i, f -> Beep(i * 0.15, f, 0.22, Wave.Sawtooth, 0.04) } + Sfx.BOOM -> listOf(Beep(0.0, 90.0, 0.5, Wave.Sawtooth, 0.09, -60.0)) + Sfx.WALL -> listOf(Beep(0.0, 300.0, 0.03, Wave.Square, 0.02)) + Sfx.TICK -> listOf(Beep(0.0, 1200.0, 0.02, Wave.Square, 0.02)) + else -> emptyList() + } + + private fun wave(w: Wave, phase: Double): Double { + val p = phase - floor(phase) + return when (w) { + Wave.Sine -> sin(2 * PI * p) + Wave.Square -> if (p < 0.5) 1.0 else -1.0 + Wave.Sawtooth -> 2 * p - 1 + Wave.Triangle -> 1 - 4 * kotlin.math.abs(p - 0.5) + } + } + + /** The sound as samples from -1 to 1: each beep's gain falls exponentially to 0.0001 over its length, as in game.js. */ + fun render(beeps: List): FloatArray { + val len = beeps.maxOfOrNull { it.at + it.dur } ?: 0.0 + val out = FloatArray(max(1, (len * RATE).toInt() + 1)) + for (b in beeps) { + val start = (b.at * RATE).toInt() + val n = (b.dur * RATE).toInt() + val end = max(40.0, b.freq + b.slide) + var phase = 0.0 + for (i in 0 until n) { + val k = i / n.toDouble() + val f = if (b.slide != 0.0) b.freq * (end / b.freq).pow(k) else b.freq + val gain = b.vol * (0.0001 / b.vol).pow(k) + val j = start + i + if (j < out.size) out[j] += (wave(b.wave, phase) * gain).toFloat() + phase += f / RATE + } + } + for (i in out.indices) out[i] = out[i].coerceIn(-1f, 1f) + return out + } + + /** 16-bit mono PCM WAV. */ + fun wav(samples: FloatArray): ByteArray { + val data = samples.size * 2 + val b = java.nio.ByteBuffer.allocate(44 + data).order(java.nio.ByteOrder.LITTLE_ENDIAN) + b.put("RIFF".toByteArray()).putInt(36 + data).put("WAVE".toByteArray()) + b.put("fmt ".toByteArray()).putInt(16).putShort(1).putShort(1).putInt(RATE).putInt(RATE * 2).putShort(2).putShort(16) + b.put("data".toByteArray()).putInt(data) + for (s in samples) b.putShort((s * 32767).toInt().toShort()) + return b.array() + } + + /** Writes every tone into [dir] once (they never change) and returns their files by [Sfx] id. */ + fun files(dir: File): Array { + dir.mkdirs() + return Array(Sfx.COUNT) { id -> + val f = File(dir, "hive-tone-v1-$id.wav") + if (!f.isFile || f.length() < 44) runCatching { val tmp = File(dir, f.name + ".tmp"); tmp.writeBytes(wav(render(beeps(id)))); tmp.renameTo(f) } + f + } + } +} diff --git a/android/app/src/test/java/tv/orbit/classic/arcade/ArcadeSessionTest.kt b/android/app/src/test/java/tv/orbit/classic/arcade/ArcadeSessionTest.kt index 86c81576..d6c6260e 100644 --- a/android/app/src/test/java/tv/orbit/classic/arcade/ArcadeSessionTest.kt +++ b/android/app/src/test/java/tv/orbit/classic/arcade/ArcadeSessionTest.kt @@ -79,11 +79,10 @@ class ArcadeSessionTest { // Restart level only inside a game. assertFalse(resetAllowed(ResetAction.RestartLevel, snake, "kids", "kids", inGame = false)) assertTrue(resetAllowed(ResetAction.RestartLevel, snake, "kids", "kids", inGame = true)) - // Level progress only where a game keeps it; BumbleHive's only once its saves are per profile. + // Level progress only where a game keeps it; BumbleHive's too, now its saves are per profile (native, 8 Nov). assertFalse(resetAllowed(ResetAction.ResetLevelProgress, snake, "p", "p", false)) assertTrue(resetAllowed(ResetAction.ResetLevelProgress, sky, "p", "p", false)) - assertFalse(resetAllowed(ResetAction.ResetLevelProgress, hive, "p", "p", false, hiveProfileSaves = false)) - assertTrue(resetAllowed(ResetAction.ResetLevelProgress, hive, "p", "p", false, hiveProfileSaves = true)) + assertTrue(resetAllowed(ResetAction.ResetLevelProgress, hive, "p", "p", false)) // A coming-soon card has nothing to clear. assertFalse(resetAllowed(ResetAction.ClearHighScores, ArcadeGames.ChannelChaos, "p", "p", false)) } diff --git a/android/app/src/test/java/tv/orbit/classic/arcade/ArcadeWordsTest.kt b/android/app/src/test/java/tv/orbit/classic/arcade/ArcadeWordsTest.kt index 2e1dea71..87c3dc4d 100644 --- a/android/app/src/test/java/tv/orbit/classic/arcade/ArcadeWordsTest.kt +++ b/android/app/src/test/java/tv/orbit/classic/arcade/ArcadeWordsTest.kt @@ -44,7 +44,8 @@ class ArcadeWordsTest { @Test fun resetWordsSayWhoseAndWhat() { assertEquals("Alfie's top scores for this game go.", resetDetail(ResetAction.ClearHighScores, ArcadeGames.Snake, "Alfie", true)) - assertEquals("BumbleHive's levels are one save for the whole TV for now.", resetDetail(ResetAction.ResetLevelProgress, ArcadeGames.Hive, "Alfie", false)) + assertEquals("Alfie's levels and unlocks for BumbleHive go back to the start.", resetDetail(ResetAction.ResetLevelProgress, ArcadeGames.Hive, "Alfie", true)) + assertEquals("Snake keeps no levels.".replace("Snake", ArcadeGames.Snake.title), resetDetail(ResetAction.ResetLevelProgress, ArcadeGames.Snake, "Alfie", false)) assertEquals("From a game's pause menu, while you play.", resetDetail(ResetAction.RestartLevel, ArcadeGames.Snake, "Alfie", false)) } diff --git a/android/app/src/test/java/tv/orbit/classic/arcade/hive/BumbleHiveParityTest.kt b/android/app/src/test/java/tv/orbit/classic/arcade/hive/BumbleHiveParityTest.kt new file mode 100644 index 00000000..644d4d7c --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/arcade/hive/BumbleHiveParityTest.kt @@ -0,0 +1,115 @@ +package tv.orbit.classic.arcade.hive + +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The port against the real game.js. src/test/resources/bumblehive/parity.json was recorded by running game.js under Node + * (src/test/js/hive-parity.js; hive-parity.test.js checks it still matches game.js). Here the Kotlin rules replay the same + * inputs and must give the same answers: every level's grid and numbers, every landing's grid and score, and every shot's + * path frame by frame. + */ +class BumbleHiveParityTest { + private val data: JSONObject by lazy { + JSONObject(javaClass.classLoader!!.getResourceAsStream("bumblehive/parity.json")!!.bufferedReader().readText()) + } + private val dt by lazy { data.getDouble("frameSeconds") } + + private fun assertGrid(what: String, expected: JSONArray, grid: HiveGrid) { + for (r in 0 until Hive.MAXROWS) { + val row = expected.getJSONArray(r) + assertEquals("$what row $r width", Hive.cellsIn(r), row.length()) + for (c in 0 until row.length()) assertEquals("$what cell $r,$c", row.getInt(c), grid[r, c]) + } + } + + private fun sim() = HiveSim(HiveSaveData(), object : HiveHost { override fun today() = "2026-11-08" }, seed = 1) + + @Test fun all200LevelsMatchGameJs() { + val levels = data.getJSONArray("levels") + assertEquals(200, levels.length()) + val grid = HiveGrid() + var matched = 0 + for (i in 0 until levels.length()) { + val l = levels.getJSONObject(i) + val n = l.getInt("n") + val info = HiveLevels.build(n, HiveMode.Normal, grid) + assertEquals("level $n colours", l.getInt("colours"), info.colours) + assertEquals("level $n rows", l.getInt("rows"), info.rows) + assertEquals("level $n shape", l.getInt("shape"), info.shape) + assertEquals("level $n panic", l.getDouble("panic"), info.panic, 0.0) + assertGrid("level $n", l.getJSONArray("grid"), grid) + matched++ + } + println("BumbleHive parity: $matched/200 levels identical to game.js") + assertEquals(200, matched) + } + + private fun screenName(s: HiveScreen) = when (s) { HiveScreen.Play -> "play"; HiveScreen.Win -> "win"; HiveScreen.Lose -> "lose"; else -> s.name.lowercase() } + + @Test fun shotScenariosLandPopDropAndScoreLikeGameJs() { + val scenarios = data.getJSONArray("scenarios") + var shots = 0; var wins = 0; var losses = 0 + for (i in 0 until scenarios.length()) { + val sc = scenarios.getJSONObject(i) + val n = sc.getInt("n") + val sim = sim() + sim.startLevel(n) + sim.save.bombs = 99 + val list = sc.getJSONArray("shots") + for (k in 0 until list.length()) { + val s = list.getJSONObject(k) + val what = "level $n shot $k" + sim.angle = s.getDouble("angle"); sim.current = s.getInt("colour"); sim.bombArmed = s.getBoolean("bomb") + sim.fire() + var frames = 0 + while (sim.shotOn && frames < 600) { sim.update(dt); frames++ } + assertEquals("$what frames", s.getInt("frames"), frames) + assertGrid(what, s.getJSONArray("grid"), sim.grid) + assertEquals("$what score", s.getInt("score"), sim.score) + assertEquals("$what ceiling", s.getDouble("top"), sim.top, 0.0) + assertEquals("$what drops", s.getInt("drops"), sim.drops) + assertEquals("$what panic", s.getDouble("panic"), sim.panic, 1e-12) + assertEquals("$what screen", s.getString("screen"), screenName(sim.screen)) + shots++ + } + when (sim.screen) { HiveScreen.Win -> wins++; HiveScreen.Lose -> losses++; else -> {} } + } + println("BumbleHive parity: $shots shots in ${scenarios.length()} levels identical ($wins won, $losses swarmed)") + assertTrue(wins >= 1 && losses >= 1) + } + + @Test fun shotPathsMatchGameJsFrameByFrame() { + val list = data.getJSONArray("trajectories") + var frames = 0 + var worst = 0.0 + for (i in 0 until list.length()) { + val t = list.getJSONObject(i) + val sim = sim() + sim.startLevel(t.getInt("n")) + sim.angle = t.getDouble("angle"); sim.current = 0 + sim.fire() + val path = t.getJSONArray("path") + var f = 0 + while (sim.shotOn && f < 600) { + sim.update(dt) + if (sim.shotOn) { + val p = path.getJSONArray(f) + val d = maxOf(kotlin.math.abs(p.getDouble(0) - sim.shotX), kotlin.math.abs(p.getDouble(1) - sim.shotY), kotlin.math.abs(p.getDouble(2) - sim.shotVx)) + worst = maxOf(worst, d) + assertEquals("shot $i frame $f x", p.getDouble(0), sim.shotX, 1e-9) + assertEquals("shot $i frame $f y", p.getDouble(1), sim.shotY, 1e-9) + assertEquals("shot $i frame $f vx", p.getDouble(2), sim.shotVx, 1e-9) + f++ + } + } + assertEquals("shot $i frames in flight", path.length(), f) + assertGrid("shot $i landed", t.getJSONArray("after"), sim.grid) + frames += f + } + println("BumbleHive parity: ${list.length()} shot paths, $frames frames, largest difference $worst") + } +} diff --git a/android/app/src/test/java/tv/orbit/classic/arcade/hive/HiveLegacyTest.kt b/android/app/src/test/java/tv/orbit/classic/arcade/hive/HiveLegacyTest.kt new file mode 100644 index 00000000..2d3e29fe --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/arcade/hive/HiveLegacyTest.kt @@ -0,0 +1,148 @@ +package tv.orbit.classic.arcade.hive + +import org.json.JSONObject +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import tv.orbit.classic.arcade.ArcadeProfileData +import tv.orbit.classic.arcade.GameRecord +import tv.orbit.classic.arcade.ResetAction +import tv.orbit.classic.arcade.applyReset +import tv.orbit.classic.arcade.decodeArcade +import tv.orbit.classic.arcade.encodeArcade + +/** The one-time carry-over of the WebView save into a read-only Household save. */ +class HiveLegacyTest { + @get:Rule val tmp = TemporaryFolder() + + /** What the downstairs TV holds, near enough: 48 unlocked, 96 stars. */ + private val downstairs: String = JSONObject().put("unlocked", 48).put("bombs", 6).put("lastSpin", "2026-11-07").put("guide", true).put("sound", true) + .put("page", 2).put("skin", "orbit") + .put("stars", JSONObject().also { o -> for (n in 1..47) o.put(n.toString(), if (n <= 2) 3 else 2) }) + .put("best", JSONObject().also { o -> for (n in 1..47) o.put(n.toString(), 1000 + n) }).toString() + + /** evaluateJavascript's answer: the script's JSON text, quoted as a JSON string. */ + private fun answer(present: Boolean, value: String?, profiles: Map = emptyMap()) = + JSONObject.quote(JSONObject().put("ok", true).put("present", present).put("value", value ?: JSONObject.NULL).put("profiles", JSONObject(profiles as Map<*, *>)).toString()) + + private class Reader(val raw: String?) { + var calls = 0 + fun read(cb: (String?) -> Unit) { calls++; cb(raw) } + } + + private fun import(dir: java.io.File, reader: Reader): HiveLegacy.Snapshot? { + var out: HiveLegacy.Snapshot? = null + var done = false + HiveLegacy.importOnce(dir, { 1_700_000_000_000L }, reader::read) { out = it; done = true } + assertTrue(done) + return out + } + + @Test fun theImportedSaveIsExactlyWhatWasStored() { + val dir = tmp.newFolder() + val snap = import(dir, Reader(answer(true, downstairs)))!! + assertTrue(snap.present) + assertEquals(downstairs, snap.value) + val save = snap.save!! + assertEquals(48, save.progress.unlocked) + assertEquals(96, save.progress.totalStars()) + assertEquals(1047, save.progress.best[47]); assertEquals(6, save.bombs) + // The file says what it is and that it's read-only. + val o = JSONObject(HiveLegacy.file(dir).readText()) + assertTrue(o.getBoolean("readOnly")); assertEquals("localStorage/orbithive-save-v1", o.getString("source")); assertEquals(HiveLegacy.ORIGIN_URL, o.getString("origin")) + } + + @Test fun itRunsOnceAndNeverRewritesTheSnapshot() { + val dir = tmp.newFolder() + import(dir, Reader(answer(true, downstairs))) + val first = HiveLegacy.file(dir).readBytes() + val again = Reader(answer(true, """{"unlocked":1}""")) + val snap = import(dir, again)!! + assertEquals(0, again.calls) + assertArrayEquals(first, HiveLegacy.file(dir).readBytes()) + assertEquals(downstairs, snap.value) + // Even asked to record directly, an existing snapshot stays. + assertTrue(HiveLegacy.record(dir, HiveLegacy.Found(true, "{}", emptyMap()), 5L)) + assertArrayEquals(first, HiveLegacy.file(dir).readBytes()) + } + + @Test fun noOldSaveIsRecordedAsNothingToOffer() { + val dir = tmp.newFolder() + val snap = import(dir, Reader(answer(false, null)))!! + assertFalse(snap.present); assertNull(snap.value); assertNull(snap.save) + assertFalse(HiveLegacy.needsImport(dir)) + assertFalse(offerHousehold(HiveSaveData(), snap.save)) + } + + @Test fun anEmptyOrCorruptOldSaveIsKeptAsItWasButNotOffered() { + for (bad in listOf("", "not json {", "[1,2,3]", "null", "{\"unlocked\":\"lots\"}")) { + val dir = tmp.newFolder() + val snap = import(dir, Reader(answer(true, bad)))!! + assertEquals("kept exactly: $bad", bad, snap.value) + assertFalse("not offered: $bad", offerHousehold(HiveSaveData(), snap.save)) + } + } + + @Test fun aFailedReadWritesNothingAndIsTriedAgainNextTime() { + val dir = tmp.newFolder() + for (failure in listOf(null, "null", JSONObject.quote("""{"ok":false,"error":"SecurityError"}"""), "garbage", JSONObject.quote("not json"))) { + assertNull(import(dir, Reader(failure))) + assertTrue(HiveLegacy.needsImport(dir)) + } + val later = Reader(answer(true, downstairs)) + assertEquals(downstairs, import(dir, later)!!.value) + assertEquals(1, later.calls) + } + + @Test fun anUnreadableSnapshotOffersNothingAndIsNotReplaced() { + val dir = tmp.newFolder() + HiveLegacy.file(dir).writeText("{broken") + val reader = Reader(answer(true, downstairs)) + assertNull(import(dir, reader)) + assertEquals(0, reader.calls) + assertEquals("{broken", HiveLegacy.file(dir).readText()) + } + + @Test fun perProfileCopiesFromTheOldGameAreRecordedToo() { + val dir = tmp.newFolder() + import(dir, Reader(answer(true, downstairs, mapOf("orbithive-save-v1:abc" to """{"unlocked":3}""")))) + assertEquals("""{"unlocked":3}""", JSONObject(HiveLegacy.file(dir).readText()).getJSONObject("profiles").getString("orbithive-save-v1:abc")) + } + + @Test fun theReadScriptOnlyReads() { + val s = HiveLegacy.READ_SCRIPT + for (word in listOf("setItem", "removeItem", "clear", "localStorage =", "delete ")) assertFalse("script contains $word", s.contains(word)) + assertTrue(s.contains("getItem('orbithive-save-v1')") || s.contains("s.getItem(k)")) + assertEquals("file:///android_asset/orbithive/index.html", HiveLegacy.ORIGIN_URL) + } + + @Test fun continuingFromTheHouseholdSaveCopiesItAndLeavesItAlone() { + val dir = tmp.newFolder() + val snap = import(dir, Reader(answer(true, downstairs)))!! + val before = HiveLegacy.file(dir).readBytes() + val save = HiveSaveData() + assertTrue(offerHousehold(save, snap.save)) + adoptHousehold(save, snap.save!!) + save.normal.unlocked = 50; save.normal.stars[48] = 3 + assertEquals(48, snap.save!!.progress.unlocked) + assertArrayEquals(before, HiveLegacy.file(dir).readBytes()) + // A second profile can continue from it too, as its own copy. + val other = HiveSaveData() + assertTrue(offerHousehold(other, HiveLegacy.load(dir)!!.save)) + adoptHousehold(other, HiveLegacy.load(dir)!!.save!!) + assertEquals(48, other.normal.unlocked); assertEquals(0, other.normal.stars[48]) + } + + @Test fun keptValuesSurviveTheFileAndALevelReset() { + val data = ArcadeProfileData("p").withGame("Hive") { GameRecord(level = mapOf("normal" to "{}"), kept = mapOf("bombs" to "7", "mode" to "hard")) } + val back = decodeArcade(encodeArcade(data), "p")!! + assertEquals(mapOf("bombs" to "7", "mode" to "hard"), back.game("Hive").kept) + val reset = applyReset(back, "Hive", ResetAction.ResetLevelProgress, 9L) + assertTrue(reset.game("Hive").level.isEmpty()) + assertEquals("7", reset.game("Hive").kept["bombs"]) + // Files from before have no "kept" and still read. + val old = JSONObject(encodeArcade(ArcadeProfileData("p").withGame("Hive") { GameRecord() })).toString() + assertTrue(decodeArcade(old, "p")!!.game("Hive").kept.isEmpty()) + } +} diff --git a/android/app/src/test/java/tv/orbit/classic/arcade/hive/HiveSimTest.kt b/android/app/src/test/java/tv/orbit/classic/arcade/hive/HiveSimTest.kt new file mode 100644 index 00000000..ec2bfaac --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/arcade/hive/HiveSimTest.kt @@ -0,0 +1,350 @@ +package tv.orbit.classic.arcade.hive + +import org.junit.Assert.* +import org.junit.Test + +/** BumbleHive's play, menus, Daily Bonus, Hard mode and saves, with no screen. */ +class HiveSimTest { + private class Host(var day: String = "2026-11-08") : HiveHost { + val sounds = ArrayList() + var persisted = 0 + val runs = ArrayList() + var left = 0 + override fun sound(id: Int) { sounds += id } + override fun persist() { persisted++ } + override fun runStart(level: Int) { runs += "start $level" } + override fun runEnd(level: Int, score: Int, finished: Boolean) { runs += "end $level $score $finished" } + override fun leave() { left++ } + override fun today() = day + } + + private fun sim(save: HiveSaveData = HiveSaveData(), host: Host = Host(), legacy: LegacyHiveSave? = null) = HiveSim(save, host, seed = 3, legacy = legacy) + + // ---------- Hard mode ---------- + + @Test fun hardModeNumbersAreAsAgreed() { + for (n in 1..200) { + val normal = HiveLevels.info(n, HiveMode.Normal) + val hard = HiveLevels.info(n, HiveMode.Hard) + // Panic ×0.6, never under 5 s; colours every 10 levels instead of 15, still at most 6; same rows and shape. + assertEquals(maxOf(5.0, normal.panic * 0.6), hard.panic, 1e-12) + assertEquals(minOf(6, 3 + (n - 1) / 10), hard.colours) + assertEquals(normal.rows, hard.rows); assertEquals(normal.shape, hard.shape) + assertTrue(hard.colours >= normal.colours && hard.colours <= 6) + } + assertEquals(12.0, HiveLevels.info(1, HiveMode.Hard).panic, 1e-12) + assertEquals(5.0, HiveLevels.info(200, HiveMode.Hard).panic, 0.0) + assertEquals(5, HiveMode.Normal.swaps); assertEquals(3, HiveMode.Hard.swaps) + } + + @Test fun hardUsesTheSameLayoutsAsNormal() { + val a = HiveGrid(); val b = HiveGrid() + for (n in 1..200) { + HiveLevels.build(n, HiveMode.Normal, a); HiveLevels.build(n, HiveMode.Hard, b) + for (i in 0 until Hive.CELLS) assertEquals("level $n cell $i occupied", a.cells[i] >= 0, b.cells[i] >= 0) + for (v in b.cells) assertTrue(v < HiveLevels.info(n, HiveMode.Hard).colours) + } + } + + @Test fun hardHasItsOwnSaveAndNeverTouchesNormal() { + val save = HiveSaveData() + save.normal.unlocked = 48; save.normal.stars[1] = 3; save.normal.best[1] = 2000 + val host = Host() + val s = sim(save, host) + // Choose Hard on the title. + s.act(s.buttons.first { it.act == HiveAct.Mode }) + assertEquals(HiveMode.Hard, s.mode); assertEquals(HiveMode.Hard, save.mode) + assertEquals("MODE: HARD", s.buttons.first { it.act == HiveAct.Mode }.label) + // Hard starts at level 1 with 3 swaps. + s.act(s.buttons.first { it.act == HiveAct.Play }) + assertEquals(1, s.level); assertEquals(3, s.swaps) + winNow(s) + assertEquals(2, save.hard.unlocked); assertTrue(save.hard.best[1] > 0) + // Normal is exactly as it was. + assertEquals(48, save.normal.unlocked); assertEquals(3, save.normal.stars[1]); assertEquals(2000, save.normal.best[1]) + // And back to Normal: its own progress and 5 swaps. + s.toMenu(); s.act(s.buttons.first { it.act == HiveAct.Mode }) + s.act(s.buttons.first { it.act == HiveAct.Play }) + assertEquals(48, s.level); assertEquals(5, s.swaps) + assertEquals(2, save.hard.unlocked) + } + + @Test fun hardAndNormalSurviveTheSaveRoundTrip() { + val save = HiveSaveData() + save.normal.unlocked = 48; save.normal.stars[3] = 2; save.hard.unlocked = 5; save.hard.best[4] = 1234; save.hard.page = 0 + val level = mapOf(HiveKeys.NORMAL to save.normal.encode(), HiveKeys.HARD to save.hard.encode()) + val back = readHiveSave(level, mapOf(HiveKeys.MODE to "hard", HiveKeys.BOMBS to "7", HiveKeys.LAST_SPIN to "2026-11-07")) { it != HiveKeys.CLASSIC } + assertEquals(48, back.normal.unlocked); assertEquals(2, back.normal.stars[3]); assertEquals(5, back.hard.unlocked); assertEquals(1234, back.hard.best[4]) + assertEquals(0, back.hard.stars[3]); assertEquals(0, back.normal.best[4]) + assertEquals(HiveMode.Hard, back.mode); assertEquals(7, back.bombs); assertEquals("2026-11-07", back.lastSpin) + assertTrue(back.skinOrbit && back.guide && back.sound) + // A level reset clears level progress (both modes) but keeps Honeybombs and the mode, as game.js kept bombs. + val reset = readHiveSave(emptyMap(), mapOf(HiveKeys.MODE to "hard", HiveKeys.BOMBS to "7")) { true } + assertEquals(1, reset.normal.unlocked); assertEquals(1, reset.hard.unlocked); assertEquals(7, reset.bombs) + } + + // ---------- play ---------- + + /** Clears the hive with one shot: a single flower left, then a match of three. */ + private fun winNow(s: HiveSim) { + s.grid.clear(); s.grid[0, 5] = 1; s.grid[0, 6] = 1 + s.current = 1; s.angle = 0.0; s.bombArmed = false + s.fire() + repeat(120) { if (s.shotOn) s.update(1.0 / 60) } + } + + @Test fun aimSpeedsUpTheLongerItsHeld() { + val s = sim(); s.startLevel(1) + s.key(HiveKey.Right, down = true, repeat = false) + assertEquals(0.012, s.angle, 1e-12) // the press itself nudges + s.update(0.05); val early = s.angle - 0.012 + repeat(14) { s.update(0.05) } + val before = s.angle; s.update(0.05); val late = s.angle - before + assertTrue("held longer aims faster ($early then $late)", late > early * 2) + // Repeats of a held arrow add nothing; release stops it. + val a = s.angle; s.key(HiveKey.Right, down = true, repeat = true); assertEquals(a, s.angle, 0.0) + s.key(HiveKey.Right, down = false, repeat = false); s.update(0.1); assertEquals(a, s.angle, 0.0) + // Never past 1.38 radians. + s.key(HiveKey.Right, down = true, repeat = false); repeat(100) { s.update(0.1) } + assertEquals(Hive.MAX_ANGLE, s.angle, 0.0) + } + + @Test fun okFiresOncePerPressAndAHeldOkDoesNotRepeat() { + val s = sim(); s.startLevel(1) + s.key(HiveKey.Ok, down = true, repeat = false); assertTrue(s.shotOn) + repeat(200) { s.update(1.0 / 60) } + assertFalse(s.shotOn) + s.key(HiveKey.Ok, down = true, repeat = true) + assertFalse(s.shotOn) + } + + @Test fun swapsRunOutAndHoneybombsCost() { + val save = HiveSaveData().also { it.bombs = 1 } + val host = Host() + val s = sim(save, host); s.startLevel(1) + val a = s.current; val b = s.next + s.action(HiveKey.Down) + assertEquals(b, s.current); assertEquals(a, s.next); assertEquals(4, s.swaps) + repeat(10) { s.action(HiveKey.Down) } + assertEquals(0, s.swaps) + s.action(HiveKey.Up); assertTrue(s.bombArmed) + s.fire(); assertTrue(s.shotBomb); assertEquals(0, save.bombs) + repeat(200) { s.update(1.0 / 60) } + // None left: the banner says so and nothing is armed. + s.action(HiveKey.Up); assertFalse(s.bombArmed); assertEquals(HiveSim.BANNER_NO_BOMBS, s.banner) + } + + @Test fun theCeilingDropsWhenThePanicBarFillsAndABreachIsSwarmed() { + val host = Host() + val s = sim(host = host); s.startLevel(1) + val panic = s.info.panic + var t = 0.0 + while (s.drops == 0) { s.update(1.0 / 60); t += 1.0 / 60 } + assertEquals(panic, t, 1.0 / 30) + assertEquals(Hive.TOP0 + Hive.RH, s.top, 1e-9) + assertTrue(Sfx.LID in host.sounds) + // Keep going: the hive comes down to the dashed line. + while (s.screen == HiveScreen.Play) s.update(1.0 / 60) + assertEquals(HiveScreen.Lose, s.screen) + assertEquals(listOf("start 1", "end 1 0 true"), host.runs) + } + + @Test fun winningScoresStarsAndUnlocks() { + val save = HiveSaveData(); val host = Host() + val s = sim(save, host); s.startLevel(1) + winNow(s) + assertEquals(HiveScreen.Win, s.screen) + // 3 popped (30) + 1000 + the panic left. + assertEquals(30 + 1000 + Math.round((1 - s.panic) * 500).toInt(), s.score) + assertEquals(3, s.stars); assertEquals(3, save.normal.stars[1]); assertEquals(2, save.normal.unlocked); assertEquals(s.score, save.normal.best[1]) + assertEquals("end 1 ${s.score} true", host.runs.last()) + assertTrue(host.persisted > 0) + assertEquals(3, s.starsFor(1)); assertEquals(2, s.starsFor(2)); assertEquals(2, s.starsFor(3)); assertEquals(1, s.starsFor(4)) + // Next level, and the result card's Back goes to Level Select. + s.nextLevel(); assertEquals(2, s.level); assertEquals(HiveScreen.Play, s.screen) + } + + @Test fun clustersPopAndLooseFlowersFallForTheBonus() { + val s = sim(); s.startLevel(1) + s.grid.clear() + // A red pair on the ceiling, and three greens hanging from the left-hand red only. + s.grid[0, 4] = 0; s.grid[0, 5] = 0 + s.grid[1, 3] = 2; s.grid[2, 3] = 2; s.grid[3, 3] = 2 + s.grid[0, 0] = 1 // so the level isn't cleared + s.current = 0; s.angle = 0.0 + s.fire(); repeat(120) { if (s.shotOn) s.update(1.0 / 60) } + // Three reds burst (30), the three blues fall (20 × 3²). + assertEquals(30 + 180, s.score) + assertEquals(1, s.grid.flowerCount()) + } + + @Test fun runsAreReportedOnceHoweverTheyEnd() { + val host = Host(); val s = sim(host = host) + s.startLevel(4); s.replay() + s.pause(); s.toLevels() + s.startLevel(5); s.closeRun(); s.closeRun() + assertEquals(listOf("start 4", "end 4 0 false", "start 4", "end 4 0 false", "start 5", "end 5 0 false"), host.runs) + } + + @Test fun backPausesInPlayAndLeavesFromTheTitle() { + val host = Host(); val s = sim(host = host) + s.action(HiveKey.Back); assertEquals(1, host.left) + s.startLevel(1); s.action(HiveKey.Back); assertEquals(HiveScreen.Pause, s.screen) + s.key(HiveKey.Pause, down = true, repeat = false); assertEquals(HiveScreen.Play, s.screen) + s.key(HiveKey.Pause, down = true, repeat = false); assertEquals(HiveScreen.Pause, s.screen) + s.resume(); s.action(HiveKey.Back); s.toLevels(); s.action(HiveKey.Back); assertEquals(HiveScreen.Title, s.screen) + } + + @Test fun levelSelectOpensOnTheFurthestLevelAndLockedOnesDontStart() { + val save = HiveSaveData().also { it.normal.unlocked = 48 } + val host = Host(); val s = sim(save, host) + s.act(s.buttons.first { it.act == HiveAct.Levels }) + assertEquals(2, save.normal.page) + assertEquals("48", s.buttons[s.focus].label) + s.act(s.buttons.first { it.level == 49 }) + assertEquals(HiveScreen.Levels, s.screen); assertEquals(Sfx.LOSE, host.sounds.last()) + s.action(HiveKey.Right); assertEquals("49", s.buttons[s.focus].label) + s.act(s.buttons.first { it.act == HiveAct.PageNext }); assertEquals(3, save.normal.page) + } + + // ---------- Bumble's Daily Bonus ---------- + + @Test fun dailyBonusIsFreeOptionalAndOncePerDay() { + val save = HiveSaveData(); val host = Host("2026-11-08") + val s = sim(save, host) + assertTrue(s.buttons.any { it.act == HiveAct.Daily }) + // Not today: nothing spent, still there after. + s.act(s.buttons.first { it.act == HiveAct.Daily }) + assertEquals(listOf("SPIN", "NOT TODAY"), s.buttons.map { it.label }) + s.act(s.buttons.first { it.act == HiveAct.NotToday }) + assertEquals(HiveScreen.Title, s.screen); assertEquals(2, save.bombs); assertTrue(s.buttons.any { it.act == HiveAct.Daily }) + // Spin: lands, pays out, and the button is gone until tomorrow. No streaks: nothing else is kept. + s.act(s.buttons.first { it.act == HiveAct.Daily }); s.act(s.buttons.first { it.act == HiveAct.Spin }) + assertTrue(s.buttons.isEmpty()) + repeat(600) { s.update(1.0 / 60) } + assertTrue(s.wheelSpun); assertTrue(s.wheelPrize in HiveSim.PRIZES) + assertEquals(2 + s.wheelPrize, save.bombs); assertEquals("2026-11-08", save.lastSpin) + assertTrue(Sfx.TICK in host.sounds) + s.act(s.buttons.first { it.act == HiveAct.Collect }) + assertFalse(s.buttons.any { it.act == HiveAct.Daily }) + host.day = "2026-11-09"; s.toMenu() + assertTrue(s.buttons.any { it.act == HiveAct.Daily }) + } + + @Test fun reduceMotionStopsTheWheelOnItsResultAtOnce() { + val save = HiveSaveData(); val s = sim(save) + s.calm = true + s.act(s.buttons.first { it.act == HiveAct.Daily }); s.act(s.buttons.first { it.act == HiveAct.Spin }) + assertTrue(s.wheelSpun); assertEquals(0.0, s.wheelSpeed, 0.0) + assertEquals(2 + s.wheelPrize, save.bombs) + } + + // ---------- help and settings ---------- + + @Test fun helpTogglesSkinGuideAndSound() { + val save = HiveSaveData(); val host = Host(); val s = sim(save, host) + s.act(s.buttons.first { it.act == HiveAct.Help }) + assertEquals(listOf("SKIN: ORBIT", "GUIDE LINE: ON", "SOUND: ON", "BACK"), s.buttons.map { it.label }) + s.buttons.take(3).forEach { s.act(it) } + assertEquals(listOf("SKIN: CLASSIC", "GUIDE LINE: OFF", "SOUND: OFF", "BACK"), s.buttons.map { it.label }) + assertFalse(save.skinOrbit); assertFalse(save.guide); assertFalse(save.sound) + s.action(HiveKey.Back); assertEquals(HiveScreen.Title, s.screen) + } + + // ---------- the Household save ---------- + + @Test fun householdSaveIsOfferedOnceAndCopiedNotLinked() { + val legacy = LegacyHiveSave.parse("""{"unlocked":48,"stars":{"1":3,"2":2},"best":{"1":1500},"bombs":9,"lastSpin":"2026-11-01","guide":false,"sound":true,"page":2,"skin":"classic"}""")!! + val save = HiveSaveData(); val host = Host() + val s = sim(save, host, legacy) + assertEquals(HiveScreen.Household, s.screen) + s.act(s.buttons.first { it.act == HiveAct.Continue }) + assertEquals(HiveScreen.Title, s.screen) + assertEquals(48, save.normal.unlocked); assertEquals(3, save.normal.stars[1]); assertEquals(1500, save.normal.best[1]) + assertEquals(9, save.bombs); assertFalse(save.guide); assertFalse(save.skinOrbit); assertEquals("copied", save.household) + // A copy: playing on changes the profile's save only. + save.normal.unlocked = 60 + assertEquals(48, legacy.progress.unlocked) + // Not asked again, and Hard is untouched. + assertFalse(offerHousehold(save, legacy)); assertEquals(1, save.hard.unlocked) + assertEquals(HiveScreen.Title, sim(save, host, legacy).screen) + } + + @Test fun startFreshIsRememberedAndBackLeaves() { + val legacy = LegacyHiveSave.parse("""{"unlocked":5}""")!! + val save = HiveSaveData(); val host = Host() + val s = sim(save, host, legacy) + s.action(HiveKey.Back); assertEquals(1, host.left) + s.act(s.buttons.first { it.act == HiveAct.Fresh }) + assertEquals("fresh", save.household); assertEquals(1, save.normal.unlocked) + assertFalse(offerHousehold(save, legacy)) + // Nothing worth offering is never asked. + assertFalse(offerHousehold(HiveSaveData(), LegacyHiveSave.parse("""{"unlocked":1}"""))) + assertFalse(offerHousehold(HiveSaveData(), null)) + } + + @Test fun theOfferWaitsUntilAnsweredAndMergesWithWhatWasPlayedMeanwhile() { + // The import finished after the game opened, and a level was cleared first: the offer still comes, at the title. + val save = HiveSaveData(); val host = Host() + val s = sim(save, host) + assertEquals(HiveScreen.Title, s.screen) + s.startLevel(1); winNow(s) + assertEquals(2, save.normal.unlocked); val mine = save.normal.best[1] + s.legacy = LegacyHiveSave.parse("""{"unlocked":48,"stars":{"1":1,"2":3},"best":{"1":5,"2":900},"bombs":1,"skin":"classic"}""") + s.toMenu() + assertEquals(HiveScreen.Household, s.screen) + s.act(s.buttons.first { it.act == HiveAct.Continue }) + // The best of both: the furthest level, each level's best stars and score; this profile's choices stay. + assertEquals(48, save.normal.unlocked); assertEquals(3, save.normal.stars[1]); assertEquals(3, save.normal.stars[2]) + assertEquals(mine, save.normal.best[1]); assertEquals(900, save.normal.best[2]) + assertEquals(2, save.bombs); assertTrue(save.skinOrbit) + s.toMenu(); assertEquals(HiveScreen.Title, s.screen) + } + + // ---------- performance ---------- + + @Test fun steadyPlayAllocatesNothing() { + val save = HiveSaveData().also { it.bombs = 1_000_000 } + val s = HiveSim(save, object : HiveHost { override fun today() = "2026-11-08" }, seed = 11) + val out = DoubleArray(128) + val mx = java.lang.management.ManagementFactory.getThreadMXBean() as com.sun.management.ThreadMXBean + var shot = 0 + var frameBytes = 0L + var shotBytes = 0L + var levels = 0 + var measuring = false + fun tick() { + when (s.screen) { + HiveScreen.Play -> if (!s.shotOn) { + shot++ + s.angle = ((shot * 37) % 200 - 100) / 100.0 * 1.2 + s.bombArmed = shot % 9 == 0 + val b = mx.currentThreadAllocatedBytes + s.guidePoints(out) + s.fire() + if (measuring) shotBytes += mx.currentThreadAllocatedBytes - b + } + else -> { s.startLevel(1 + shot % 60); levels++ } + } + // The frame: flight, landing, bursts, falls, the ceiling, effects. This is what runs 60 times a second. + val b = mx.currentThreadAllocatedBytes + s.update(1.0 / 60) + if (measuring) frameBytes += mx.currentThreadAllocatedBytes - b + } + s.startLevel(1) + repeat(3_000) { tick() } + measuring = true + val shotsBefore = shot; levels = 0 + var maxFx = 0 + for (i in 0 until 10_000) { tick(); if (s.fxCount > maxFx) maxFx = s.fxCount } + val shots = shot - shotsBefore + println("BumbleHive: 10,000 ticks ($shots shots, $levels new levels) allocated $frameBytes bytes in the frames; " + + "aiming and firing ${shotBytes / maxOf(1, shots)} bytes a shot (the JVM's StrictMath.sin/cos; native on Android); most effects at once $maxFx (cap ${Fx.CAP})") + assertTrue(maxFx < Fx.CAP) + assertTrue(shots > 100) + // Every frame of steady play: nothing. 4 KB leaves room for the JVM's own noise. + assertTrue("frames allocated $frameBytes bytes", frameBytes < 4 * 1024) + // Aiming and firing: four sin/cos calls (guide line and shot), each at most the JVM's small reduction arrays (none on Android). + assertTrue("a shot allocated ${shotBytes / shots} bytes", shotBytes / shots <= 256) + } +} diff --git a/android/app/src/test/js/hive-parity.js b/android/app/src/test/js/hive-parity.js new file mode 100644 index 00000000..2491601e --- /dev/null +++ b/android/app/src/test/js/hive-parity.js @@ -0,0 +1,129 @@ +// BumbleHive native parity (8 November 2026): runs the real game.js headless and records what the Kotlin port must match. +// +// node android/app/src/test/js/hive-parity.js > android/app/src/test/resources/bumblehive/parity.json +// +// Records: all 200 levels (grid, colours, rows, shape, panic), scripted shot scenarios (grid, score, ceiling, drops and +// screen after every landing, bombs included) and shot trajectories (the shot's position every frame and where it lands). +// The Kotlin test (BumbleHiveParityTest) replays the same inputs and asserts the same results. hive-parity.test.js checks +// that the committed file still matches game.js, so a change to either side shows up. +'use strict'; +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); + +const DIR = path.join(__dirname, '../../main/assets/orbithive'); +const GAME_JS = fs.readFileSync(path.join(DIR, 'game.js'), 'utf8'); +const SAVE_JS = fs.readFileSync(path.join(DIR, 'hive-save.js'), 'utf8'); + +// The script's own choices (angles, colours): a small LCG, written out so the Kotlin test can do the same. +function scriptRng(seed) { + let s = seed >>> 0; + return () => { s = (Math.imul(s, 1103515245) + 12345) >>> 0; return s / 4294967296; }; +} + +function load(stored = {}) { + const ctx = new Proxy({}, { + get(_, name) { + if (name === 'createLinearGradient' || name === 'createRadialGradient') return () => ({ addColorStop() {} }); + return () => {}; + }, + set() { return true; }, + }); + const canvasLike = () => ({ width: 0, height: 0, getContext: () => ctx, focus() {}, addEventListener() {}, getBoundingClientRect: () => ({ left: 0, top: 0 }) }); + const canvas = canvasLike(); + let rafSeq = 0; const rafs = new Map(); + const map = new Map(Object.entries(stored)); + const writes = []; + const localStorage = { getItem: (k) => (map.has(k) ? map.get(k) : null), setItem: (k, v) => { writes.push(k); map.set(k, String(v)); }, removeItem: (k) => { writes.push(k); map.delete(k); } }; + // Math.random only picks the next flower and how fallen ones tumble; the scenarios set the flower themselves. + const rand = scriptRng(99); + const SeededMath = Object.create(Math); SeededMath.random = rand; + let now = 1000; + const sandbox = { + console, Math: SeededMath, JSON, Date, Object, Array, Number, String, Set, Map, Promise, Error, + innerWidth: 1280, innerHeight: 720, devicePixelRatio: 1, + addEventListener: () => {}, + requestAnimationFrame: (f) => { rafSeq += 1; rafs.set(rafSeq, f); return rafSeq; }, + cancelAnimationFrame: (id) => { rafs.delete(id); }, + performance: { now: () => now }, + setTimeout: (f) => { f(); return 0; }, + localStorage, navigator: { getGamepads: () => [] }, + document: { hidden: false, getElementById: () => canvas, createElement: () => canvasLike(), addEventListener: () => {} }, + }; + sandbox.window = sandbox; + vm.createContext(sandbox); + vm.runInContext(SAVE_JS, sandbox); + vm.runInContext(GAME_JS, sandbox); + const hive = sandbox.orbitHive; + return { + hive, map, writes, + // One frame of 16 ms: update(0.016) then a render. + frame() { now += 16; const pending = [...rafs.entries()]; rafs.clear(); pending.forEach(([, f]) => f(now)); }, + }; +} + +const flat = (grid) => grid.map((row) => row.slice()); + +function levels(g) { + const out = []; + for (let n = 1; n <= 200; n++) { + g.hive.startLevel(n); + const { grid, info } = g.hive.game; + out.push({ n, colours: info.colours, rows: info.rows, shape: info.shape, panic: info.panic, grid: flat(grid) }); + } + return out; +} + +// Shots fired into real levels: a scripted angle and flower for each, every fifth a Honeybomb, each one flown to its +// landing 16 ms at a time. The state after every landing is recorded. +function scenarios(g) { + const out = []; + const LEVELS = [1, 2, 4, 7, 12, 19, 25, 33, 41, 58, 77, 96, 120, 150, 199]; + for (const n of LEVELS) { + const pick = scriptRng(n * 31 + 7); + g.hive.startLevel(n); + g.hive.save.bombs = 99; + const shots = []; + for (let i = 0; i < 40 && g.hive.screen === 'play'; i++) { + const angle = (pick() * 2 - 1) * 1.3; + const game = g.hive.game; + // The flower: one of the colours still in the hive, as the game would offer. + const left = []; game.grid.forEach((row) => row.forEach((c) => { if (c >= 0 && !left.includes(c)) left.push(c); })); + const colour = left.length ? left[Math.floor(pick() * left.length)] : 0; + const bomb = i % 5 === 4; + game.angle = angle; game.current = colour; game.bombArmed = bomb; + g.hive.fire(); + let frames = 0; + while (g.hive.game.shot && frames < 600) { g.frame(); frames++; } + shots.push({ angle, colour, bomb, frames, grid: flat(game.grid), score: game.score, top: game.top, drops: game.drops, panic: game.panic, screen: g.hive.screen }); + } + out.push({ n, shots }); + } + return out; +} + +// The shot's path, every frame, for a spread of angles into level 5 and level 40 (walls and bounces included). +function trajectories(g) { + const out = []; + for (const n of [5, 40]) { + for (let k = -6; k <= 6; k++) { + const angle = k * 0.215; + g.hive.startLevel(n); + const game = g.hive.game; + game.angle = angle; game.current = 0; + g.hive.fire(); + const path = []; + while (game.shot && path.length < 600) { g.frame(); if (game.shot) path.push([game.shot.x, game.shot.y, game.shot.vx]); } + out.push({ n, angle, path, after: flat(game.grid) }); + } + } + return out; +} + +function dump() { + const g = load(); + return { source: 'android/app/src/main/assets/orbithive/game.js', frameSeconds: 0.016, levels: levels(g), scenarios: scenarios(g), trajectories: trajectories(g) }; +} + +module.exports = { dump, scriptRng, load }; +if (require.main === module) process.stdout.write(JSON.stringify(dump())); diff --git a/android/app/src/test/js/hive-parity.test.js b/android/app/src/test/js/hive-parity.test.js new file mode 100644 index 00000000..7960f6e3 --- /dev/null +++ b/android/app/src/test/js/hive-parity.test.js @@ -0,0 +1,83 @@ +// BumbleHive native (8 November 2026): the parity record still matches game.js, and the save import script only reads. +// Run with: node --test android/app/src/test/js (tools/test-bumblehive.sh). +'use strict'; +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const { dump, load } = require('./hive-parity.js'); + +const FIXTURE = path.join(__dirname, '../resources/bumblehive/parity.json'); +const LEGACY_KT = path.join(__dirname, '../../main/java/tv/orbit/classic/arcade/hive/HiveLegacy.kt'); + +test('the committed parity record is what game.js gives today (regenerate with node hive-parity.js)', () => { + const fresh = JSON.parse(JSON.stringify(dump())); + const committed = JSON.parse(fs.readFileSync(FIXTURE, 'utf8')); + assert.equal(committed.levels.length, 200); + assert.deepEqual(committed, fresh); +}); + +// The Kotlin constant READ_SCRIPT, exactly as the app sends it to evaluateJavascript. +function readScript() { + const src = fs.readFileSync(LEGACY_KT, 'utf8'); + const block = src.slice(src.indexOf('// READ_SCRIPT_BEGIN'), src.indexOf('// READ_SCRIPT_END')); + const m = block.match(/const val READ_SCRIPT = """([\s\S]*?)"""/); + assert.ok(m, 'READ_SCRIPT found'); + return m[1]; +} + +// A localStorage that records every call and refuses any change. +function storage(entries, { throwOnRead = false } = {}) { + const map = new Map(Object.entries(entries)); + const calls = []; + const deny = (name) => () => { calls.push(name); throw new Error(`${name} is not allowed`); }; + const s = { + calls, + get length() { calls.push('length'); return map.size; }, + key(i) { calls.push('key'); return [...map.keys()][i] ?? null; }, + getItem(k) { calls.push('getItem'); if (throwOnRead) throw new Error('SecurityError'); return map.has(k) ? map.get(k) : null; }, + setItem: deny('setItem'), removeItem: deny('removeItem'), clear: deny('clear'), + }; + return { s, map }; +} + +function run(entries, opts) { + const { s, map } = storage(entries, opts); + const before = JSON.stringify([...map.entries()]); + const sandbox = { JSON, String, window: { localStorage: s } }; + const out = vm.runInNewContext(readScript(), sandbox); + assert.equal(JSON.stringify([...map.entries()]), before, 'storage unchanged'); + assert.ok(!s.calls.some((c) => c === 'setItem' || c === 'removeItem' || c === 'clear'), `only reads: ${s.calls.join(',')}`); + return JSON.parse(out); +} + +test('the import script returns the old save exactly and touches nothing', () => { + const save = JSON.stringify({ unlocked: 48, stars: { 1: 3 }, best: { 1: 1500 }, bombs: 6, lastSpin: '2026-11-07', guide: true, sound: true, page: 2, skin: 'orbit' }); + const r = run({ 'orbithive-save-v1': save, 'orbithive-save-v1:abc': '{"unlocked":3}', 'other-game': 'x' }); + assert.deepEqual(r, { ok: true, present: true, value: save, profiles: { 'orbithive-save-v1:abc': '{"unlocked":3}' } }); +}); + +test('no old save, an empty one, and unreadable storage', () => { + assert.deepEqual(run({}), { ok: true, present: false, value: null, profiles: {} }); + assert.deepEqual(run({ 'orbithive-save-v1': '' }), { ok: true, present: true, value: '', profiles: {} }); + const failed = run({ 'orbithive-save-v1': '{}' }, { throwOnRead: true }); + assert.equal(failed.ok, false); +}); + +test('the native port reads the same URL the WebView game loaded', () => { + const kt = fs.readFileSync(LEGACY_KT, 'utf8'); + const html = fs.readFileSync(path.join(__dirname, '../../main/assets/orbithive/index.html'), 'utf8'); + assert.match(kt, /ORIGIN_URL = "file:\/\/\/android_asset\/orbithive\/index\.html"/); + assert.match(html, /