Bela v0: local game against bots, counting training, settings with self-update
- engine: Croatian Bela rules (deal, trump call, declarations, play rules, scoring), heuristic bot, counting drill; unit tests and a 1000-game simulation - app: Jetpack Compose table with partner and two bot opponents, Hungarian deck, card-counting training, settings with in-app update and a QR code for sharing - tools: card import/render/upscale scripts and the launcher icon generator Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
No files matched your search
@@ -0,0 +1,8 @@
|
||||
* text=auto
|
||||
gradlew text eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.ps1 text eol=crlf
|
||||
*.png binary
|
||||
*.webp binary
|
||||
*.ttf binary
|
||||
*.jar binary
|
||||
@@ -0,0 +1,18 @@
|
||||
.gradle/
|
||||
.kotlin/
|
||||
build/
|
||||
local.properties
|
||||
.idea/
|
||||
*.iml
|
||||
.DS_Store
|
||||
captures/
|
||||
|
||||
# Release signing and publishing secrets: never commit (this repository is public).
|
||||
keystore.properties
|
||||
*.jks
|
||||
*.keystore
|
||||
.gitea-token
|
||||
*.apk
|
||||
|
||||
# IDE build output
|
||||
bin/
|
||||
@@ -0,0 +1,63 @@
|
||||
# Bela
|
||||
|
||||
Android aplikacija za Belu: ti i bot partner protiv dva bota, do 1001 boda. Ovo je verzija 0: lokalna igra, bez mreže i računa.
|
||||
|
||||
## Struktura
|
||||
|
||||
| Modul | Što je u njemu |
|
||||
| --- | --- |
|
||||
| `engine/` | Čisti Kotlin, bez Androida: karte, pravila, zvanja, bodovanje, bot. Kasnije se može prebaciti u Kotlin Multiplatform za server ili iOS. |
|
||||
| `app/` | Android aplikacija (Jetpack Compose): početni ekran, stol, dijalozi. |
|
||||
|
||||
Važne datoteke:
|
||||
|
||||
- `engine/.../Game.kt`: tijek partije (dijeljenje, zvanje aduta, štihovi, obračun).
|
||||
- `engine/.../Trick.kt`: dozvoljeni potezi (praćenje boje, iber, sječenje).
|
||||
- `engine/.../Declarations.kt`: zvanja.
|
||||
- `engine/.../RuleSet.kt`: kućna pravila (do koliko se igra, štiglja, iber, belot, "visi").
|
||||
- `engine/.../Bot.kt`: heuristički bot.
|
||||
- `app/.../ui/CardArt.kt`: **sve što crta kartu**, vidi niže.
|
||||
|
||||
## Build i pokretanje
|
||||
|
||||
```
|
||||
gradlew :engine:test # testovi pravila + simulacija 1000 partija
|
||||
gradlew :app:assembleDebug # APK u app/build/outputs/apk/debug/
|
||||
gradlew :app:installDebug # instalacija na spojeni uređaj ili emulator
|
||||
```
|
||||
|
||||
Projekt koristi AGP 9.4.1, Kotlin 2.4.21, Gradle 9.8.2 i compileSdk 36, iste verzije kao AndroidTV projekt.
|
||||
|
||||
## Karte
|
||||
|
||||
Aplikacija koristi slike iz `app/src/main/res/drawable-nodpi/` (`card_<boja>_<vrijednost>.webp`, `suit_<boja>.webp`). Postoje dva izvora, a skripta odabranog izvora prepisuje te slike:
|
||||
|
||||
| Izvor | Naredba | Napomena |
|
||||
| --- | --- | --- |
|
||||
| **PNG špil** (trenutno u upotrebi): [tomasdrus/hungarian-playing-cards](https://github.com/tomasdrus/hungarian-playing-cards), kopiran u `card_assets/hungarian-playing-cards/` | `python tools/import_png_cards.py` | 363×585 px, WebP bez gubitaka. **Repozitorij nema licencu**, vidi `NOTICE.md` u toj mapi. Prije objave aplikacije treba dopuštenje autora. |
|
||||
| Naši SVG-ovi u `card_assets/*.svg` | `python tools/render_cards.py` | Treba Inkscape 1.x. Renderira 720 px. |
|
||||
|
||||
Poleđina je naša i crta se vektorski u kodu (`CardBack`).
|
||||
|
||||
**Pravilo oštrine:** karta se nikad ne crta šire od svoje slike. Svaka veličina karte ograničava se s `maxCardWidth()` (za PNG špil to je 363 px, na ovom emulatoru ~138dp). Slike se dekodiraju u rezoluciji u kojoj se crtaju, s mipmapama. U debug buildu svako povećanje slike zapisuje se u logcat pod oznakom `BelaCards`, pa se provjerava s `adb logcat -s BelaCards`.
|
||||
|
||||
Sve što crta kartu nalazi se u `app/src/main/kotlin/hr/bela/app/ui/CardArt.kt` (`CardFace`, `CardBack`, `SuitIcon`, `maxCardWidth`).
|
||||
|
||||
U kodu se boje zovu `HERC`, `KARO`, `PIK` i `TREF` (= srce, zvono, list, žir), a vrijednosti `SEDAM` … `AS`.
|
||||
|
||||
## Trening brojanja
|
||||
|
||||
S početnog ekrana ("Trening brojanja"). Svaka runda je hrpa osvojenih štihova (po 4 karte) s izmišljenim adutom i ponekad zadnjim štihom (+10). Karte se pokazuju jedna po jedna, a zatim igrač bira jedan od četiri zbroja. Netočni odgovori nastaju iz tipičnih grešaka (dečko ili devetka u adutu, zaboravljen zadnji štih, propuštena desetka ili as…). Nakon odgovora vidi se svaka karta s bodovima i objašnjenje greške.
|
||||
|
||||
- Logika runde: `engine/.../CountingDrill.kt` (s testovima).
|
||||
- Razine (Lako 8 karata, Srednje 12–16, Teško 20–28) i stanje: `app/.../TrainingViewModel.kt`.
|
||||
- Ekran: `app/.../ui/TrainingScreen.kt`.
|
||||
|
||||
## Izgled
|
||||
|
||||
- Fontovi: **Cinzel** (naslovi, rezultat, oznake) i **Inter** (tekst), u `app/src/main/res/font/`. Oba su pod licencom SIL Open Font License, tekst licence je u `licenses/`.
|
||||
- Boje, prijelazi i filc stola su u `ui/Theme.kt`, zajednički gumbi i ukrasi u `ui/Components.kt`.
|
||||
|
||||
## Spremanje partije
|
||||
|
||||
Partija se sprema nakon svakog poteza kao seed i popis poteza (`GameRecord`), pa se nakon zatvaranja aplikacije vraća točno gdje je stala.
|
||||
@@ -0,0 +1,89 @@
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.compose.compiler)
|
||||
}
|
||||
|
||||
// versionCode is the git commit count (monotonic, no manual bumps), so every release is strictly
|
||||
// newer than the last, which is what the in-app updater compares. A build without .git can pass it in:
|
||||
// -PbelaVersionCode=<n>.
|
||||
val gitCommitCount: Int = providers.gradleProperty("belaVersionCode").orNull?.toIntOrNull()
|
||||
?: runCatching {
|
||||
providers.exec { commandLine("git", "rev-list", "--count", "HEAD") }
|
||||
.standardOutput.asText.get().trim().toInt()
|
||||
}.getOrDefault(1)
|
||||
|
||||
// versionName is the commit count as a base-10 odometer (commit #13 -> 0.1.3, #100 -> 1.0.0), so the
|
||||
// updater can turn a release tag back into its versionCode. Same scheme as the Keep app.
|
||||
val versionNameFromGit = "${gitCommitCount / 100}.${(gitCommitCount / 10) % 10}.${gitCommitCount % 10}"
|
||||
|
||||
// Release signing reads keystore.properties in the project root (gitignored, made by
|
||||
// tools/build-release.ps1 on first run). Without it the release build stays unsigned.
|
||||
val keystorePropsFile = rootProject.file("keystore.properties")
|
||||
val keystoreProps = Properties().apply {
|
||||
if (keystorePropsFile.exists()) keystorePropsFile.inputStream().use { load(it) }
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "hr.bela.app"
|
||||
compileSdk = 36
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "hr.bela.app"
|
||||
minSdk = 26
|
||||
targetSdk = 36
|
||||
versionCode = gitCommitCount
|
||||
versionName = versionNameFromGit
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
if (keystorePropsFile.exists()) {
|
||||
storeFile = rootProject.file(keystoreProps.getProperty("storeFile"))
|
||||
storePassword = keystoreProps.getProperty("storePassword")
|
||||
keyAlias = keystoreProps.getProperty("keyAlias")
|
||||
keyPassword = keystoreProps.getProperty("keyPassword")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
debug {
|
||||
isMinifyEnabled = false
|
||||
}
|
||||
release {
|
||||
isMinifyEnabled = true
|
||||
isShrinkResources = true
|
||||
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"))
|
||||
if (keystorePropsFile.exists()) signingConfig = signingConfigs.getByName("release")
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
compose = true
|
||||
buildConfig = true
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":engine"))
|
||||
|
||||
implementation(platform(libs.compose.bom))
|
||||
implementation(libs.compose.ui)
|
||||
implementation(libs.compose.foundation)
|
||||
implementation(libs.compose.material3)
|
||||
implementation(libs.compose.ui.tooling.preview)
|
||||
debugImplementation(libs.compose.ui.tooling)
|
||||
|
||||
implementation(libs.activity.compose)
|
||||
implementation(libs.lifecycle.runtime.compose)
|
||||
implementation(libs.lifecycle.viewmodel.compose)
|
||||
implementation(libs.coroutines.android)
|
||||
implementation(libs.zxing.core)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<!-- Settings: check the public release repo for a newer version and download it. -->
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<!-- Hand the downloaded update to the system installer (the user still confirms it). -->
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:roundIcon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.Bela">
|
||||
|
||||
<!-- Portrait only for v0: the table layout is built for a phone held upright. -->
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:screenOrientation="portrait">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- Shares a downloaded update APK with the package installer. -->
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.updates"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/update_paths" />
|
||||
</provider>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,178 @@
|
||||
package hr.bela.app
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import hr.bela.engine.Action
|
||||
import hr.bela.engine.Bela
|
||||
import hr.bela.engine.BotStrategy
|
||||
import hr.bela.engine.Card
|
||||
import hr.bela.engine.CompletedTrick
|
||||
import hr.bela.engine.GameRecord
|
||||
import hr.bela.engine.GameState
|
||||
import hr.bela.engine.HeuristicBot
|
||||
import hr.bela.engine.Phase
|
||||
import hr.bela.engine.Suit
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** The person holding the phone always sits at seat 0; the partner bot is seat 2. */
|
||||
const val HUMAN = 0
|
||||
|
||||
data class UiState(
|
||||
/** Null on the home screen. */
|
||||
val game: GameState? = null,
|
||||
/** A finished trick kept on the table for a moment before it is gathered. */
|
||||
val shownTrick: CompletedTrick? = null,
|
||||
/** Short speech bubble over a seat, such as "Bela!". */
|
||||
val bubble: Pair<Int, String>? = null,
|
||||
val hasSavedGame: Boolean = false,
|
||||
val showScoreSheet: Boolean = false,
|
||||
val showLastTrick: Boolean = false,
|
||||
) {
|
||||
/** The table is busy showing a trick; the player cannot act yet. */
|
||||
val inputLocked: Boolean get() = shownTrick != null
|
||||
}
|
||||
|
||||
class GameViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val prefs = app.getSharedPreferences("bela", Context.MODE_PRIVATE)
|
||||
private val bot: BotStrategy = HeuristicBot
|
||||
|
||||
private val _ui = MutableStateFlow(UiState(hasSavedGame = savedRecord() != null))
|
||||
val ui: StateFlow<UiState> = _ui.asStateFlow()
|
||||
|
||||
/** Seed plus every action so far; saved after each move so a game survives the app being closed. */
|
||||
private var record: GameRecord? = null
|
||||
private var botLoop: Job? = null
|
||||
private var bubbleJob: Job? = null
|
||||
|
||||
fun newGame() {
|
||||
val game = Bela.newGame()
|
||||
record = GameRecord(game.seed)
|
||||
_ui.value = UiState(game = game, hasSavedGame = true)
|
||||
save()
|
||||
driveBots()
|
||||
}
|
||||
|
||||
fun continueGame() {
|
||||
val saved = savedRecord()
|
||||
val game = saved?.let { runCatching { it.replay() }.getOrNull() }
|
||||
if (saved == null || game == null) return newGame()
|
||||
record = saved
|
||||
_ui.value = UiState(game = game, hasSavedGame = true)
|
||||
driveBots()
|
||||
}
|
||||
|
||||
fun leaveTable() {
|
||||
botLoop?.cancel()
|
||||
bubbleJob?.cancel()
|
||||
_ui.value = UiState(hasSavedGame = savedRecord() != null)
|
||||
}
|
||||
|
||||
fun callTrump(suit: Suit?) {
|
||||
val game = _ui.value.game ?: return
|
||||
if (game.phase != Phase.BIDDING || game.toAct != HUMAN) return
|
||||
if (suit == null && !game.canPass(HUMAN)) return
|
||||
act(Action.Call(HUMAN, suit))
|
||||
driveBots()
|
||||
}
|
||||
|
||||
fun playCard(card: Card) {
|
||||
val state = _ui.value
|
||||
val game = state.game ?: return
|
||||
if (state.inputLocked || card !in game.legalMoves(HUMAN)) return
|
||||
act(Action.Play(HUMAN, card))
|
||||
driveBots()
|
||||
}
|
||||
|
||||
fun nextHand() {
|
||||
val state = _ui.value
|
||||
if (state.game?.phase != Phase.HAND_OVER || state.inputLocked) return
|
||||
act(Action.NextHand)
|
||||
driveBots()
|
||||
}
|
||||
|
||||
fun showScoreSheet(show: Boolean) = _ui.update { it.copy(showScoreSheet = show) }
|
||||
|
||||
fun showLastTrick(show: Boolean) = _ui.update { it.copy(showLastTrick = show) }
|
||||
|
||||
private fun act(action: Action) {
|
||||
val before = _ui.value.game ?: return
|
||||
val after = before.apply(action)
|
||||
record = record?.plus(action)
|
||||
|
||||
val finishedTrick = (action as? Action.Play)
|
||||
?.takeIf { after.hand.tricks.size > before.hand.tricks.size }
|
||||
?.let { after.hand.tricks.last() }
|
||||
_ui.update {
|
||||
it.copy(
|
||||
game = after,
|
||||
shownTrick = finishedTrick ?: it.shownTrick,
|
||||
showLastTrick = it.showLastTrick && action !is Action.NextHand,
|
||||
)
|
||||
}
|
||||
|
||||
if (action is Action.Play && !before.hand.belaAnnounced && after.hand.belaAnnounced) {
|
||||
showBubble(action.seat, "Bela!")
|
||||
}
|
||||
if (after.phase == Phase.GAME_OVER) clearSave() else save()
|
||||
}
|
||||
|
||||
/** Let the bots act, with short pauses so the player can follow, until it is the player's turn. */
|
||||
private fun driveBots() {
|
||||
botLoop?.cancel()
|
||||
botLoop = viewModelScope.launch {
|
||||
while (true) {
|
||||
if (_ui.value.shownTrick != null) {
|
||||
delay(TRICK_PAUSE_MS)
|
||||
_ui.update { it.copy(shownTrick = null) }
|
||||
}
|
||||
val game = _ui.value.game ?: return@launch
|
||||
val seat = game.toAct ?: return@launch
|
||||
if (seat == HUMAN) return@launch
|
||||
delay(if (game.phase == Phase.BIDDING) BID_DELAY_MS else PLAY_DELAY_MS)
|
||||
val action = if (game.phase == Phase.BIDDING) {
|
||||
Action.Call(seat, bot.chooseTrump(game, seat))
|
||||
} else {
|
||||
Action.Play(seat, bot.chooseCard(game, seat))
|
||||
}
|
||||
act(action)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun showBubble(seat: Int, text: String) {
|
||||
bubbleJob?.cancel()
|
||||
_ui.update { it.copy(bubble = seat to text) }
|
||||
bubbleJob = viewModelScope.launch {
|
||||
delay(BUBBLE_MS)
|
||||
_ui.update { it.copy(bubble = null) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun save() {
|
||||
record?.let { prefs.edit().putString(KEY_GAME, it.encode()).apply() }
|
||||
}
|
||||
|
||||
private fun clearSave() {
|
||||
prefs.edit().remove(KEY_GAME).apply()
|
||||
_ui.update { it.copy(hasSavedGame = false) }
|
||||
}
|
||||
|
||||
private fun savedRecord(): GameRecord? = prefs.getString(KEY_GAME, null)?.let(GameRecord::decode)
|
||||
|
||||
private companion object {
|
||||
const val KEY_GAME = "saved_game"
|
||||
const val BID_DELAY_MS = 700L
|
||||
const val PLAY_DELAY_MS = 600L
|
||||
/** How long a finished trick stays on the table; the UI slides it to the winner near the end (TrickArea). */
|
||||
const val TRICK_PAUSE_MS = 1500L
|
||||
const val BUBBLE_MS = 1600L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package hr.bela.app
|
||||
|
||||
import android.graphics.Color
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.SystemBarStyle
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import hr.bela.app.ui.BelaTheme
|
||||
import hr.bela.app.ui.HomeScreen
|
||||
import hr.bela.app.ui.SettingsScreen
|
||||
import hr.bela.app.ui.TableScreen
|
||||
import hr.bela.app.ui.TrainingScreen
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
// The felt is always dark, so system bar icons stay light whatever the system theme.
|
||||
enableEdgeToEdge(
|
||||
statusBarStyle = SystemBarStyle.dark(Color.TRANSPARENT),
|
||||
navigationBarStyle = SystemBarStyle.dark(Color.TRANSPARENT),
|
||||
)
|
||||
setContent {
|
||||
BelaTheme {
|
||||
BelaApp()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Screens reached from the home screen; a running game is shown whenever one is open. */
|
||||
private enum class Screen { HOME, TRAINING, SETTINGS }
|
||||
|
||||
@Composable
|
||||
private fun BelaApp(vm: GameViewModel = viewModel()) {
|
||||
val state by vm.ui.collectAsStateWithLifecycle()
|
||||
var screen by rememberSaveable { mutableStateOf(Screen.HOME) }
|
||||
if (screen == Screen.TRAINING) {
|
||||
TrainingScreen(onExit = { screen = Screen.HOME })
|
||||
} else if (screen == Screen.SETTINGS) {
|
||||
SettingsScreen(onExit = { screen = Screen.HOME })
|
||||
} else if (state.game == null) {
|
||||
HomeScreen(
|
||||
hasSavedGame = state.hasSavedGame,
|
||||
onContinue = vm::continueGame,
|
||||
onNewGame = vm::newGame,
|
||||
onTraining = { screen = Screen.TRAINING },
|
||||
onSettings = { screen = Screen.SETTINGS },
|
||||
)
|
||||
} else {
|
||||
TableScreen(
|
||||
state = state,
|
||||
onCall = vm::callTrump,
|
||||
onPlay = vm::playCard,
|
||||
onNextHand = vm::nextHand,
|
||||
onNewGame = vm::newGame,
|
||||
onLeave = vm::leaveTable,
|
||||
onScoreSheet = vm::showScoreSheet,
|
||||
onLastTrick = vm::showLastTrick,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package hr.bela.app
|
||||
|
||||
import android.app.Application
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import hr.bela.app.update.ReleaseInfo
|
||||
import hr.bela.app.update.UpdateCheck
|
||||
import hr.bela.app.update.Updates
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import java.io.File
|
||||
|
||||
/** Where the update flow in Settings stands. */
|
||||
sealed interface UpdateState {
|
||||
data object Checking : UpdateState
|
||||
data class UpToDate(val latest: String) : UpdateState
|
||||
data object NoReleases : UpdateState
|
||||
data class Available(val release: ReleaseInfo) : UpdateState
|
||||
data class Downloading(val release: ReleaseInfo, val progress: Float) : UpdateState
|
||||
|
||||
/** Downloaded, but Android needs "install unknown apps" allowed for Bela first. */
|
||||
data class NeedsPermission(val release: ReleaseInfo, val apk: File) : UpdateState
|
||||
|
||||
/** The system installer was opened. */
|
||||
data class Installing(val release: ReleaseInfo, val apk: File) : UpdateState
|
||||
data class Failed(val message: String) : UpdateState
|
||||
}
|
||||
|
||||
class SettingsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val updates = Updates(app)
|
||||
private val _update = MutableStateFlow<UpdateState>(UpdateState.Checking)
|
||||
val update: StateFlow<UpdateState> = _update.asStateFlow()
|
||||
|
||||
init {
|
||||
check()
|
||||
}
|
||||
|
||||
fun check() {
|
||||
_update.value = UpdateState.Checking
|
||||
viewModelScope.launch {
|
||||
_update.value = when (val result = updates.check()) {
|
||||
is UpdateCheck.Available -> UpdateState.Available(result.release)
|
||||
is UpdateCheck.UpToDate -> UpdateState.UpToDate(result.latest.versionName)
|
||||
UpdateCheck.NoReleases -> UpdateState.NoReleases
|
||||
is UpdateCheck.Failed -> UpdateState.Failed(result.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun download(release: ReleaseInfo) {
|
||||
_update.value = UpdateState.Downloading(release, 0f)
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val apk = updates.download(release) { progress -> _update.value = UpdateState.Downloading(release, progress) }
|
||||
install(release, apk)
|
||||
} catch (e: Exception) {
|
||||
_update.value = UpdateState.Failed(e.message ?: "Preuzimanje nije uspjelo")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens the installer, or asks for the "install unknown apps" permission first. */
|
||||
fun install(release: ReleaseInfo, apk: File) {
|
||||
if (updates.canInstall()) {
|
||||
updates.install(apk)
|
||||
_update.value = UpdateState.Installing(release, apk)
|
||||
} else {
|
||||
_update.value = UpdateState.NeedsPermission(release, apk)
|
||||
}
|
||||
}
|
||||
|
||||
fun openInstallPermission() = updates.openInstallPermissionSettings()
|
||||
|
||||
/** Back from the system settings: continue if the permission was granted. */
|
||||
fun onResume() {
|
||||
val state = _update.value
|
||||
if (state is UpdateState.NeedsPermission && updates.canInstall()) install(state.release, state.apk)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package hr.bela.app
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import hr.bela.engine.AnswerOption
|
||||
import hr.bela.engine.CountingDrill
|
||||
import hr.bela.engine.CountingRound
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlin.random.Random
|
||||
|
||||
/** How big the pile is: number of won tricks (4 cards each) and how often the last trick (+10) is included. */
|
||||
enum class DrillLevel(val label: String, val tricks: IntRange, val lastTrickChance: Double) {
|
||||
LAKO("Lako", 2..2, 0.0),
|
||||
SREDNJE("Srednje", 3..4, 0.5),
|
||||
TESKO("Teško", 5..7, 0.5),
|
||||
}
|
||||
|
||||
enum class DrillPhase {
|
||||
/** Cards are shown one at a time. */
|
||||
COUNTING,
|
||||
|
||||
/** All cards seen; pick one of four totals. */
|
||||
ANSWERING,
|
||||
|
||||
/** Answer given; show the verdict and the breakdown. */
|
||||
RESULT,
|
||||
}
|
||||
|
||||
data class TrainingState(
|
||||
val level: DrillLevel,
|
||||
val round: CountingRound,
|
||||
/** How many cards of the pile have been shown so far (the last of them is on screen). */
|
||||
val shown: Int = 1,
|
||||
val phase: DrillPhase = DrillPhase.COUNTING,
|
||||
val chosen: AnswerOption? = null,
|
||||
val answered: Int = 0,
|
||||
val correct: Int = 0,
|
||||
val streak: Int = 0,
|
||||
val bestStreak: Int = 0,
|
||||
) {
|
||||
val isLastCard: Boolean get() = shown >= round.cards.size
|
||||
val wasCorrect: Boolean get() = chosen?.value == round.total
|
||||
}
|
||||
|
||||
/** Card-counting practice: count a pile card by card, then pick the right total of four. */
|
||||
class TrainingViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val prefs = app.getSharedPreferences("bela_training", Context.MODE_PRIVATE)
|
||||
private val random = Random.Default
|
||||
|
||||
private val _state = MutableStateFlow(
|
||||
TrainingState(
|
||||
level = DrillLevel.SREDNJE,
|
||||
round = newRound(DrillLevel.SREDNJE),
|
||||
bestStreak = prefs.getInt(KEY_BEST_STREAK, 0),
|
||||
),
|
||||
)
|
||||
val state: StateFlow<TrainingState> = _state.asStateFlow()
|
||||
|
||||
/** Show the next card, or move on to the answers after the last one. */
|
||||
fun next() = _state.update { s ->
|
||||
when {
|
||||
s.phase != DrillPhase.COUNTING -> s
|
||||
s.isLastCard -> s.copy(phase = DrillPhase.ANSWERING)
|
||||
else -> s.copy(shown = s.shown + 1)
|
||||
}
|
||||
}
|
||||
|
||||
fun answer(option: AnswerOption) = _state.update { s ->
|
||||
if (s.phase != DrillPhase.ANSWERING) return@update s
|
||||
val right = option.value == s.round.total
|
||||
val streak = if (right) s.streak + 1 else 0
|
||||
val best = maxOf(s.bestStreak, streak)
|
||||
if (best > s.bestStreak) prefs.edit().putInt(KEY_BEST_STREAK, best).apply()
|
||||
s.copy(
|
||||
phase = DrillPhase.RESULT,
|
||||
chosen = option,
|
||||
answered = s.answered + 1,
|
||||
correct = s.correct + if (right) 1 else 0,
|
||||
streak = streak,
|
||||
bestStreak = best,
|
||||
)
|
||||
}
|
||||
|
||||
fun nextRound() = _state.update { s ->
|
||||
s.copy(round = newRound(s.level), shown = 1, phase = DrillPhase.COUNTING, chosen = null)
|
||||
}
|
||||
|
||||
fun setLevel(level: DrillLevel) = _state.update { s ->
|
||||
if (level == s.level) s else s.copy(level = level, round = newRound(level), shown = 1, phase = DrillPhase.COUNTING, chosen = null)
|
||||
}
|
||||
|
||||
private fun newRound(level: DrillLevel): CountingRound =
|
||||
CountingDrill.round(random, level.tricks.random(random), lastTrick = random.nextDouble() < level.lastTrickChance)
|
||||
|
||||
private companion object {
|
||||
const val KEY_BEST_STREAK = "best_streak"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
package hr.bela.app.ui
|
||||
|
||||
import android.content.res.Resources
|
||||
import android.graphics.BitmapFactory
|
||||
import android.util.Log
|
||||
import android.util.LruCache
|
||||
import androidx.annotation.DrawableRes
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.drawWithCache
|
||||
import androidx.compose.ui.draw.shadow
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.FilterQuality
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.graphics.drawscope.clipRect
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import androidx.compose.ui.unit.dp
|
||||
import hr.bela.app.BuildConfig
|
||||
import hr.bela.app.R
|
||||
import hr.bela.engine.Card
|
||||
import hr.bela.engine.Suit
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/*
|
||||
* Card artwork. Every card on screen is drawn by CardFace, CardBack or SuitIcon in this file.
|
||||
*
|
||||
* The images are WebP files in res/drawable-nodpi (card_<suit>_<rank>, suit_<suit>), produced by
|
||||
* tools/import_png_cards.py (the PNG deck in card_assets/hungarian-playing-cards) or tools/render_cards.py
|
||||
* (our own SVG cards). Cards are never drawn wider than their image: use maxCardWidth() when sizing them.
|
||||
* The back is our own design, drawn as vectors (CardBack).
|
||||
*/
|
||||
|
||||
/** Card width divided by height (363 x 585 for the PNG deck, 175 x 282 for the SVG deck: the same shape). */
|
||||
const val CARD_ASPECT = 363f / 585f
|
||||
|
||||
/** Same corner radius as the artwork (22 px on a 363 px card), so its own outline is not cut. */
|
||||
private val CardShape = RoundedCornerShape(6)
|
||||
|
||||
/**
|
||||
* Decodes card images for the size they are drawn at: the smallest power-of-two reduction that is still at least
|
||||
* as wide as on screen, with mipmaps, so they stay sharp from tiny (declarations) to full size (training) without
|
||||
* keeping full-size bitmaps of the whole deck in memory.
|
||||
*/
|
||||
private object CardBitmaps {
|
||||
private val cache = object : LruCache<Long, ImageBitmap>(32 * 1024 * 1024) {
|
||||
override fun sizeOf(key: Long, value: ImageBitmap) = value.width * value.height * 4
|
||||
}
|
||||
private val sizes = HashMap<Int, IntSize>()
|
||||
|
||||
/** Pixel size of the image file, read without decoding it. */
|
||||
fun sourceSize(resources: Resources, @DrawableRes id: Int): IntSize = sizes.getOrPut(id) {
|
||||
val bounds = BitmapFactory.Options().apply {
|
||||
inJustDecodeBounds = true
|
||||
inScaled = false
|
||||
}
|
||||
BitmapFactory.decodeResource(resources, id, bounds)
|
||||
IntSize(bounds.outWidth, bounds.outHeight)
|
||||
}
|
||||
|
||||
fun get(resources: Resources, @DrawableRes id: Int, widthPx: Int): ImageBitmap {
|
||||
val source = sourceSize(resources, id).width
|
||||
if (BuildConfig.DEBUG && widthPx > source) {
|
||||
Log.w("BelaCards", "Upscaled: ${resources.getResourceEntryName(id)} drawn $widthPx px wide, image is $source px")
|
||||
}
|
||||
var sample = 1
|
||||
while (source / (sample * 2) >= widthPx) sample *= 2
|
||||
val key = (id.toLong() shl 8) or sample.toLong()
|
||||
cache.get(key)?.let { return it }
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inSampleSize = sample
|
||||
inScaled = false
|
||||
}
|
||||
val bitmap = BitmapFactory.decodeResource(resources, id, options)
|
||||
bitmap.setHasMipMap(true)
|
||||
return bitmap.asImageBitmap().also { cache.put(key, it) }
|
||||
}
|
||||
}
|
||||
|
||||
/** The widest a card may be drawn without enlarging its image (363 px of artwork, in dp for this screen). */
|
||||
@Composable
|
||||
fun maxCardWidth(): Dp {
|
||||
val width = CardBitmaps.sourceSize(LocalContext.current.resources, R.drawable.card_srce_as).width
|
||||
return with(LocalDensity.current) { width.toDp() }
|
||||
}
|
||||
|
||||
/** Card images per suit, in rank order 7, 8, 9, 10, dečko, dama, kralj, as (the order of [hr.bela.engine.Rank]). */
|
||||
private val CARD_IMAGES: Map<Suit, List<Int>> = mapOf(
|
||||
Suit.HERC to listOf(
|
||||
R.drawable.card_srce_7, R.drawable.card_srce_8, R.drawable.card_srce_9, R.drawable.card_srce_10,
|
||||
R.drawable.card_srce_decko, R.drawable.card_srce_dama, R.drawable.card_srce_kralj, R.drawable.card_srce_as,
|
||||
),
|
||||
Suit.KARO to listOf(
|
||||
R.drawable.card_zvono_7, R.drawable.card_zvono_8, R.drawable.card_zvono_9, R.drawable.card_zvono_10,
|
||||
R.drawable.card_zvono_decko, R.drawable.card_zvono_dama, R.drawable.card_zvono_kralj, R.drawable.card_zvono_as,
|
||||
),
|
||||
Suit.PIK to listOf(
|
||||
R.drawable.card_list_7, R.drawable.card_list_8, R.drawable.card_list_9, R.drawable.card_list_10,
|
||||
R.drawable.card_list_decko, R.drawable.card_list_dama, R.drawable.card_list_kralj, R.drawable.card_list_as,
|
||||
),
|
||||
Suit.TREF to listOf(
|
||||
R.drawable.card_zir_7, R.drawable.card_zir_8, R.drawable.card_zir_9, R.drawable.card_zir_10,
|
||||
R.drawable.card_zir_decko, R.drawable.card_zir_dama, R.drawable.card_zir_kralj, R.drawable.card_zir_as,
|
||||
),
|
||||
)
|
||||
|
||||
@DrawableRes
|
||||
fun cardImage(card: Card): Int = CARD_IMAGES.getValue(card.suit)[card.rank.ordinal]
|
||||
|
||||
@DrawableRes
|
||||
fun suitImage(suit: Suit): Int = when (suit) {
|
||||
Suit.HERC -> R.drawable.suit_srce
|
||||
Suit.KARO -> R.drawable.suit_zvono
|
||||
Suit.PIK -> R.drawable.suit_list
|
||||
Suit.TREF -> R.drawable.suit_zir
|
||||
}
|
||||
|
||||
/** Draws the image [id] over the whole element, decoded for the element's pixel size. */
|
||||
private fun Modifier.cardImage(resources: Resources, @DrawableRes id: Int): Modifier = drawWithCache {
|
||||
val w = size.width.roundToInt().coerceAtLeast(1)
|
||||
val h = size.height.roundToInt().coerceAtLeast(1)
|
||||
val bitmap = CardBitmaps.get(resources, id, w)
|
||||
onDrawBehind { drawImage(bitmap, dstSize = IntSize(w, h), filterQuality = FilterQuality.High) }
|
||||
}
|
||||
|
||||
/**
|
||||
* [elevation] sets the drop shadow. A highlighted card (the trick winner) gets a gold frame;
|
||||
* [glow] casts a gold shadow instead of a black one (cards the player may play).
|
||||
*/
|
||||
@Composable
|
||||
fun CardFace(
|
||||
card: Card,
|
||||
modifier: Modifier = Modifier,
|
||||
dimmed: Boolean = false,
|
||||
highlighted: Boolean = false,
|
||||
glow: Boolean = false,
|
||||
elevation: Dp = 2.dp,
|
||||
) {
|
||||
val resources = LocalContext.current.resources
|
||||
val name = cardName(card)
|
||||
Box(
|
||||
modifier
|
||||
.aspectRatio(CARD_ASPECT)
|
||||
.shadow(
|
||||
elevation = if (highlighted) elevation + 6.dp else elevation,
|
||||
shape = CardShape,
|
||||
ambientColor = if (glow) Gold else Color.Black,
|
||||
spotColor = if (highlighted || glow) Gold else Color.Black,
|
||||
)
|
||||
.clip(CardShape)
|
||||
.cardImage(resources, cardImage(card))
|
||||
.then(if (highlighted) Modifier.border(3.dp, Gold, CardShape) else Modifier)
|
||||
.semantics { contentDescription = name },
|
||||
) {
|
||||
if (dimmed) Box(Modifier.fillMaxSize().background(Color(0x73000000)))
|
||||
}
|
||||
}
|
||||
|
||||
private val BackBase = Brush.linearGradient(listOf(Color(0xFF8E2530), Color(0xFF5A1019), Color(0xFF3E0A11)))
|
||||
|
||||
/**
|
||||
* Our own card back, drawn as vectors so it is sharp at any size: burgundy with a gold lattice, frame and centre
|
||||
* medallion. [small] is for the bots' fans (thinner edge); [landscape] lays the card on its side.
|
||||
*/
|
||||
@Composable
|
||||
fun CardBack(modifier: Modifier = Modifier, small: Boolean = false, landscape: Boolean = false) {
|
||||
Canvas(
|
||||
modifier
|
||||
.aspectRatio(if (landscape) 1f / CARD_ASPECT else CARD_ASPECT)
|
||||
.shadow(if (small) 3.dp else 4.dp, CardShape)
|
||||
.clip(CardShape)
|
||||
.background(BackBase)
|
||||
.border(if (small) 0.75.dp else 1.dp, Cream.copy(alpha = 0.9f), CardShape),
|
||||
) {
|
||||
val w = size.width
|
||||
val h = size.height
|
||||
val short = minOf(w, h)
|
||||
val inset = short * 0.09f
|
||||
// Diagonal gold lattice inside the frame.
|
||||
clipRect(inset, inset, w - inset, h - inset) {
|
||||
val step = short / 5f
|
||||
var x = -h
|
||||
while (x < w + h) {
|
||||
drawLine(Gold.copy(alpha = 0.22f), Offset(x, 0f), Offset(x + h, h), strokeWidth = short * 0.012f)
|
||||
drawLine(Gold.copy(alpha = 0.22f), Offset(x + h, 0f), Offset(x, h), strokeWidth = short * 0.012f)
|
||||
x += step
|
||||
}
|
||||
}
|
||||
drawRoundRect(
|
||||
Gold.copy(alpha = 0.75f),
|
||||
topLeft = Offset(inset, inset),
|
||||
size = Size(w - 2 * inset, h - 2 * inset),
|
||||
cornerRadius = CornerRadius(short * 0.04f),
|
||||
style = Stroke(width = short * 0.02f),
|
||||
)
|
||||
// Medallion: a gold diamond with a burgundy centre.
|
||||
val c = Offset(w / 2, h / 2)
|
||||
val r = short * 0.2f
|
||||
val outer = Path().apply {
|
||||
moveTo(c.x, c.y - r); lineTo(c.x + r, c.y); lineTo(c.x, c.y + r); lineTo(c.x - r, c.y); close()
|
||||
}
|
||||
drawPath(outer, GoldBrush)
|
||||
val ri = r * 0.55f
|
||||
val inner = Path().apply {
|
||||
moveTo(c.x, c.y - ri); lineTo(c.x + ri, c.y); lineTo(c.x, c.y + ri); lineTo(c.x - ri, c.y); close()
|
||||
}
|
||||
drawPath(inner, Color(0xFF5A1019))
|
||||
}
|
||||
}
|
||||
|
||||
/** A suit symbol, kept at its own proportions and centred in a [size] square. */
|
||||
@Composable
|
||||
fun SuitIcon(suit: Suit, size: Dp, modifier: Modifier = Modifier) {
|
||||
val resources = LocalContext.current.resources
|
||||
val id = suitImage(suit)
|
||||
val name = suitName(suit)
|
||||
Box(
|
||||
modifier
|
||||
.size(size)
|
||||
.drawWithCache {
|
||||
val source = CardBitmaps.sourceSize(resources, id)
|
||||
val scale = min(this.size.width / source.width, this.size.height / source.height)
|
||||
val w = (source.width * scale).roundToInt().coerceAtLeast(1)
|
||||
val h = (source.height * scale).roundToInt().coerceAtLeast(1)
|
||||
val bitmap = CardBitmaps.get(resources, id, w)
|
||||
val offset = Offset((this.size.width - w) / 2, (this.size.height - h) / 2)
|
||||
onDrawBehind {
|
||||
drawImage(
|
||||
bitmap,
|
||||
dstOffset = IntOffset(offset.x.roundToInt(), offset.y.roundToInt()),
|
||||
dstSize = IntSize(w, h),
|
||||
filterQuality = FilterQuality.High,
|
||||
)
|
||||
}
|
||||
}
|
||||
.semantics { contentDescription = name },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package hr.bela.app.ui
|
||||
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.safeDrawing
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.ripple
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.rotate
|
||||
import androidx.compose.ui.draw.shadow
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import hr.bela.engine.Suit
|
||||
|
||||
private val ButtonShape = RoundedCornerShape(16.dp)
|
||||
|
||||
/** How far from the physical top edge top-centre content must start to clear a punch-hole camera. */
|
||||
private val CameraZoneBottom = 66.dp
|
||||
|
||||
/**
|
||||
* Extra top space for screens whose top bar holds content in the centre, so a punch-hole camera never covers it.
|
||||
* Many phones (and emulators) do not report the hole, so this does not rely on the cutout insets alone:
|
||||
* it tops up whatever the system insets already give to [CameraZoneBottom].
|
||||
*/
|
||||
@Composable
|
||||
fun cameraClearance(): Dp {
|
||||
val top = with(LocalDensity.current) { WindowInsets.safeDrawing.getTop(this).toDp() }
|
||||
return (CameraZoneBottom - top).coerceAtLeast(0.dp)
|
||||
}
|
||||
|
||||
/** Shrinks slightly while pressed. */
|
||||
@Composable
|
||||
private fun pressScale(interaction: MutableInteractionSource): Float {
|
||||
val pressed by interaction.collectIsPressedAsState()
|
||||
val scale by animateFloatAsState(if (pressed) 0.97f else 1f, tween(120), label = "press")
|
||||
return scale
|
||||
}
|
||||
|
||||
/** Main call to action: polished gold, engraved capitals. */
|
||||
@Composable
|
||||
fun GoldButton(text: String, onClick: () -> Unit, modifier: Modifier = Modifier) {
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val scale = pressScale(interaction)
|
||||
Box(
|
||||
modifier
|
||||
.fillMaxWidth()
|
||||
.height(54.dp)
|
||||
.graphicsLayer {
|
||||
scaleX = scale
|
||||
scaleY = scale
|
||||
}
|
||||
.shadow(12.dp, ButtonShape, ambientColor = GoldDeep, spotColor = GoldDeep)
|
||||
.clip(ButtonShape)
|
||||
.background(GoldVertical)
|
||||
.border(1.dp, Brush.verticalGradient(listOf(Color(0xFFFFF6D2), Color(0x00FFF6D2))), ButtonShape)
|
||||
.clickable(interaction, ripple(color = Ink), onClick = onClick),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(text.uppercase(), color = Ink, fontFamily = Cinzel, fontWeight = FontWeight.Bold, fontSize = 15.sp, letterSpacing = 1.5.sp)
|
||||
}
|
||||
}
|
||||
|
||||
/** Secondary action: smoked glass with a faint edge. */
|
||||
@Composable
|
||||
fun GlassButton(text: String, onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true) {
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val scale = pressScale(interaction)
|
||||
Box(
|
||||
modifier
|
||||
.fillMaxWidth()
|
||||
.height(50.dp)
|
||||
.graphicsLayer {
|
||||
scaleX = scale
|
||||
scaleY = scale
|
||||
}
|
||||
.clip(ButtonShape)
|
||||
.background(Glass)
|
||||
.border(1.dp, if (enabled) Cream.copy(alpha = 0.3f) else CreamFaint, ButtonShape)
|
||||
.clickable(interaction, ripple(color = Cream), enabled = enabled, onClick = onClick),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
text.uppercase(),
|
||||
color = if (enabled) Cream else CreamMuted,
|
||||
fontFamily = Cinzel,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
fontSize = 14.sp,
|
||||
letterSpacing = 1.5.sp,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Round glass button holding a line icon. */
|
||||
@Composable
|
||||
fun GlassIconButton(icon: ImageVector, description: String, onClick: () -> Unit, modifier: Modifier = Modifier, tint: Color = Cream) {
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val scale = pressScale(interaction)
|
||||
Box(
|
||||
modifier
|
||||
.size(42.dp)
|
||||
.graphicsLayer {
|
||||
scaleX = scale
|
||||
scaleY = scale
|
||||
}
|
||||
.clip(CircleShape)
|
||||
.background(Glass)
|
||||
.border(1.dp, CreamFaint, CircleShape)
|
||||
.clickable(interaction, ripple(color = Cream), onClick = onClick),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(icon, contentDescription = description, tint = tint, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/** A small gold diamond. */
|
||||
@Composable
|
||||
fun Diamond(size: Dp = 6.dp, modifier: Modifier = Modifier) {
|
||||
Box(modifier.size(size).rotate(45f).background(GoldBrush))
|
||||
}
|
||||
|
||||
/** Hairline — diamond — hairline, the divider used under titles. */
|
||||
@Composable
|
||||
fun Ornament(modifier: Modifier = Modifier, lineWidth: Dp = 44.dp) {
|
||||
Row(modifier, verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(Modifier.width(lineWidth).height(1.dp).background(Brush.horizontalGradient(listOf(Color.Transparent, Gold))))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Diamond()
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Box(Modifier.width(lineWidth).height(1.dp).background(Brush.horizontalGradient(listOf(Gold, Color.Transparent))))
|
||||
}
|
||||
}
|
||||
|
||||
/** Spaced small capitals used for labels ("ADUT", "RUKA 3"). */
|
||||
@Composable
|
||||
fun Overline(text: String, modifier: Modifier = Modifier, color: Color = CreamMuted) {
|
||||
Text(
|
||||
text.uppercase(),
|
||||
modifier = modifier,
|
||||
color = color,
|
||||
fontFamily = Cinzel,
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 11.sp,
|
||||
letterSpacing = 2.5.sp,
|
||||
)
|
||||
}
|
||||
|
||||
/** A suit on a cream coin with a gold rim; an empty glass rim with "?" when [suit] is null. */
|
||||
@Composable
|
||||
fun SuitMedallion(suit: Suit?, size: Dp, modifier: Modifier = Modifier) {
|
||||
Box(
|
||||
modifier
|
||||
.size(size)
|
||||
.shadow(if (suit != null) 8.dp else 0.dp, CircleShape)
|
||||
.clip(CircleShape)
|
||||
.background(
|
||||
if (suit != null) {
|
||||
Brush.radialGradient(listOf(Color(0xFFFFFDF6), Color(0xFFE8E0C8)))
|
||||
} else {
|
||||
Brush.radialGradient(listOf(Glass, Glass))
|
||||
},
|
||||
)
|
||||
.border(size * 0.05f, if (suit != null) GoldBrush else Brush.linearGradient(listOf(CreamFaint, CreamFaint)), CircleShape),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (suit != null) {
|
||||
SuitIcon(suit, size * 0.62f)
|
||||
} else {
|
||||
Text("?", color = CreamMuted, fontFamily = Cinzel, fontWeight = FontWeight.Bold, fontSize = 18.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Name in a small smoked-glass capsule. */
|
||||
@Composable
|
||||
fun NamePlate(name: String, modifier: Modifier = Modifier) {
|
||||
Box(
|
||||
modifier
|
||||
.clip(RoundedCornerShape(50))
|
||||
.background(Glass)
|
||||
.border(1.dp, CreamFaint, RoundedCornerShape(50))
|
||||
.padding(horizontal = 10.dp, vertical = 2.dp),
|
||||
) {
|
||||
Text(name, color = Cream, fontSize = 12.sp, fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
package hr.bela.app.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.shadow
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import hr.bela.app.HUMAN
|
||||
import hr.bela.engine.GameState
|
||||
import hr.bela.engine.HandResult
|
||||
import hr.bela.engine.Outcome
|
||||
import hr.bela.engine.Suit
|
||||
import hr.bela.engine.points
|
||||
|
||||
private val Tabular = TextStyle(fontFeatureSettings = "tnum")
|
||||
private val DialogShape = RoundedCornerShape(28.dp)
|
||||
|
||||
/** The app's dialog frame: deep green with a polished gold edge. Content is centred. */
|
||||
@Composable
|
||||
private fun BelaDialog(onDismiss: () -> Unit, dismissable: Boolean = true, content: @Composable ColumnScope.() -> Unit) {
|
||||
Dialog(
|
||||
onDismissRequest = { if (dismissable) onDismiss() },
|
||||
properties = DialogProperties(dismissOnBackPress = dismissable, dismissOnClickOutside = dismissable),
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.shadow(24.dp, DialogShape)
|
||||
.clip(DialogShape)
|
||||
.background(DialogBrush)
|
||||
.border(1.dp, GoldBrush, DialogShape)
|
||||
.padding(horizontal = 24.dp, vertical = 24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Overline, ornament and a title in Cinzel: the head of every dialog. */
|
||||
@Composable
|
||||
private fun DialogHeader(overline: String?, title: String, titleColor: Color = Cream, titleBrush: Brush? = null) {
|
||||
if (overline != null) Overline(overline)
|
||||
Text(
|
||||
title,
|
||||
color = titleColor,
|
||||
style = if (titleBrush != null) TextStyle(brush = titleBrush) else TextStyle.Default,
|
||||
fontFamily = Cinzel,
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 32.sp,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.padding(top = 2.dp),
|
||||
)
|
||||
Ornament(Modifier.padding(top = 6.dp, bottom = 14.dp))
|
||||
}
|
||||
|
||||
/** A row of the score tables: label (optionally followed by a suit icon and [trailing] text), then Mi and Vi. */
|
||||
@Composable
|
||||
private fun ScoreLine(
|
||||
label: String,
|
||||
mi: String,
|
||||
vi: String,
|
||||
strong: Boolean = false,
|
||||
header: Boolean = false,
|
||||
suit: Suit? = null,
|
||||
trailing: String = "",
|
||||
) {
|
||||
val weight = if (strong) FontWeight.Bold else FontWeight.Normal
|
||||
val color = if (header) CreamMuted else Cream
|
||||
val size = if (strong) 16.sp else 14.sp
|
||||
val numberStyle = if (header) {
|
||||
TextStyle(fontFamily = Cinzel, fontWeight = FontWeight.Bold, fontSize = 11.sp, letterSpacing = 2.sp)
|
||||
} else {
|
||||
Tabular.copy(fontWeight = weight, fontSize = size)
|
||||
}
|
||||
Row(Modifier.fillMaxWidth().padding(vertical = 3.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(label, color = color, fontWeight = weight, fontSize = size)
|
||||
suit?.let {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
SuitIcon(it, 16.dp)
|
||||
}
|
||||
if (trailing.isNotEmpty()) Text(trailing, color = CreamMuted, fontSize = 13.sp)
|
||||
}
|
||||
Text(mi, Modifier.width(60.dp), color = color, textAlign = TextAlign.End, style = numberStyle)
|
||||
Text(vi, Modifier.width(60.dp), color = color, textAlign = TextAlign.End, style = numberStyle)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ScoreLine(label: String, values: List<Int>, strong: Boolean = false, suit: Suit? = null, trailing: String = "") =
|
||||
ScoreLine(label, values[0].toString(), values[1].toString(), strong = strong, suit = suit, trailing = trailing)
|
||||
|
||||
@Composable
|
||||
private fun Rule() {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 6.dp)
|
||||
.height(1.dp)
|
||||
.background(Brush.horizontalGradient(listOf(Color.Transparent, Gold.copy(alpha = 0.45f), Color.Transparent))),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun HandResultDialog(game: GameState, result: HandResult, onNextHand: () -> Unit) {
|
||||
val we = result.callerTeam == 0
|
||||
val (headline, color) = when (result.outcome) {
|
||||
Outcome.PASSED -> "Prolaz" to (if (we) WinGreen else LossRed)
|
||||
Outcome.FELL -> "Pad" to (if (we) LossRed else WinGreen)
|
||||
Outcome.TIED -> "Visi" to Gold
|
||||
}
|
||||
BelaDialog(onDismiss = {}, dismissable = false) {
|
||||
DialogHeader("Ruka ${game.results.size}", headline, titleColor = color)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(if (result.caller == HUMAN) "Zvao si" else "${seatName(result.caller)} je zvao", color = Cream, fontSize = 14.sp)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
SuitIcon(result.trump, 18.dp)
|
||||
Text(" ${suitName(result.trump)}", color = Cream, fontSize = 14.sp, fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
Text(
|
||||
when (result.outcome) {
|
||||
Outcome.PASSED -> if (we) "Prošli smo s više od pola bodova." else "Protivnici su prošli s više od pola bodova."
|
||||
Outcome.FELL -> if (we) "Pali smo: svi bodovi idu protivnicima." else "Protivnici su pali: svi bodovi idu nama."
|
||||
Outcome.TIED -> if (we) "Izjednačeno: naši bodovi vise do sljedeće ruke." else "Izjednačeno: bodovi protivnika vise do sljedeće ruke."
|
||||
},
|
||||
color = CreamMuted,
|
||||
fontSize = 13.sp,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.padding(top = 4.dp, bottom = 14.dp),
|
||||
)
|
||||
ScoreLine("", "MI", "VI", header = true)
|
||||
ScoreLine("Karte i zadnji štih", result.cardPoints)
|
||||
ScoreLine("Zvanja", result.declarationPoints)
|
||||
ScoreLine("Bela", result.belaPoints)
|
||||
if (result.stigljaPoints.sum() > 0) ScoreLine("Štiglja", result.stigljaPoints)
|
||||
Rule()
|
||||
ScoreLine("Upisano", result.awarded, strong = true)
|
||||
if (result.settledHanging > 0) {
|
||||
Text("Uključeno ${pointsText(result.settledHanging)} koji su visjeli.", color = CreamMuted, fontSize = 12.sp)
|
||||
}
|
||||
Rule()
|
||||
ScoreLine("Stanje", game.scores, strong = true)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
GoldButton("Sljedeća ruka", onNextHand)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun GameOverDialog(game: GameState, onNewGame: () -> Unit, onLeave: () -> Unit) {
|
||||
val won = game.winnerTeam == 0
|
||||
BelaDialog(onDismiss = {}, dismissable = false) {
|
||||
DialogHeader("Kraj partije", if (won) "Pobjeda" else "Poraz", titleBrush = if (won) GoldVertical else null)
|
||||
game.belotSeat?.let { seat ->
|
||||
Text(
|
||||
if (seat == HUMAN) {
|
||||
"Belot! Imaš svih 8 karata iste boje i odmah dobivate partiju."
|
||||
} else {
|
||||
"Belot! ${seatName(seat)} ima svih 8 karata iste boje i odmah dobiva partiju."
|
||||
},
|
||||
color = Cream,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.padding(bottom = 12.dp),
|
||||
)
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
FinalScore("Mi", game.scores[0], won)
|
||||
Diamond(7.dp, Modifier.padding(horizontal = 22.dp))
|
||||
FinalScore("Vi", game.scores[1], !won)
|
||||
}
|
||||
Text("Odigrano ruku: ${game.results.size}", color = CreamMuted, fontSize = 13.sp, modifier = Modifier.padding(top = 10.dp))
|
||||
Spacer(Modifier.height(22.dp))
|
||||
GoldButton("Nova partija", onNewGame)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
GlassButton("Izbornik", onLeave)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FinalScore(label: String, score: Int, winner: Boolean) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Overline(label)
|
||||
Text(
|
||||
"$score",
|
||||
color = if (winner) Gold else Cream,
|
||||
fontFamily = Cinzel,
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 32.sp,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** The "blok": what each hand wrote for both teams. */
|
||||
@Composable
|
||||
fun ScoreSheetDialog(game: GameState, onDismiss: () -> Unit) {
|
||||
BelaDialog(onDismiss = onDismiss) {
|
||||
DialogHeader(null, "Blok")
|
||||
ScoreLine("", "MI", "VI", header = true)
|
||||
Rule()
|
||||
if (game.results.isEmpty()) {
|
||||
Text("Još nema odigranih ruku.", color = CreamMuted, modifier = Modifier.padding(vertical = 8.dp))
|
||||
}
|
||||
LazyColumn(Modifier.heightIn(max = 340.dp)) {
|
||||
itemsIndexed(game.results) { i, r ->
|
||||
val mark = when (r.outcome) {
|
||||
Outcome.PASSED -> ""
|
||||
Outcome.FELL -> " pad"
|
||||
Outcome.TIED -> " visi"
|
||||
}
|
||||
ScoreLine("${i + 1}. ${seatName(r.caller)}", r.awarded, suit = r.trump, trailing = mark)
|
||||
}
|
||||
}
|
||||
Rule()
|
||||
ScoreLine("Ukupno", game.scores, strong = true)
|
||||
if (game.hanging > 0) Text("Visi: ${pointsText(game.hanging)}", color = Gold, fontSize = 13.sp)
|
||||
Spacer(Modifier.height(18.dp))
|
||||
GlassButton("Zatvori", onDismiss)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun LastTrickDialog(game: GameState, onDismiss: () -> Unit) {
|
||||
val last = game.hand.tricks.lastOrNull()
|
||||
val trump = game.hand.trump
|
||||
if (last == null || trump == null) return
|
||||
BelaDialog(onDismiss = onDismiss) {
|
||||
DialogHeader(null, "Zadnji štih")
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
last.trick.cards.forEachIndexed { i, card ->
|
||||
val seat = last.trick.seatAt(i)
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
CardFace(card, Modifier.width(60.dp), highlighted = seat == last.winner, elevation = 6.dp)
|
||||
Text(
|
||||
seatName(seat),
|
||||
color = if (seat == last.winner) Gold else CreamMuted,
|
||||
fontSize = 12.sp,
|
||||
fontWeight = if (seat == last.winner) FontWeight.SemiBold else FontWeight.Normal,
|
||||
modifier = Modifier.padding(top = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"Štih nosi ${seatName(last.winner)} · ${pointsText(last.trick.points(trump))}",
|
||||
color = Cream,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.padding(top = 16.dp),
|
||||
)
|
||||
Spacer(Modifier.height(18.dp))
|
||||
GlassButton("Zatvori", onDismiss)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package hr.bela.app.ui
|
||||
|
||||
import androidx.compose.animation.core.RepeatMode
|
||||
import androidx.compose.animation.core.animateFloat
|
||||
import androidx.compose.animation.core.infiniteRepeatable
|
||||
import androidx.compose.animation.core.rememberInfiniteTransition
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.safeDrawingPadding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.shadow
|
||||
import androidx.compose.ui.graphics.FilterQuality
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.res.imageResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import hr.bela.app.R
|
||||
|
||||
@Composable
|
||||
fun HomeScreen(
|
||||
hasSavedGame: Boolean,
|
||||
onContinue: () -> Unit,
|
||||
onNewGame: () -> Unit,
|
||||
onTraining: () -> Unit,
|
||||
onSettings: () -> Unit,
|
||||
) {
|
||||
Box(Modifier.fillMaxSize().feltBackground().safeDrawingPadding().padding(horizontal = 28.dp, vertical = 24.dp)) {
|
||||
GlassIconButton(BelaIcons.Settings, "Postavke", onSettings, Modifier.align(Alignment.TopEnd))
|
||||
Column(
|
||||
Modifier.align(Alignment.Center).fillMaxWidth(),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Logo()
|
||||
Ornament(Modifier.padding(top = 22.dp, bottom = 10.dp), lineWidth = 60.dp)
|
||||
Overline("Ti i partner protiv računala")
|
||||
Spacer(Modifier.height(40.dp))
|
||||
if (hasSavedGame) {
|
||||
GoldButton("Nastavi partiju", onContinue)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
GlassButton("Nova partija", onNewGame)
|
||||
} else {
|
||||
GoldButton("Nova partija", onNewGame)
|
||||
}
|
||||
Spacer(Modifier.height(12.dp))
|
||||
GlassButton("Trening brojanja", onTraining)
|
||||
}
|
||||
Text(
|
||||
"Do 1001 · štiglja 90 · obvezno pobijanje",
|
||||
color = CreamMuted,
|
||||
fontSize = 12.sp,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** The app's logo (icon.png) as a gold-edged tile, floating gently. */
|
||||
@Composable
|
||||
private fun Logo() {
|
||||
val float by rememberInfiniteTransition(label = "logo").animateFloat(
|
||||
initialValue = 0f,
|
||||
targetValue = 1f,
|
||||
animationSpec = infiniteRepeatable(tween(2800), RepeatMode.Reverse),
|
||||
label = "float",
|
||||
)
|
||||
BoxWithConstraints(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
val size = minOf(240.dp, maxWidth * 0.66f)
|
||||
val shape = RoundedCornerShape(22)
|
||||
Image(
|
||||
bitmap = ImageBitmap.imageResource(R.drawable.logo),
|
||||
contentDescription = "Bela",
|
||||
filterQuality = FilterQuality.High,
|
||||
modifier = Modifier
|
||||
.size(size)
|
||||
.graphicsLayer { translationY = -4.dp.toPx() * float }
|
||||
.shadow(22.dp, shape, spotColor = GoldDeep)
|
||||
.clip(shape)
|
||||
.border(1.5.dp, GoldBrush, shape),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package hr.bela.app.ui
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.graphics.StrokeCap
|
||||
import androidx.compose.ui.graphics.StrokeJoin
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.graphics.vector.addPathNodes
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/** A few line icons (24 x 24, 2 px stroke), drawn here so the app needs no icon library. Tint them with Icon(tint = …). */
|
||||
object BelaIcons {
|
||||
val Back: ImageVector = strokeIcon("back", "M15 18l-6-6 6-6")
|
||||
|
||||
val ScoreSheet: ImageVector = strokeIcon(
|
||||
"score_sheet",
|
||||
"M8 3h8a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",
|
||||
"M9.5 8h5",
|
||||
"M9.5 12h5",
|
||||
"M9.5 16h3",
|
||||
)
|
||||
|
||||
val LastTrick: ImageVector = strokeIcon(
|
||||
"last_trick",
|
||||
"M3 12a9 9 0 1 0 2.64-6.36",
|
||||
"M3 4v5h5",
|
||||
"M12 8v4l3 2",
|
||||
)
|
||||
|
||||
/** A gear: ring, hub and eight teeth. */
|
||||
val Settings: ImageVector = strokeIcon(
|
||||
"settings",
|
||||
"M12 5.5a6.5 6.5 0 1 0 0 13a6.5 6.5 0 1 0 0-13z",
|
||||
"M12 9.5a2.5 2.5 0 1 0 0 5a2.5 2.5 0 1 0 0-5z",
|
||||
"M12 2.5v3", "M12 18.5v3", "M2.5 12h3", "M18.5 12h3",
|
||||
"M5.3 5.3l2.1 2.1", "M16.6 16.6l2.1 2.1", "M18.7 5.3l-2.1 2.1", "M5.3 18.7l2.1-2.1",
|
||||
)
|
||||
|
||||
val Download: ImageVector = strokeIcon("download", "M12 3v12", "M7 10l5 5 5-5", "M5 21h14")
|
||||
|
||||
val Share: ImageVector = strokeIcon(
|
||||
"share",
|
||||
"M18 2.5a3 3 0 1 0 0 6a3 3 0 1 0 0-6z",
|
||||
"M6 9a3 3 0 1 0 0 6a3 3 0 1 0 0-6z",
|
||||
"M18 15.5a3 3 0 1 0 0 6a3 3 0 1 0 0-6z",
|
||||
"M8.6 13.5l6.8 4", "M15.4 6.5l-6.8 4",
|
||||
)
|
||||
|
||||
val External: ImageVector = strokeIcon("external", "M14 4h6v6", "M20 4l-9 9", "M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5")
|
||||
|
||||
private fun strokeIcon(name: String, vararg paths: String): ImageVector =
|
||||
ImageVector.Builder(name, 24.dp, 24.dp, 24f, 24f).apply {
|
||||
paths.forEach { d ->
|
||||
addPath(
|
||||
pathData = addPathNodes(d),
|
||||
stroke = SolidColor(Color.White),
|
||||
strokeLineWidth = 2f,
|
||||
strokeLineCap = StrokeCap.Round,
|
||||
strokeLineJoin = StrokeJoin.Round,
|
||||
)
|
||||
}
|
||||
}.build()
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
package hr.bela.app.ui
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.safeDrawingPadding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.shadow
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.FilterQuality
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.imageResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LifecycleEventEffect
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import com.google.zxing.BarcodeFormat
|
||||
import com.google.zxing.EncodeHintType
|
||||
import com.google.zxing.qrcode.QRCodeWriter
|
||||
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
|
||||
import hr.bela.app.BuildConfig
|
||||
import hr.bela.app.R
|
||||
import hr.bela.app.SettingsViewModel
|
||||
import hr.bela.app.UpdateState
|
||||
import hr.bela.app.update.ReleaseChannel
|
||||
|
||||
/** Settings: about the app, updating it, and a QR code that shares the newest APK. */
|
||||
@Composable
|
||||
fun SettingsScreen(onExit: () -> Unit, vm: SettingsViewModel = viewModel()) {
|
||||
val update by vm.update.collectAsStateWithLifecycle()
|
||||
val context = LocalContext.current
|
||||
BackHandler(onBack = onExit)
|
||||
LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { vm.onResume() }
|
||||
|
||||
fun open(url: String) = runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) }
|
||||
|
||||
Box(Modifier.fillMaxSize().feltBackground()) {
|
||||
Column(Modifier.fillMaxSize().safeDrawingPadding().padding(horizontal = 16.dp)) {
|
||||
Box(Modifier.fillMaxWidth().padding(top = cameraClearance()).height(68.dp)) {
|
||||
GlassIconButton(BelaIcons.Back, "Natrag", onExit, Modifier.align(Alignment.CenterStart))
|
||||
Column(Modifier.align(Alignment.Center), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Overline("Bela", color = Gold)
|
||||
Text("Postavke", color = Cream, fontFamily = Cinzel, fontWeight = FontWeight.Bold, fontSize = 22.sp)
|
||||
}
|
||||
}
|
||||
Column(
|
||||
Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(top = 8.dp, bottom = 24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
) {
|
||||
AboutSection()
|
||||
Section("Ažuriranje") { UpdateSection(update, vm, open = ::open) }
|
||||
Section("Podijeli aplikaciju") { ShareSection(open = ::open) }
|
||||
CreditsSection(open = ::open)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A titled glass panel with a gold hairline edge. */
|
||||
@Composable
|
||||
private fun Section(title: String, content: @Composable ColumnScope.() -> Unit) {
|
||||
val shape = RoundedCornerShape(22.dp)
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(shape)
|
||||
.background(Glass)
|
||||
.border(1.dp, GoldBrush, shape)
|
||||
.padding(18.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Overline(title, color = Gold)
|
||||
Ornament(Modifier.padding(top = 6.dp, bottom = 14.dp), lineWidth = 30.dp)
|
||||
content()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AboutSection() {
|
||||
Section("O aplikaciji") {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
val shape = RoundedCornerShape(22)
|
||||
Image(
|
||||
bitmap = ImageBitmap.imageResource(R.drawable.logo),
|
||||
contentDescription = "Bela",
|
||||
filterQuality = FilterQuality.High,
|
||||
modifier = Modifier.size(72.dp).shadow(8.dp, shape).clip(shape).border(1.dp, GoldBrush, shape),
|
||||
)
|
||||
Spacer(Modifier.width(14.dp))
|
||||
Column {
|
||||
Text("Bela", color = Cream, fontFamily = Cinzel, fontWeight = FontWeight.Bold, fontSize = 24.sp)
|
||||
Text(
|
||||
"Verzija ${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})",
|
||||
color = CreamMuted,
|
||||
fontSize = 13.sp,
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"Hrvatska Bela za četvero: ti i partner protiv računala, do 1001. " +
|
||||
"Uz partiju tu je i trening brojanja karata.",
|
||||
color = Cream,
|
||||
fontSize = 14.sp,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 14.dp),
|
||||
)
|
||||
Text(
|
||||
"Pravila: do 1001 · štiglja 90 · djelitelj mora zvati · obvezno pobijanje · belot dobiva partiju.",
|
||||
color = CreamMuted,
|
||||
fontSize = 12.sp,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun UpdateSection(update: UpdateState, vm: SettingsViewModel, open: (String) -> Unit) {
|
||||
val status = when (update) {
|
||||
UpdateState.Checking -> "Provjeravam ima li nova verzija…"
|
||||
is UpdateState.UpToDate -> "Imaš najnoviju verziju (${update.latest})."
|
||||
UpdateState.NoReleases -> "Još nema objavljenih verzija."
|
||||
is UpdateState.Available -> "Dostupna je nova verzija ${update.release.versionName}."
|
||||
is UpdateState.Downloading -> "Preuzimam verziju ${update.release.versionName}…"
|
||||
is UpdateState.NeedsPermission ->
|
||||
"Za instalaciju dopusti Beli instaliranje aplikacija (\"Instaliranje nepoznatih aplikacija\"), pa se vrati ovamo."
|
||||
is UpdateState.Installing -> "Potvrdi instalaciju verzije ${update.release.versionName}."
|
||||
is UpdateState.Failed -> update.message
|
||||
}
|
||||
Text(
|
||||
status,
|
||||
color = if (update is UpdateState.Failed) LossRed else Cream,
|
||||
fontSize = 14.sp,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
if (update is UpdateState.Available) {
|
||||
update.release.notes?.let {
|
||||
Text(it, color = CreamMuted, fontSize = 12.sp, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth().padding(top = 6.dp))
|
||||
}
|
||||
}
|
||||
if (update is UpdateState.Downloading) {
|
||||
Box(Modifier.padding(top = 12.dp).fillMaxWidth().height(6.dp).clip(RoundedCornerShape(3.dp)).background(CreamFaint)) {
|
||||
if (update.progress >= 0f) Box(Modifier.fillMaxHeight().fillMaxWidth(update.progress).background(GoldBrush))
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(14.dp))
|
||||
when (update) {
|
||||
is UpdateState.Available -> GoldButton("Preuzmi i instaliraj", { vm.download(update.release) })
|
||||
is UpdateState.NeedsPermission -> GoldButton("Dopusti instalaciju", vm::openInstallPermission)
|
||||
is UpdateState.Installing -> GlassButton("Ponovno otvori instalaciju", { vm.install(update.release, update.apk) })
|
||||
is UpdateState.Downloading, UpdateState.Checking -> Unit
|
||||
else -> GlassButton("Provjeri ponovno", vm::check)
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
LinkRow("Sva izdanja", BelaIcons.External) { open(ReleaseChannel.RELEASES_PAGE) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ShareSection(open: (String) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
Text(
|
||||
"Skeniraj kod mobitelom za preuzimanje najnovije verzije.",
|
||||
color = Cream,
|
||||
fontSize = 14.sp,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(14.dp))
|
||||
QrCode(ReleaseChannel.LATEST_APK_URL, Modifier.width(220.dp))
|
||||
Spacer(Modifier.height(16.dp))
|
||||
GlassButton("Podijeli poveznicu", {
|
||||
val send = Intent(Intent.ACTION_SEND)
|
||||
.setType("text/plain")
|
||||
.putExtra(Intent.EXTRA_SUBJECT, "Bela")
|
||||
.putExtra(Intent.EXTRA_TEXT, "Igraj Belu sa mnom! Preuzmi aplikaciju: ${ReleaseChannel.LATEST_APK_URL}")
|
||||
context.startActivity(Intent.createChooser(send, "Podijeli Belu"))
|
||||
})
|
||||
Spacer(Modifier.height(10.dp))
|
||||
LinkRow("Preuzmi APK u pregledniku", BelaIcons.Download) { open(ReleaseChannel.LATEST_APK_URL) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CreditsSection(open: (String) -> Unit) {
|
||||
Section("Zasluge") {
|
||||
Credit("Karte", "Mađarske karte iz projekta tomasdrus/hungarian-playing-cards") {
|
||||
open("https://github.com/tomasdrus/hungarian-playing-cards")
|
||||
}
|
||||
Credit("Fontovi", "Cinzel i Inter, SIL Open Font License 1.1") { open("https://openfontlicense.org") }
|
||||
Credit("QR kod", "ZXing, Apache License 2.0") { open("https://github.com/zxing/zxing") }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Credit(title: String, text: String, onClick: () -> Unit) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.clickable(onClick = onClick)
|
||||
.padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, color = Gold, fontSize = 13.sp, fontWeight = FontWeight.SemiBold)
|
||||
Text(text, color = CreamMuted, fontSize = 12.sp)
|
||||
}
|
||||
androidx.compose.material3.Icon(BelaIcons.External, contentDescription = null, tint = CreamMuted, modifier = Modifier.size(16.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LinkRow(text: String, icon: androidx.compose.ui.graphics.vector.ImageVector, onClick: () -> Unit) {
|
||||
Row(
|
||||
Modifier.clip(RoundedCornerShape(50)).clickable(onClick = onClick).padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
androidx.compose.material3.Icon(icon, contentDescription = null, tint = Gold, modifier = Modifier.size(16.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(text, color = Gold, fontSize = 13.sp, fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* QR code for [text] on a white tile, with the app icon in the middle. Error correction level H lets
|
||||
* the code lose up to ~30% of its modules, so the small logo does not stop it from scanning.
|
||||
*/
|
||||
@Composable
|
||||
fun QrCode(text: String, modifier: Modifier = Modifier) {
|
||||
val matrix = remember(text) {
|
||||
QRCodeWriter().encode(
|
||||
text,
|
||||
BarcodeFormat.QR_CODE,
|
||||
0,
|
||||
0,
|
||||
mapOf(EncodeHintType.ERROR_CORRECTION to ErrorCorrectionLevel.H, EncodeHintType.MARGIN to 0),
|
||||
)
|
||||
}
|
||||
val shape = RoundedCornerShape(18.dp)
|
||||
Box(
|
||||
modifier
|
||||
.aspectRatio(1f)
|
||||
.shadow(12.dp, shape)
|
||||
.clip(shape)
|
||||
.background(Color.White)
|
||||
.border(1.5.dp, GoldBrush, shape)
|
||||
.padding(14.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Canvas(Modifier.fillMaxSize()) {
|
||||
val n = matrix.width
|
||||
val cell = size.width / n
|
||||
for (y in 0 until n) {
|
||||
for (x in 0 until n) {
|
||||
if (matrix[x, y]) {
|
||||
// Slight overlap so neighbouring modules join without hairline gaps.
|
||||
drawRect(Color(0xFF14261C), topLeft = Offset(x * cell, y * cell), size = Size(cell + 0.6f, cell + 0.6f))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val logoShape = RoundedCornerShape(22)
|
||||
Image(
|
||||
bitmap = ImageBitmap.imageResource(R.drawable.logo),
|
||||
contentDescription = null,
|
||||
filterQuality = FilterQuality.High,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth(0.22f)
|
||||
.aspectRatio(1f)
|
||||
.clip(logoShape)
|
||||
.background(Color.White)
|
||||
.border(3.dp, Color.White, logoShape),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,818 @@
|
||||
package hr.bela.app.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.core.Animatable
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.animation.core.RepeatMode
|
||||
import androidx.compose.animation.core.animateDpAsState
|
||||
import androidx.compose.animation.core.animateFloat
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.animateIntAsState
|
||||
import androidx.compose.animation.core.infiniteRepeatable
|
||||
import androidx.compose.animation.core.rememberInfiniteTransition
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.safeDrawingPadding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.ripple
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.shadow
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.TransformOrigin
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.DpOffset
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.zIndex
|
||||
import hr.bela.app.HUMAN
|
||||
import hr.bela.app.UiState
|
||||
import hr.bela.engine.Card
|
||||
import hr.bela.engine.GameState
|
||||
import hr.bela.engine.Phase
|
||||
import hr.bela.engine.Rank
|
||||
import hr.bela.engine.Suit
|
||||
import hr.bela.engine.points
|
||||
import hr.bela.engine.teamOf
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlin.math.sin
|
||||
|
||||
/** Width of the left and right player columns. */
|
||||
private val SideColumnWidth = 70.dp
|
||||
|
||||
@Composable
|
||||
fun TableScreen(
|
||||
state: UiState,
|
||||
onCall: (Suit?) -> Unit,
|
||||
onPlay: (Card) -> Unit,
|
||||
onNextHand: () -> Unit,
|
||||
onNewGame: () -> Unit,
|
||||
onLeave: () -> Unit,
|
||||
onScoreSheet: (Boolean) -> Unit,
|
||||
onLastTrick: (Boolean) -> Unit,
|
||||
) {
|
||||
val game = state.game ?: return
|
||||
BackHandler(onBack = onLeave)
|
||||
|
||||
Box(Modifier.fillMaxSize().feltBackground()) {
|
||||
Column(Modifier.fillMaxSize().safeDrawingPadding()) {
|
||||
TopBar(game, onLeave = onLeave, onScoreSheet = { onScoreSheet(true) })
|
||||
InfoChips(game, onLastTrick = { onLastTrick(true) })
|
||||
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth().padding(horizontal = 6.dp)) {
|
||||
val cardWidth = minOf(
|
||||
minOf(96.dp, maxCardWidth()),
|
||||
(maxWidth - SideColumnWidth * 2 - 8.dp) / 2.9f,
|
||||
(maxHeight - 150.dp) / 2.2f * CARD_ASPECT,
|
||||
)
|
||||
TableMarkings(ringWidth = maxWidth - SideColumnWidth * 2 + 4.dp, ringHeight = cardWidth / CARD_ASPECT * 2.25f)
|
||||
PartnerSeat(game, state, Modifier.align(Alignment.TopCenter))
|
||||
SideSeat(game, state, seat = 3, modifier = Modifier.align(Alignment.CenterStart))
|
||||
SideSeat(game, state, seat = 1, modifier = Modifier.align(Alignment.CenterEnd))
|
||||
TrickArea(game, state, cardWidth, Modifier.align(Alignment.Center))
|
||||
val bidding = game.phase == Phase.BIDDING && game.toAct == HUMAN
|
||||
Column(Modifier.align(Alignment.BottomCenter), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
DeclarationBanner(game)
|
||||
if (!bidding) MySeat(game, state)
|
||||
}
|
||||
if (bidding) BiddingPanel(game.canPass(HUMAN), onCall, Modifier.align(Alignment.BottomCenter))
|
||||
}
|
||||
HandRow(game, state, onPlay)
|
||||
}
|
||||
|
||||
if (state.shownTrick == null) {
|
||||
when (game.phase) {
|
||||
Phase.HAND_OVER -> game.lastResult?.let { HandResultDialog(game, it, onNextHand) }
|
||||
Phase.GAME_OVER -> GameOverDialog(game, onNewGame = onNewGame, onLeave = onLeave)
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
if (state.showScoreSheet) ScoreSheetDialog(game, onDismiss = { onScoreSheet(false) })
|
||||
if (state.showLastTrick) LastTrickDialog(game, onDismiss = { onLastTrick(false) })
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- top
|
||||
|
||||
@Composable
|
||||
private fun TopBar(game: GameState, onLeave: () -> Unit, onScoreSheet: () -> Unit) {
|
||||
Box(Modifier.fillMaxWidth().padding(top = cameraClearance()).height(76.dp).padding(horizontal = 12.dp)) {
|
||||
GlassIconButton(BelaIcons.Back, "Izbornik", onLeave, Modifier.align(Alignment.CenterStart))
|
||||
Scoreboard(game, Modifier.align(Alignment.Center))
|
||||
Row(Modifier.align(Alignment.CenterEnd), verticalAlignment = Alignment.CenterVertically) {
|
||||
TrumpMedallion(game.hand.trump)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
GlassIconButton(BelaIcons.ScoreSheet, "Blok", onScoreSheet)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** MI and VI with a thin bar showing how far each team is towards the target. */
|
||||
@Composable
|
||||
private fun Scoreboard(game: GameState, modifier: Modifier) {
|
||||
val shape = RoundedCornerShape(20.dp)
|
||||
Row(
|
||||
modifier
|
||||
.shadow(10.dp, shape)
|
||||
.clip(shape)
|
||||
.background(Brush.verticalGradient(listOf(Color(0xCC0B2016), Color(0xE6061510))))
|
||||
.border(1.dp, GoldBrush, shape)
|
||||
.padding(horizontal = 16.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
TeamScore("MI", game.scores[0], game.rules.targetScore, ours = true, leading = game.scores[0] > game.scores[1])
|
||||
Column(Modifier.padding(horizontal = 12.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Diamond(5.dp)
|
||||
Text(
|
||||
"${game.rules.targetScore}",
|
||||
color = CreamMuted,
|
||||
fontFamily = Cinzel,
|
||||
fontSize = 9.sp,
|
||||
letterSpacing = 1.sp,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
TeamScore("VI", game.scores[1], game.rules.targetScore, ours = false, leading = game.scores[1] > game.scores[0])
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TeamScore(label: String, score: Int, target: Int, ours: Boolean, leading: Boolean) {
|
||||
val shown by animateIntAsState(score, tween(durationMillis = 800), label = "score")
|
||||
val progress by animateFloatAsState((score.toFloat() / target).coerceIn(0f, 1f), tween(800), label = "progress")
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.width(58.dp)) {
|
||||
Text(label, color = CreamMuted, fontFamily = Cinzel, fontWeight = FontWeight.Bold, fontSize = 10.sp, letterSpacing = 3.sp)
|
||||
Text(
|
||||
"$shown",
|
||||
color = if (leading) Gold else Cream,
|
||||
fontFamily = Cinzel,
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 24.sp,
|
||||
lineHeight = 26.sp,
|
||||
)
|
||||
Box(Modifier.padding(top = 3.dp).width(52.dp).height(3.dp).clip(RoundedCornerShape(2.dp)).background(CreamFaint)) {
|
||||
Box(Modifier.fillMaxHeight().fillMaxWidth(progress).background(if (ours) GoldBrush else SilverBrush))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TrumpMedallion(trump: Suit?) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
SuitMedallion(trump, 42.dp)
|
||||
Text(
|
||||
"ADUT",
|
||||
color = if (trump != null) Gold else CreamMuted,
|
||||
fontFamily = Cinzel,
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 8.sp,
|
||||
letterSpacing = 1.5.sp,
|
||||
modifier = Modifier.padding(top = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InfoChip(label: String, value: String, valueColor: Color = Cream) {
|
||||
Row(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(50))
|
||||
.background(Glass)
|
||||
.border(1.dp, CreamFaint, RoundedCornerShape(50))
|
||||
.padding(horizontal = 10.dp, vertical = 3.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(label, color = CreamMuted, fontFamily = Cinzel, fontWeight = FontWeight.Bold, fontSize = 9.sp, letterSpacing = 1.5.sp)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(value, color = valueColor, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, style = TextStyle(fontFeatureSettings = "tnum"))
|
||||
}
|
||||
}
|
||||
|
||||
/** Dealer during bidding; tricks and card points during play. */
|
||||
@Composable
|
||||
private fun InfoChips(game: GameState, onLastTrick: () -> Unit) {
|
||||
val hand = game.hand
|
||||
val trump = hand.trump
|
||||
Box(Modifier.fillMaxWidth().height(38.dp).padding(horizontal = 12.dp)) {
|
||||
Row(Modifier.align(Alignment.Center), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (game.phase == Phase.BIDDING || trump == null) {
|
||||
InfoChip("DIJELI", seatName(hand.dealer))
|
||||
} else {
|
||||
val tricks = IntArray(2)
|
||||
val points = IntArray(2)
|
||||
hand.tricks.forEach {
|
||||
tricks[teamOf(it.winner)]++
|
||||
points[teamOf(it.winner)] += it.trick.points(trump)
|
||||
}
|
||||
InfoChip("ŠTIHOVI", "${tricks[0]} : ${tricks[1]}")
|
||||
InfoChip("BODOVI", "${points[0]} : ${points[1]}")
|
||||
}
|
||||
if (game.hanging > 0) InfoChip("VISI", "${game.hanging}", Gold)
|
||||
}
|
||||
if (game.phase != Phase.BIDDING && hand.tricks.isNotEmpty()) {
|
||||
GlassIconButton(
|
||||
BelaIcons.LastTrick,
|
||||
"Zadnji štih",
|
||||
onLastTrick,
|
||||
Modifier.align(Alignment.CenterEnd).size(34.dp),
|
||||
tint = Gold,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** What is printed on the felt: a pool of light, a double gold ring round the play area and the name in the middle. */
|
||||
@Composable
|
||||
private fun TableMarkings(ringWidth: Dp, ringHeight: Dp) {
|
||||
Canvas(Modifier.fillMaxSize()) {
|
||||
val c = Offset(size.width / 2, size.height / 2)
|
||||
drawCircle(
|
||||
Brush.radialGradient(listOf(Color(0x24FFFFFF), Color.Transparent), center = c, radius = size.minDimension * 0.62f),
|
||||
radius = size.minDimension * 0.62f,
|
||||
center = c,
|
||||
)
|
||||
val w = ringWidth.toPx()
|
||||
val h = ringHeight.toPx()
|
||||
val gap = 6.dp.toPx()
|
||||
drawRoundRect(
|
||||
Gold.copy(alpha = 0.2f),
|
||||
topLeft = Offset(c.x - w / 2, c.y - h / 2),
|
||||
size = Size(w, h),
|
||||
cornerRadius = CornerRadius(w / 2, w / 2),
|
||||
style = Stroke(width = 1.2.dp.toPx()),
|
||||
)
|
||||
drawRoundRect(
|
||||
Gold.copy(alpha = 0.09f),
|
||||
topLeft = Offset(c.x - w / 2 + gap, c.y - h / 2 + gap),
|
||||
size = Size(w - 2 * gap, h - 2 * gap),
|
||||
cornerRadius = CornerRadius(w / 2 - gap, w / 2 - gap),
|
||||
style = Stroke(width = 1.dp.toPx()),
|
||||
)
|
||||
}
|
||||
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text(
|
||||
"BELA",
|
||||
color = Gold.copy(alpha = 0.13f),
|
||||
fontFamily = Cinzel,
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 34.sp,
|
||||
letterSpacing = 10.sp,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- seats
|
||||
|
||||
private enum class Tone { QUIET, ACTIVE, BUBBLE }
|
||||
|
||||
private data class SeatStatus(val text: String, val tone: Tone, val suit: Suit? = null)
|
||||
|
||||
private fun seatStatus(game: GameState, state: UiState, seat: Int): SeatStatus? {
|
||||
state.bubble?.takeIf { it.first == seat }?.let { return SeatStatus(it.second, Tone.BUBBLE) }
|
||||
val active = game.toAct == seat && !state.inputLocked
|
||||
if (game.phase == Phase.BIDDING) {
|
||||
game.hand.bids.lastOrNull { it.seat == seat }?.let {
|
||||
return if (it.suit == null) SeatStatus("dalje", Tone.QUIET) else SeatStatus("zove", Tone.QUIET, it.suit)
|
||||
}
|
||||
if (active) return SeatStatus(if (seat == HUMAN) "tvoj red" else "zove…", Tone.ACTIVE)
|
||||
return null
|
||||
}
|
||||
if (active) return SeatStatus(if (seat == HUMAN) "Tvoj potez" else "igra…", Tone.ACTIVE)
|
||||
return null
|
||||
}
|
||||
|
||||
/** A seat's status in a fixed-height slot, so nothing around it jumps when it changes. */
|
||||
@Composable
|
||||
private fun StatusSlot(status: SeatStatus?) {
|
||||
Box(Modifier.height(22.dp), contentAlignment = Alignment.Center) {
|
||||
if (status == null) return@Box
|
||||
when (status.tone) {
|
||||
Tone.BUBBLE -> Box(
|
||||
Modifier
|
||||
.shadow(6.dp, RoundedCornerShape(11.dp), spotColor = GoldDeep)
|
||||
.clip(RoundedCornerShape(11.dp))
|
||||
.background(GoldVertical)
|
||||
.padding(horizontal = 10.dp, vertical = 1.dp),
|
||||
) {
|
||||
Text(status.text, color = Ink, fontFamily = Cinzel, fontWeight = FontWeight.Bold, fontSize = 12.sp)
|
||||
}
|
||||
Tone.ACTIVE -> {
|
||||
val pulse by rememberInfiniteTransition(label = "status").animateFloat(
|
||||
initialValue = 0.55f,
|
||||
targetValue = 1f,
|
||||
animationSpec = infiniteRepeatable(tween(700), RepeatMode.Reverse),
|
||||
label = "status-alpha",
|
||||
)
|
||||
Text(status.text, color = Gold.copy(alpha = pulse), fontSize = 12.sp, fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
Tone.QUIET -> Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(status.text, color = CreamMuted, fontSize = 12.sp)
|
||||
status.suit?.let {
|
||||
Spacer(Modifier.width(4.dp))
|
||||
SuitIcon(it, 16.dp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Round portrait with a team-coloured rim (gold for us, silver for them). The player whose turn it is
|
||||
* gets a breathing gold halo. Dealer and caller chips sit on the rim.
|
||||
*/
|
||||
@Composable
|
||||
private fun Avatar(game: GameState, state: UiState, seat: Int, size: Dp = 48.dp) {
|
||||
val active = game.toAct == seat && !state.inputLocked
|
||||
val halo = if (active) {
|
||||
val pulse by rememberInfiniteTransition(label = "turn").animateFloat(
|
||||
initialValue = 0.25f,
|
||||
targetValue = 0.7f,
|
||||
animationSpec = infiniteRepeatable(tween(800), RepeatMode.Reverse),
|
||||
label = "halo",
|
||||
)
|
||||
pulse
|
||||
} else {
|
||||
0f
|
||||
}
|
||||
val ours = teamOf(seat) == 0
|
||||
Box(Modifier.size(size + 16.dp), contentAlignment = Alignment.Center) {
|
||||
if (halo > 0f) {
|
||||
Canvas(Modifier.fillMaxSize()) {
|
||||
drawCircle(Brush.radialGradient(listOf(Gold.copy(alpha = halo), Color.Transparent)))
|
||||
}
|
||||
}
|
||||
Box(
|
||||
Modifier
|
||||
.size(size)
|
||||
.shadow(8.dp, CircleShape)
|
||||
.clip(CircleShape)
|
||||
.background(Brush.linearGradient(listOf(Color(0xFF1F4A36), Color(0xFF0B2219))))
|
||||
.border(2.dp, if (ours) GoldBrush else SilverBrush, CircleShape),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Silhouette(if (ours) GoldBrush else SilverBrush)
|
||||
}
|
||||
if (seat == game.hand.dealer) DealerChip(Modifier.align(Alignment.BottomEnd).padding(end = 6.dp, bottom = 6.dp))
|
||||
if (seat == game.hand.caller) {
|
||||
game.hand.trump?.let { CallerChip(it, Modifier.align(Alignment.TopEnd).padding(end = 4.dp, top = 4.dp)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Head and shoulders, cut off by the round frame. */
|
||||
@Composable
|
||||
private fun Silhouette(brush: Brush) {
|
||||
Canvas(Modifier.fillMaxSize()) {
|
||||
val w = size.width
|
||||
val h = size.height
|
||||
drawCircle(brush, radius = w * 0.17f, center = Offset(w / 2, h * 0.4f), alpha = 0.9f)
|
||||
drawOval(brush, topLeft = Offset(w * 0.2f, h * 0.64f), size = Size(w * 0.6f, h * 0.56f), alpha = 0.9f)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DealerChip(modifier: Modifier = Modifier) {
|
||||
Box(
|
||||
modifier.size(18.dp).shadow(3.dp, CircleShape).clip(CircleShape).background(GoldVertical),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text("D", color = Ink, fontFamily = Cinzel, fontSize = 10.sp, fontWeight = FontWeight.Black)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CallerChip(suit: Suit, modifier: Modifier = Modifier) {
|
||||
Box(
|
||||
modifier.size(22.dp).shadow(3.dp, CircleShape).clip(CircleShape).background(Cream).border(1.5.dp, GoldBrush, CircleShape),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
SuitIcon(suit, 14.dp)
|
||||
}
|
||||
}
|
||||
|
||||
/** Left and right players: portrait, name, status and their fanned cards, all in a narrow column. */
|
||||
@Composable
|
||||
private fun SideSeat(game: GameState, state: UiState, seat: Int, modifier: Modifier) {
|
||||
Column(modifier.width(SideColumnWidth), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Avatar(game, state, seat)
|
||||
NamePlate(seatName(seat))
|
||||
StatusSlot(seatStatus(game, state, seat))
|
||||
BotFan(game.hand.cards[seat].size + game.hand.talon[seat].size, if (seat == 3) FanSide.LEFT else FanSide.RIGHT)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PartnerSeat(game: GameState, state: UiState, modifier: Modifier) {
|
||||
val seat = 2
|
||||
Column(modifier, horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Avatar(game, state, seat)
|
||||
Column(Modifier.padding(start = 2.dp)) {
|
||||
NamePlate(seatName(seat))
|
||||
StatusSlot(seatStatus(game, state, seat))
|
||||
}
|
||||
}
|
||||
BotFan(game.hand.cards[seat].size + game.hand.talon[seat].size, FanSide.TOP)
|
||||
}
|
||||
}
|
||||
|
||||
/** The player's own plate, just above the hand. */
|
||||
@Composable
|
||||
private fun MySeat(game: GameState, state: UiState) {
|
||||
val active = game.toAct == HUMAN && !state.inputLocked
|
||||
val shape = RoundedCornerShape(50)
|
||||
Row(
|
||||
Modifier
|
||||
.padding(bottom = 4.dp)
|
||||
.clip(shape)
|
||||
.background(Glass)
|
||||
.border(1.dp, if (active) GoldBrush else Brush.linearGradient(listOf(CreamFaint, CreamFaint)), shape)
|
||||
.padding(start = 12.dp, end = 12.dp, top = 3.dp, bottom = 3.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Text("Ti", color = Cream, fontSize = 13.sp, fontWeight = FontWeight.SemiBold)
|
||||
if (game.hand.dealer == HUMAN) DealerChip()
|
||||
if (game.hand.caller == HUMAN) game.hand.trump?.let { CallerChip(it) }
|
||||
StatusSlot(seatStatus(game, state, HUMAN))
|
||||
}
|
||||
}
|
||||
|
||||
private enum class FanSide { LEFT, RIGHT, TOP }
|
||||
|
||||
/** A bot's cards held in a fan that opens towards the middle of the table. */
|
||||
@Composable
|
||||
private fun BotFan(count: Int, side: FanSide) {
|
||||
if (count == 0) {
|
||||
Spacer(Modifier.height(if (side == FanSide.TOP) 52.dp else 80.dp))
|
||||
return
|
||||
}
|
||||
val middle = (count - 1) / 2f
|
||||
when (side) {
|
||||
FanSide.LEFT, FanSide.RIGHT -> Box(Modifier.width(62.dp).height(80.dp)) {
|
||||
val left = side == FanSide.LEFT
|
||||
repeat(count) { i ->
|
||||
CardBack(
|
||||
Modifier
|
||||
.align(if (left) Alignment.CenterStart else Alignment.CenterEnd)
|
||||
.width(42.dp)
|
||||
.graphicsLayer {
|
||||
rotationZ = (if (left) i - middle else middle - i) * 7f
|
||||
transformOrigin = TransformOrigin(if (left) 0.1f else 0.9f, 0.5f)
|
||||
},
|
||||
small = true,
|
||||
landscape = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
FanSide.TOP -> Box(Modifier.width(110.dp).height(52.dp)) {
|
||||
repeat(count) { i ->
|
||||
CardBack(
|
||||
Modifier
|
||||
.align(Alignment.TopCenter)
|
||||
.width(26.dp)
|
||||
.graphicsLayer {
|
||||
rotationZ = (middle - i) * 8f
|
||||
transformOrigin = TransformOrigin(0.5f, 0.1f)
|
||||
},
|
||||
small = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- middle
|
||||
|
||||
/** Where each seat's card lands in the trick, relative to the centre. */
|
||||
private fun trickOffset(seat: Int, dx: Dp, dy: Dp): DpOffset = when (seat) {
|
||||
0 -> DpOffset(0.dp, dy)
|
||||
1 -> DpOffset(dx, 0.dp)
|
||||
2 -> DpOffset(0.dp, -dy)
|
||||
else -> DpOffset(-dx, 0.dp)
|
||||
}
|
||||
|
||||
/** The current trick, each card in front of its player. A finished trick slides off towards its winner. */
|
||||
@Composable
|
||||
private fun TrickArea(game: GameState, state: UiState, cardWidth: Dp, modifier: Modifier) {
|
||||
val shown = state.shownTrick
|
||||
val trick = shown?.trick ?: game.hand.trick.takeIf { game.phase == Phase.PLAYING } ?: return
|
||||
val cardHeight = cardWidth / CARD_ASPECT
|
||||
val dx = cardWidth * 0.94f
|
||||
val dy = cardHeight * 0.58f
|
||||
|
||||
// The finished trick stays still for a second (winner framed in gold), then slides off.
|
||||
// Keep 1000 + 380 ms below GameViewModel.TRICK_PAUSE_MS.
|
||||
val gather = remember(shown) { Animatable(0f) }
|
||||
LaunchedEffect(shown) {
|
||||
if (shown != null) {
|
||||
delay(1000)
|
||||
gather.animateTo(1f, tween(durationMillis = 380, easing = FastOutSlowInEasing))
|
||||
}
|
||||
}
|
||||
val gatherTo = shown?.let { trickOffset(it.winner, dx * 2.6f, dy * 2.6f) }
|
||||
|
||||
Box(modifier.width(cardWidth + dx * 2 + 16.dp).height(cardHeight + dy * 2 + 16.dp)) {
|
||||
trick.cards.forEachIndexed { i, card ->
|
||||
val seat = trick.seatAt(i)
|
||||
key(card) {
|
||||
PlayedCard(
|
||||
card = card,
|
||||
width = cardWidth,
|
||||
target = trickOffset(seat, dx, dy),
|
||||
tilt = seatTilt(seat) + ((card.suit.ordinal * 8 + card.rank.ordinal) * 37 % 5 - 2) * 1.3f,
|
||||
gatherTo = gatherTo,
|
||||
gather = { gather.value },
|
||||
highlighted = shown?.winner == seat,
|
||||
modifier = Modifier.align(Alignment.Center).zIndex(i.toFloat()),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun seatTilt(seat: Int): Float = when (seat) {
|
||||
0 -> 2f
|
||||
1 -> -7f
|
||||
2 -> -2f
|
||||
else -> 7f
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PlayedCard(
|
||||
card: Card,
|
||||
width: Dp,
|
||||
target: DpOffset,
|
||||
tilt: Float,
|
||||
gatherTo: DpOffset?,
|
||||
gather: () -> Float,
|
||||
highlighted: Boolean,
|
||||
modifier: Modifier,
|
||||
) {
|
||||
val appear = remember { Animatable(0f) }
|
||||
LaunchedEffect(Unit) { appear.animateTo(1f, tween(durationMillis = 280, easing = FastOutSlowInEasing)) }
|
||||
CardFace(
|
||||
card = card,
|
||||
highlighted = highlighted,
|
||||
elevation = 10.dp,
|
||||
modifier = modifier
|
||||
.offset(x = target.x, y = target.y)
|
||||
.width(width)
|
||||
.graphicsLayer {
|
||||
val p = appear.value
|
||||
val g = gather()
|
||||
// Fly in from the player's side of the table, then (when the trick is done) off towards the winner.
|
||||
var tx = target.x.toPx() * 1.7f * (1 - p)
|
||||
var ty = target.y.toPx() * 1.7f * (1 - p)
|
||||
if (gatherTo != null) {
|
||||
tx += (gatherTo.x - target.x).toPx() * g
|
||||
ty += (gatherTo.y - target.y).toPx() * g
|
||||
}
|
||||
translationX = tx
|
||||
translationY = ty
|
||||
alpha = p * (1 - g)
|
||||
val scale = (0.86f + 0.14f * p) * (1 - 0.4f * g)
|
||||
scaleX = scale
|
||||
scaleY = scale
|
||||
rotationZ = tilt * p
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** The declarations that count, shown during the first trick. */
|
||||
@Composable
|
||||
private fun DeclarationBanner(game: GameState) {
|
||||
val hand = game.hand
|
||||
val team = hand.declarationTeam
|
||||
if (game.phase != Phase.PLAYING || hand.tricks.isNotEmpty() || team == null) return
|
||||
val list = hand.scoringDeclarations
|
||||
val shape = RoundedCornerShape(14.dp)
|
||||
Column(
|
||||
Modifier
|
||||
.padding(bottom = 8.dp)
|
||||
.shadow(8.dp, shape)
|
||||
.clip(shape)
|
||||
.background(Color(0xD90B2016))
|
||||
.border(1.dp, GoldBrush, shape)
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
) {
|
||||
Overline("Zvanja · ${teamName(team)} ${list.sumOf { it.points }}", color = Gold)
|
||||
list.forEach { d ->
|
||||
Row(
|
||||
Modifier.padding(top = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(3.dp),
|
||||
) {
|
||||
Text(seatName(d.seat), color = Cream, fontSize = 12.sp, modifier = Modifier.width(54.dp))
|
||||
d.cards.forEach { CardFace(it, Modifier.width(20.dp), elevation = 1.dp) }
|
||||
Text("${d.points}", color = Cream, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.padding(start = 6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BiddingPanel(canPass: Boolean, onCall: (Suit?) -> Unit, modifier: Modifier) {
|
||||
val shape = RoundedCornerShape(24.dp)
|
||||
Column(
|
||||
modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 8.dp, vertical = 4.dp)
|
||||
.shadow(16.dp, shape)
|
||||
.clip(shape)
|
||||
.background(DialogBrush)
|
||||
.border(1.dp, GoldBrush, shape)
|
||||
.padding(16.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Overline("Zovi adut", color = Gold)
|
||||
Ornament(Modifier.padding(top = 6.dp), lineWidth = 36.dp)
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(top = 12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
Suit.entries.forEach { suit -> SuitTile(suit, Modifier.weight(1f)) { onCall(suit) } }
|
||||
}
|
||||
GlassButton(
|
||||
if (canPass) "Dalje" else "Djelitelj mora zvati",
|
||||
onClick = { onCall(null) },
|
||||
enabled = canPass,
|
||||
modifier = Modifier.padding(top = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SuitTile(suit: Suit, modifier: Modifier, onClick: () -> Unit) {
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val pressed by interaction.collectIsPressedAsState()
|
||||
val scale by animateFloatAsState(if (pressed) 0.94f else 1f, tween(120), label = "tile")
|
||||
val shape = RoundedCornerShape(16.dp)
|
||||
Column(
|
||||
modifier
|
||||
.height(82.dp)
|
||||
.graphicsLayer {
|
||||
scaleX = scale
|
||||
scaleY = scale
|
||||
}
|
||||
.shadow(6.dp, shape)
|
||||
.clip(shape)
|
||||
.background(Brush.verticalGradient(listOf(Color(0xFFFFFDF6), Color(0xFFEAE2CB))))
|
||||
.border(1.dp, GoldBrush, shape)
|
||||
.clickable(interaction, ripple(color = GoldDeep), onClick = onClick),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
SuitIcon(suit, 40.dp)
|
||||
Text(suitName(suit), color = Color(0xFF3B3324), fontFamily = Cinzel, fontWeight = FontWeight.Bold, fontSize = 11.sp)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- hand
|
||||
|
||||
/**
|
||||
* The player's cards as a gentle fan. Number cards keep about two thirds of their width visible so the value mark
|
||||
* (VII…X, in the middle of the top edge) stays readable; picture cards are recognised from their left half and
|
||||
* overlap more. New cards are dealt in with a flip; legal cards rise and glow gold when it is the player's turn.
|
||||
*/
|
||||
@Composable
|
||||
private fun HandRow(game: GameState, state: UiState, onPlay: (Card) -> Unit) {
|
||||
val hand = game.hand
|
||||
val cards = sortHand(hand.cards[HUMAN], hand.trump)
|
||||
val talon = hand.talon[HUMAN].size
|
||||
val myTurn = game.phase == Phase.PLAYING && game.toAct == HUMAN && !state.inputLocked
|
||||
val legal = if (myTurn) game.legalMoves(HUMAN).toSet() else emptySet()
|
||||
val items: List<Card?> = cards + List(talon) { null } // null = a face-down talon card
|
||||
val haptic = LocalHapticFeedback.current
|
||||
// Cards already shown this hand; anything new (the deal, the talon) gets the deal-in animation, staggered.
|
||||
val dealt = remember(hand.number) { mutableSetOf<Card>() }
|
||||
|
||||
BoxWithConstraints(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(Brush.verticalGradient(listOf(Color.Transparent, Color(0x80000000))))
|
||||
.padding(horizontal = 4.dp),
|
||||
) {
|
||||
val width = minOf(96.dp, maxWidth / 4.5f, maxCardWidth())
|
||||
val height = width / CARD_ASPECT
|
||||
val count = items.size
|
||||
val fanStep = 1.6f // degrees between neighbouring cards
|
||||
val maxAngle = fanStep * (count - 1) / 2
|
||||
val spill = height * sin(Math.toRadians(maxAngle.toDouble())).toFloat()
|
||||
|
||||
// How much of each card must stay uncovered, from where its value can be read on this deck:
|
||||
// VII and IX carry the numeral in the top-left corner, VIII and X in the middle of the top edge
|
||||
// (up to ~60% of the width); picture cards are recognised by their suit mark and figure on the left.
|
||||
val gaps = items.dropLast(1).map { card ->
|
||||
width * when (card?.rank) {
|
||||
Rank.SEDAM, Rank.DEVET -> 0.42f
|
||||
Rank.OSAM, Rank.DESET -> 0.63f
|
||||
else -> 0.47f
|
||||
}
|
||||
}
|
||||
val wanted = gaps.fold(0.dp) { sum, gap -> sum + gap }
|
||||
val room = maxWidth - width - spill * 2
|
||||
val squeeze = if (wanted > room && wanted > 0.dp) room / wanted else 1f
|
||||
val start = (maxWidth - width - wanted * squeeze) / 2
|
||||
val lefts = items.indices.map { i -> start + gaps.take(i).fold(0.dp) { sum, gap -> sum + gap } * squeeze }
|
||||
val middle = (count - 1) / 2f
|
||||
var entering = 0
|
||||
|
||||
Box(Modifier.fillMaxWidth().height(height + 52.dp)) {
|
||||
items.forEachIndexed { i, card ->
|
||||
val angle = (i - middle) * fanStep
|
||||
val drop = 1.0.dp * ((i - middle) * (i - middle))
|
||||
val place = Modifier
|
||||
.align(Alignment.BottomStart)
|
||||
.offset(x = lefts[i], y = drop - 18.dp)
|
||||
.width(width)
|
||||
if (card == null) {
|
||||
CardBack(
|
||||
place.graphicsLayer {
|
||||
rotationZ = angle
|
||||
transformOrigin = TransformOrigin(0.5f, 1f)
|
||||
},
|
||||
)
|
||||
} else {
|
||||
val order = if (card in dealt) -1 else entering++
|
||||
key(card) {
|
||||
val enter = remember { Animatable(if (order < 0) 1f else 0f) }
|
||||
LaunchedEffect(Unit) {
|
||||
if (order >= 0) {
|
||||
delay(order * 70L)
|
||||
enter.animateTo(1f, tween(durationMillis = 420, easing = FastOutSlowInEasing))
|
||||
}
|
||||
dealt += card
|
||||
}
|
||||
val playable = card in legal
|
||||
val lift by animateDpAsState(if (playable) 20.dp else 0.dp, tween(180), label = "lift")
|
||||
CardFace(
|
||||
card = card,
|
||||
dimmed = myTurn && !playable,
|
||||
glow = playable,
|
||||
elevation = if (playable) 16.dp else 8.dp,
|
||||
modifier = place
|
||||
.graphicsLayer {
|
||||
val e = enter.value
|
||||
rotationZ = angle
|
||||
rotationY = (1 - e) * 90f
|
||||
translationY = (1 - e) * 140.dp.toPx()
|
||||
alpha = if (e < 0.01f) 0f else 1f
|
||||
cameraDistance = 14f * density
|
||||
transformOrigin = TransformOrigin(0.5f, 1f)
|
||||
}
|
||||
.offset(y = -lift)
|
||||
.then(
|
||||
if (playable) {
|
||||
Modifier.clickable {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
|
||||
onPlay(card)
|
||||
}
|
||||
} else {
|
||||
Modifier
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package hr.bela.app.ui
|
||||
|
||||
import hr.bela.engine.Card
|
||||
import hr.bela.engine.Outcome
|
||||
import hr.bela.engine.Rank
|
||||
import hr.bela.engine.Suit
|
||||
import hr.bela.engine.strength
|
||||
|
||||
/** Suit names for the Hungarian deck the app uses (herc = srce, karo = zvono, pik = list, tref = žir). */
|
||||
fun suitName(suit: Suit): String = when (suit) {
|
||||
Suit.HERC -> "Srce"
|
||||
Suit.KARO -> "Zvono"
|
||||
Suit.PIK -> "List"
|
||||
Suit.TREF -> "Žir"
|
||||
}
|
||||
|
||||
fun rankName(rank: Rank): String = when (rank) {
|
||||
Rank.SEDAM -> "sedmica"
|
||||
Rank.OSAM -> "osmica"
|
||||
Rank.DEVET -> "devetka"
|
||||
Rank.DESET -> "desetka"
|
||||
Rank.DECKO -> "dečko"
|
||||
Rank.DAMA -> "dama"
|
||||
Rank.KRALJ -> "kralj"
|
||||
Rank.AS -> "as"
|
||||
}
|
||||
|
||||
/** Spoken name of a card, e.g. "Srce kralj"; used for accessibility. */
|
||||
fun cardName(card: Card): String = "${suitName(card.suit)} ${rankName(card.rank)}"
|
||||
|
||||
/** Seat names as seen from the player (seat 0). Play goes counterclockwise: you, right, partner, left. */
|
||||
fun seatName(seat: Int): String = when (seat) {
|
||||
0 -> "Ti"
|
||||
1 -> "Desni"
|
||||
2 -> "Partner"
|
||||
else -> "Lijevi"
|
||||
}
|
||||
|
||||
fun teamName(team: Int): String = if (team == 0) "Mi" else "Vi"
|
||||
|
||||
/** "1 bod", "2 boda", "5 bodova", with Croatian number agreement. */
|
||||
fun pointsText(n: Int): String {
|
||||
val word = when {
|
||||
n % 10 == 1 && n % 100 != 11 -> "bod"
|
||||
n % 10 in 2..4 && n % 100 !in 12..14 -> "boda"
|
||||
else -> "bodova"
|
||||
}
|
||||
return "$n $word"
|
||||
}
|
||||
|
||||
fun outcomeLabel(outcome: Outcome): String = when (outcome) {
|
||||
Outcome.PASSED -> "Prolaz"
|
||||
Outcome.FELL -> "Pad"
|
||||
Outcome.TIED -> "Visi"
|
||||
}
|
||||
|
||||
private val SUIT_ORDER = listOf(Suit.HERC, Suit.PIK, Suit.KARO, Suit.TREF)
|
||||
|
||||
/**
|
||||
* The player's hand grouped by suit, strongest card first within a suit. Trump comes first once it is known,
|
||||
* and the suits alternate red and black wherever the hand allows it.
|
||||
*/
|
||||
fun sortHand(cards: List<Card>, trump: Suit?): List<Card> {
|
||||
val remaining = SUIT_ORDER.filter { suit -> cards.any { it.suit == suit } }.toMutableList()
|
||||
val order = mutableListOf<Suit>()
|
||||
if (trump != null && remaining.remove(trump)) order += trump
|
||||
while (remaining.isNotEmpty()) {
|
||||
val last = order.lastOrNull()
|
||||
val next = remaining.firstOrNull { last == null || it.isRed != last.isRed } ?: remaining.first()
|
||||
order += next
|
||||
remaining.remove(next)
|
||||
}
|
||||
return cards.sortedWith(compareBy({ order.indexOf(it.suit) }, { -it.strength(trump) }))
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package hr.bela.app.ui
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Typography
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.drawBehind
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.ImageShader
|
||||
import androidx.compose.ui.graphics.ShaderBrush
|
||||
import androidx.compose.ui.graphics.TileMode
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.text.ExperimentalTextApi
|
||||
import androidx.compose.ui.text.font.Font
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontVariation
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import hr.bela.app.R
|
||||
|
||||
// ---------------------------------------------------------------- colours
|
||||
|
||||
val FeltLight = Color(0xFF2F7F57)
|
||||
val Felt = Color(0xFF1D5C3D)
|
||||
val FeltDeep = Color(0xFF0A281B)
|
||||
val Gold = Color(0xFFE9C46A)
|
||||
val GoldLight = Color(0xFFF8E7AE)
|
||||
val GoldDeep = Color(0xFFB0812C)
|
||||
val Cream = Color(0xFFF7F3E8)
|
||||
val CreamMuted = Color(0xB3F7F3E8)
|
||||
val CreamFaint = Color(0x33F7F3E8)
|
||||
val Ink = Color(0xFF2A1E02)
|
||||
val Shade = Color(0x59000000)
|
||||
val Glass = Color(0x5C000000)
|
||||
val PanelGreen = Color(0xFF0E271B)
|
||||
val DialogTop = Color(0xFF184432)
|
||||
val DialogBottom = Color(0xFF0D2A1E)
|
||||
val SuitBlack = Color(0xFF1B1B1B)
|
||||
val WinGreen = Color(0xFF8FD3A4)
|
||||
val LossRed = Color(0xFFF0958C)
|
||||
val Silver = Color(0xFFC7D0D8)
|
||||
|
||||
/** Polished gold: light at the top-left, deep at the bottom-right. */
|
||||
val GoldBrush: Brush = Brush.linearGradient(listOf(GoldLight, Gold, GoldDeep))
|
||||
val GoldVertical: Brush = Brush.verticalGradient(listOf(GoldLight, Gold, GoldDeep))
|
||||
val SilverBrush: Brush = Brush.linearGradient(listOf(Color(0xFFF1F4F7), Silver, Color(0xFF7E8B97)))
|
||||
val DialogBrush: Brush = Brush.verticalGradient(listOf(DialogTop, DialogBottom))
|
||||
|
||||
// ---------------------------------------------------------------- type
|
||||
|
||||
/** Classic Roman capitals; matches the Roman numerals on the cards. Used for titles, scores and labels. */
|
||||
@OptIn(ExperimentalTextApi::class)
|
||||
val Cinzel = FontFamily(
|
||||
Font(R.font.cinzel, FontWeight.Normal, variationSettings = FontVariation.Settings(FontVariation.weight(400))),
|
||||
Font(R.font.cinzel, FontWeight.SemiBold, variationSettings = FontVariation.Settings(FontVariation.weight(600))),
|
||||
Font(R.font.cinzel, FontWeight.Bold, variationSettings = FontVariation.Settings(FontVariation.weight(700))),
|
||||
Font(R.font.cinzel, FontWeight.Black, variationSettings = FontVariation.Settings(FontVariation.weight(900))),
|
||||
)
|
||||
|
||||
/** Body text. */
|
||||
@OptIn(ExperimentalTextApi::class)
|
||||
val Inter = FontFamily(
|
||||
Font(R.font.inter, FontWeight.Normal, variationSettings = FontVariation.Settings(FontVariation.weight(400))),
|
||||
Font(R.font.inter, FontWeight.Medium, variationSettings = FontVariation.Settings(FontVariation.weight(500))),
|
||||
Font(R.font.inter, FontWeight.SemiBold, variationSettings = FontVariation.Settings(FontVariation.weight(600))),
|
||||
Font(R.font.inter, FontWeight.Bold, variationSettings = FontVariation.Settings(FontVariation.weight(700))),
|
||||
)
|
||||
|
||||
private fun Typography.withFont(family: FontFamily) = Typography(
|
||||
displayLarge = displayLarge.copy(fontFamily = family),
|
||||
displayMedium = displayMedium.copy(fontFamily = family),
|
||||
displaySmall = displaySmall.copy(fontFamily = family),
|
||||
headlineLarge = headlineLarge.copy(fontFamily = family),
|
||||
headlineMedium = headlineMedium.copy(fontFamily = family),
|
||||
headlineSmall = headlineSmall.copy(fontFamily = family),
|
||||
titleLarge = titleLarge.copy(fontFamily = family),
|
||||
titleMedium = titleMedium.copy(fontFamily = family),
|
||||
titleSmall = titleSmall.copy(fontFamily = family),
|
||||
bodyLarge = bodyLarge.copy(fontFamily = family),
|
||||
bodyMedium = bodyMedium.copy(fontFamily = family),
|
||||
bodySmall = bodySmall.copy(fontFamily = family),
|
||||
labelLarge = labelLarge.copy(fontFamily = family),
|
||||
labelMedium = labelMedium.copy(fontFamily = family),
|
||||
labelSmall = labelSmall.copy(fontFamily = family),
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun BelaTheme(content: @Composable () -> Unit) {
|
||||
MaterialTheme(
|
||||
colorScheme = darkColorScheme(
|
||||
primary = Gold,
|
||||
onPrimary = Ink,
|
||||
secondary = Cream,
|
||||
background = FeltDeep,
|
||||
surface = DialogBottom,
|
||||
onSurface = Cream,
|
||||
surfaceContainerHigh = DialogBottom,
|
||||
),
|
||||
typography = Typography().withFont(Inter),
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- felt
|
||||
|
||||
/** Fine random grain, tiled over the felt so it reads as cloth rather than a flat gradient. */
|
||||
private val FeltGrain: ShaderBrush by lazy {
|
||||
val size = 128
|
||||
val random = java.util.Random(7)
|
||||
val pixels = IntArray(size * size) {
|
||||
val alpha = random.nextInt(16)
|
||||
if (random.nextBoolean()) (alpha shl 24) or 0xFFFFFF else alpha shl 24
|
||||
}
|
||||
val bitmap = Bitmap.createBitmap(pixels, size, size, Bitmap.Config.ARGB_8888).asImageBitmap()
|
||||
ShaderBrush(ImageShader(bitmap, TileMode.Repeated, TileMode.Repeated))
|
||||
}
|
||||
|
||||
/** Card-table felt: lit in the middle, grain on top, dark vignette at the rim. */
|
||||
fun Modifier.feltBackground(): Modifier = drawBehind {
|
||||
drawRect(
|
||||
Brush.radialGradient(
|
||||
colors = listOf(FeltLight, Felt, FeltDeep),
|
||||
center = Offset(size.width / 2, size.height * 0.45f),
|
||||
radius = size.maxDimension * 0.72f,
|
||||
),
|
||||
)
|
||||
drawRect(FeltGrain)
|
||||
drawRect(
|
||||
Brush.radialGradient(
|
||||
colors = listOf(Color.Transparent, Color.Transparent, Color(0x8C000000)),
|
||||
center = Offset(size.width / 2, size.height / 2),
|
||||
radius = size.maxDimension * 0.68f,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
package hr.bela.app.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.core.Animatable
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.safeDrawingPadding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.ripple
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.shadow
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import hr.bela.app.DrillLevel
|
||||
import hr.bela.app.DrillPhase
|
||||
import hr.bela.app.TrainingState
|
||||
import hr.bela.app.TrainingViewModel
|
||||
import hr.bela.engine.AnswerOption
|
||||
import hr.bela.engine.Card
|
||||
import hr.bela.engine.CountingMistake
|
||||
import hr.bela.engine.CountingRound
|
||||
import hr.bela.engine.points
|
||||
|
||||
/** Card-counting practice: a pile of won cards is shown one by one, then the player picks the total. */
|
||||
@Composable
|
||||
fun TrainingScreen(onExit: () -> Unit, vm: TrainingViewModel = viewModel()) {
|
||||
val s by vm.state.collectAsStateWithLifecycle()
|
||||
BackHandler(onBack = onExit)
|
||||
|
||||
Box(Modifier.fillMaxSize().feltBackground()) {
|
||||
Column(Modifier.fillMaxSize().safeDrawingPadding().padding(horizontal = 16.dp)) {
|
||||
TrainingHeader(s, onExit)
|
||||
LevelPicker(s.level, vm::setLevel)
|
||||
TrumpBanner(s.round)
|
||||
Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
when (s.phase) {
|
||||
DrillPhase.COUNTING -> CountingStage(s, vm::next)
|
||||
DrillPhase.ANSWERING -> AnswerStage(s.round, vm::answer)
|
||||
DrillPhase.RESULT -> ResultStage(s)
|
||||
}
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().height(78.dp), contentAlignment = Alignment.Center) {
|
||||
when (s.phase) {
|
||||
DrillPhase.COUNTING -> GoldButton(if (s.isLastCard) "Zbroji" else "Sljedeća karta", vm::next)
|
||||
DrillPhase.ANSWERING -> Text("Odaberi zbroj", color = CreamMuted, fontSize = 13.sp)
|
||||
DrillPhase.RESULT -> GoldButton("Nova runda", vm::nextRound)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TrainingHeader(s: TrainingState, onExit: () -> Unit) {
|
||||
Box(Modifier.fillMaxWidth().padding(top = cameraClearance()).height(68.dp)) {
|
||||
GlassIconButton(BelaIcons.Back, "Natrag", onExit, Modifier.align(Alignment.CenterStart))
|
||||
Column(Modifier.align(Alignment.Center), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Overline("Trening", color = Gold)
|
||||
Text("Brojanje", color = Cream, fontFamily = Cinzel, fontWeight = FontWeight.Bold, fontSize = 22.sp)
|
||||
}
|
||||
Column(Modifier.align(Alignment.CenterEnd), horizontalAlignment = Alignment.End) {
|
||||
Row(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(50))
|
||||
.background(Glass)
|
||||
.border(1.dp, if (s.streak > 0) GoldBrush else Brush.linearGradient(listOf(CreamFaint, CreamFaint)), RoundedCornerShape(50))
|
||||
.padding(horizontal = 10.dp, vertical = 3.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text("NIZ", color = CreamMuted, fontFamily = Cinzel, fontWeight = FontWeight.Bold, fontSize = 9.sp, letterSpacing = 1.5.sp)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("${s.streak}", color = if (s.streak > 0) Gold else Cream, fontFamily = Cinzel, fontWeight = FontWeight.Bold, fontSize = 15.sp)
|
||||
}
|
||||
Text(
|
||||
"${s.correct}/${s.answered} · rekord ${s.bestStreak}",
|
||||
color = CreamMuted,
|
||||
fontSize = 11.sp,
|
||||
modifier = Modifier.padding(top = 3.dp, end = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LevelPicker(current: DrillLevel, onPick: (DrillLevel) -> Unit) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(top = 4.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
|
||||
) {
|
||||
DrillLevel.entries.forEach { level ->
|
||||
val selected = level == current
|
||||
val shape = RoundedCornerShape(50)
|
||||
Box(
|
||||
Modifier
|
||||
.clip(shape)
|
||||
.then(if (selected) Modifier.background(GoldVertical) else Modifier.background(Glass))
|
||||
.border(1.dp, if (selected) GoldBrush else Brush.linearGradient(listOf(CreamFaint, CreamFaint)), shape)
|
||||
.clickable { onPick(level) }
|
||||
.padding(horizontal = 16.dp, vertical = 6.dp),
|
||||
) {
|
||||
Text(
|
||||
level.label.uppercase(),
|
||||
color = if (selected) Ink else Cream,
|
||||
fontFamily = Cinzel,
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 12.sp,
|
||||
letterSpacing = 1.sp,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The made-up trump for this pile, with a reminder of the two cards that change value. */
|
||||
@Composable
|
||||
private fun TrumpBanner(round: CountingRound) {
|
||||
Column(Modifier.fillMaxWidth().padding(top = 16.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
SuitMedallion(round.trump, 56.dp)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column {
|
||||
Overline("Adut", color = Gold)
|
||||
Text(suitName(round.trump), color = Cream, fontFamily = Cinzel, fontWeight = FontWeight.Bold, fontSize = 22.sp)
|
||||
Text("dečko 20 · devetka 14", color = CreamMuted, fontSize = 12.sp)
|
||||
}
|
||||
}
|
||||
if (round.lastTrick) {
|
||||
Row(
|
||||
Modifier
|
||||
.padding(top = 10.dp)
|
||||
.clip(RoundedCornerShape(50))
|
||||
.background(Glass)
|
||||
.border(1.dp, GoldBrush, RoundedCornerShape(50))
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text("+10", color = Gold, fontFamily = Cinzel, fontWeight = FontWeight.Bold, fontSize = 13.sp)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("Zadnji štih je vaš", color = Cream, fontSize = 12.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One card at a time; the cards already counted lie face down behind it. Tap the card (or the button) for the next. */
|
||||
@Composable
|
||||
private fun CountingStage(s: TrainingState, onNext: () -> Unit) {
|
||||
val cards = s.round.cards
|
||||
BoxWithConstraints(Modifier.fillMaxSize()) {
|
||||
// As large as the space allows, but never wider than the artwork itself, so it is never enlarged.
|
||||
val width = minOf(maxCardWidth(), maxWidth * 0.7f, (maxHeight - 70.dp) * CARD_ASPECT)
|
||||
Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
|
||||
Overline("Karta ${s.shown} / ${cards.size}")
|
||||
Box(Modifier.padding(top = 6.dp, bottom = 18.dp).width(160.dp).height(3.dp).clip(RoundedCornerShape(2.dp)).background(CreamFaint)) {
|
||||
Box(Modifier.fillMaxHeight().fillMaxWidth(s.shown / cards.size.toFloat()).background(GoldBrush))
|
||||
}
|
||||
Box(
|
||||
Modifier.clickable(remember { MutableInteractionSource() }, indication = null, onClick = onNext),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
val counted = (s.shown - 1).coerceAtMost(3)
|
||||
for (depth in counted downTo 1) {
|
||||
CardBack(
|
||||
Modifier
|
||||
.width(width)
|
||||
.graphicsLayer {
|
||||
translationX = -depth * 14.dp.toPx()
|
||||
translationY = depth * 4.dp.toPx()
|
||||
rotationZ = -depth * 4f
|
||||
alpha = 1f - depth * 0.2f
|
||||
},
|
||||
)
|
||||
}
|
||||
key(s.shown) { RevealedCard(cards[s.shown - 1], width) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RevealedCard(card: Card, width: Dp) {
|
||||
val flip = remember { Animatable(0f) }
|
||||
LaunchedEffect(Unit) { flip.animateTo(1f, tween(durationMillis = 340, easing = FastOutSlowInEasing)) }
|
||||
CardFace(
|
||||
card = card,
|
||||
elevation = 18.dp,
|
||||
modifier = Modifier
|
||||
.width(width)
|
||||
.graphicsLayer {
|
||||
val p = flip.value
|
||||
rotationY = (1 - p) * -90f
|
||||
translationX = (1 - p) * 90.dp.toPx()
|
||||
cameraDistance = 16f * density
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AnswerStage(round: CountingRound, onAnswer: (AnswerOption) -> Unit) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
|
||||
Text("Koliko bodova?", color = Cream, fontFamily = Cinzel, fontWeight = FontWeight.Bold, fontSize = 26.sp)
|
||||
Text(
|
||||
"${round.cards.size} karata" + if (round.lastTrick) " i zadnji štih" else "",
|
||||
color = CreamMuted,
|
||||
fontSize = 13.sp,
|
||||
modifier = Modifier.padding(top = 4.dp, bottom = 24.dp),
|
||||
)
|
||||
round.options.chunked(2).forEach { pair ->
|
||||
Row(Modifier.fillMaxWidth().padding(bottom = 12.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
pair.forEach { option -> OptionTile(option.value, Modifier.weight(1f)) { onAnswer(option) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun OptionTile(value: Int, modifier: Modifier, onClick: () -> Unit) {
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val pressed by interaction.collectIsPressedAsState()
|
||||
val scale by animateFloatAsState(if (pressed) 0.95f else 1f, tween(120), label = "option")
|
||||
val shape = RoundedCornerShape(18.dp)
|
||||
Box(
|
||||
modifier
|
||||
.height(88.dp)
|
||||
.graphicsLayer {
|
||||
scaleX = scale
|
||||
scaleY = scale
|
||||
}
|
||||
.shadow(8.dp, shape)
|
||||
.clip(shape)
|
||||
.background(Brush.verticalGradient(listOf(Color(0xFFFFFDF6), Color(0xFFEAE2CB))))
|
||||
.border(1.dp, GoldBrush, shape)
|
||||
.clickable(interaction, ripple(color = GoldDeep), onClick = onClick),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text("$value", color = Color(0xFF2E2717), fontFamily = Cinzel, fontWeight = FontWeight.Bold, fontSize = 34.sp)
|
||||
}
|
||||
}
|
||||
|
||||
private fun mistakeText(mistake: CountingMistake?): String = when (mistake) {
|
||||
CountingMistake.TRUMP_JACK_AS_PLAIN -> "Dečko u adutu vrijedi 20 bodova, a ne 2."
|
||||
CountingMistake.TRUMP_NINE_AS_PLAIN -> "Devetka u adutu vrijedi 14 bodova, a ne 0."
|
||||
CountingMistake.PLAIN_JACK_AS_TRUMP -> "Dečko izvan aduta vrijedi samo 2 boda."
|
||||
CountingMistake.PLAIN_NINE_AS_TRUMP -> "Devetka izvan aduta ne nosi bodove."
|
||||
CountingMistake.FORGOT_LAST_TRICK -> "Zadnji štih nosi još 10 bodova."
|
||||
CountingMistake.ADDED_LAST_TRICK -> "Zadnji štih ovaj put nije bio vaš."
|
||||
CountingMistake.MISSED_TEN -> "Jedna desetka nije ubrojena: svaka vrijedi 10."
|
||||
CountingMistake.MISSED_ACE -> "Jedan as nije ubrojen: svaki vrijedi 11."
|
||||
CountingMistake.KING_QUEEN_MIXUP -> "Kralj vrijedi 4, a dama 3."
|
||||
null -> "Zbroj se ne slaže. Pogledaj vrijednosti karata ispod."
|
||||
}
|
||||
|
||||
private val GridGap = 8.dp
|
||||
private val GridRowGap = 10.dp
|
||||
private val PointsLabel = 22.dp
|
||||
|
||||
/**
|
||||
* Column count that makes [count] cards (each with its points label underneath) as large as possible in
|
||||
* [width] x [height], and the card width that gives. Never wider than [maxCard].
|
||||
*/
|
||||
private fun bestGrid(count: Int, width: Dp, height: Dp, maxCard: Dp): Pair<Int, Dp> {
|
||||
var best = 1 to 0.dp
|
||||
for (columns in 2..10) {
|
||||
val rows = (count + columns - 1) / columns
|
||||
val byWidth = (width - GridGap * (columns - 1)) / columns
|
||||
val byHeight = ((height - GridRowGap * (rows - 1)) / rows - PointsLabel) * CARD_ASPECT
|
||||
val card = minOf(byWidth, byHeight, maxCard)
|
||||
if (card > best.second) best = columns to card
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
/** Verdict, then every card with its value and the sum, so the player sees where the count went wrong. */
|
||||
@Composable
|
||||
private fun ResultStage(s: TrainingState) {
|
||||
val round = s.round
|
||||
val right = s.wasCorrect
|
||||
Column(
|
||||
Modifier.fillMaxSize().padding(top = 8.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Text(
|
||||
if (right) "Točno!" else "Netočno",
|
||||
color = if (right) WinGreen else LossRed,
|
||||
fontFamily = Cinzel,
|
||||
fontWeight = FontWeight.Black,
|
||||
fontSize = 34.sp,
|
||||
)
|
||||
if (right) {
|
||||
Text(
|
||||
if (s.streak > 1) "Niz od ${s.streak} točnih odgovora." else "Bravo, zbroj je ${round.total}.",
|
||||
color = Cream,
|
||||
fontSize = 14.sp,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
} else {
|
||||
Text("Točno je ${round.total}, odabrano ${s.chosen?.value}.", color = Cream, fontSize = 15.sp, fontWeight = FontWeight.SemiBold)
|
||||
Text(
|
||||
mistakeText(s.chosen?.mistake),
|
||||
color = CreamMuted,
|
||||
fontSize = 14.sp,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
Ornament(Modifier.padding(vertical = 12.dp))
|
||||
// The cards fill whatever room is left, as large as they fit.
|
||||
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
val cards = sortHand(round.cards, round.trump)
|
||||
val (columns, cardWidth) = bestGrid(cards.size, maxWidth, maxHeight, maxCardWidth())
|
||||
Column(verticalArrangement = Arrangement.spacedBy(GridRowGap)) {
|
||||
cards.chunked(columns).forEach { row ->
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(GridGap), modifier = Modifier.align(Alignment.CenterHorizontally)) {
|
||||
row.forEach { card ->
|
||||
val points = card.points(round.trump)
|
||||
val isTrump = card.suit == round.trump
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
CardFace(card, Modifier.width(cardWidth), highlighted = isTrump && points >= 14, elevation = 4.dp)
|
||||
Text(
|
||||
"$points",
|
||||
color = when {
|
||||
isTrump && points > 0 -> Gold
|
||||
points > 0 -> Cream
|
||||
else -> CreamMuted
|
||||
},
|
||||
fontFamily = Cinzel,
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 14.sp,
|
||||
modifier = Modifier.height(PointsLabel).padding(top = 3.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Text(
|
||||
buildString {
|
||||
append("Karte ${round.cardPoints}")
|
||||
if (round.lastTrick) append(" + zadnji štih 10")
|
||||
append(" = ${round.total}")
|
||||
},
|
||||
color = Gold,
|
||||
fontFamily = Cinzel,
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 16.sp,
|
||||
modifier = Modifier.padding(top = 12.dp, bottom = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package hr.bela.app.update
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.provider.Settings
|
||||
import androidx.core.content.FileProvider
|
||||
import hr.bela.app.BuildConfig
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.security.MessageDigest
|
||||
|
||||
/** The public repository the app is released to (one Gitea release per version, APK attached as [APK_NAME]). */
|
||||
object ReleaseChannel {
|
||||
const val REPO_URL = "https://git.mariosem.es/msemes/Bela-Release-Android"
|
||||
const val API_LATEST = "https://git.mariosem.es/api/v1/repos/msemes/Bela-Release-Android/releases/latest"
|
||||
|
||||
/** Every release attaches the APK under this same name, so [LATEST_APK_URL] never changes. */
|
||||
const val APK_NAME = "bela.apk"
|
||||
|
||||
/** Always the newest APK: the server resolves "latest" to the newest release. Used for the QR code. */
|
||||
const val LATEST_APK_URL = "$REPO_URL/releases/download/latest/$APK_NAME"
|
||||
const val RELEASES_PAGE = "$REPO_URL/releases"
|
||||
}
|
||||
|
||||
data class ReleaseInfo(
|
||||
val versionName: String,
|
||||
val versionCode: Int,
|
||||
val apkUrl: String,
|
||||
val notes: String?,
|
||||
val sha256: String?,
|
||||
)
|
||||
|
||||
sealed interface UpdateCheck {
|
||||
data class Available(val release: ReleaseInfo) : UpdateCheck
|
||||
data class UpToDate(val latest: ReleaseInfo) : UpdateCheck
|
||||
data object NoReleases : UpdateCheck
|
||||
data class Failed(val message: String) : UpdateCheck
|
||||
}
|
||||
|
||||
/**
|
||||
* In-app self-update, same scheme as the Keep app: read the latest release from the public release repo,
|
||||
* compare its version with the running build, download the APK (checking the published SHA-256) and hand it
|
||||
* to the system installer, which asks the user to confirm.
|
||||
*/
|
||||
class Updates(private val context: Context) {
|
||||
|
||||
suspend fun check(): UpdateCheck = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val connection = open(ReleaseChannel.API_LATEST).apply { setRequestProperty("Accept", "application/json") }
|
||||
val code = connection.responseCode
|
||||
if (code == HttpURLConnection.HTTP_NOT_FOUND) return@withContext UpdateCheck.NoReleases
|
||||
if (code !in 200..299) return@withContext UpdateCheck.Failed("Server je odgovorio $code")
|
||||
val json = JSONObject(connection.inputStream.bufferedReader().use { it.readText() })
|
||||
|
||||
val versionName = json.optString("tag_name").removePrefix("v")
|
||||
val versionCode = versionCodeOf(versionName)
|
||||
?: return@withContext UpdateCheck.Failed("Nepoznata oznaka verzije: ${json.optString("tag_name")}")
|
||||
val assets = json.optJSONArray("assets")
|
||||
val apk = (0 until (assets?.length() ?: 0)).map { assets!!.getJSONObject(it) }
|
||||
.firstOrNull { it.optString("name") == ReleaseChannel.APK_NAME }
|
||||
?: return@withContext UpdateCheck.Failed("Izdanje nema APK")
|
||||
val body = json.optString("body")
|
||||
val release = ReleaseInfo(
|
||||
versionName = versionName,
|
||||
versionCode = versionCode,
|
||||
apkUrl = apk.optString("browser_download_url"),
|
||||
notes = SHA256_LINE.replace(body, "").trim().takeIf { it.isNotBlank() },
|
||||
sha256 = SHA256_LINE.find(body)?.groupValues?.get(1)?.lowercase(),
|
||||
)
|
||||
if (versionCode > BuildConfig.VERSION_CODE) UpdateCheck.Available(release) else UpdateCheck.UpToDate(release)
|
||||
} catch (e: IOException) {
|
||||
UpdateCheck.Failed("Nema veze sa serverom")
|
||||
} catch (e: Exception) {
|
||||
UpdateCheck.Failed(e.message ?: "Provjera nije uspjela")
|
||||
}
|
||||
}
|
||||
|
||||
/** Streams the APK to the app's cache, reporting progress 0..1 (or -1 when the size is unknown). */
|
||||
suspend fun download(release: ReleaseInfo, onProgress: (Float) -> Unit): File = withContext(Dispatchers.IO) {
|
||||
val dir = File(context.externalCacheDir ?: context.cacheDir, "updates").apply { mkdirs() }
|
||||
dir.listFiles()?.forEach { it.delete() }
|
||||
val file = File(dir, "bela-${release.versionName}.apk")
|
||||
val connection = open(release.apkUrl)
|
||||
if (connection.responseCode !in 200..299) throw IOException("Preuzimanje nije uspjelo (${connection.responseCode})")
|
||||
val total = connection.contentLengthLong
|
||||
connection.inputStream.use { input ->
|
||||
file.outputStream().use { output ->
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
var done = 0L
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
output.write(buffer, 0, read)
|
||||
done += read
|
||||
onProgress(if (total > 0) done.toFloat() / total else -1f)
|
||||
}
|
||||
}
|
||||
}
|
||||
val expected = release.sha256
|
||||
if (expected != null && !sha256Hex(file).equals(expected, ignoreCase = true)) {
|
||||
file.delete()
|
||||
throw IOException("Preuzeta datoteka nije ispravna (kontrolni zbroj se ne slaže)")
|
||||
}
|
||||
file
|
||||
}
|
||||
|
||||
/** Whether Android currently lets this app open the package installer. */
|
||||
fun canInstall(): Boolean = context.packageManager.canRequestPackageInstalls()
|
||||
|
||||
/** The "install unknown apps" switch for this app. */
|
||||
fun openInstallPermissionSettings() {
|
||||
val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:${context.packageName}"))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
runCatching { context.startActivity(intent) }
|
||||
}
|
||||
|
||||
/** Opens the system installer for [apk]; Android asks the user to confirm the update. */
|
||||
fun install(apk: File) {
|
||||
val uri = FileProvider.getUriForFile(context, "${context.packageName}.updates", apk)
|
||||
val intent = Intent(Intent.ACTION_VIEW)
|
||||
.setDataAndType(uri, "application/vnd.android.package-archive")
|
||||
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
context.startActivity(intent)
|
||||
}
|
||||
|
||||
private fun open(url: String): HttpURLConnection =
|
||||
(URL(url).openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 15_000
|
||||
readTimeout = 60_000
|
||||
instanceFollowRedirects = true
|
||||
}
|
||||
|
||||
private fun sha256Hex(file: File): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
file.inputStream().use { input ->
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
digest.update(buffer, 0, read)
|
||||
}
|
||||
}
|
||||
return digest.digest().joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** Integrity line in the release notes, written by tools/build-release.ps1: "sha256:<64 hex>". */
|
||||
private val SHA256_LINE = Regex("(?im)^\\s*sha256:([0-9a-f]{64})\\s*$")
|
||||
|
||||
/** Inverse of the odometer versionName in app/build.gradle.kts: "0.1.3" -> 13. */
|
||||
fun versionCodeOf(versionName: String): Int? {
|
||||
val parts = versionName.split('.').map { it.toIntOrNull() ?: return null }
|
||||
if (parts.size != 3 || parts[1] !in 0..9 || parts[2] !in 0..9) return null
|
||||
return parts[0] * 100 + parts[1] * 10 + parts[2]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 169 KiB |
|
After Width: | Height: | Size: 188 KiB |
|
After Width: | Height: | Size: 210 KiB |
|
After Width: | Height: | Size: 149 KiB |
|
After Width: | Height: | Size: 259 KiB |
|
After Width: | Height: | Size: 205 KiB |
|
After Width: | Height: | Size: 186 KiB |
|
After Width: | Height: | Size: 241 KiB |
|
After Width: | Height: | Size: 165 KiB |
|
After Width: | Height: | Size: 190 KiB |
|
After Width: | Height: | Size: 215 KiB |
|
After Width: | Height: | Size: 173 KiB |
|
After Width: | Height: | Size: 236 KiB |
|
After Width: | Height: | Size: 191 KiB |
|
After Width: | Height: | Size: 158 KiB |
|
After Width: | Height: | Size: 228 KiB |
|
After Width: | Height: | Size: 178 KiB |
|
After Width: | Height: | Size: 207 KiB |
|
After Width: | Height: | Size: 218 KiB |
|
After Width: | Height: | Size: 164 KiB |
|
After Width: | Height: | Size: 217 KiB |
|
After Width: | Height: | Size: 194 KiB |
|
After Width: | Height: | Size: 176 KiB |
|
After Width: | Height: | Size: 234 KiB |
|
After Width: | Height: | Size: 218 KiB |
|
After Width: | Height: | Size: 166 KiB |
|
After Width: | Height: | Size: 222 KiB |
|
After Width: | Height: | Size: 194 KiB |
|
After Width: | Height: | Size: 243 KiB |
|
After Width: | Height: | Size: 195 KiB |
|
After Width: | Height: | Size: 187 KiB |
|
After Width: | Height: | Size: 234 KiB |
|
After Width: | Height: | Size: 116 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 41 KiB |
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by tools/make_icon.py from icon.png. -->
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/ic_launcher_background" />
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
|
After Width: | Height: | Size: 6.5 KiB |
|
After Width: | Height: | Size: 3.6 KiB |
|
After Width: | Height: | Size: 9.9 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 26 KiB |
@@ -0,0 +1,4 @@
|
||||
<resources>
|
||||
<color name="felt">#1F5C3A</color>
|
||||
<color name="felt_dark">#123722</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="ic_launcher_background">#042608</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,3 @@
|
||||
<resources>
|
||||
<string name="app_name">Bela</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,8 @@
|
||||
<resources>
|
||||
<!-- Compose paints the UI; this theme only sets the window background and transparent system bars. -->
|
||||
<style name="Theme.Bela" parent="@android:style/Theme.Material.NoActionBar">
|
||||
<item name="android:windowBackground">@color/felt_dark</item>
|
||||
<item name="android:statusBarColor">@android:color/transparent</item>
|
||||
<item name="android:navigationBarColor">@android:color/transparent</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Where Updates.download() stores the APK before handing it to the installer. -->
|
||||
<paths>
|
||||
<external-cache-path name="updates" path="updates/" />
|
||||
<cache-path name="updates_internal" path="updates/" />
|
||||
</paths>
|
||||
@@ -0,0 +1,5 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.application) apply false
|
||||
alias(libs.plugins.kotlin.jvm) apply false
|
||||
alias(libs.plugins.compose.compiler) apply false
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
# Source and licence
|
||||
|
||||
Copied from https://github.com/tomasdrus/hungarian-playing-cards (commit in `SOURCE_COMMIT.txt`):
|
||||
`cards-large/` (32 cards + back, 363 x 585 px PNG) and the large suit icons.
|
||||
|
||||
**The repository has no licence.** Without one, all rights are reserved by the author. These images are fine for
|
||||
local development, but before the app is published we need written permission from the author (or a licence
|
||||
added to the repository), or we switch back to our own SVG cards (`python tools/render_cards.py`).
|
||||
@@ -0,0 +1,47 @@
|
||||
# Hungarian playing cards PNG images
|
||||
|
||||
Images of each card from full deck of Hungarian playing cards (32 cards) also know as European / German type / Tell / Magyar kártya / Mariášové karty.
|
||||
In addition back side of one of the cards => 32+1 images of cards.
|
||||
|
||||

|
||||
|
||||
Every image has transparent background and PNG format.
|
||||
|
||||
## 3 image sizes (300dpi)
|
||||
|
||||
- Large / 363x585px / 271-423kB / all 11,4MB
|
||||
- Medium / 181x293px / 75-112kB / all 3,1MB
|
||||
- Small / 91x146px / 22-31kB / all 880kB
|
||||
|
||||
## 3 suits icon sizes
|
||||
|
||||
Every suit from cards has 3 icon sizes: small, medium and large.
|
||||
|
||||
## Card suits
|
||||
|
||||
- Hearts
|
||||
|
||||

|
||||
|
||||
- Leaves
|
||||
|
||||

|
||||
|
||||
- Bells
|
||||
|
||||

|
||||
|
||||
- Acorns
|
||||
|
||||

|
||||
|
||||
## Card values
|
||||
|
||||
- Ace
|
||||
- King
|
||||
- Ober (Over-knave)
|
||||
- Unter (Under-knave)
|
||||
- X (10)
|
||||
- IX (9)
|
||||
- VII (8)
|
||||
- VI (7)
|
||||
@@ -0,0 +1 @@
|
||||
6c4c7252af5aef50e189bc033ca4f69feb469b69 Thu Sep 9 00:01:28 2021 +0200
|
||||
|
After Width: | Height: | Size: 774 KiB |
|
After Width: | Height: | Size: 822 KiB |
|
After Width: | Height: | Size: 815 KiB |
|
After Width: | Height: | Size: 674 KiB |
|
After Width: | Height: | Size: 736 KiB |
|
After Width: | Height: | Size: 792 KiB |
|
After Width: | Height: | Size: 730 KiB |
|
After Width: | Height: | Size: 622 KiB |
|
After Width: | Height: | Size: 850 KiB |
|
After Width: | Height: | Size: 851 KiB |
|
After Width: | Height: | Size: 803 KiB |
|
After Width: | Height: | Size: 755 KiB |
|
After Width: | Height: | Size: 687 KiB |
|
After Width: | Height: | Size: 652 KiB |
|
After Width: | Height: | Size: 823 KiB |
|
After Width: | Height: | Size: 667 KiB |
|
After Width: | Height: | Size: 870 KiB |
|
After Width: | Height: | Size: 829 KiB |
|
After Width: | Height: | Size: 801 KiB |
|
After Width: | Height: | Size: 696 KiB |
|
After Width: | Height: | Size: 701 KiB |
|
After Width: | Height: | Size: 750 KiB |
|
After Width: | Height: | Size: 701 KiB |
|
After Width: | Height: | Size: 590 KiB |
|
After Width: | Height: | Size: 935 KiB |
|
After Width: | Height: | Size: 780 KiB |