From c05c39ff3608ffe95a99c2effef52ec1390fe456 Mon Sep 17 00:00:00 2001 From: tkrmagid Date: Wed, 4 Nov 2026 10:43:32 +0900 Subject: [PATCH] =?UTF-8?q?=EC=95=B1:=20=EB=A9=80=ED=8B=B0=ED=94=8C?= =?UTF-8?q?=EB=A0=88=EC=9D=B4=C2=B7=EA=B3=84=EC=A0=95=C2=B7=EB=A6=AC?= =?UTF-8?q?=EB=8D=94=EB=B3=B4=EB=93=9C=C2=B7=EA=B4=91=EA=B3=A0=20=EC=97=B0?= =?UTF-8?q?=EA=B2=B0=20(Phase=204~7=20=ED=81=B4=EB=9D=BC=EC=9D=B4=EC=96=B8?= =?UTF-8?q?=ED=8A=B8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 게스트 자동 발급, 이메일 가입/로그인(게스트 기록 이전), 닉네임 변경, 계정 삭제 - 커스텀 방 만들기/참가, 로비(호스트 규칙), 1:1·FFA 대전, 가비지 게이지·상쇄·삽입, 상대 미니보드 탭 타겟팅, KO 피드, 관전, 리매치 투표, 재접속 - 리그 대기열·매칭·FT3/FT5·결과(TR/배치), 리더보드 4종, 프로필 전적 - AdMob(UMP 동의) 배너·결과 카드·전면(3판당 1회, 첫 판 제외), 기본은 테스트 ID - 서버: 앱 레벨 keepalive(auto-response), KO 후 로비 갱신, 재접속 시 결과 재전송, x-info 헤더 ASCII 인코딩, 계정 삭제 API - 개인정보처리방침·스토어 등록정보 갱신 (온라인·광고 반영) Co-Authored-By: Claude Opus 5.5 --- app/composeApp/build.gradle.kts | 11 + .../src/androidMain/AndroidManifest.xml | 7 + .../kotlin/kr/tkrmagid/tetrig/MainActivity.kt | 2 + .../kr/tkrmagid/tetrig/ads/Ads.android.kt | 161 +++++++ .../kr/tkrmagid/tetrig/net/Net.android.kt | 62 +++ .../kotlin/kr/tkrmagid/tetrig/ads/Ads.kt | 50 ++ .../kotlin/kr/tkrmagid/tetrig/data/Store.kt | 3 + .../kr/tkrmagid/tetrig/engine/Engine.kt | 22 +- .../kr/tkrmagid/tetrig/engine/Versus.kt | 106 +++++ .../kr/tkrmagid/tetrig/game/GameState.kt | 39 +- .../kr/tkrmagid/tetrig/game/RoomClient.kt | 405 ++++++++++++++++ .../kotlin/kr/tkrmagid/tetrig/net/Api.kt | 191 ++++++++ .../kotlin/kr/tkrmagid/tetrig/net/Net.kt | 29 ++ .../kotlin/kr/tkrmagid/tetrig/ui/App.kt | 54 ++- .../kr/tkrmagid/tetrig/ui/GameScreen.kt | 43 +- .../kr/tkrmagid/tetrig/ui/MainScreen.kt | 98 ++-- .../kr/tkrmagid/tetrig/ui/OnlineScreens.kt | 438 +++++++++++++++++ .../kr/tkrmagid/tetrig/ui/RoomScreen.kt | 446 ++++++++++++++++++ .../kr/tkrmagid/tetrig/engine/VersusTest.kt | 79 ++++ app/gradle.properties | 10 + app/gradle/libs.versions.toml | 8 + server/scripts/e2e.mjs | 4 + server/src/index.js | 13 +- server/src/matchmaker.js | 9 +- server/src/room-logic.js | 16 +- server/src/room.js | 11 +- server/test/room.test.js | 15 + store/listing.md | 80 ++-- store/privacy.html | 96 ++-- 29 files changed, 2341 insertions(+), 167 deletions(-) create mode 100644 app/composeApp/src/androidMain/kotlin/kr/tkrmagid/tetrig/ads/Ads.android.kt create mode 100644 app/composeApp/src/androidMain/kotlin/kr/tkrmagid/tetrig/net/Net.android.kt create mode 100644 app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ads/Ads.kt create mode 100644 app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/engine/Versus.kt create mode 100644 app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/game/RoomClient.kt create mode 100644 app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/net/Api.kt create mode 100644 app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/net/Net.kt create mode 100644 app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/OnlineScreens.kt create mode 100644 app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/RoomScreen.kt create mode 100644 app/composeApp/src/commonTest/kotlin/kr/tkrmagid/tetrig/engine/VersusTest.kt diff --git a/app/composeApp/build.gradle.kts b/app/composeApp/build.gradle.kts index cc05985..e06330f 100644 --- a/app/composeApp/build.gradle.kts +++ b/app/composeApp/build.gradle.kts @@ -34,6 +34,7 @@ kotlin { implementation(compose.ui) implementation(compose.components.resources) implementation(libs.androidx.lifecycle.viewmodel) + implementation(libs.kotlinx.serialization.json) } commonTest.dependencies { implementation(libs.kotlin.test) @@ -41,6 +42,9 @@ kotlin { androidMain.dependencies { implementation(compose.preview) implementation(libs.androidx.activity.compose) + implementation(libs.okhttp) + implementation(libs.play.services.ads) + implementation(libs.ump) } } } @@ -55,6 +59,13 @@ android { targetSdk = 36 versionCode = appVersionCode versionName = appVersionName + + // AdMob — 기본값은 Google 공식 테스트 ID. 실제 ID 는 gradle.properties 의 admob* 값만 바꾸면 된다. + fun prop(k: String, d: String) = (findProperty(k) as String?)?.takeIf { it.isNotBlank() } ?: d + manifestPlaceholders["admobAppId"] = prop("admobAppId", "ca-app-pub-3940256099942544~3347511713") + resValue("string", "admob_banner", prop("admobBanner", "ca-app-pub-3940256099942544/9214589741")) + resValue("string", "admob_card", prop("admobCard", "ca-app-pub-3940256099942544/6300978111")) + resValue("string", "admob_interstitial", prop("admobInterstitial", "ca-app-pub-3940256099942544/1033173712")) } sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml") diff --git a/app/composeApp/src/androidMain/AndroidManifest.xml b/app/composeApp/src/androidMain/AndroidManifest.xml index 5e44231..aec9e41 100644 --- a/app/composeApp/src/androidMain/AndroidManifest.xml +++ b/app/composeApp/src/androidMain/AndroidManifest.xml @@ -1,6 +1,9 @@ + + + + + + if (err != null) Log.w(TAG, "consent form: ${err.message}") + if (consent.canRequestAds()) init(act) + } + }, + { err -> Log.w(TAG, "consent update: ${err.message}"); if (consent.canRequestAds()) init(act) }, + ) + if (consent.canRequestAds()) init(act) + } + + private fun init(act: Activity) { + if (!started.compareAndSet(false, true)) return + MobileAds.initialize(act.applicationContext) { + ready = true + Log.i(TAG, "MobileAds ready") + loadInterstitial() + } + } + + fun loadInterstitial() { + val act = activity ?: return + if (!ready || interstitial != null) return + InterstitialAd.load(act, act.getString(R.string.admob_interstitial), AdRequest.Builder().build(), + object : InterstitialAdLoadCallback() { + override fun onAdLoaded(ad: InterstitialAd) { + interstitial = ad + Log.i(TAG, "interstitial loaded") + } + override fun onAdFailedToLoad(e: LoadAdError) { + Log.w(TAG, "interstitial failed: ${e.message}") + } + }) + } + + fun show(then: () -> Unit) { + val act = activity + val ad = interstitial + if (act == null || ad == null) { + Log.i(TAG, "interstitial skipped (not loaded)") + then() + loadInterstitial() + return + } + interstitial = null + ad.fullScreenContentCallback = object : FullScreenContentCallback() { + override fun onAdDismissedFullScreenContent() { + Log.i(TAG, "interstitial dismissed") + then() + loadInterstitial() + } + override fun onAdFailedToShowFullScreenContent(e: com.google.android.gms.ads.AdError) { + then() + loadInterstitial() + } + } + Log.i(TAG, "interstitial show") + ad.show(act) + } +} + +actual fun showInterstitial(then: () -> Unit) = AdsAndroid.show(then) + +@Composable +actual fun AdBanner(modifier: Modifier) { + val widthDp = LocalConfiguration.current.screenWidthDp + if (!AdsAndroid.ready) { + Box(modifier.fillMaxWidth().height(50.dp)) + return + } + AndroidView( + modifier = modifier.fillMaxWidth(), + factory = { ctx -> + AdView(ctx).apply { + adUnitId = ctx.getString(R.string.admob_banner) + setAdSize(AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(ctx, widthDp)) + adListener = object : AdListener() { + override fun onAdLoaded() { Log.i(TAG, "banner loaded") } + override fun onAdFailedToLoad(e: LoadAdError) { Log.w(TAG, "banner failed: ${e.message}") } + } + loadAd(AdRequest.Builder().build()) + } + }, + onRelease = { it.destroy() }, + ) +} + +@Composable +actual fun AdCard(modifier: Modifier) { + if (!AdsAndroid.ready) { + Box(modifier.size(300.dp, 250.dp)) + return + } + AndroidView( + modifier = modifier.size(300.dp, 250.dp), + factory = { ctx -> + AdView(ctx).apply { + adUnitId = ctx.getString(R.string.admob_card) + setAdSize(AdSize.MEDIUM_RECTANGLE) + adListener = object : AdListener() { + override fun onAdLoaded() { Log.i(TAG, "card loaded") } + override fun onAdFailedToLoad(e: LoadAdError) { Log.w(TAG, "card failed: ${e.message}") } + } + loadAd(AdRequest.Builder().build()) + } + }, + onRelease = { it.destroy() }, + ) +} diff --git a/app/composeApp/src/androidMain/kotlin/kr/tkrmagid/tetrig/net/Net.android.kt b/app/composeApp/src/androidMain/kotlin/kr/tkrmagid/tetrig/net/Net.android.kt new file mode 100644 index 0000000..82e004d --- /dev/null +++ b/app/composeApp/src/androidMain/kotlin/kr/tkrmagid/tetrig/net/Net.android.kt @@ -0,0 +1,62 @@ +package kr.tkrmagid.tetrig.net + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import okhttp3.Response +import okhttp3.WebSocket +import okhttp3.WebSocketListener +import java.util.concurrent.TimeUnit + +private val client = OkHttpClient.Builder() + .connectTimeout(10, TimeUnit.SECONDS) + .readTimeout(15, TimeUnit.SECONDS) + // 프로토콜 ping 은 쓰지 않는다: 하이버네이션 DO 가 pong 을 늦게/안 줘서 OkHttp 가 연결을 끊었다. + // 대신 앱 레벨 {"t":"ping"} keepalive (서버 auto-response) 를 RoomClient/QueueClient 가 보낸다. + .build() + +private val JSON = "application/json; charset=utf-8".toMediaType() + +actual suspend fun httpRequest(method: String, url: String, body: String?, token: String?): HttpResult = + withContext(Dispatchers.IO) { + val b = Request.Builder().url(url) + if (token != null) b.header("Authorization", "Bearer $token") + when (method) { + "GET" -> b.get() + else -> b.method(method, (body ?: "{}").toRequestBody(JSON)) + } + try { + client.newCall(b.build()).execute().use { HttpResult(it.code, it.body?.string() ?: "") } + } catch (e: Exception) { + HttpResult(0, "") + } + } + +actual fun openSocket(url: String, listener: SocketListener): PlatformSocket { + var closed = false + val ws = client.newWebSocket(Request.Builder().url(url).build(), object : WebSocketListener() { + override fun onOpen(webSocket: WebSocket, response: Response) = listener.onOpen() + override fun onMessage(webSocket: WebSocket, text: String) = listener.onMessage(text) + override fun onClosing(webSocket: WebSocket, code: Int, reason: String) { + webSocket.close(1000, null) + } + override fun onClosed(webSocket: WebSocket, code: Int, reason: String) { + if (!closed) { closed = true; listener.onClosed(code, reason) } + } + override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { + android.util.Log.w("TetrigNet", "ws failure ${response?.code}: ${t.javaClass.simpleName} ${t.message}") + if (!closed) { closed = true; listener.onClosed(response?.code ?: 0, t.message ?: "연결 실패") } + } + }) + return object : PlatformSocket { + override fun send(text: String): Boolean = ws.send(text) + override fun close() { + ws.close(1000, "bye") + } + } +} + +actual fun nowMs(): Long = System.currentTimeMillis() diff --git a/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ads/Ads.kt b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ads/Ads.kt new file mode 100644 index 0000000..d081c51 --- /dev/null +++ b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ads/Ads.kt @@ -0,0 +1,50 @@ +package kr.tkrmagid.tetrig.ads + +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier + +/** + * 광고 슬롯 (명세서 §10). 플레이 중 화면(솔로·대전 인게임)에는 절대 넣지 않는다. + * - AdBanner: 메인(탭바 위)·커스텀 로비 하단, 적응형 배너 + * - AdCard: 모든 결과 화면, 300×250 + * - 전면: 결과 확인 → 다음 행동 사이에만, 3판당 1회, 세션 첫 판 제외 + */ +@Composable +expect fun AdBanner(modifier: Modifier = Modifier) + +@Composable +expect fun AdCard(modifier: Modifier = Modifier) + +/** 전면 광고 빈도 규칙. 플랫폼 구현은 showInterstitial 만 담당. */ +object AdPolicy { + /** 이번 세션(앱 실행)에서 끝낸 판 수. */ + var gamesThisSession = 0 + private set + private var shownAt = -1 + + const val EVERY = 3 + + fun onGameFinished() { + gamesThisSession++ + } + + /** 3, 6, 9 … 판째 결과에서 다음 행동으로 넘어갈 때만. 첫 판은 자연히 제외된다. */ + fun shouldShow(): Boolean = + gamesThisSession >= EVERY && gamesThisSession % EVERY == 0 && shownAt != gamesThisSession + + fun markShown() { + shownAt = gamesThisSession + } +} + +/** 결과 화면의 "다음 행동" 버튼에서 부른다. 광고를 띄우면 닫힌 뒤 then 실행. */ +fun maybeInterstitial(then: () -> Unit) { + if (!AdPolicy.shouldShow()) { + then() + return + } + AdPolicy.markShown() + showInterstitial(then) +} + +expect fun showInterstitial(then: () -> Unit) diff --git a/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/data/Store.kt b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/data/Store.kt index 1b7dff5..f22397d 100644 --- a/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/data/Store.kt +++ b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/data/Store.kt @@ -23,6 +23,9 @@ object Prefs { store.putString(key, value) } + fun str(key: String, default: String = ""): String = read(key, default) + fun setStr(key: String, value: String) = write(key, value) + // ── 설정 ── fun flag(key: String, default: Boolean): Boolean = read("flag.$key", if (default) "1" else "0") == "1" fun setFlag(key: String, value: Boolean) = write("flag.$key", if (value) "1" else "0") diff --git a/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/engine/Engine.kt b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/engine/Engine.kt index cb26ba5..08dc1ea 100644 --- a/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/engine/Engine.kt +++ b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/engine/Engine.kt @@ -360,13 +360,13 @@ class TetrigGame(seed: Int = 1) { } /** 하드드롭. 떨어진 칸 수와 락 결과를 반환한다. */ - fun hardDrop(): Pair? { + fun hardDrop(beforeSpawn: (LockResult) -> Unit = {}): Pair? { if (over) return null val a = active var d = 0 while (!collides(board, pieceCells(a.type, a.state, a.x, a.y - d - 1))) d++ a.y -= d - return d to lock() + return d to lock(beforeSpawn) } fun holdSwap(): Boolean { @@ -384,7 +384,20 @@ class TetrigGame(seed: Int = 1) { return true } - fun lock(): LockResult { + /** + * 가비지 n줄을 바닥에 밀어 넣는다 (구멍 열 hole). 위로 밀려 버퍼 밖으로 나가는 + * 블록이 있으면 톱아웃. 락과 다음 스폰 사이(beforeSpawn)에서 부른다. + */ + fun insertGarbage(n: Int, hole: Int) { + if (n <= 0) return + val w = board[0].size + val h = board.size + for (y in h - n until h) if (board[y].any { it != null }) over = true + for (y in h - 1 downTo n) board[y] = board[y - n] + for (y in 0 until n) board[y] = Array(w) { x -> if (x == hole) null else 'G' } + } + + fun lock(beforeSpawn: (LockResult) -> Unit = {}): LockResult { val a = active val tspin = detectTSpin(board, a.type, a.state, a.x, a.y, lastMoveRotation) for (c in cells()) { @@ -398,7 +411,8 @@ class TetrigGame(seed: Int = 1) { val result = LockResult(a.type, cleared, tspin, allClear, combo, b2b, diff) lastClear = result holdUsed = false - spawn() + beforeSpawn(result) + if (!over) spawn() return result } } diff --git a/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/engine/Versus.kt b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/engine/Versus.kt new file mode 100644 index 0000000..4348ceb --- /dev/null +++ b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/engine/Versus.kt @@ -0,0 +1,106 @@ +package kr.tkrmagid.tetrig.engine + +/** + * 대전 규칙 (명세서 §6). 서버 server/src/rules.js 의 attackFor 와 값이 같아야 한다. + */ +object VersusRules { + val LINES = intArrayOf(0, 0, 1, 2, 4) + val TSPIN_MINI = intArrayOf(0, 1) + val TSPIN = intArrayOf(0, 2, 4, 6) + const val B2B_BONUS = 1 + const val ALL_CLEAR = 5 + val COMBO = intArrayOf(1, 1, 2, 2, 3, 3, 4, 4, 4, 5) + const val MAX_INSERT = 8 + const val SAME_HOLE_CHANCE = 0.7 +} + +/** 한 번의 락으로 보낼 줄 수 (상쇄 전). */ +fun attackFor(r: LockResult): Int { + if (r.lines <= 0) return 0 + var n = when (r.tspin) { + "tspin" -> VersusRules.TSPIN[minOf(r.lines, 3)] + "mini" -> VersusRules.TSPIN_MINI[minOf(r.lines, 1)] + else -> VersusRules.LINES[minOf(r.lines, 4)] + } + if (r.difficult && r.b2b >= 1) n += VersusRules.B2B_BONUS + if (r.combo >= 1) n += VersusRules.COMBO[minOf(r.combo - 1, VersusRules.COMBO.size - 1)] + if (r.allClear) n += VersusRules.ALL_CLEAR + return n +} + +/** + * 받은 가비지 대기열. 상쇄(counter)는 내 클라이언트가 직접 처리하고, 상쇄 후 남은 + * 공격만 서버로 보낸다 — 대기열을 고치는 쪽이 한 곳뿐이라 desync 가 생기지 않는다. + */ +class GarbageQueue(private val rng: () -> Double) { + private val chunks = ArrayDeque() + private var lastHole = (rng() * Config.BOARD_W).toInt() + + val total: Int get() = chunks.sum() + + fun add(lines: Int) { + if (lines > 0) chunks.addLast(lines) + } + + /** 공격량으로 대기열을 깎고, 남은 공격량을 돌려준다. */ + fun counter(attack: Int): Int { + var a = attack + while (a > 0 && chunks.isNotEmpty()) { + val c = chunks.removeFirst() + if (c > a) { + chunks.addFirst(c - a) + a = 0 + } else { + a -= c + } + } + return a + } + + /** 이번 락에 밀어 넣을 줄들: (줄 수, 구멍 열) 목록. 한 번에 최대 8줄. */ + fun take(): List> { + val out = mutableListOf>() + var budget = VersusRules.MAX_INSERT + while (budget > 0 && chunks.isNotEmpty()) { + val c = chunks.removeFirst() + val n = minOf(c, budget) + if (c > n) chunks.addFirst(c - n) + budget -= n + if (rng() >= VersusRules.SAME_HOLE_CHANCE) { + var h = (rng() * (Config.BOARD_W - 1)).toInt() + if (h >= lastHole) h++ + lastHole = h + } + out += n to lastHole + } + return out + } + + fun clear() = chunks.clear() +} + +/** 보이는 20행을 200자 문자열로 (위→아래, '.' = 빈칸). 서버 board 메시지 형식. */ +fun encodeBoard(board: Board, active: Active? = null): String { + val sb = StringBuilder(Config.BOARD_W * Config.VISIBLE_H) + val act = HashSet() + if (active != null) for (c in pieceCells(active.type, active.state, active.x, active.y)) act += c[1] * 100 + c[0] + for (y in Config.VISIBLE_H - 1 downTo 0) { + for (x in 0 until Config.BOARD_W) { + val v = board[y][x] + sb.append( + when { + v != null -> v + active != null && (y * 100 + x) in act -> active.type + else -> '.' + } + ) + } + } + return sb.toString() +} + +/** encodeBoard 의 역. grid[row][col], row 0 = 맨 위. */ +fun decodeBoard(s: String): List = + (0 until Config.VISIBLE_H).map { r -> + CharArray(Config.BOARD_W) { c -> s.getOrElse(r * Config.BOARD_W + c) { '.' } } + } diff --git a/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/game/GameState.kt b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/game/GameState.kt index cf44f2e..e8ec43c 100644 --- a/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/game/GameState.kt +++ b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/game/GameState.kt @@ -15,6 +15,19 @@ enum class Mode(val id: String, val title: String, val desc: String) { Sprint("sprint", "SPRINT", "40줄 최속 클리어"), TimeAttack("time", "TIME ATTACK", "2분 점수 어택 · 레벨 가속"), Endless("endless", "ENDLESS", "무한 · 톱아웃해도 계속"), + Versus("versus", "VERSUS", "대전"); + + companion object { + val solo = listOf(Sprint, TimeAttack, Endless) + } +} + +/** 대전 모드에서 GameState 가 부르는 훅. 가비지 삽입·공격 전송·톱아웃 보고. */ +interface VersusHooks { + /** 락 직후, 다음 피스가 나오기 전. 여기서 가비지를 밀어 넣는다. */ + fun beforeSpawn(game: TetrigGame, res: LockResult) + fun afterLock(res: LockResult, piecesPlaced: Int) + fun onTopOut() } const val SPRINT_GOAL_LINES = 40 @@ -24,7 +37,7 @@ const val TIME_ATTACK_MS = 120_000L * 모드 규칙 + 타이밍(중력/락딜레이/DAS/ARR)을 담당하는 상태 홀더. * 엔진은 순수 로직이고, 시간은 전부 여기서 구동한다. */ -class GameState(val mode: Mode, seed: Int) { +class GameState(val mode: Mode, seed: Int, val versus: VersusHooks? = null) { var game = TetrigGame(seed) private set @@ -68,7 +81,7 @@ class GameState(val mode: Mode, seed: Int) { } private fun gravityMs(): Int = when (mode) { - Mode.Sprint -> Config.DEFAULT_GRAVITY_MS + Mode.Sprint, Mode.Versus -> Config.DEFAULT_GRAVITY_MS else -> gravityMsForLevel(level) } @@ -129,7 +142,7 @@ class GameState(val mode: Mode, seed: Int) { } else { lockAcc += dtMs if (lockAcc >= Config.LOCK_DELAY_MS) { - applyLock(game.lock()) + applyLock(game.lock(::beforeSpawn)) } } } @@ -174,11 +187,21 @@ class GameState(val mode: Mode, seed: Int) { fun hardDrop() { if (finished || paused) return - val r = game.hardDrop() ?: return + val r = game.hardDrop(::beforeSpawn) ?: return score += r.first * 2 applyLock(r.second) } + private fun beforeSpawn(res: LockResult) { + versus?.beforeSpawn(game, res) + } + + /** 대전에서 라운드가 바깥 사유(상대 전멸 등)로 끝났을 때. */ + fun forceEnd() { + finished = true + bump() + } + private fun applyLock(res: LockResult) { piecesPlaced++ gravityAcc = 0 @@ -193,10 +216,14 @@ class GameState(val mode: Mode, seed: Int) { when (mode) { Mode.Sprint -> if (lines >= SPRINT_GOAL_LINES) finished = true Mode.TimeAttack -> Unit - Mode.Endless -> Unit + Mode.Endless, Mode.Versus -> Unit } + versus?.afterLock(res, piecesPlaced) if (game.over) { - if (mode == Mode.Endless) { + if (mode == Mode.Versus) { + finished = true + versus?.onTopOut() + } else if (mode == Mode.Endless) { // 톱아웃해도 계속: 보드를 비우고 이어간다. val keptScore = score val keptLines = lines diff --git a/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/game/RoomClient.kt b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/game/RoomClient.kt new file mode 100644 index 0000000..02619ea --- /dev/null +++ b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/game/RoomClient.kt @@ -0,0 +1,405 @@ +package kr.tkrmagid.tetrig.game + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonObject +import kr.tkrmagid.tetrig.engine.GarbageQueue +import kr.tkrmagid.tetrig.engine.LockResult +import kr.tkrmagid.tetrig.engine.TetrigGame +import kr.tkrmagid.tetrig.engine.attackFor +import kr.tkrmagid.tetrig.engine.encodeBoard +import kr.tkrmagid.tetrig.engine.makeRng +import kr.tkrmagid.tetrig.net.JsonCodec +import kr.tkrmagid.tetrig.net.PlatformSocket +import kr.tkrmagid.tetrig.net.Session +import kr.tkrmagid.tetrig.net.SocketListener +import kr.tkrmagid.tetrig.net.WS_SERVER +import kr.tkrmagid.tetrig.net.arr +import kr.tkrmagid.tetrig.net.bool +import kr.tkrmagid.tetrig.net.dbl +import kr.tkrmagid.tetrig.net.int +import kr.tkrmagid.tetrig.net.jsonOf +import kr.tkrmagid.tetrig.net.nowMs +import kr.tkrmagid.tetrig.net.obj +import kr.tkrmagid.tetrig.net.openSocket +import kr.tkrmagid.tetrig.net.str + +private const val PING = "{\"t\":\"ping\"}" + +data class RoomPlayer( + val id: String, val nick: String, val guest: Boolean, val wins: Int, val alive: Boolean, val inRound: Boolean, + val connected: Boolean, val rematch: Boolean, val tr: Int?, val rank: String?, +) + +data class RoomRules(val garbageMul: Double = 1.0, val ft: Int = 0, val sameBag: Boolean = false, val overtime: Boolean = true) + +data class Standing(val id: String, val nick: String, val wins: Int, val rank: Int) + +data class MatchEnd( + val winner: String?, + val standings: List, + val score: Map, + val trDelta: Int?, + val trAfter: Int?, + val rankAfter: String?, + val placementAfter: Int?, +) + +enum class Conn { Connecting, Open, Reconnecting, Closed } + +/** + * 경기방 WebSocket 클라이언트 (커스텀·리그 공용). 서버 메시지를 Compose 상태로 옮기고, + * 내 라운드 GameState 에 대전 훅(가비지·공격·톱아웃)을 연결한다. + */ +class RoomClient(val kind: String, val roomId: String) { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main) + private var socket: PlatformSocket? = null + private var leaving = false + private var reconnectUntil = 0L + + var conn by mutableStateOf(Conn.Connecting) + private set + var fatal by mutableStateOf(null) + private set + var toast by mutableStateOf(null) + + var me by mutableStateOf("") + private set + var code by mutableStateOf(null) + private set + var host by mutableStateOf(null) + private set + var phase by mutableStateOf("lobby") + private set + var round by mutableIntStateOf(0) + private set + var rules by mutableStateOf(RoomRules()) + private set + val players = mutableStateListOf() + val boards = mutableStateMapOf() + val koFeed = mutableStateListOf() + var targeting by mutableStateOf(null) + private set + var manualTarget by mutableStateOf(false) + private set + + /** 내 라운드. 관전 중이면 null. */ + var game by mutableStateOf(null) + private set + var roundStartsAt by mutableStateOf(0L) + private set + var pending by mutableIntStateOf(0) + private set + var roundBanner by mutableStateOf(null) + private set + var matchEnd by mutableStateOf(null) + private set + var rematchVotes by mutableStateOf>(emptyList()) + private set + var rematchNeeded by mutableIntStateOf(0) + private set + + private var garbage = GarbageQueue(makeRng(1)) + private var lastBoardSent = "" + + val isHost get() = host == me + fun nick(id: String?): String = players.firstOrNull { it.id == id }?.nick ?: "?" + val opponents get() = players.filter { it.id != me && it.inRound } + + private val url get() = if (kind == "league") "$WS_SERVER/ws/league/$roomId?token=${Session.token}" else "$WS_SERVER/ws/room/$roomId?token=${Session.token}" + + private var generation = 0 + private var lastHeard = 0L + + init { + // keepalive: 4초마다 ping, 9초 넘게 아무것도 못 받으면 죽은 연결로 보고 다시 붙는다. + // 서버 재접속 유예가 15초라 그 안에 감지·재연결이 끝나야 한다. + scope.launch { + while (true) { + delay(4_000) + val s = socket ?: continue + if (conn != Conn.Open) continue + if (nowMs() - lastHeard > 9_000) { + generation++ // 옛 소켓 콜백 무시 + s.close() + socket = null + onSocketClosed(1006, "keepalive timeout") + } else { + s.send(PING) + } + } + } + } + + fun connect() { + leaving = false + conn = if (conn == Conn.Reconnecting) Conn.Reconnecting else Conn.Connecting + // 소켓마다 세대 번호를 붙여, 교체된 옛 소켓의 콜백이 새 연결 상태를 덮어쓰지 않게 한다. + val gen = ++generation + socket = openSocket(url, object : SocketListener { + override fun onOpen() { + scope.launch { if (gen == generation) { conn = Conn.Open; reconnectUntil = 0; lastHeard = nowMs() } } + } + + override fun onMessage(text: String) { + val m = runCatching { JsonCodec.parseToJsonElement(text).jsonObject }.getOrNull() ?: return + scope.launch { if (gen == generation) { lastHeard = nowMs(); handle(m) } } + } + + override fun onClosed(code: Int, reason: String) { + scope.launch { if (gen == generation) onSocketClosed(code, reason) } + } + }) + } + + private suspend fun onSocketClosed(code: Int, reason: String) { + socket = null + if (leaving || fatal != null || code == 4000) { + conn = Conn.Closed + return + } + // 서버 유예 15초 안에 다시 붙는다. + if (reconnectUntil == 0L) reconnectUntil = nowMs() + 14_000 + if (nowMs() > reconnectUntil) { + conn = Conn.Closed + fatal = "연결이 끊겼습니다" + return + } + conn = Conn.Reconnecting + delay(1_000) + if (!leaving) connect() + } + + fun send(vararg pairs: Pair) { + socket?.send(jsonOf(*pairs).toString()) + } + + // ── 사용자 동작 ── + fun start() = send("t" to "start") + fun updateRules(r: RoomRules) = send("t" to "rules", "rules" to mapOf("garbageMul" to r.garbageMul, "ft" to r.ft, "sameBag" to r.sameBag, "overtime" to r.overtime)) + fun target(id: String) = send("t" to "target", "id" to id) + fun rematch(vote: Boolean) = send("t" to "rematch", "vote" to vote) + fun stopToLobby() = send("t" to "stop") + + fun leave() { + leaving = true + send("t" to "leave") + socket?.close() + scope.launch { + delay(300) + scope.cancel() + } + } + + /** 화면이 주기적으로 부른다: 보드 스냅샷 (변경 있을 때만). */ + fun pushBoard(lock: Boolean = false) { + val g = game ?: return + if (!g.game.over && g.finished) return + val s = encodeBoard(g.game.board, if (g.game.over) null else g.game.active) + if (s == lastBoardSent && !lock) return + lastBoardSent = s + send("t" to "board", "grid" to s, "lock" to lock, "pending" to garbage.total) + } + + // ── 서버 메시지 ── + private fun handle(m: JsonObject) { + when (m.str("t")) { + "sync" -> { + me = m.str("you") ?: me + applyLobby(m) + m.obj("boards")?.forEach { (k, v) -> (v as? kotlinx.serialization.json.JsonPrimitive)?.content?.let { boards[k] = it } } + } + "lobby" -> applyLobby(m) + "round_start" -> onRoundStart(m) + "garbage" -> { + val n = m.int("lines") ?: 0 + garbage.add(n) + pending = garbage.total + } + "board" -> { + val id = m.str("id") ?: return + boards[id] = m.str("grid") ?: return + } + "ko" -> { + val who = m.str("who") + val by = m.str("by") + val line = when { + m.bool("forfeit") == true -> "${nick(who)} 기권" + by != null -> "${nick(by)} → ${nick(who)} 격추!" + else -> "${nick(who)} 탈락" + } + koFeed.add(0, line) + while (koFeed.size > 5) koFeed.removeAt(koFeed.lastIndex) + if (targeting == who) targeting = null + } + "targeting" -> { + targeting = m.str("id") + manualTarget = m.bool("manual") == true + } + "round_end" -> { + val w = m.str("winner") + game?.let { if (!it.finished) it.forceEnd() } + roundBanner = when { + w == null -> "ROUND ${m.int("n")} · 무승부" + w == me -> "ROUND ${m.int("n")} · 승리!" + else -> "ROUND ${m.int("n")} · ${nick(w)} 승리" + } + } + "match_end" -> onMatchEnd(m) + "rematch_state" -> { + rematchVotes = (m["votes"] as? kotlinx.serialization.json.JsonArray)?.mapNotNull { (it as? kotlinx.serialization.json.JsonPrimitive)?.content } ?: emptyList() + rematchNeeded = m.int("needed") ?: 0 + } + "error" -> { + val msg = m.str("msg") ?: "오류" + if (m.bool("fatal") == true) fatal = msg else toast = msg + } + } + } + + private fun applyLobby(m: JsonObject) { + code = m.str("code") ?: code + host = m.str("host") + val newPhase = m.str("phase") ?: phase + if (newPhase == "lobby" && phase != "lobby") { + game = null + roundBanner = null + } + if (newPhase != "match_end") matchEnd?.let { if (newPhase == "countdown") matchEnd = null } + phase = newPhase + round = m.int("round") ?: round + m.obj("rules")?.let { r -> + rules = RoomRules(r.dbl("garbageMul") ?: 1.0, r.int("ft") ?: 0, r.bool("sameBag") ?: false, r.bool("overtime") ?: true) + } + val list = m.arr("players").map { p -> + RoomPlayer( + p.str("id") ?: "", p.str("nick") ?: "?", p.bool("guest") ?: false, p.int("wins") ?: 0, + p.bool("alive") ?: false, p.bool("inRound") ?: false, p.bool("connected") ?: false, + p.bool("rematch") ?: false, p.int("tr"), p.str("rank"), + ) + } + players.clear() + players.addAll(list) + val ids = list.map { it.id }.toSet() + boards.keys.filter { it !in ids }.forEach { boards.remove(it) } + } + + private fun onRoundStart(m: JsonObject) { + matchEnd = null + roundBanner = null + koFeed.clear() + boards.clear() + targeting = null + manualTarget = false + lastBoardSent = "" + round = m.int("n") ?: round + roundStartsAt = nowMs() + (m.int("startIn") ?: 3000) + val seed = m.int("seed") + if (seed == null) { + game = null // 관전 (도중 입장) + return + } + garbage = GarbageQueue(makeRng(seed xor 0x5bd1e995)) + pending = 0 + game = GameState(Mode.Versus, seed, hooks) + } + + private val hooks = object : VersusHooks { + override fun beforeSpawn(game: TetrigGame, res: LockResult) { + if (res.lines == 0) { + for ((n, hole) in garbage.take()) game.insertGarbage(n, hole) + pending = garbage.total + } + } + + override fun afterLock(res: LockResult, piecesPlaced: Int) { + val atk = attackFor(res) + val net = garbage.counter(atk) + pending = garbage.total + send("t" to "attack", "lines" to net, "pieces" to piecesPlaced) + pushBoard(lock = true) + } + + override fun onTopOut() { + pushBoard(lock = true) + send("t" to "topout") + } + } + + private fun onMatchEnd(m: JsonObject) { + game?.let { if (!it.finished) it.forceEnd() } + val standings = m.arr("result").map { Standing(it.str("id") ?: "", it.str("nick") ?: "?", it.int("wins") ?: 0, it.int("rank") ?: 0) } + val score = m.obj("score")?.mapValues { (_, v) -> (v as? kotlinx.serialization.json.JsonPrimitive)?.content?.toIntOrNull() ?: 0 } ?: emptyMap() + val after = m.obj("after") + matchEnd = MatchEnd( + winner = m.str("winner"), standings = standings, score = score, + trDelta = m.int("trDelta"), trAfter = after?.int("tr"), rankAfter = after?.str("rank"), placementAfter = after?.int("placement"), + ) + phase = "match_end" + } +} + +/** 리그 대기열 (MatchmakerDO). matched 를 받으면 onMatched(roomId). */ +class QueueClient(private val onMatched: (room: String, opponent: String) -> Unit) { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main) + private var socket: PlatformSocket? = null + var waitMs by mutableStateOf(0L) + private set + var hint by mutableStateOf(false) + private set + var error by mutableStateOf(null) + private set + private var done = false + + init { + scope.launch { + while (true) { + delay(8_000) + socket?.send(PING) + } + } + } + + fun connect() { + socket = openSocket("$WS_SERVER/ws/queue?token=${Session.token}", object : SocketListener { + override fun onOpen() {} + override fun onMessage(text: String) { + val m = runCatching { JsonCodec.parseToJsonElement(text).jsonObject }.getOrNull() ?: return + scope.launch { + when (m.str("t")) { + "queue" -> { + waitMs = m.long2("waitMs") + hint = m.bool("hint") == true + } + "matched" -> { + done = true + onMatched(m.str("room") ?: return@launch, m.obj("opponent")?.str("nick") ?: "?") + } + } + } + } + override fun onClosed(code: Int, reason: String) { + scope.launch { if (!done) error = if (code == 403) "리그전은 로그인 후 참가할 수 있습니다" else "대기열 연결이 끊겼습니다" } + } + }) + } + + fun cancel() { + done = true + socket?.close() + scope.cancel() + } + + private fun JsonObject.long2(k: String): Long = (this[k] as? kotlinx.serialization.json.JsonPrimitive)?.content?.toLongOrNull() ?: 0L +} diff --git a/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/net/Api.kt b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/net/Api.kt new file mode 100644 index 0000000..cf62640 --- /dev/null +++ b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/net/Api.kt @@ -0,0 +1,191 @@ +package kr.tkrmagid.tetrig.net + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.doubleOrNull +import kotlinx.serialization.json.intOrNull +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.longOrNull +import kr.tkrmagid.tetrig.data.Prefs + +/** 화면 수명과 무관하게 끝까지 돌아야 하는 작업용 (기록 업로드 등). */ +val AppScope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.Main) + +const val SERVER = "https://tetrig.tkrmagid.workers.dev" +val WS_SERVER = SERVER.replaceFirst("https://", "wss://") + +val JsonCodec = Json { ignoreUnknownKeys = true } + +// ── JsonObject 편의 접근자 ── +fun JsonObject.str(k: String): String? = (this[k] as? JsonPrimitive)?.takeIf { it.isString }?.content +fun JsonObject.int(k: String): Int? = (this[k] as? JsonPrimitive)?.intOrNull +fun JsonObject.long(k: String): Long? = (this[k] as? JsonPrimitive)?.longOrNull +fun JsonObject.dbl(k: String): Double? = (this[k] as? JsonPrimitive)?.doubleOrNull +fun JsonObject.bool(k: String): Boolean? = (this[k] as? JsonPrimitive)?.booleanOrNull +fun JsonObject.obj(k: String): JsonObject? = this[k] as? JsonObject +fun JsonObject.arr(k: String): List = (this[k] as? JsonArray)?.mapNotNull { it as? JsonObject } ?: emptyList() + +fun jsonOf(vararg pairs: Pair): JsonObject = buildJsonObject { + for ((k, v) in pairs) put(k, toJson(v)) +} + +private fun toJson(v: Any?): JsonElement = when (v) { + null -> JsonNull + is JsonElement -> v + is String -> JsonPrimitive(v) + is Number -> JsonPrimitive(v) + is Boolean -> JsonPrimitive(v) + is Map<*, *> -> buildJsonObject { for ((k, x) in v) put(k.toString(), toJson(x)) } + is List<*> -> JsonArray(v.map { toJson(it) }) + else -> JsonPrimitive(v.toString()) +} + +class ApiResult(val code: Int, val data: JsonObject) { + val ok get() = code in 200..299 + val error: String get() = data.str("error") ?: if (code == 0) "서버에 연결할 수 없습니다" else "오류 ($code)" +} + +data class User(val id: String, val nickname: String, val guest: Boolean, val email: String?) + +data class League( + val placed: Boolean, val placement: Int, val tr: Int?, val rank: String?, val games: Int, val wins: Int, +) + +/** 로그인 상태. 앱 전역에서 관찰한다. */ +object Session { + var user by mutableStateOf(null) + private set + var league by mutableStateOf(null) + private set + var seasonN by mutableStateOf(1) + private set + var seasonEndsAt by mutableStateOf(0L) + private set + var offline by mutableStateOf(false) + private set + + val token: String? get() = Prefs.str("auth.token").ifBlank { null } + + suspend fun call(method: String, path: String, body: JsonObject? = null, withToken: Boolean = true): ApiResult { + val r = httpRequest(method, SERVER + path, body?.toString(), if (withToken) token else null) + val data = runCatching { JsonCodec.parseToJsonElement(r.body).jsonObject }.getOrElse { JsonObject(emptyMap()) } + return ApiResult(r.code, data) + } + + private fun adopt(r: ApiResult) { + r.data.str("token")?.let { Prefs.setStr("auth.token", it) } + r.data.obj("user")?.let { user = parseUser(it) } + } + + private fun parseUser(u: JsonObject) = + User(u.str("id") ?: "", u.str("nickname") ?: "?", u.bool("guest") ?: true, u.str("email")) + + /** 앱 시작 시: 토큰이 없거나 만료면 게스트 발급, 그다음 프로필 갱신. */ + suspend fun ensure(): Boolean { + if (token == null && !newGuest()) return false + val me = refresh() + if (me?.code == 401) { + if (!newGuest()) return false + refresh() + } + return user != null + } + + private suspend fun newGuest(): Boolean { + var dev = Prefs.str("device.id") + if (dev.isBlank()) { + dev = newDeviceId() + Prefs.setStr("device.id", dev) + } + val r = call("POST", "/api/guest", jsonOf("deviceId" to dev), withToken = false) + offline = r.code == 0 + if (!r.ok) return false + adopt(r) + return true + } + + /** /api/me 응답 전체 (프로필 화면용). */ + var profile by mutableStateOf(null) + private set + + suspend fun refresh(): ApiResult? { + if (token == null) return null + val r = call("GET", "/api/me") + offline = r.code == 0 + if (!r.ok) return r + profile = r.data + r.data.obj("user")?.let { user = parseUser(it) } + r.data.obj("league")?.let { l -> + league = League( + l.bool("placed") ?: false, l.int("placement") ?: 0, l.int("tr"), l.str("rank"), + l.int("games") ?: 0, l.int("wins") ?: 0, + ) + } + r.data.obj("season")?.let { s -> + seasonN = s.int("n") ?: 1 + seasonEndsAt = s.long("endsAt") ?: 0L + } + // 서버 베스트가 더 좋으면 로컬 기록에도 반영 (다른 기기·병합된 기록) + r.data.obj("solo")?.let { solo -> + solo.long("sprint")?.let { Prefs.submitSprint(it) } + solo.int("time")?.let { Prefs.submitScore("time", it) } + solo.int("endless")?.let { Prefs.submitScore("endless", it) } + } + return r + } + + suspend fun register(email: String, password: String, nickname: String?): String? { + val r = call("POST", "/api/register", jsonOf("email" to email, "password" to password, "nickname" to nickname?.ifBlank { null })) + if (!r.ok) return r.error + adopt(r) + refresh() + return null + } + + suspend fun login(email: String, password: String): String? { + val r = call("POST", "/api/login", jsonOf("email" to email, "password" to password)) + if (!r.ok) return r.error + adopt(r) + refresh() + return null + } + + suspend fun logout() { + Prefs.setStr("auth.token", "") + user = null + league = null + profile = null + ensure() + } + + /** 계정과 서버 기록을 지우고 새 게스트로 돌아간다. */ + suspend fun deleteAccount(): String? { + val r = call("POST", "/api/me/delete") + if (!r.ok) return r.error + logout() + return null + } + + suspend fun changeNickname(n: String): String? { + val r = call("POST", "/api/nickname", jsonOf("nickname" to n)) + if (!r.ok) return r.error + adopt(r) + refresh() + return null + } + + /** 솔로 기록 업로드 (실패해도 로컬 기록은 이미 저장됨). */ + suspend fun submitSolo(mode: String, value: Long) { + if (token == null || value <= 0) return + call("POST", "/api/solo", jsonOf("mode" to mode, "value" to value)) + } +} diff --git a/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/net/Net.kt b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/net/Net.kt new file mode 100644 index 0000000..bc992bc --- /dev/null +++ b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/net/Net.kt @@ -0,0 +1,29 @@ +package kr.tkrmagid.tetrig.net + +/** 플랫폼 HTTP / WebSocket. Android 는 OkHttp. */ +class HttpResult(val code: Int, val body: String) + +expect suspend fun httpRequest(method: String, url: String, body: String?, token: String?): HttpResult + +interface SocketListener { + fun onOpen() + fun onMessage(text: String) + /** 정상/비정상 종료 모두. code 0 = 연결 실패. */ + fun onClosed(code: Int, reason: String) +} + +interface PlatformSocket { + fun send(text: String): Boolean + fun close() +} + +expect fun openSocket(url: String, listener: SocketListener): PlatformSocket + +/** 현재 시각(ms). */ +expect fun nowMs(): Long + +/** 기기 고유 ID 대용 — 처음 실행 때 만든 무작위 값. */ +fun newDeviceId(): String { + val chars = "abcdefghijklmnopqrstuvwxyz0123456789" + return (1..24).map { chars[kotlin.random.Random.nextInt(chars.length)] }.joinToString("") +} diff --git a/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/App.kt b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/App.kt index 30ef571..19fd85a 100644 --- a/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/App.kt +++ b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/App.kt @@ -7,6 +7,7 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -14,13 +15,19 @@ import androidx.compose.runtime.setValue import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.Modifier import kr.tkrmagid.tetrig.game.Mode +import kr.tkrmagid.tetrig.game.RoomClient +import kr.tkrmagid.tetrig.net.Session val LocalLayout = staticCompositionLocalOf { layoutFor(androidx.compose.ui.unit.Dp(390f), androidx.compose.ui.unit.Dp(844f)) } sealed interface Screen { data object Main : Screen data object Settings : Screen - data class Soon(val title: String) : Screen + data object Profile : Screen + data object Leaderboard : Screen + data object CustomEntry : Screen + data object Queue : Screen + data class Room(val client: RoomClient) : Screen data class Game(val mode: Mode, val seed: Int) : Screen data class Result(val mode: Mode, val score: Int, val lines: Int, val timeMs: Long, val pps: Double) : Screen } @@ -29,10 +36,24 @@ sealed interface Screen { fun App() { var screen by remember { mutableStateOf(Screen.Main) } + // 첫 실행: 게스트 자동 발급 (가입 없이 즉시 플레이). 실패해도 솔로는 오프라인으로 된다. + LaunchedEffect(Unit) { Session.ensure() } + + val onTab: (Int) -> Unit = { i -> + screen = when (i) { + 1 -> Screen.Leaderboard + 2 -> Screen.Profile + 3 -> Screen.Settings + else -> Screen.Main + } + } + + val dark = screen is Screen.Game || (screen as? Screen.Room)?.client?.let { it.phase != "lobby" && it.phase != "match_end" } == true + BoxWithConstraints( modifier = Modifier .fillMaxSize() - .background(if (screen is Screen.Game) Palette.Ink else Palette.Bone) + .background(if (dark) Palette.Ink else Palette.Bone) ) { val layout = remember(maxWidth, maxHeight) { layoutFor(maxWidth, maxHeight) } CompositionLocalProvider(LocalLayout provides layout) { @@ -40,13 +61,34 @@ fun App() { when (val s = screen) { is Screen.Main -> MainScreen( onMode = { screen = Screen.Game(it, randomSeed()) }, - onSettings = { screen = Screen.Settings }, - onSoon = { screen = Screen.Soon(it) }, + onTab = onTab, + onLeague = { + // 게스트는 리그전 불가 (§9) → 프로필에서 로그인 유도 + screen = if (Session.user?.guest == false) Screen.Queue else Screen.Profile + }, + onCustom = { screen = Screen.CustomEntry }, ) - is Screen.Settings -> SettingsScreen(onBack = { screen = Screen.Main }) + is Screen.Settings -> SettingsScreen(onBack = { screen = Screen.Main }, onTab = onTab) + is Screen.Profile -> ProfileScreen(onTab = onTab) + is Screen.Leaderboard -> LeaderboardScreen(onTab = onTab) - is Screen.Soon -> SoonScreen(s.title, onBack = { screen = Screen.Main }) + is Screen.CustomEntry -> CustomEntryScreen( + onJoin = { code -> screen = Screen.Room(RoomClient("custom", code)) }, + onBack = { screen = Screen.Main }, + ) + + is Screen.Queue -> QueueScreen( + onMatched = { room -> screen = Screen.Room(RoomClient("league", room)) }, + onBack = { screen = Screen.Main }, + onCustom = { screen = Screen.CustomEntry }, + ) + + is Screen.Room -> RoomScreen( + client = s.client, + onExit = { screen = Screen.Main }, + onRequeue = { screen = Screen.Queue }, + ) is Screen.Game -> GameScreen( mode = s.mode, diff --git a/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/GameScreen.kt b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/GameScreen.kt index a1daa93..bfcab12 100644 --- a/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/GameScreen.kt +++ b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/GameScreen.kt @@ -32,7 +32,11 @@ 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 kotlinx.coroutines.launch +import kr.tkrmagid.tetrig.ads.AdPolicy import kr.tkrmagid.tetrig.data.Prefs +import kr.tkrmagid.tetrig.net.AppScope +import kr.tkrmagid.tetrig.net.Session import kr.tkrmagid.tetrig.engine.Config import kr.tkrmagid.tetrig.game.GameState import kr.tkrmagid.tetrig.game.Mode @@ -69,9 +73,18 @@ fun GameScreen( LaunchedEffect(state.finished) { if (state.finished) { when (mode) { - Mode.Sprint -> if (state.lines >= SPRINT_GOAL_LINES) Prefs.submitSprint(state.elapsedMs) - else -> Prefs.submitScore(mode.id, state.score) + Mode.Sprint -> if (state.lines >= SPRINT_GOAL_LINES) { + Prefs.submitSprint(state.elapsedMs) + val ms = state.elapsedMs + AppScope.launch { Session.submitSolo("sprint", ms) } + } + else -> { + Prefs.submitScore(mode.id, state.score) + val sc = state.score.toLong() + AppScope.launch { Session.submitSolo(mode.id, sc) } + } } + AdPolicy.onGameFinished() onFinish(state.score, state.lines, state.elapsedMs, state.pps) } } @@ -128,13 +141,13 @@ private fun Hud(state: GameState, onPause: () -> Unit, onExit: () -> Unit) { val headline = when (state.mode) { Mode.Sprint -> formatMs(state.elapsedMs) Mode.TimeAttack -> formatMs(state.remainingMs) - Mode.Endless -> state.score.toString() + Mode.Endless, Mode.Versus -> state.score.toString() } Disp(headline, color = Palette.Bone, size = (30 * s).sp) val sub = when (state.mode) { Mode.Sprint -> "LINES ${state.lines}/$SPRINT_GOAL_LINES · PPS ${fmt2(state.pps)}" Mode.TimeAttack -> "SCORE ${state.score} · LV ${state.level}" - Mode.Endless -> "LINES ${state.lines} · LV ${state.level}" + Mode.Endless, Mode.Versus -> "LINES ${state.lines} · LV ${state.level}" } Mono(sub, color = Palette.DSub, size = (12 * s).sp) } @@ -162,11 +175,12 @@ private fun Hud(state: GameState, onPause: () -> Unit, onExit: () -> Unit) { // ── 보드 + HOLD/NEXT ────────────────────────────────────────────── @Composable -private fun BoardWithPanels(state: GameState, ghostOn: Boolean, l: Layout, stacked: Boolean) { +internal fun BoardWithPanels(state: GameState, ghostOn: Boolean, l: Layout, stacked: Boolean, gauge: (() -> Int)? = null) { val s = l.uiScale BoxWithConstraints(Modifier.fillMaxSize().padding(horizontal = (10 * s).dp)) { val panelW: Dp = if (l.isTiny) (46 * s).dp else (68 * s).dp - val availW = maxWidth - panelW - (10 * s).dp + val gaugeW: Dp = if (gauge != null) (8 * s).dp else 0.dp + val availW = maxWidth - panelW - gaugeW - ((if (gauge != null) 16 else 10) * s).dp val availH = maxHeight val cell = minOf(availW.value / Config.BOARD_W, availH.value / Config.VISIBLE_H) val boardW = (cell * Config.BOARD_W).dp @@ -175,8 +189,9 @@ private fun BoardWithPanels(state: GameState, ghostOn: Boolean, l: Layout, stack Row( Modifier.align(Alignment.Center), verticalAlignment = Alignment.Top, - horizontalArrangement = Arrangement.spacedBy((10 * s).dp), + horizontalArrangement = Arrangement.spacedBy(((if (gauge != null) 6 else 10) * s).dp), ) { + if (gauge != null) GarbageGauge(gauge, Modifier.size(gaugeW, boardH)) Box(Modifier.size(boardW, boardH)) { BoardCanvas(state, ghostOn) } @@ -187,6 +202,16 @@ private fun BoardWithPanels(state: GameState, ghostOn: Boolean, l: Layout, stack } } +/** 받을 가비지 게이지 (보드 왼쪽 세로 막대, 20줄 = 꽉 참). */ +@Composable +private fun GarbageGauge(gauge: () -> Int, modifier: Modifier) { + Canvas(modifier.background(Palette.DPanel)) { + val n = gauge().coerceIn(0, Config.VISIBLE_H) + val h = size.height * n / Config.VISIBLE_H + drawRect(Palette.Safety, topLeft = Offset(0f, size.height - h), size = Size(size.width, h)) + } +} + /** * HOLD / NEXT 패널. * @@ -316,7 +341,7 @@ private fun MiniPiece(type: Char) { // ── 조작 ────────────────────────────────────────────────────────── @Composable -private fun ControlPad(state: GameState, lefty: Boolean, scale: Float, compactHeight: Boolean) { +internal fun ControlPad(state: GameState, lefty: Boolean, scale: Float, compactHeight: Boolean) { val h = ((if (compactHeight) 130 else 168) * scale).dp val gap = (8 * scale).dp // 아랫줄 3개(하드 드롭·홀드·소프트 드롭)를 정확히 1/3 씩 주려면 그 줄이 @@ -376,7 +401,7 @@ private fun ControlPad(state: GameState, lefty: Boolean, scale: Float, compactHe } @Composable -private fun ControlColumn(state: GameState, left: Boolean, scale: Float, modifier: Modifier) { +internal fun ControlColumn(state: GameState, left: Boolean, scale: Float, modifier: Modifier) { Column( modifier.padding((8 * scale).dp), verticalArrangement = Arrangement.spacedBy((8 * scale).dp), diff --git a/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/MainScreen.kt b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/MainScreen.kt index e54265f..8876ca8 100644 --- a/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/MainScreen.kt +++ b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/MainScreen.kt @@ -30,14 +30,20 @@ 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 kr.tkrmagid.tetrig.ads.AdBanner +import kr.tkrmagid.tetrig.ads.AdCard +import kr.tkrmagid.tetrig.ads.maybeInterstitial import kr.tkrmagid.tetrig.data.Prefs +import kr.tkrmagid.tetrig.net.Session +import kr.tkrmagid.tetrig.net.nowMs import kr.tkrmagid.tetrig.game.Mode @Composable fun MainScreen( onMode: (Mode) -> Unit, - onSettings: () -> Unit, - onSoon: (String) -> Unit, + onTab: (Int) -> Unit, + onLeague: () -> Unit, + onCustom: () -> Unit, ) { val l = LocalLayout.current val s = l.uiScale @@ -64,34 +70,25 @@ fun MainScreen( ModeCard("솔로", "SPRINT · TIME ATTACK · ENDLESS", Palette.Cobalt, s) { showModes = true } } Box(Modifier.weight(1f)) { - ModeCard("멀티 · 리그전", "실시간 1:1 랭크 매치 · 배치 10경기", Palette.Safety, s, soon = true) { onSoon("멀티 · 리그전") } + ModeCard("멀티 · 리그전", "실시간 1:1 랭크 매치 · 배치 10경기", Palette.Safety, s) { onLeague() } } Box(Modifier.weight(1f)) { - ModeCard("커스텀", "코드로 만들고 참가 · 인원 제한 없음", null, s, soon = true) { onSoon("커스텀") } + ModeCard("커스텀", "코드로 만들고 참가 · 인원 제한 없음", null, s) { onCustom() } } } } else { Box(Modifier.widthIn(max = 720.dp).align(Alignment.CenterHorizontally)) { Column { ModeCard("솔로", "SPRINT · TIME ATTACK · ENDLESS", Palette.Cobalt, s) { showModes = true } - ModeCard("멀티 · 리그전", "실시간 1:1 랭크 매치 · 배치 10경기", Palette.Safety, s, soon = true) { onSoon("멀티 · 리그전") } - ModeCard("커스텀", "코드로 만들고 참가 · 인원 제한 없음", null, s, soon = true) { onSoon("커스텀") } + ModeCard("멀티 · 리그전", "실시간 1:1 랭크 매치 · 배치 10경기", Palette.Safety, s) { onLeague() } + ModeCard("커스텀", "코드로 만들고 참가 · 인원 제한 없음", null, s) { onCustom() } } } } } - TabBar( - selected = 0, - scale = s, - onSelect = { i -> - when (i) { - 1 -> onSoon("리더보드") - 2 -> onSoon("프로필") - 3 -> onSettings() - } - }, - ) + AdBanner() + TabBar(selected = 0, scale = s, onSelect = onTab) } if (showModes) { @@ -115,11 +112,19 @@ private fun Header(s: Float) { Box(Modifier.width((120 * s).dp).height((8 * s).dp).background(Palette.Ink)) } Spacer(Modifier.weight(1f)) - NeoPanel(shadow = false, modifier = Modifier.padding(end = 6.dp)) { - Mono("게스트", Modifier.padding(horizontal = 8.dp, vertical = 3.dp), size = (12 * s).sp, weight = FontWeight.Bold) - } - NeoPanel(background = Palette.Safety, shadow = false) { - Mono("—", Modifier.padding(horizontal = 10.dp, vertical = 3.dp), size = (12 * s).sp, weight = FontWeight.Bold) + val user = Session.user + val league = Session.league + Column(horizontalAlignment = Alignment.End) { + Row { + NeoPanel(shadow = false, modifier = Modifier.padding(end = 6.dp)) { + Mono(if (user == null || user.guest) "게스트" else "계정", Modifier.padding(horizontal = 8.dp, vertical = 3.dp), size = (12 * s).sp, weight = FontWeight.Bold) + } + NeoPanel(background = Palette.Safety, shadow = false) { + Mono(league?.rank ?: league?.tr?.toString() ?: "—", Modifier.padding(horizontal = 10.dp, vertical = 3.dp), size = (12 * s).sp, weight = FontWeight.Bold) + } + } + Spacer(Modifier.height(4.dp)) + Mono(user?.nickname ?: if (Session.offline) "오프라인" else "", color = Palette.Sub, size = (11 * s).sp) } } } @@ -131,9 +136,15 @@ private fun SeasonBar(s: Float) { Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = (9 * s).dp), verticalAlignment = Alignment.CenterVertically, ) { - Mono("SEASON 1 · D-42", size = (14 * s).sp) + val ends = Session.seasonEndsAt + val days = if (ends > 0) ((ends - nowMs()) / 86_400_000L).coerceAtLeast(0) else null + Mono("SEASON ${Session.seasonN}" + (days?.let { " · D-$it" } ?: ""), size = (14 * s).sp) Spacer(Modifier.weight(1f)) - Mono("배치 0/10", color = Palette.Cobalt, size = (14 * s).sp, weight = FontWeight.Bold) + val l = Session.league + Mono( + if (l == null) "배치 0/10" else if (!l.placed) "배치 ${l.placement}/10" else "${l.tr} TR", + color = Palette.Cobalt, size = (14 * s).sp, weight = FontWeight.Bold, + ) } } } @@ -264,7 +275,7 @@ fun SoloSheet(scale: Float, onDismiss: () -> Unit, onPick: (Mode) -> Unit) { Spacer(Modifier.height((14 * scale).dp)) Disp("솔로", size = (24 * scale).sp) Spacer(Modifier.height((12 * scale).dp)) - Mode.entries.forEach { m -> SoloRow(m, scale) { onPick(m) } } + Mode.solo.forEach { m -> SoloRow(m, scale) { onPick(m) } } Spacer(Modifier.height((6 * scale).dp)) } } @@ -281,6 +292,7 @@ private fun SoloRow(mode: Mode, scale: Float, onClick: () -> Unit) { Mode.Sprint -> Palette.Mint Mode.TimeAttack -> Palette.Amber Mode.Endless -> Palette.Violet + Mode.Versus -> Palette.Safety } Box(Modifier.fillMaxWidth().padding(bottom = (12 * scale).dp)) { NeoPanel(modifier = Modifier.fillMaxWidth(), onClick = onClick) { @@ -302,28 +314,6 @@ private fun SoloRow(mode: Mode, scale: Float, onClick: () -> Unit) { } } -@Composable -fun SoonScreen(title: String, onBack: () -> Unit) { - val s = LocalLayout.current.uiScale - Column(Modifier.fillMaxSize().padding((20 * s).dp)) { - Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { - Disp("준비 중", size = (24 * s).sp) - Spacer(Modifier.weight(1f)) - NeoPanel(shadow = false, onClick = onBack) { - Mono("← 뒤로", Modifier.padding(horizontal = 12.dp, vertical = 6.dp), size = (13 * s).sp) - } - } - Spacer(Modifier.height((24 * s).dp)) - NeoPanel(modifier = Modifier.fillMaxWidth()) { - Column(Modifier.padding((20 * s).dp)) { - Disp(title, size = (20 * s).sp) - Spacer(Modifier.height(10.dp)) - Mono("아직 구현되지 않았습니다. 다음 업데이트에서 열립니다.", color = Palette.Sub, size = (12 * s).sp, maxLines = 3) - } - } - } -} - @Composable fun ResultScreen( mode: Mode, @@ -336,7 +326,7 @@ fun ResultScreen( ) { val s = LocalLayout.current.uiScale Column( - Modifier.fillMaxSize().padding((20 * s).dp), + Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding((20 * s).dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { @@ -352,9 +342,11 @@ fun ResultScreen( StatRow("PPS", ((pps * 100).toInt() / 100.0).toString(), s) } } - Spacer(Modifier.height((18 * s).dp)) + Spacer(Modifier.height((14 * s).dp)) + AdCard() + Spacer(Modifier.height((14 * s).dp)) Row(Modifier.widthIn(max = 560.dp).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { - NeoPanel(background = Palette.Safety, modifier = Modifier.weight(1f), onClick = onRetry) { + NeoPanel(background = Palette.Safety, modifier = Modifier.weight(1f), onClick = { maybeInterstitial(onRetry) }) { Mono( "다시 하기", Modifier.fillMaxWidth().padding(vertical = (14 * s).dp), @@ -363,7 +355,7 @@ fun ResultScreen( align = TextAlign.Center, ) } - NeoPanel(modifier = Modifier.weight(1f), onClick = onHome) { + NeoPanel(modifier = Modifier.weight(1f), onClick = { maybeInterstitial(onHome) }) { Mono( "홈으로", Modifier.fillMaxWidth().padding(vertical = (14 * s).dp), @@ -386,7 +378,7 @@ private fun StatRow(label: String, value: String, s: Float) { } @Composable -fun SettingsScreen(onBack: () -> Unit) { +fun SettingsScreen(onBack: () -> Unit, onTab: (Int) -> Unit = { if (it == 0) onBack() }) { val s = LocalLayout.current.uiScale var ghost by remember { mutableStateOf(Prefs.flag("ghost", true)) } var lefty by remember { mutableStateOf(Prefs.flag("lefty", false)) } @@ -416,7 +408,7 @@ fun SettingsScreen(onBack: () -> Unit) { } } } - TabBar(selected = 3, scale = s, onSelect = { if (it == 0) onBack() }) + TabBar(selected = 3, scale = s, onSelect = onTab) } } diff --git a/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/OnlineScreens.kt b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/OnlineScreens.kt new file mode 100644 index 0000000..e0543dc --- /dev/null +++ b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/OnlineScreens.kt @@ -0,0 +1,438 @@ +package kr.tkrmagid.tetrig.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +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.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.text.input.VisualTransformation +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import kotlinx.coroutines.launch +import kotlinx.serialization.json.JsonObject +import kr.tkrmagid.tetrig.game.QueueClient +import kr.tkrmagid.tetrig.net.Session +import kr.tkrmagid.tetrig.net.arr +import kr.tkrmagid.tetrig.net.bool +import kr.tkrmagid.tetrig.net.int +import kr.tkrmagid.tetrig.net.jsonOf +import kr.tkrmagid.tetrig.net.long +import kr.tkrmagid.tetrig.net.obj +import kr.tkrmagid.tetrig.net.str + +// ── 공통 ───────────────────────────────────────────────────────── +@Composable +fun TopBar(title: String, s: Float, onBack: (() -> Unit)?) { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Disp(title, size = (24 * s).sp) + Spacer(Modifier.weight(1f)) + if (onBack != null) { + NeoPanel(shadow = false, onClick = onBack) { + Mono("← 뒤로", Modifier.padding(horizontal = 12.dp, vertical = 6.dp), size = (13 * s).sp) + } + } + } +} + +@Composable +fun NeoButton(label: String, s: Float, modifier: Modifier = Modifier, accent: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) { + NeoPanel( + modifier = modifier, + background = if (!enabled) Palette.Paper else if (accent) Palette.Safety else Palette.Bone, + onClick = if (enabled) onClick else null, + ) { + Mono( + label, + Modifier.fillMaxWidth().padding(vertical = (13 * s).dp, horizontal = 8.dp), + color = if (enabled) Palette.Ink else Palette.Sub, + size = (14 * s).sp, weight = FontWeight.Bold, align = TextAlign.Center, + ) + } +} + +@Composable +fun NeoField( + value: String, + onChange: (String) -> Unit, + placeholder: String, + s: Float, + password: Boolean = false, + keyboard: KeyboardType = KeyboardType.Text, + caps: Boolean = false, + big: Boolean = false, +) { + NeoPanel(modifier = Modifier.fillMaxWidth(), shadow = false) { + Box(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = (12 * s).dp)) { + val style = TextStyle( + fontFamily = FontFamily.Monospace, fontSize = ((if (big) 26 else 15) * s).sp, + fontWeight = if (big) FontWeight.Black else FontWeight.Normal, color = Palette.Ink, + textAlign = if (big) TextAlign.Center else TextAlign.Start, + ) + if (value.isEmpty()) Mono(placeholder, Modifier.fillMaxWidth(), color = Palette.Sub, size = ((if (big) 26 else 15) * s).sp, align = if (big) TextAlign.Center else TextAlign.Start) + BasicTextField( + value = value, + onValueChange = onChange, + singleLine = true, + textStyle = style, + visualTransformation = if (password) PasswordVisualTransformation() else VisualTransformation.None, + keyboardOptions = KeyboardOptions( + keyboardType = if (password) KeyboardType.Password else keyboard, + capitalization = if (caps) KeyboardCapitalization.Characters else KeyboardCapitalization.None, + autoCorrectEnabled = false, + ), + modifier = Modifier.fillMaxWidth(), + ) + } + } +} + +@Composable +private fun ErrorLine(msg: String?, s: Float) { + if (msg != null) { + Spacer(Modifier.height(8.dp)) + Mono(msg, color = Palette.Safety, size = (12 * s).sp, weight = FontWeight.Bold, maxLines = 3) + } +} + +// ── 프로필 (⑦) ─────────────────────────────────────────────────── +@Composable +fun ProfileScreen(onTab: (Int) -> Unit) { + val s = LocalLayout.current.uiScale + val scope = rememberCoroutineScope() + val user = Session.user + var busy by remember { mutableStateOf(false) } + var msg by remember { mutableStateOf(null) } + var registerMode by remember { mutableStateOf(true) } + var email by remember { mutableStateOf("") } + var pw by remember { mutableStateOf("") } + var nick by remember { mutableStateOf("") } + var newNick by remember { mutableStateOf("") } + var confirmDelete by remember { mutableStateOf(false) } + + LaunchedEffect(Unit) { Session.refresh() } + + Column(Modifier.fillMaxSize()) { + Column(Modifier.weight(1f).verticalScroll(rememberScrollState()).padding((20 * s).dp)) { + TopBar("프로필", s, null) + Spacer(Modifier.height((16 * s).dp)) + Box(Modifier.widthIn(max = 720.dp)) { + Column { + NeoPanel(modifier = Modifier.fillMaxWidth()) { + Column(Modifier.padding((16 * s).dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Disp(user?.nickname ?: (if (Session.offline) "오프라인" else "…"), size = (22 * s).sp) + Spacer(Modifier.width(8.dp)) + if (user?.guest != false) Badge("게스트", Palette.Sub, s) else Badge("계정", Palette.Cobalt, s) + } + user?.email?.let { Spacer(Modifier.height(4.dp)); Mono(it, color = Palette.Sub, size = (12 * s).sp) } + Spacer(Modifier.height(12.dp)) + LeagueSummary(s) + } + } + Spacer(Modifier.height((16 * s).dp)) + + if (user == null || user.guest) { + Mono( + "로그인하면 리그전 참가, 리더보드 등록, 닉네임 변경이 가능합니다. 지금까지의 게스트 기록은 계정으로 옮겨집니다.", + color = Palette.Sub, size = (12 * s).sp, maxLines = 4, + ) + Spacer(Modifier.height(12.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + NeoButton("이메일 가입", s, Modifier.weight(1f), accent = registerMode) { registerMode = true; msg = null } + NeoButton("로그인", s, Modifier.weight(1f), accent = !registerMode) { registerMode = false; msg = null } + } + Spacer(Modifier.height(12.dp)) + NeoField(email, { email = it.trim() }, "이메일", s, keyboard = KeyboardType.Email) + Spacer(Modifier.height(8.dp)) + NeoField(pw, { pw = it }, "비밀번호 (8자 이상)", s, password = true) + if (registerMode) { + Spacer(Modifier.height(8.dp)) + NeoField(nick, { nick = it.take(12) }, "닉네임 (선택, 2~12자)", s) + } + ErrorLine(msg, s) + Spacer(Modifier.height(12.dp)) + NeoButton(if (busy) "처리 중…" else if (registerMode) "가입하기" else "로그인", s, Modifier.fillMaxWidth(), accent = true, enabled = !busy) { + busy = true + msg = null + scope.launch { + msg = if (registerMode) Session.register(email, pw, nick) else Session.login(email, pw) + if (msg == null) pw = "" + busy = false + } + } + Spacer(Modifier.height(8.dp)) + Mono("비밀번호 재설정은 아직 지원하지 않습니다. 비밀번호를 꼭 기억해 주세요.", color = Palette.Sub, size = (11 * s).sp, maxLines = 3) + } else { + Mono("닉네임 변경 (30일에 1회)", size = (13 * s).sp, weight = FontWeight.Bold) + Spacer(Modifier.height(8.dp)) + NeoField(newNick, { newNick = it.take(12) }, user.nickname, s) + ErrorLine(msg, s) + Spacer(Modifier.height(8.dp)) + NeoButton("닉네임 변경", s, Modifier.fillMaxWidth(), enabled = !busy && newNick.length >= 2) { + busy = true + scope.launch { + msg = Session.changeNickname(newNick) ?: "변경되었습니다" + busy = false + } + } + Spacer(Modifier.height(12.dp)) + NeoButton("로그아웃", s, Modifier.fillMaxWidth()) { + scope.launch { Session.logout() } + } + Spacer(Modifier.height(12.dp)) + NeoButton( + if (confirmDelete) "정말 삭제합니다 (되돌릴 수 없음)" else "계정 삭제", + s, Modifier.fillMaxWidth(), enabled = !busy, + ) { + if (!confirmDelete) { + confirmDelete = true + } else { + busy = true + scope.launch { + msg = Session.deleteAccount() + confirmDelete = false + busy = false + } + } + } + if (confirmDelete) { + Spacer(Modifier.height(6.dp)) + Mono("계정, 리그 레이팅, 서버 기록, 커스텀 전적이 모두 삭제됩니다. 한 번 더 누르면 진행합니다.", color = Palette.Safety, size = (11 * s).sp, maxLines = 3) + } + } + + Spacer(Modifier.height((20 * s).dp)) + RecentMatches(Session.profile, s) + } + } + } + TabBar(selected = 2, scale = s, onSelect = onTab) + } +} + +@Composable +fun Badge(text: String, color: androidx.compose.ui.graphics.Color, s: Float) { + Box(Modifier.background(color).padding(horizontal = (7 * s).dp, vertical = (2 * s).dp)) { + Mono(text, color = Palette.Bone, size = (11 * s).sp, weight = FontWeight.Bold) + } +} + +@Composable +private fun LeagueSummary(s: Float) { + val l = Session.league + Row(Modifier.fillMaxWidth()) { + Stat("TR", if (l?.placed == true) "${l.tr}" else "배치 ${l?.placement ?: 0}/10", s, Modifier.weight(1f)) + Stat("랭크", l?.rank ?: "—", s, Modifier.weight(1f)) + Stat("시즌 전적", "${l?.wins ?: 0}승 ${(l?.games ?: 0) - (l?.wins ?: 0)}패", s, Modifier.weight(1f)) + } +} + +@Composable +private fun Stat(label: String, value: String, s: Float, modifier: Modifier) { + Column(modifier) { + Mono(label, color = Palette.Sub, size = (11 * s).sp) + Mono(value, size = (16 * s).sp, weight = FontWeight.Bold) + } +} + +@Composable +private fun RecentMatches(profile: JsonObject?, s: Float) { + val recent = profile?.arr("recent") ?: emptyList() + Mono("최근 전적", size = (13 * s).sp, weight = FontWeight.Bold) + Spacer(Modifier.height(8.dp)) + if (recent.isEmpty()) { + Mono("아직 대전 기록이 없습니다", color = Palette.Sub, size = (12 * s).sp) + return + } + for (m in recent.take(10)) { + val line = if (m.str("mode") == "league") { + val won = m.bool("won") == true + val d = m.int("trDelta") ?: 0 + "리그 · ${if (won) "승" else "패"} vs ${m.str("opponent")} · ${if (d >= 0) "+$d" else "$d"} TR" + } else { + "커스텀 · ${m.int("size")}인 중 ${m.int("place")}위 · ${m.int("wins")}승" + } + NeoPanel(modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp), shadow = false) { + Mono(line, Modifier.padding(horizontal = 12.dp, vertical = 9.dp), size = (12 * s).sp) + } + } +} + +// ── 리더보드 ───────────────────────────────────────────────────── +@Composable +fun LeaderboardScreen(onTab: (Int) -> Unit) { + val s = LocalLayout.current.uiScale + val boards = listOf("league" to "리그", "sprint" to "SPRINT", "time" to "TIME ATK", "endless" to "ENDLESS") + var board by remember { mutableStateOf("league") } + var rows by remember { mutableStateOf?>(null) } + var err by remember { mutableStateOf(null) } + + LaunchedEffect(board) { + rows = null + err = null + val r = Session.call("GET", "/api/leaderboard?board=$board", withToken = false) + if (r.ok) rows = r.data.arr("rows") else err = r.error + } + + Column(Modifier.fillMaxSize()) { + Column(Modifier.weight(1f).verticalScroll(rememberScrollState()).padding((20 * s).dp)) { + TopBar("리더보드", s, null) + Spacer(Modifier.height((14 * s).dp)) + Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + for ((id, label) in boards) { + NeoPanel( + modifier = Modifier.weight(1f), + background = if (id == board) Palette.Safety else Palette.Bone, + shadow = false, + onClick = { board = id }, + ) { + Mono(label, Modifier.fillMaxWidth().padding(vertical = 8.dp), size = (11 * s).sp, weight = FontWeight.Bold, align = TextAlign.Center) + } + } + } + Spacer(Modifier.height((14 * s).dp)) + when { + err != null -> Mono(err!!, color = Palette.Safety, size = (13 * s).sp) + rows == null -> Mono("불러오는 중…", color = Palette.Sub, size = (13 * s).sp) + rows!!.isEmpty() -> Mono( + if (board == "league") "아직 배치 10경기를 마친 플레이어가 없습니다" else "아직 등록된 기록이 없습니다 (로그인한 플레이어만 등재)", + color = Palette.Sub, size = (12 * s).sp, maxLines = 3, + ) + else -> for (r in rows!!) { + val mine = r.str("id") == Session.user?.id + val value = when (board) { + "league" -> "${r.int("tr") ?: "-"} TR · ${r.str("rank") ?: "?"}" + "sprint" -> formatMs(r.long("best") ?: 0) + else -> "${r.int("best") ?: 0}" + } + NeoPanel(modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp), background = if (mine) Palette.Paper else Palette.Bone, shadow = false) { + Row(Modifier.padding(horizontal = 12.dp, vertical = 9.dp), verticalAlignment = Alignment.CenterVertically) { + Mono("${r.int("pos")}", Modifier.width((34 * s).dp), size = (13 * s).sp, weight = FontWeight.Bold) + Mono(r.str("nickname") ?: "?", Modifier.weight(1f), size = (13 * s).sp) + Mono(value, size = (13 * s).sp, weight = FontWeight.Bold) + } + } + } + } + } + TabBar(selected = 1, scale = s, onSelect = onTab) + } +} + +// ── 커스텀: 만들기 / 참가 ──────────────────────────────────────── +@Composable +fun CustomEntryScreen(onJoin: (code: String) -> Unit, onBack: () -> Unit) { + val s = LocalLayout.current.uiScale + val scope = rememberCoroutineScope() + var code by remember { mutableStateOf("") } + var busy by remember { mutableStateOf(false) } + var msg by remember { mutableStateOf(null) } + Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding((20 * s).dp)) { + TopBar("커스텀", s, onBack) + Spacer(Modifier.height((20 * s).dp)) + Box(Modifier.widthIn(max = 560.dp).align(Alignment.CenterHorizontally)) { + Column { + Mono("방 만들기", size = (14 * s).sp, weight = FontWeight.Bold) + Spacer(Modifier.height(6.dp)) + Mono("6자리 코드가 발급됩니다. 친구에게 코드를 알려주세요. 인원 제한 없음.", color = Palette.Sub, size = (12 * s).sp, maxLines = 3) + Spacer(Modifier.height(10.dp)) + NeoButton(if (busy) "만드는 중…" else "방 만들기", s, Modifier.fillMaxWidth(), accent = true, enabled = !busy) { + busy = true + msg = null + scope.launch { + val r = Session.call("POST", "/api/rooms", jsonOf("rules" to emptyMap())) + busy = false + val c = r.data.str("code") + if (r.ok && c != null) onJoin(c) else msg = r.error + } + } + Spacer(Modifier.height((28 * s).dp)) + Mono("참가하기", size = (14 * s).sp, weight = FontWeight.Bold) + Spacer(Modifier.height(10.dp)) + NeoField(code, { v -> code = v.uppercase().filter { it in "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" }.take(6) }, "코드 6자리", s, caps = true, big = true) + Spacer(Modifier.height(10.dp)) + NeoButton("참가", s, Modifier.fillMaxWidth(), enabled = !busy && code.length == 6) { + busy = true + msg = null + scope.launch { + val r = Session.call("GET", "/api/rooms/$code", withToken = false) + busy = false + if (r.ok && r.data.bool("exists") == true) onJoin(code) else msg = if (r.code == 0) r.error else "없는 방 코드입니다" + } + } + ErrorLine(msg, s) + } + } + } +} + +// ── 리그 대기열 ────────────────────────────────────────────────── +@Composable +fun QueueScreen(onMatched: (room: String) -> Unit, onBack: () -> Unit, onCustom: () -> Unit) { + val s = LocalLayout.current.uiScale + var opponent by remember { mutableStateOf(null) } + val q = remember { + QueueClient { room, opp -> + opponent = opp + onMatched(room) + } + } + DisposableEffect(q) { + q.connect() + onDispose { q.cancel() } + } + Column( + Modifier.fillMaxSize().padding((20 * s).dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + TopBar("리그전", s, onBack) + Spacer(Modifier.weight(1f)) + Disp(if (opponent != null) "매칭 완료!" else "상대 찾는 중", size = (28 * s).sp) + Spacer(Modifier.height(10.dp)) + Mono(formatMs(q.waitMs).substringBefore('.') + "초", size = (18 * s).sp) + Spacer(Modifier.height(12.dp)) + Session.league?.let { l -> + Mono(if (l.placed) "${l.tr} TR · ${l.rank ?: "랭크 산정 중"}" else "배치 ${l.placement}/10", color = Palette.Sub, size = (13 * s).sp) + } + q.error?.let { + Spacer(Modifier.height(12.dp)) + Mono(it, color = Palette.Safety, size = (13 * s).sp, weight = FontWeight.Bold, maxLines = 3, align = TextAlign.Center) + } + if (q.hint) { + Spacer(Modifier.height(20.dp)) + Mono("대기가 길어지고 있습니다. 커스텀 룸에서 친구와 플레이해 보세요.", color = Palette.Sub, size = (12 * s).sp, maxLines = 3, align = TextAlign.Center) + Spacer(Modifier.height(10.dp)) + NeoButton("커스텀 룸 열기", s, Modifier.widthIn(max = 320.dp).fillMaxWidth(), onClick = onCustom) + } + Spacer(Modifier.weight(1f)) + NeoButton("취소", s, Modifier.widthIn(max = 320.dp).fillMaxWidth(), onClick = onBack) + } +} diff --git a/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/RoomScreen.kt b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/RoomScreen.kt new file mode 100644 index 0000000..39c1388 --- /dev/null +++ b/app/composeApp/src/commonMain/kotlin/kr/tkrmagid/tetrig/ui/RoomScreen.kt @@ -0,0 +1,446 @@ +package kr.tkrmagid.tetrig.ui + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +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.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableLongStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.withFrameNanos +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +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 kr.tkrmagid.tetrig.ads.AdBanner +import kr.tkrmagid.tetrig.ads.AdCard +import kr.tkrmagid.tetrig.ads.AdPolicy +import kr.tkrmagid.tetrig.ads.maybeInterstitial +import kr.tkrmagid.tetrig.data.Prefs +import kr.tkrmagid.tetrig.engine.Config +import kr.tkrmagid.tetrig.game.Conn +import kr.tkrmagid.tetrig.game.GameState +import kr.tkrmagid.tetrig.game.RoomClient +import kr.tkrmagid.tetrig.game.RoomPlayer +import kr.tkrmagid.tetrig.game.RoomRules +import kr.tkrmagid.tetrig.net.Session +import kr.tkrmagid.tetrig.net.nowMs + +/** + * 경기방 화면 하나로 로비 → 라운드 → 결과를 오간다 (⑤ 로비, ③ 리그 1:1, ④ 커스텀 FFA, ⑥/⑨ 결과). + */ +@Composable +fun RoomScreen(client: RoomClient, onExit: () -> Unit, onRequeue: () -> Unit) { + DisposableEffect(client) { + client.connect() + onDispose { client.leave() } + } + LaunchedEffect(client.matchEnd) { + if (client.matchEnd != null) { + AdPolicy.onGameFinished() + if (client.kind == "league") Session.refresh() + } + } + + val fatal = client.fatal + val phase = client.phase + val inMatch = phase == "countdown" || phase == "playing" || phase == "between" + when { + fatal != null -> FatalView(fatal, onExit) + client.matchEnd != null && phase == "match_end" -> MatchResultView(client, onExit, onRequeue) + inMatch || (client.game != null && phase != "lobby") -> VersusView(client, onExit) + client.kind == "league" -> LeagueWaitView(client, onExit) + else -> LobbyView(client, onExit) + } +} + +@Composable +private fun FatalView(msg: String, onExit: () -> Unit) { + val s = LocalLayout.current.uiScale + Column(Modifier.fillMaxSize().padding((20 * s).dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) { + Disp("연결 종료", size = (24 * s).sp) + Spacer(Modifier.height(10.dp)) + Mono(msg, color = Palette.Sub, size = (13 * s).sp, maxLines = 3, align = TextAlign.Center) + Spacer(Modifier.height(20.dp)) + NeoButton("홈으로", s, Modifier.widthIn(max = 320.dp).fillMaxWidth(), accent = true, onClick = onExit) + } +} + +@Composable +private fun ConnBadge(client: RoomClient, s: Float) { + when (client.conn) { + Conn.Open -> Unit + Conn.Connecting -> Badge("연결 중", Palette.Sub, s) + Conn.Reconnecting -> Badge("재접속 중…", Palette.Safety, s) + Conn.Closed -> Badge("끊김", Palette.Safety, s) + } +} + +// ── 로비 (⑤) ───────────────────────────────────────────────────── +@Composable +private fun LobbyView(client: RoomClient, onExit: () -> Unit) { + val s = LocalLayout.current.uiScale + val host = client.isHost + val r = client.rules + Column(Modifier.fillMaxSize()) { + Column(Modifier.weight(1f).verticalScroll(rememberScrollState()).padding((20 * s).dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Disp("커스텀 로비", size = (22 * s).sp) + Spacer(Modifier.width(8.dp)) + ConnBadge(client, s) + Spacer(Modifier.weight(1f)) + NeoPanel(shadow = false, onClick = onExit) { + Mono("나가기", Modifier.padding(horizontal = 12.dp, vertical = 6.dp), size = (13 * s).sp) + } + } + Spacer(Modifier.height((14 * s).dp)) + NeoPanel(modifier = Modifier.fillMaxWidth(), background = Palette.Ink) { + Column(Modifier.fillMaxWidth().padding((14 * s).dp), horizontalAlignment = Alignment.CenterHorizontally) { + Mono("방 코드", color = Palette.DSub, size = (12 * s).sp) + Disp(client.code ?: "------", color = Palette.Safety, size = (38 * s).sp) + Mono("친구에게 이 코드를 알려주세요", color = Palette.DSub, size = (11 * s).sp) + } + } + Spacer(Modifier.height((16 * s).dp)) + Mono("참가자 ${client.players.size}명", size = (13 * s).sp, weight = FontWeight.Bold) + Spacer(Modifier.height(8.dp)) + for (p in client.players) PlayerRow(p, p.id == client.host, p.id == client.me, s) + + Spacer(Modifier.height((16 * s).dp)) + Mono(if (host) "규칙 (호스트)" else "규칙", size = (13 * s).sp, weight = FontWeight.Bold) + Spacer(Modifier.height(8.dp)) + RuleRow("가비지 배율", "${r.garbageMul}×", host, s) { + val steps = listOf(0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0) + val i = steps.indexOfFirst { it >= r.garbageMul - 1e-6 }.coerceAtLeast(0) + client.updateRules(r.copy(garbageMul = steps[(i + 1) % steps.size])) + } + RuleRow("목표 승수", if (r.ft == 0) "무제한" else "FT${r.ft}", host, s) { + val order = listOf(0, 1, 3, 5) + client.updateRules(r.copy(ft = order[(order.indexOf(r.ft) + 1) % order.size])) + } + RuleRow("시드", if (r.sameBag) "동일 bag (공정전)" else "개인 bag", host, s) { + client.updateRules(r.copy(sameBag = !r.sameBag)) + } + RuleRow("장기전 배율", if (r.overtime) "켬 (90초 후 +25%/30초)" else "끔", host, s) { + client.updateRules(r.copy(overtime = !r.overtime)) + } + client.toast?.let { + Spacer(Modifier.height(8.dp)) + Mono(it, color = Palette.Safety, size = (12 * s).sp, weight = FontWeight.Bold) + } + Spacer(Modifier.height((16 * s).dp)) + if (host) { + NeoButton( + if (client.players.count { it.connected } < 2) "2명 이상 모이면 시작" else "시작", + s, Modifier.fillMaxWidth(), accent = true, enabled = client.players.count { it.connected } >= 2, + ) { client.toast = null; client.start() } + } else { + Mono("호스트가 시작하기를 기다리는 중…", color = Palette.Sub, size = (13 * s).sp) + } + } + AdBanner() + } +} + +@Composable +private fun PlayerRow(p: RoomPlayer, isHost: Boolean, isMe: Boolean, s: Float) { + NeoPanel(modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp), background = if (isMe) Palette.Paper else Palette.Bone, shadow = false) { + Row(Modifier.padding(horizontal = 12.dp, vertical = 9.dp), verticalAlignment = Alignment.CenterVertically) { + Mono(p.nick + if (isMe) " (나)" else "", Modifier.weight(1f), size = (13 * s).sp, weight = if (isMe) FontWeight.Bold else FontWeight.Normal) + if (p.guest) { Badge("게스트", Palette.Sub, s); Spacer(Modifier.width(4.dp)) } + if (isHost) { Badge("호스트", Palette.Safety, s); Spacer(Modifier.width(4.dp)) } + if (!p.connected) Badge("끊김", Palette.Sub, s) + if (p.wins > 0) Mono(" ${p.wins}승", size = (13 * s).sp, weight = FontWeight.Bold) + } + } +} + +@Composable +private fun RuleRow(label: String, value: String, editable: Boolean, s: Float, onTap: () -> Unit) { + NeoPanel(modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp), shadow = false, onClick = if (editable) onTap else null) { + Row(Modifier.padding(horizontal = 12.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically) { + Mono(label, Modifier.weight(1f), color = Palette.Sub, size = (12 * s).sp) + Mono(value, size = (13 * s).sp, weight = FontWeight.Bold) + if (editable) Mono(" ›", color = Palette.Sub, size = (14 * s).sp) + } + } +} + +@Composable +private fun LeagueWaitView(client: RoomClient, onExit: () -> Unit) { + val s = LocalLayout.current.uiScale + Column(Modifier.fillMaxSize().padding((20 * s).dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) { + Disp("리그전", size = (26 * s).sp) + Spacer(Modifier.height(10.dp)) + val opp = client.players.firstOrNull { it.id != client.me } + Mono(if (opp == null) "상대 접속 대기 중…" else "vs ${opp.nick}", size = (15 * s).sp) + Spacer(Modifier.height(6.dp)) + ConnBadge(client, s) + Spacer(Modifier.height(24.dp)) + NeoButton("기권하고 나가기", s, Modifier.widthIn(max = 320.dp).fillMaxWidth(), onClick = onExit) + } +} + +// ── 대전 (③ 1:1 / ④ FFA) ───────────────────────────────────────── +@Composable +private fun VersusView(client: RoomClient, onExit: () -> Unit) { + val l = LocalLayout.current + val s = l.uiScale + val game = client.game + val ghostOn = remember { Prefs.flag("ghost", true) } + val lefty = remember { Prefs.flag("lefty", false) } + val bigButtons = remember { Prefs.flag("bigButtons", false) } + var now by remember { mutableLongStateOf(nowMs()) } + + // 프레임 루프: 카운트다운이 끝나야 내 게임이 움직인다. 보드 스냅샷은 0.3초마다. + LaunchedEffect(game) { + var last = 0L + var lastPush = 0L + while (true) { + withFrameNanos { t -> + now = nowMs() + val g = game + if (g != null && now >= client.roundStartsAt && !g.finished) { + if (last != 0L) g.tick(((t - last) / 1_000_000L).coerceAtMost(100L)) + last = t + if (now - lastPush >= 300) { + lastPush = now + client.pushBoard() + } + } else { + last = 0L + } + } + } + } + + Column(Modifier.fillMaxSize().background(Palette.Ink)) { + // 상단: 라운드·스코어·나가기 + Row(Modifier.fillMaxWidth().padding(horizontal = (12 * s).dp, vertical = (6 * s).dp), verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Mono( + (if (client.kind == "league") "리그전" else "커스텀") + " · ROUND ${client.round}" + + (if (client.rules.ft > 0) " · FT${client.rules.ft}" else ""), + color = Palette.DSub, size = (11 * s).sp, + ) + val myWins = client.players.firstOrNull { it.id == client.me }?.wins ?: 0 + Mono("내 승수 $myWins · 생존 ${client.players.count { it.inRound && it.alive }}/${client.players.count { it.inRound }}", color = Palette.Bone, size = (13 * s).sp, weight = FontWeight.Bold) + } + ConnBadge(client, s) + Spacer(Modifier.width(8.dp)) + HoldButton( + modifier = Modifier.size(width = (54 * s).dp, height = (34 * s).dp), + background = Palette.DPanel, borderColor = Palette.Bone, onTap = onExit, + ) { Mono(if (client.kind == "league") "기권" else "나가기", color = Palette.Bone, size = (10 * s).sp) } + } + + OpponentStrip(client, s, if (client.opponents.size <= 1) (if (game == null) 260 else 110) else 92) + + // 피드 + Box(Modifier.fillMaxWidth().height((18 * s).dp)) { + client.koFeed.firstOrNull()?.let { + Mono(it, Modifier.fillMaxWidth(), color = Palette.Safety, size = (12 * s).sp, weight = FontWeight.Bold, align = TextAlign.Center) + } + } + + if (game != null) { + Box(Modifier.weight(1f).fillMaxWidth()) { + if (l.isLandscape) { + Row(Modifier.fillMaxSize()) { + ControlColumn(game, left = !lefty, scale = s * if (bigButtons) 1.2f else 1f, modifier = Modifier.weight(1f).fillMaxHeight()) + Box(Modifier.weight(1.6f).fillMaxHeight(), contentAlignment = Alignment.Center) { + BoardWithPanels(game, ghostOn, l, stacked = false, gauge = { client.pending }) + } + ControlColumn(game, left = lefty, scale = s * if (bigButtons) 1.2f else 1f, modifier = Modifier.weight(1f).fillMaxHeight()) + } + } else { + Column(Modifier.fillMaxSize()) { + Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) { + BoardWithPanels(game, ghostOn, l, stacked = true, gauge = { client.pending }) + } + ControlPad(game, lefty = lefty, scale = s * if (bigButtons) 1.15f else 1f, compactHeight = true) + } + } + Overlays(client, game, now, s) + } + } else { + Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Disp("관전 중", color = Palette.Bone, size = (22 * s).sp) + Mono("다음 라운드부터 참가합니다", color = Palette.DSub, size = (12 * s).sp) + client.roundBanner?.let { Spacer(Modifier.height(8.dp)); Mono(it, color = Palette.Safety, size = (14 * s).sp, weight = FontWeight.Bold) } + } + } + } + } +} + +@Composable +private fun Overlays(client: RoomClient, game: GameState, now: Long, s: Float) { + val text: String? + val sub: String? + when { + now < client.roundStartsAt -> { + text = "${((client.roundStartsAt - now) / 1000 + 1)}" + sub = "ROUND ${client.round}" + } + client.roundBanner != null -> { + text = client.roundBanner + sub = "다음 라운드 준비 중…" + } + game.finished -> { + text = "KO" + sub = "관전 중 · 라운드가 끝나면 다시 시작합니다" + } + else -> { + text = null + sub = null + } + } + if (text != null) { + Box(Modifier.fillMaxSize().background(Color(0x9917161B)), contentAlignment = Alignment.Center) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Disp(text, color = Palette.Safety, size = ((if (text.length <= 2) 64 else 26) * s).sp) + sub?.let { Mono(it, color = Palette.Bone, size = (12 * s).sp, align = TextAlign.Center, maxLines = 2) } + } + } + } +} + +/** 상대 보드들. 1:1 은 크게 하나, FFA 는 가로 스크롤 미니보드 — 탭하면 타겟 지정. */ +@Composable +private fun OpponentStrip(client: RoomClient, s: Float, heightDp: Int) { + val opps = client.players.filter { it.id != client.me && (it.inRound || client.game == null) } + if (opps.isEmpty()) return + val h = (heightDp * s).dp + Row( + Modifier.fillMaxWidth().height(h + (16 * s).dp).horizontalScroll(rememberScrollState()).padding(horizontal = (10 * s).dp), + horizontalArrangement = Arrangement.spacedBy((8 * s).dp, Alignment.CenterHorizontally), + ) { + for (p in opps) { + val targeted = client.targeting == p.id + Column( + horizontalAlignment = Alignment.CenterHorizontally, + modifier = if (opps.size > 1 && p.alive) Modifier.then( + Modifier.androidxClick { client.target(p.id) } + ) else Modifier, + ) { + MiniBoard(client.boards[p.id], h / 2.1f * 1f, h, dead = p.inRound && !p.alive, targeted = targeted && opps.size > 1) + Mono( + (if (targeted && opps.size > 1) "▶ " else "") + p.nick.take(8) + if (p.wins > 0) " ${p.wins}" else "", + color = if (targeted) Palette.Safety else Palette.DSub, size = (10 * s).sp, + ) + } + } + } +} + +private fun Modifier.androidxClick(onTap: () -> Unit): Modifier = + this.pointerInput(onTap) { detectTapGestures { onTap() } } + +@Composable +private fun MiniBoard(grid: String?, w: Dp, h: Dp, dead: Boolean, targeted: Boolean) { + Canvas( + Modifier.size(w, h).background(Palette.Dwell) + .border(if (targeted) 2.dp else 1.dp, if (targeted) Palette.Safety else Palette.DGrid), + ) { + val cw = size.width / Config.BOARD_W + val ch = size.height / Config.VISIBLE_H + if (grid != null) { + for (r in 0 until Config.VISIBLE_H) for (c in 0 until Config.BOARD_W) { + val v = grid.getOrNull(r * Config.BOARD_W + c) ?: '.' + if (v != '.') drawRect(pieceColor(v), topLeft = Offset(c * cw, r * ch), size = Size(cw - 0.5f, ch - 0.5f)) + } + } + if (dead) drawRect(Color(0xAA17161B)) + } +} + +// ── 결과 (⑥ 리그 / ⑨ 일반전) ──────────────────────────────────── +@Composable +private fun MatchResultView(client: RoomClient, onExit: () -> Unit, onRequeue: () -> Unit) { + val s = LocalLayout.current.uiScale + val m = client.matchEnd ?: return + val won = m.winner == client.me + Column( + Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding((20 * s).dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Mono(if (client.kind == "league") "리그전 결과" else "일반전 결과", color = Palette.Sub, size = (13 * s).sp) + Disp(if (won) "승리!" else if (m.winner == null) "종료" else "패배", color = if (won) Palette.Safety else Palette.Ink, size = (36 * s).sp) + Spacer(Modifier.height(10.dp)) + Box(Modifier.widthIn(max = 560.dp).fillMaxWidth()) { + NeoPanel(modifier = Modifier.fillMaxWidth()) { + Column(Modifier.padding((16 * s).dp)) { + if (client.kind == "league") { + val opp = m.score.keys.firstOrNull { it != client.me } + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Mono("vs ${client.nick(opp)}", Modifier.weight(1f), size = (14 * s).sp) + Disp("${m.score[client.me] ?: 0} : ${m.score[opp] ?: 0}", size = (24 * s).sp) + } + Spacer(Modifier.height(8.dp)) + val d = m.trDelta + if (m.placementAfter != null && m.trAfter == null) { + Mono("배치 ${m.placementAfter}/10 — 10경기 후 TR 공개", size = (13 * s).sp, weight = FontWeight.Bold) + } else if (d != null) { + Mono("TR ${m.trAfter} (${if (d >= 0) "+$d" else "$d"})" + (m.rankAfter?.let { " · $it" } ?: ""), size = (15 * s).sp, weight = FontWeight.Bold) + } else { + Mono("레이팅 반영 중 오류 — 전적은 저장되지 않았을 수 있습니다", color = Palette.Safety, size = (12 * s).sp, maxLines = 2) + } + } else { + for (st in m.standings) { + Row(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { + Mono("${st.rank}", Modifier.width((28 * s).dp), size = (14 * s).sp, weight = FontWeight.Bold) + Mono(st.nick + if (st.id == client.me) " (나)" else "", Modifier.weight(1f), size = (14 * s).sp) + Mono("${st.wins}승", size = (14 * s).sp, weight = FontWeight.Bold) + } + } + } + } + } + } + Spacer(Modifier.height((14 * s).dp)) + AdCard() + Spacer(Modifier.height((14 * s).dp)) + Column(Modifier.widthIn(max = 560.dp).fillMaxWidth()) { + if (client.kind == "league") { + NeoButton("다시 매칭", s, Modifier.fillMaxWidth(), accent = true) { maybeInterstitial(onRequeue) } + } else { + val voted = client.rematchVotes.contains(client.me) + NeoButton( + (if (voted) "리매치 투표 취소" else "리매치 투표") + " (${client.rematchVotes.size}/${client.rematchNeeded})", + s, Modifier.fillMaxWidth(), accent = !voted, + ) { client.rematch(!voted) } + } + Spacer(Modifier.height(10.dp)) + NeoButton("홈으로", s, Modifier.fillMaxWidth()) { maybeInterstitial(onExit) } + } + } +} diff --git a/app/composeApp/src/commonTest/kotlin/kr/tkrmagid/tetrig/engine/VersusTest.kt b/app/composeApp/src/commonTest/kotlin/kr/tkrmagid/tetrig/engine/VersusTest.kt new file mode 100644 index 0000000..8fd0aab --- /dev/null +++ b/app/composeApp/src/commonTest/kotlin/kr/tkrmagid/tetrig/engine/VersusTest.kt @@ -0,0 +1,79 @@ +package kr.tkrmagid.tetrig.engine + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class VersusTest { + private fun r(lines: Int, tspin: String = "none", ac: Boolean = false, combo: Int = 0, b2b: Int = 0, diff: Boolean = false) = + LockResult('T', lines, tspin, ac, combo, b2b, diff) + + @Test + fun attackTableMatchesServer() { + // server/test/rules.test.js 와 같은 케이스 + assertEquals(0, attackFor(r(1))) + assertEquals(1, attackFor(r(2))) + assertEquals(2, attackFor(r(3))) + assertEquals(4, attackFor(r(4, diff = true, b2b = 0))) + assertEquals(5, attackFor(r(4, diff = true, b2b = 1))) + assertEquals(1, attackFor(r(1, "mini"))) + assertEquals(0, attackFor(r(0, "mini"))) + assertEquals(4, attackFor(r(2, "tspin", diff = true))) + assertEquals(6, attackFor(r(3, "tspin", diff = true))) + assertEquals(1, attackFor(r(1, combo = 1))) + assertEquals(5, attackFor(r(1, combo = 20))) + assertEquals(9, attackFor(r(4, ac = true))) + } + + @Test + fun counterCancelsPendingFirst() { + val q = GarbageQueue(makeRng(7)) + q.add(3); q.add(2) + assertEquals(0, q.counter(4)) // 4줄 공격 → 대기 5줄 중 4줄 상쇄, 전송 0 + assertEquals(1, q.total) + assertEquals(3, q.counter(4)) // 남은 1줄 상쇄 후 3줄 전송 + assertEquals(0, q.total) + } + + @Test + fun takeCapsAtEightLines() { + val q = GarbageQueue(makeRng(7)) + q.add(6); q.add(5) + val first = q.take() + assertEquals(8, first.sumOf { it.first }) + assertEquals(3, q.total) + assertTrue(first.all { it.second in 0 until Config.BOARD_W }) + } + + @Test + fun insertGarbagePushesBoardUpWithHole() { + val g = TetrigGame(1) + g.board[0][0] = 'I' + g.insertGarbage(2, 4) + assertEquals('I', g.board[2][0]) + for (y in 0..1) for (x in 0 until Config.BOARD_W) assertEquals(if (x == 4) null else 'G', g.board[y][x]) + assertFalse(g.over) + } + + @Test + fun garbageInsertedBeforeSpawnCanTopOut() { + val g = TetrigGame(1) + // 거의 꽉 찬 탑을 만들고 가비지를 크게 밀어 넣으면 톱아웃 + for (y in 0 until 20) for (x in 0 until Config.BOARD_W) if (x != y % Config.BOARD_W) g.board[y][x] = 'G' + g.hardDrop { g.insertGarbage(20, 0) } + assertTrue(g.over) + } + + @Test + fun boardRoundTrip() { + val g = TetrigGame(3) + g.board[0][3] = 'Z' + val s = encodeBoard(g.board) + assertEquals(200, s.length) + assertEquals('Z', decodeBoard(s)[19][3]) + repeat(5) { g.softDrop() } // 스폰 위치는 일부가 숨김 버퍼(y≥20)라 조금 내린다 + val withActive = encodeBoard(g.board, g.active) + assertTrue(withActive.count { it != '.' } == 5) + } +} diff --git a/app/gradle.properties b/app/gradle.properties index a8eee9a..6c0d803 100644 --- a/app/gradle.properties +++ b/app/gradle.properties @@ -12,3 +12,13 @@ kotlin.daemon.jvmargs=-Xmx2g # 버전은 CI/로컬에서 -PappVersionName -PappVersionCode 로 덮어쓸 수 있다. appVersionName=2.0.4 appVersionCode=6 + +# AdMob — 비워 두면 Google 공식 테스트 광고 ID 를 쓴다. 실제 ID 를 받으면 여기만 채운다. +# admobAppId=ca-app-pub-XXXXXXXXXXXXXXXX~YYYYYYYYYY +# admobBanner=ca-app-pub-XXXXXXXXXXXXXXXX/ZZZZZZZZZZ (메인·로비 하단 적응형 배너) +# admobCard=ca-app-pub-XXXXXXXXXXXXXXXX/ZZZZZZZZZZ (결과 화면 300×250) +# admobInterstitial=ca-app-pub-XXXXXXXXXXXXXXXX/ZZZZZZZZZZ (전면, 3판당 1회) +admobAppId= +admobBanner= +admobCard= +admobInterstitial= diff --git a/app/gradle/libs.versions.toml b/app/gradle/libs.versions.toml index a8ee687..8ed0b13 100644 --- a/app/gradle/libs.versions.toml +++ b/app/gradle/libs.versions.toml @@ -4,10 +4,18 @@ kotlin = "2.2.20" compose = "1.10.3" androidx-activityCompose = "1.11.0" androidx-lifecycle = "2.9.4" +kotlinx-serialization = "1.9.0" +okhttp = "4.12.0" +play-services-ads = "25.5.0" +ump = "4.0.0" [libraries] androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activityCompose" } androidx-lifecycle-viewmodel = { module = "org.jetbrains.androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "androidx-lifecycle" } +kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinx-serialization" } +okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" } +play-services-ads = { module = "com.google.android.gms:play-services-ads", version.ref = "play-services-ads" } +ump = { module = "com.google.android.ump:user-messaging-platform", version.ref = "ump" } kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" } [plugins] diff --git a/server/scripts/e2e.mjs b/server/scripts/e2e.mjs index 272d6d3..4ce8a96 100644 --- a/server/scripts/e2e.mjs +++ b/server/scripts/e2e.mjs @@ -120,5 +120,9 @@ la.ws.close(); lb.ws.close(); const lbSprint = await api("/api/leaderboard?board=sprint"); check(lbSprint.data.rows.some((r) => r.id === acct[0].user.id) && !lbSprint.data.rows.some((r) => r.id === ids[3]), "SPRINT 리더보드: 계정만 등재"); +// ── 계정 삭제 ── +const del = await api("/api/me/delete", { method: "POST", token: acct[1].token }); +check(del.status === 200 && (await api("/api/me", { token: acct[1].token })).status === 401, "계정 삭제 후 토큰 무효"); + console.log(fails ? `\n실패 ${fails}건` : "\n전부 통과"); process.exit(fails ? 1 : 0); diff --git a/server/src/index.js b/server/src/index.js index cc0bc7a..232455b 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -73,7 +73,7 @@ async function routeWs(req, env, url, u, ns, name, path = "/ws") { const stub = ns.get(ns.idFromName(name)); const headers = new Headers(req.headers); headers.set("x-uid", u.id); - headers.set("x-info", JSON.stringify(await playerInfo(env, u))); + headers.set("x-info", encodeURIComponent(JSON.stringify(await playerInfo(env, u)))); // 헤더는 ASCII 만 안전 return stub.fetch(new Request(`https://do${path}`, { headers })); } @@ -204,6 +204,17 @@ async function handle(req, env) { }); } + // 계정 삭제 (Play 정책: 계정을 만들 수 있으면 앱 안에서 삭제도 가능해야 한다) + if (path === "/api/me/delete" && req.method === "POST") { + await db.batch([ + db.prepare("DELETE FROM solo_records WHERE user_id = ?").bind(me.id), + db.prepare("DELETE FROM ratings WHERE user_id = ?").bind(me.id), + db.prepare("DELETE FROM matches WHERE p1 = ? AND mode = 'custom'").bind(me.id), + db.prepare("DELETE FROM users WHERE id = ?").bind(me.id), + ]); + return json({ ok: true }); + } + if (path === "/api/nickname" && req.method === "POST") { if (me.is_guest) return err("게스트는 닉네임을 바꿀 수 없습니다. 로그인해 주세요", 403); const b = await body(req); diff --git a/server/src/matchmaker.js b/server/src/matchmaker.js index 2d52e84..d2be8dd 100644 --- a/server/src/matchmaker.js +++ b/server/src/matchmaker.js @@ -6,10 +6,15 @@ import { MM_HINT_AFTER_MS, leagueFt } from "./rules.js"; const SWEEP_MS = 3_000; export class MatchmakerDO extends DurableObject { + constructor(ctx, env) { + super(ctx, env); + ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair('{"t":"ping"}', '{"t":"pong"}')); + } + async fetch(req) { if (req.headers.get("Upgrade") !== "websocket") return new Response("websocket only", { status: 426 }); const uid = req.headers.get("x-uid"); - const info = JSON.parse(req.headers.get("x-info") || "{}"); + const info = JSON.parse(decodeURIComponent(req.headers.get("x-info") || "%7B%7D")); for (const old of this.ctx.getWebSockets(uid)) { try { old.serializeAttachment({ ...old.deserializeAttachment(), gone: true }); @@ -65,7 +70,7 @@ export class MatchmakerDO extends DurableObject { } async webSocketMessage(ws, data) { - if (data === "leave" || String(data).includes('"leave"')) ws.close(1000, "left"); + if (String(data).includes('"leave"')) ws.close(1000, "left"); } async webSocketClose() {} diff --git a/server/src/room-logic.js b/server/src/room-logic.js index e496510..4891915 100644 --- a/server/src/room-logic.js +++ b/server/src/room-logic.js @@ -31,7 +31,8 @@ export class RoomLogic { this.roundStartAt = 0; this.nextRoundAt = 0; this.matchId = null; - this.finished = false; // 리그 경기 종료 후 방 폐기 표시 + this.finished = false; + this.lastEnd = null; // 끊겼다 돌아온 사람에게 다시 보낼 match_end ({uid|"*": msg}) // 리그 경기 종료 후 방 폐기 표시 this.outbox = []; // {to: uid|null, except?: uid, msg} this.effects = []; // {type, ...} @@ -58,7 +59,7 @@ export class RoomLogic { id: this.id, kind: this.kind, code: this.code, allowed: this.allowed, rules: this.rules, players: [...this.players.values()], order: this.order, host: this.host, phase: this.phase, round: this.round, roundStartAt: this.roundStartAt, nextRoundAt: this.nextRoundAt, - matchId: this.matchId, finished: this.finished, + matchId: this.matchId, finished: this.finished, lastEnd: this.lastEnd, }; } static fromJSON(j, deps = {}) { @@ -66,6 +67,7 @@ export class RoomLogic { Object.assign(r, { rules: j.rules, order: j.order, host: j.host, phase: j.phase, round: j.round, roundStartAt: j.roundStartAt, nextRoundAt: j.nextRoundAt, matchId: j.matchId, finished: j.finished, + lastEnd: j.lastEnd ?? null, }); for (const p of j.players) r.players.set(p.uid, p); return r; @@ -113,6 +115,10 @@ export class RoomLogic { existing.disconnectedAt = 0; Object.assign(existing, pickInfo(info)); this.send(uid, this.syncMsg(uid)); + if (this.phase === "match_end" && this.lastEnd) { + const end = this.lastEnd[uid] ?? this.lastEnd["*"]; + if (end) this.send(uid, end); + } if (existing.pendingGarbage?.length) { for (const g of existing.pendingGarbage) this.send(uid, g); existing.pendingGarbage = []; @@ -375,6 +381,7 @@ export class RoomLogic { this.broadcast({ t: "ko", who: uid, by: p.lastAttacker, place: p.place }); const left = this.alive; if (left.length <= 1) this.endRound(left[0] ?? null); + else this.broadcast(this.lobbyMsg()); // 생존 인원·KO 표시 갱신 } endRound(winner) { @@ -416,7 +423,9 @@ export class RoomLogic { // match_end 메시지는 레이팅 반영 후 래퍼가 trDelta 를 붙여 보낸다. } else { this.effects.push({ type: "custom_end", standings, size: this.order.length }); - this.broadcast({ t: "match_end", result: standings, winner: winnerUid }); + const msg = { t: "match_end", result: standings, winner: winnerUid }; + this.lastEnd = { "*": msg }; + this.broadcast(msg); this.broadcastRematch(); } this.broadcast(this.lobbyMsg()); @@ -434,6 +443,7 @@ export class RoomLogic { } resetWins() { + this.lastEnd = null; for (const p of this.players.values()) { p.wins = 0; p.rematch = false; diff --git a/server/src/room.js b/server/src/room.js index e745590..b636a61 100644 --- a/server/src/room.js +++ b/server/src/room.js @@ -10,6 +10,8 @@ export class GameRoomDO extends DurableObject { constructor(ctx, env) { super(ctx, env); this.logic = null; + // 클라이언트 keepalive: DO 를 깨우지 않고 런타임이 바로 응답한다. + ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair('{"t":"ping"}', '{"t":"pong"}')); } async load() { @@ -50,7 +52,7 @@ export class GameRoomDO extends DurableObject { const l = await this.load(); if (!l) return new Response("no such room", { status: 404 }); const uid = req.headers.get("x-uid"); - const info = JSON.parse(req.headers.get("x-info") || "{}"); + const info = JSON.parse(decodeURIComponent(req.headers.get("x-info") || "%7B%7D")); const pair = new WebSocketPair(); const [client, server] = Object.values(pair); // 같은 유저의 이전 소켓은 정리 (재접속) @@ -162,11 +164,14 @@ export class GameRoomDO extends DurableObject { } catch (err) { console.error("league_end failed", err); } + l.lastEnd = {}; for (const uid of [e.winner, e.loser]) { - l.send(uid, { + const msg = { t: "match_end", winner: e.winner, score: e.score, trDelta: result?.[uid]?.trDelta ?? null, before: result?.[uid]?.before ?? null, after: result?.[uid]?.after ?? null, - }); + }; + l.lastEnd[uid] = msg; + l.send(uid, msg); } } else if (e.type === "custom_end") { try { diff --git a/server/test/room.test.js b/server/test/room.test.js index 0c0287f..bb6d6ea 100644 --- a/server/test/room.test.js +++ b/server/test/room.test.js @@ -175,3 +175,18 @@ test("보드 스냅샷 검증·중계", () => { r.handle("a", { t: "board", grid: ".".repeat(190) + "GGGGGGGGG.", lock: true }); assert.equal(msgs(r, "b", "board").length, 1); }); + +test("끝난 경기 결과는 재접속한 사람에게 다시 보낸다", () => { + const { r, clock } = mkRoom(); + r.join("a"); r.join("b"); + r.handle("a", { t: "rules", rules: { ft: 1 } }); + startPlaying(r, clock); + r.disconnect("b"); + r.handle("a", { t: "topout" }); // b 가 끊긴 사이 경기 종료 (b 승) + assert.equal(r.phase, "match_end"); + r.drain(); + r.join("b"); + const end = msgs(r, "b", "match_end"); + assert.equal(end.length, 1); + assert.equal(end[0].winner, "b"); +}); diff --git a/store/listing.md b/store/listing.md index 0baa5bc..4560fca 100644 --- a/store/listing.md +++ b/store/listing.md @@ -11,43 +11,46 @@ Play Console → 스토어 설정 / 기본 스토어 등록정보에 그대로 TETRIG ``` -## 간단한 설명 (80자 이내) — 현재 31자 +## 간단한 설명 (80자 이내) — 현재 47자 ``` -스프린트·타임어택·엔들리스. 광고 없는 순수 블록 퍼즐. +실시간 1:1 리그전부터 인원 무제한 커스텀 난투까지 — 모바일 대전 블록 스태커 ``` ## 자세한 설명 (4000자 이내) ``` -TETRIG은 군더더기를 걷어낸 블록 스태킹 퍼즐입니다. 로그인도, 광고도, 결제도 없습니다. 앱을 열면 바로 게임이 시작됩니다. +쌓아라, 부숴라, 올라가라. TETRIG은 모바일에 맞춰 다시 설계한 실시간 대전 블록 스태커입니다. 가입 없이 바로 시작하고, 원하면 계정을 만들어 랭크로 실력을 증명하세요. -■ 세 가지 솔로 모드 -· SPRINT — 40줄을 얼마나 빨리 지우는지 겨루는 기록 경기입니다. -· TIME ATTACK — 2분 동안 최대 점수를 뽑아내는 모드입니다. 시간이 갈수록 레벨이 올라갑니다. -· ENDLESS — 제한이 없습니다. 탑아웃해도 이어서 계속 쌓을 수 있어 연습에 좋습니다. +■ 리그전 +· 실시간 1:1 랭크 매치. 비슷한 실력의 상대를 자동으로 찾아 줍니다. +· Glicko-2 레이팅과 18단계 랭크(D ~ X+). 배치 10경기를 마치면 TR 이 공개됩니다. +· 3선승제, 상위 랭크는 5선승제. 시즌제로 운영됩니다. -■ 제대로 된 조작감 -· SRS+180 회전과 킥 테이블을 구현해, 익숙한 회전 보정이 그대로 통합니다. -· 7-bag 랜덤이라 같은 블록이 몰려 나오지 않습니다. -· 홀드, 고스트(착지 위치 미리보기), 하드 드롭, 소프트 드롭, 180도 회전을 모두 지원합니다. -· T-스핀, 백투백, 콤보, 퍼펙트 클리어를 판정해 점수에 반영합니다. -· DAS/ARR, 락 딜레이를 조정해 반응이 끊기지 않게 맞췄습니다. +■ 커스텀 룸 +· 6자리 코드로 방을 만들고 친구를 부르세요. 인원 제한이 없습니다. +· 2명이면 1:1, 3명 이상이면 최후의 1인이 살아남는 난투. +· 가비지 배율, 목표 승수, 동일 bag 공정전, 장기전 배율을 방장이 정합니다. +· 상대 보드를 눌러 공격 대상을 직접 고르고, 격추 피드로 판세를 확인하세요. 끝나면 리매치 투표로 바로 한 판 더. -■ 어떤 화면에서든 맞춰집니다 -· 일반 스마트폰은 물론 갤럭시 폴드(접었을 때·펼쳤을 때), 플립, 태블릿까지 화면 크기에 따라 배치가 바뀝니다. -· 가로 화면에서는 조작 버튼이 좌우로 갈라져 양손 엄지에 닿습니다. -· 폴드를 펼치거나 화면을 돌려도 게임이 재시작되지 않고 그대로 이어집니다. -· 태블릿·폴드용 '큰 버튼' 옵션과 왼손잡이용 좌우 반전 옵션이 있습니다. +■ 솔로 +· SPRINT — 40줄 최속 클리어 +· TIME ATTACK — 2분 점수 어택 +· ENDLESS — 톱아웃해도 이어지는 연습 모드 -■ 개인정보를 수집하지 않습니다 -· 인터넷 권한조차 요청하지 않습니다. 앱은 네트워크에 전혀 접속하지 않습니다. -· 기록과 설정은 기기 안에만 저장되고 어디로도 전송되지 않습니다. -· 회원가입, 광고, 추적, 분석 도구가 없습니다. -· 비행기 모드에서도 모든 기능이 동일하게 동작합니다. +■ 손맛 +· SRS+180 회전·킥, 7-bag, 홀드, 고스트, T-스핀, 백투백, 콤보, 올 클리어 판정 +· 상쇄(카운터)와 가비지 게이지까지 갖춘 대전 규칙 -■ 광고도 결제도 없습니다 -전체 기능이 처음부터 열려 있습니다. 결제 유도, 에너지·하트 같은 플레이 제한, 보상형 광고가 없습니다. +■ 기록 +· 리그·SPRINT·TIME ATTACK·ENDLESS 리더보드, 프로필 전적 + +■ 어떤 화면에서든 +· 스마트폰, 갤럭시 폴드·플립, 태블릿, 가로 화면까지 배치가 자동으로 맞춰집니다. 왼손 배치·큰 버튼 옵션 제공. + +게임 플레이 중에는 광고가 나오지 않습니다. 계정은 앱 안 프로필에서 언제든 삭제할 수 있습니다. + +배치 10경기를 끝내보세요. 개인정보처리방침: https://tetrig.pages.dev/privacy @@ -72,21 +75,28 @@ TETRIG은 개인이 만든 앱입니다. Tetris Holding LLC 및 관련 회사와 --- -## 데이터 보안(Data safety) 설문 답안 +## 데이터 보안(Data safety) 설문 답안 (v2.1.0~, 온라인·광고 추가 후) -릴리스 APK의 권한을 확인한 결과 `INTERNET` 권한이 없다(`kr.tkrmagid.tetrig.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION` 하나뿐). 그래서 모든 문항이 "아니요"로 끝난다. +- 사용자 데이터를 수집하거나 공유하나요? → **예** +- 전송 중 암호화 → **예** (HTTPS/WSS) +- 사용자가 데이터 삭제를 요청할 수 있나요? → **예** (앱 프로필 > 계정 삭제, 또는 이메일 요청 — 개인정보처리방침 4항) +- 수집 항목 + - 개인 정보 > 이메일 주소: 수집(선택), 목적 = 계정 관리. 공유 안 함 + - 개인 정보 > 사용자 ID(닉네임·내부 ID): 수집(필수), 목적 = 앱 기능·계정 관리. 공유 안 함 + - 앱 활동 > 기타 사용자 생성 콘텐츠/게임 기록: 수집, 목적 = 앱 기능. 공유 안 함 + - 기기 또는 기타 ID > 광고 ID: 수집·**공유**(Google AdMob), 목적 = 광고 +- 계정 삭제 URL(웹): `https://tetrig.pages.dev/privacy` (4항 — 이메일 삭제 요청 안내) -- 앱이 필요한 사용자 데이터 유형을 수집하거나 공유하나요? → **아니요** -- 모든 사용자 데이터가 전송 중에 암호화되나요? → (수집 없음이므로 해당 없음) -- 사용자가 데이터 삭제를 요청할 수 있나요? → (수집 없음이므로 해당 없음) -- 앱에 광고가 포함되어 있나요? → **아니요** -- 인앱 구매 → **없음** +## 광고 (AdMob) -근거: 기록·설정은 안드로이드 SharedPreferences 로 기기 내부에만 저장되고 외부로 나가지 않는다. +- 앱 콘텐츠 > 광고: **예, 광고 포함** +- 광고 단위 ID 는 `app/gradle.properties` 의 `admob*` 값. 비어 있으면 Google 테스트 광고. +- 노출 규칙: 메인·커스텀 로비 하단 배너, 모든 결과 화면 300×250, 결과 → 다음 행동 사이 전면(3판당 1회, 세션 첫 판 제외). 플레이 화면 광고 0. +- `app-ads.txt`: AdMob 에서 받은 한 줄을 개발자 웹사이트 루트에 올린다. ## 콘텐츠 등급 설문 -퍼즐 게임 카테고리로, 폭력·성적 내용·욕설·도박·약물 요소가 전부 없고 사용자 간 소통 기능도 없다. 전 문항 "아니요"로 답하면 전체이용가(ESRB Everyone / PEGI 3 / GRAC 전체이용가)가 나온다. +퍼즐 게임 카테고리로, 폭력·성적 내용·욕설·도박·약물 요소가 전부 없다. 채팅은 없지만 온라인 대전에서 다른 사용자의 닉네임이 보이므로 "사용자 간 상호작용: 예(채팅 없음)"로 답한다. ## 기타 Play Console 입력값 @@ -95,7 +105,7 @@ TETRIG은 개인이 만든 앱입니다. Tetris Holding LLC 및 관련 회사와 - 태그: 퍼즐 / 캐주얼 / 아케이드 - 무료 또는 유료: **무료** - 대상 연령: 전체 -- 광고 포함: **아니요** +- 광고 포함: **예** - 개인정보처리방침 URL: `https://tetrig.pages.dev/privacy` - 이메일: `tkrmagid@gmail.com` - 패키지명: `kr.tkrmagid.tetrig` diff --git a/store/privacy.html b/store/privacy.html index 9489481..e840e44 100644 --- a/store/privacy.html +++ b/store/privacy.html @@ -25,77 +25,83 @@

TETRIG 개인정보처리방침

-

최종 수정일: 2026-09-24 · 앱 패키지: kr.tkrmagid.tetrig

+

최종 수정일: 2026-11-04 · 앱 패키지: kr.tkrmagid.tetrig

-

요약: TETRIG은 개인정보를 일절 수집하지 않습니다. 앱에는 인터넷 접근 권한조차 없으며, - 모든 데이터는 기기 안에만 저장됩니다.

+

요약: 온라인 대전(커스텀 방·리그전)과 리더보드를 위해 게임 계정 정보와 경기 기록을 서버에 저장합니다. + 무료 운영을 위해 Google AdMob 광고를 표시하며, 이 과정에서 광고 ID 등 기기 정보가 Google 에 전송될 수 있습니다. + 솔로 모드는 계정 없이도 쓸 수 있고, 계정은 앱 안에서 언제든 삭제할 수 있습니다.

-

1. 수집하는 개인정보

-

없습니다. TETRIG은 이름, 이메일, 전화번호, 위치, 연락처, 사진, 기기 식별자 등 - 어떤 개인정보도 수집·요청·전송하지 않습니다. 회원가입 절차가 없습니다.

- -

2. 기기에 저장되는 정보

-

아래 항목만 기기 내부 저장소(Android SharedPreferences)에 저장되며 외부로 전송되지 않습니다.

+

1. 수집하는 정보와 목적

    -
  • 솔로 모드 최고 기록 (SPRINT 최단 시간, TIME ATTACK / ENDLESS 최고 점수)
  • -
  • 게임 설정값 (고스트 표시, 왼손 배치, 큰 버튼)
  • +
  • 게스트 계정: 앱이 처음 실행될 때 무작위 닉네임과 무작위 기기 식별값(앱이 직접 만든 값, 하드웨어 ID 아님)을 서버에 등록합니다. 온라인 대전 참가와 기록 저장에 씁니다.
  • +
  • 이메일 계정(선택): 이메일 주소, 비밀번호(PBKDF2 해시로만 저장, 원문 저장 안 함), 닉네임. 로그인과 기록 이전에 씁니다.
  • +
  • 게임 기록: 솔로 최고 기록, 리그 레이팅(Glicko-2·TR)·전적, 커스텀 방 순위. 리더보드·프로필 표시와 매칭에 씁니다.
  • +
  • 대전 중 데이터: 보드 상태, 공격량 등 경기 진행 신호. 실시간 중계와 부정행위 방지에만 쓰며 경기가 끝나면 결과만 남습니다.
-

앱을 삭제하면 이 데이터도 함께 삭제됩니다.

-

3. 권한

-

TETRIG은 인터넷, 저장소, 위치, 카메라, 마이크, 연락처 등 어떤 런타임 권한도 요청하지 않습니다.

+

2. 광고 (Google AdMob)

+

메인 화면·커스텀 로비 하단 배너, 결과 화면 광고, 그리고 3판에 한 번 결과 화면을 나갈 때 전면 광고를 표시합니다. 게임 플레이 중에는 광고가 나오지 않습니다. + 광고 제공을 위해 Google 이 광고 ID, IP 주소, 기기·앱 정보를 수집·처리할 수 있습니다. 유럽경제지역·영국 등에서는 처음 실행 시 동의 화면이 표시됩니다. + Google 의 처리 방식: https://policies.google.com/technologies/partner-sites. + 기기 설정 > Google > 광고에서 광고 ID 를 재설정하거나 삭제할 수 있습니다.

-

4. 제3자 제공 · 광고 · 분석

-

광고 SDK, 분석 SDK, 크래시 리포팅 도구를 일절 포함하지 않습니다. - 따라서 제3자에게 제공되는 데이터도 없습니다.

+

3. 보관과 처리 위치

+

서버는 Cloudflare(Workers·D1)에서 운영되며 전송 구간은 모두 HTTPS/WSS 로 암호화됩니다. 계정을 삭제하기 전까지 보관하고, 삭제하면 즉시 지웁니다. + 리그 경기 결과에는 상대 플레이어의 전적 보존을 위해 개인을 식별할 수 없는 내부 ID 와 점수만 남습니다.

-

5. 아동 개인정보

-

어떤 이용자로부터도 개인정보를 수집하지 않으므로, 만 14세 미만 아동의 개인정보 역시 수집하지 않습니다.

+

4. 계정 삭제

+

앱 > 프로필 > 계정 삭제를 누르면 계정, 이메일, 비밀번호 해시, 닉네임, 레이팅, 솔로 기록, 커스텀 전적이 즉시 삭제됩니다. + 앱을 쓸 수 없는 경우 가입한 이메일로 tkrmagid@gmail.com 에 삭제를 요청하면 7일 안에 처리합니다.

-

6. 변경 고지

-

향후 온라인 대전 기능이 추가되어 수집 항목이 생기면, 이 문서를 갱신하고 - 앱 업데이트 시점에 안내합니다.

+

5. 기기에 저장되는 정보

+

로그인 토큰, 솔로 최고 기록, 설정값(고스트·왼손 배치·큰 버튼)이 기기 안(SharedPreferences)에 저장되며 앱을 삭제하면 함께 지워집니다.

-

7. 문의

-

개인정보 관련 문의: tkrmagid@gmail.com

+

6. 권한

+

인터넷·네트워크 상태 권한만 사용합니다(온라인 대전과 광고). 위치·카메라·마이크·연락처 권한은 요청하지 않습니다.

+ +

7. 제3자 제공

+

광고를 위한 Google AdMob 외에는 어떤 제3자에게도 정보를 판매·제공하지 않습니다. 분석·추적 SDK 는 쓰지 않습니다.

+ +

8. 아동

+

만 14세 미만 아동을 대상으로 하지 않으며, 그 사실을 알게 되면 해당 계정을 삭제합니다.

+ +

9. 문의

+

tkrmagid@gmail.com


TETRIG Privacy Policy

-

Last updated: 2026-09-24 · Package: kr.tkrmagid.tetrig

+

Last updated: 2026-11-04 · Package: kr.tkrmagid.tetrig

-

Summary: TETRIG collects no personal data. The app does not even hold the - INTERNET permission. All data stays on your device.

+

Summary: To provide online matches (custom rooms, ranked league) and leaderboards, we store your game account and match records on our server. + The app shows Google AdMob ads, which may send device information such as the advertising ID to Google. + Solo modes work without an account, and you can delete your account in the app at any time.

1. Data we collect

-

None. TETRIG does not collect, request, or transmit any personal information such as name, - email, phone number, location, contacts, photos, or device identifiers. There is no account system.

- -

2. Data stored on your device

    -
  • Solo mode personal bests (SPRINT time, TIME ATTACK / ENDLESS score)
  • -
  • Gameplay settings (ghost piece, left-handed layout, large buttons)
  • +
  • Guest account: a random nickname and a random app-generated install ID (not a hardware ID), created on first launch.
  • +
  • Email account (optional): email, password (stored only as a PBKDF2 hash), nickname.
  • +
  • Game records: solo bests, league rating and match history, custom room placements.
  • +
  • In-match signals: board state and attacks, used only to relay the live match and prevent cheating.
-

Uninstalling the app removes this data.

-

3. Permissions

-

TETRIG requests no runtime permissions and has no internet access.

+

2. Advertising (Google AdMob)

+

Banner ads on the home screen and custom lobby, an ad on result screens, and an interstitial at most once every three games when leaving a result screen. No ads during gameplay. + Google may collect the advertising ID, IP address and device/app information to serve ads. Users in the EEA/UK see a consent form on first launch. + See https://policies.google.com/technologies/partner-sites.

-

4. Third parties, ads, analytics

-

No advertising SDK, no analytics SDK, no crash reporting. No data is shared with anyone.

+

3. Storage

+

The server runs on Cloudflare (Workers, D1); all traffic is encrypted (HTTPS/WSS). Data is kept until you delete your account.

-

5. Children

-

Since no personal data is collected from any user, none is collected from children either.

+

4. Account deletion

+

In the app: Profile > 계정 삭제 (Delete account) deletes your account, email, password hash, nickname, rating, solo records and custom history immediately. + If you cannot use the app, email tkrmagid@gmail.com from your registered address; requests are handled within 7 days.

-

6. Changes

-

If online multiplayer is added later and data collection begins, this document will be updated - and the change announced with the app update.

- -

7. Contact

+

5. Contact

tkrmagid@gmail.com