Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fb992c7eb5 | |||
| c05c39ff36 | |||
| 8fcef8e720 | |||
| 845969297e | |||
| 5464b53f3f |
@@ -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")
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
|
||||
<!-- 폴드/플립/태블릿 대응: 화면 크기가 자유롭게 바뀌어도 액티비티를 재시작하지 않는다. -->
|
||||
<supports-screens
|
||||
android:anyDensity="true"
|
||||
@@ -19,6 +22,10 @@
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.Tetrig">
|
||||
|
||||
<meta-data
|
||||
android:name="com.google.android.gms.ads.APPLICATION_ID"
|
||||
android:value="${admobAppId}" />
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboardHidden|density|uiMode|layoutDirection|navigation"
|
||||
|
||||
@@ -5,6 +5,7 @@ import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import kr.tkrmagid.tetrig.ads.AdsAndroid
|
||||
import kr.tkrmagid.tetrig.data.AndroidStoreHolder
|
||||
import kr.tkrmagid.tetrig.ui.App
|
||||
|
||||
@@ -20,6 +21,7 @@ class MainActivity : ComponentActivity() {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
AndroidStoreHolder.init(this)
|
||||
AdsAndroid.start(this)
|
||||
setContent { App() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package kr.tkrmagid.tetrig.ads
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.Activity
|
||||
import android.util.Log
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import com.google.android.gms.ads.AdListener
|
||||
import com.google.android.gms.ads.AdRequest
|
||||
import com.google.android.gms.ads.AdSize
|
||||
import com.google.android.gms.ads.AdView
|
||||
import com.google.android.gms.ads.FullScreenContentCallback
|
||||
import com.google.android.gms.ads.LoadAdError
|
||||
import com.google.android.gms.ads.MobileAds
|
||||
import com.google.android.gms.ads.interstitial.InterstitialAd
|
||||
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback
|
||||
import com.google.android.ump.ConsentInformation
|
||||
import com.google.android.ump.ConsentRequestParameters
|
||||
import com.google.android.ump.UserMessagingPlatform
|
||||
import kr.tkrmagid.tetrig.R
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
private const val TAG = "TetrigAds"
|
||||
|
||||
@SuppressLint("StaticFieldLeak")
|
||||
object AdsAndroid {
|
||||
var activity: Activity? = null
|
||||
private val started = AtomicBoolean(false)
|
||||
/** 동의 확인 + SDK 초기화가 끝나야 광고를 요청한다 (Compose 가 관찰). */
|
||||
var ready by mutableStateOf(false)
|
||||
private set
|
||||
private var interstitial: InterstitialAd? = null
|
||||
|
||||
/**
|
||||
* UMP 동의(유럽·영국 등 필요한 지역에서만 팝업) → MobileAds 초기화 → 전면 광고 선로드.
|
||||
* 동의 결과와 무관하게 canRequestAds() 가 true 일 때만 광고를 요청한다.
|
||||
*/
|
||||
fun start(act: Activity) {
|
||||
activity = act
|
||||
val consent = UserMessagingPlatform.getConsentInformation(act)
|
||||
consent.requestConsentInfoUpdate(
|
||||
act, ConsentRequestParameters.Builder().build(),
|
||||
{
|
||||
UserMessagingPlatform.loadAndShowConsentFormIfRequired(act) { err ->
|
||||
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() },
|
||||
)
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
@@ -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")
|
||||
|
||||
@@ -360,13 +360,13 @@ class TetrigGame(seed: Int = 1) {
|
||||
}
|
||||
|
||||
/** 하드드롭. 떨어진 칸 수와 락 결과를 반환한다. */
|
||||
fun hardDrop(): Pair<Int, LockResult>? {
|
||||
fun hardDrop(beforeSpawn: (LockResult) -> Unit = {}): Pair<Int, LockResult>? {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Int>()
|
||||
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<Pair<Int, Int>> {
|
||||
val out = mutableListOf<Pair<Int, Int>>()
|
||||
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<Int>()
|
||||
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<CharArray> =
|
||||
(0 until Config.VISIBLE_H).map { r ->
|
||||
CharArray(Config.BOARD_W) { c -> s.getOrElse(r * Config.BOARD_W + c) { '.' } }
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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<Standing>,
|
||||
val score: Map<String, Int>,
|
||||
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<String?>(null)
|
||||
private set
|
||||
var toast by mutableStateOf<String?>(null)
|
||||
|
||||
var me by mutableStateOf("")
|
||||
private set
|
||||
var code by mutableStateOf<String?>(null)
|
||||
private set
|
||||
var host by mutableStateOf<String?>(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<RoomPlayer>()
|
||||
val boards = mutableStateMapOf<String, String>()
|
||||
val koFeed = mutableStateListOf<String>()
|
||||
var targeting by mutableStateOf<String?>(null)
|
||||
private set
|
||||
var manualTarget by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/** 내 라운드. 관전 중이면 null. */
|
||||
var game by mutableStateOf<GameState?>(null)
|
||||
private set
|
||||
var roundStartsAt by mutableStateOf(0L)
|
||||
private set
|
||||
var pending by mutableIntStateOf(0)
|
||||
private set
|
||||
var roundBanner by mutableStateOf<String?>(null)
|
||||
private set
|
||||
var matchEnd by mutableStateOf<MatchEnd?>(null)
|
||||
private set
|
||||
var rematchVotes by mutableStateOf<List<String>>(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<String, Any?>) {
|
||||
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<String?>(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
|
||||
}
|
||||
@@ -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<JsonObject> = (this[k] as? JsonArray)?.mapNotNull { it as? JsonObject } ?: emptyList()
|
||||
|
||||
fun jsonOf(vararg pairs: Pair<String, Any?>): 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<User?>(null)
|
||||
private set
|
||||
var league by mutableStateOf<League?>(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<JsonObject?>(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))
|
||||
}
|
||||
}
|
||||
@@ -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("")
|
||||
}
|
||||
@@ -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>(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,
|
||||
|
||||
@@ -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,56 +341,67 @@ 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
|
||||
Row(
|
||||
val gap = (8 * scale).dp
|
||||
// 아랫줄 3개(하드 드롭·홀드·소프트 드롭)를 정확히 1/3 씩 주려면 그 줄이
|
||||
// 화면 전체 폭을 차지해야 한다. 그래서 좌/우 컬럼으로 쪼개지 않고
|
||||
// 바깥을 Column 으로 두어 윗줄·아랫줄을 각각 통짜 Row 로 깐다.
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(h)
|
||||
.padding(horizontal = (10 * scale).dp, vertical = (6 * scale).dp),
|
||||
horizontalArrangement = Arrangement.spacedBy((8 * scale).dp),
|
||||
verticalArrangement = Arrangement.spacedBy(gap),
|
||||
) {
|
||||
val actions: @Composable (Modifier) -> Unit = { m ->
|
||||
// 회전은 위쪽 한 줄, 아래는 하드 드롭 + 홀드를 반씩 나눈다.
|
||||
// 두 컬럼의 행 높이 비율(1.4 : 1)을 맞춰야 좌우가 나란히 떨어진다.
|
||||
Column(m.fillMaxHeight(), verticalArrangement = Arrangement.spacedBy((8 * scale).dp)) {
|
||||
Row(Modifier.weight(1.4f).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy((8 * scale).dp)) {
|
||||
// HOLD 가 아랫줄로 내려가며 빈 한 칸을 회전 두 개가 나눠 갖는다.
|
||||
// 180° 는 폭을 유지해야 하므로 4등분 중 1칸(weight 1)을 그대로
|
||||
// 두고, ↺·↻ 가 1.5 씩 받아 3/8 폭이 된다.
|
||||
// ── 윗줄: 회전 | 좌우 이동 ──
|
||||
Row(Modifier.weight(1.4f).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(gap)) {
|
||||
val rotates: @Composable (Modifier) -> Unit = { m ->
|
||||
Row(m.fillMaxHeight(), horizontalArrangement = Arrangement.spacedBy(gap)) {
|
||||
// 180° 는 폭을 유지해야 해서 4등분 중 1칸을 그대로 두고,
|
||||
// ↺·↻ 가 1.5 씩 받아 3/8 폭이 된다.
|
||||
CtrlButton("↺", Modifier.weight(1.5f).fillMaxHeight(), scale) { state.rotate("ccw") }
|
||||
CtrlButton("↻", Modifier.weight(1.5f).fillMaxHeight(), scale) { state.rotate("cw") }
|
||||
CtrlButton("180°", Modifier.weight(1f).fillMaxHeight(), scale) { state.rotate("180") }
|
||||
}
|
||||
Row(Modifier.weight(1f).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy((8 * scale).dp)) {
|
||||
CtrlButton("하드 드롭", Modifier.weight(1f).fillMaxHeight(), scale, accent = true) { state.hardDrop() }
|
||||
CtrlButton("HOLD", Modifier.weight(1f).fillMaxHeight(), scale) { state.hold() }
|
||||
}
|
||||
}
|
||||
}
|
||||
val moves: @Composable (Modifier) -> Unit = { m ->
|
||||
Column(m.fillMaxHeight(), verticalArrangement = Arrangement.spacedBy((8 * scale).dp)) {
|
||||
Row(Modifier.weight(1.4f).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy((8 * scale).dp)) {
|
||||
val moves: @Composable (Modifier) -> Unit = { m ->
|
||||
Row(m.fillMaxHeight(), horizontalArrangement = Arrangement.spacedBy(gap)) {
|
||||
HoldCtrl("◀", Modifier.weight(1f).fillMaxHeight(), scale, { state.press(-1) }, { state.release(-1) })
|
||||
HoldCtrl("▶", Modifier.weight(1f).fillMaxHeight(), scale, { state.press(1) }, { state.release(1) })
|
||||
}
|
||||
HoldCtrl("▼ 소프트", Modifier.weight(1f).fillMaxWidth(), scale, { state.setSoft(true) }, { state.setSoft(false) })
|
||||
}
|
||||
if (lefty) {
|
||||
moves(Modifier.weight(1f))
|
||||
rotates(Modifier.weight(1.35f))
|
||||
} else {
|
||||
rotates(Modifier.weight(1.35f))
|
||||
moves(Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
// 액션쪽이 한 줄에 버튼 4개라 폭을 더 준다. 1.1 이면 버튼이 세로로 길쭉해져
|
||||
// 엄지로 누르기 불편했다.
|
||||
if (lefty) {
|
||||
moves(Modifier.weight(1f))
|
||||
actions(Modifier.weight(1.35f))
|
||||
} else {
|
||||
actions(Modifier.weight(1.35f))
|
||||
moves(Modifier.weight(1f))
|
||||
|
||||
// ── 아랫줄: 하드 드롭 · 홀드 · 소프트 드롭 3등분 ──
|
||||
Row(Modifier.weight(1f).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(gap)) {
|
||||
val third = Modifier.weight(1f).fillMaxHeight()
|
||||
val hardDrop: @Composable (Modifier) -> Unit = { m ->
|
||||
CtrlButton("하드 드롭", m, scale, accent = true) { state.hardDrop() }
|
||||
}
|
||||
val hold: @Composable (Modifier) -> Unit = { m -> CtrlButton("HOLD", m, scale) { state.hold() } }
|
||||
val soft: @Composable (Modifier) -> Unit = { m ->
|
||||
HoldCtrl("▼ 소프트", m, scale, { state.setSoft(true) }, { state.setSoft(false) })
|
||||
}
|
||||
// 왼손 배치에서는 좌우를 뒤집는다 (소프트가 왼쪽 엄지 쪽으로).
|
||||
if (lefty) {
|
||||
soft(third); hold(third); hardDrop(third)
|
||||
} else {
|
||||
hardDrop(third); hold(third); soft(third)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@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),
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<String?>(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<List<JsonObject>?>(null) }
|
||||
var err by remember { mutableStateOf<String?>(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<String?>(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<String, Any>()))
|
||||
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<String?>(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)
|
||||
}
|
||||
}
|
||||
@@ -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) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -10,5 +10,15 @@ kotlin.code.style=official
|
||||
kotlin.daemon.jvmargs=-Xmx2g
|
||||
|
||||
# 버전은 CI/로컬에서 -PappVersionName -PappVersionCode 로 덮어쓸 수 있다.
|
||||
appVersionName=2.0.3
|
||||
appVersionCode=5
|
||||
appVersionName=2.1.0
|
||||
appVersionCode=7
|
||||
|
||||
# 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=
|
||||
|
||||
@@ -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]
|
||||
|
||||
3
server/.gitignore
vendored
Normal file
3
server/.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
.wrangler/
|
||||
.dev.vars
|
||||
49
server/README.md
Normal file
49
server/README.md
Normal file
@@ -0,0 +1,49 @@
|
||||
# TETRIG 서버 (Cloudflare Workers)
|
||||
|
||||
배포 주소: https://tetrig.tkrmagid.workers.dev
|
||||
|
||||
- `src/index.js` — REST API + WebSocket 라우팅 + Cron
|
||||
- `src/room-logic.js` — 경기방 상태 기계 (리그 1:1 · 커스텀 N인 공용, 순수 로직)
|
||||
- `src/room.js` — GameRoomDO (WebSocket Hibernation, 상태는 DO storage 에 저장)
|
||||
- `src/matchmaker.js` / `src/matchmaking.js` — 리그 대기열 (R ± 2×RD, 30초마다 ×1.2 확장)
|
||||
- `src/glicko.js` — Glicko-2, `src/rules.js` — 튜닝 상수 전부
|
||||
- `migrations/` — D1 스키마
|
||||
|
||||
## 개발
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm test # 단위 테스트
|
||||
printf 'TOKEN_SECRET=dev\n' > .dev.vars
|
||||
npx wrangler d1 migrations apply tetrig --local
|
||||
npx wrangler dev --local --port 8799
|
||||
node scripts/e2e.mjs http://127.0.0.1:8799 # 종단 테스트 (게스트·FFA·계정·리그)
|
||||
```
|
||||
|
||||
## 배포
|
||||
|
||||
```bash
|
||||
export CLOUDFLARE_API_TOKEN=... CLOUDFLARE_ACCOUNT_ID=...
|
||||
npx wrangler d1 migrations apply tetrig --remote
|
||||
npx wrangler deploy
|
||||
```
|
||||
|
||||
비밀값 `TOKEN_SECRET` 은 `wrangler secret put` 으로만 넣는다 (재설정하면 기존 로그인 세션이 모두 끊김).
|
||||
Google 로그인은 `wrangler.toml` 의 `GOOGLE_CLIENT_IDS` 에 OAuth 클라이언트 ID 를 넣으면 켜진다.
|
||||
|
||||
## API 요약
|
||||
|
||||
| 경로 | 설명 |
|
||||
|---|---|
|
||||
| `POST /api/guest` | 게스트 발급 (랜덤 닉) → `{token, user}` |
|
||||
| `POST /api/register` | 이메일 가입. 게스트 토큰을 같이 보내면 그 계정을 승격(기록 유지) |
|
||||
| `POST /api/login` | 이메일 로그인. 게스트 토큰을 같이 보내면 기록 병합 |
|
||||
| `POST /api/google` | Google ID 토큰 로그인 |
|
||||
| `GET /api/me` | 프로필·리그 요약·솔로 베스트·최근 전적 |
|
||||
| `POST /api/nickname` · `GET /api/nickname/check?n=` | 닉 변경(30일 쿨다운) · 중복 검사 |
|
||||
| `POST /api/solo` | 솔로 베스트 제출 `{mode, value}` |
|
||||
| `GET /api/leaderboard?board=league\|sprint\|time\|endless` | 상위 100 (계정만) |
|
||||
| `POST /api/rooms` · `GET /api/rooms/:code` | 커스텀 방 생성 · 조회 |
|
||||
| `WS /ws/room/:code` · `WS /ws/league/:id` · `WS /ws/queue` | 경기방 · 리그 경기 · 리그 대기열 (`?token=`) |
|
||||
|
||||
WebSocket 메시지 형식은 명세서 §14.3 + `src/room-logic.js` 의 `handle()` 참고.
|
||||
58
server/migrations/0001_init.sql
Normal file
58
server/migrations/0001_init.sql
Normal file
@@ -0,0 +1,58 @@
|
||||
-- TETRIG D1 스키마 (명세서 §14.2 기반)
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id TEXT PRIMARY KEY,
|
||||
nickname TEXT UNIQUE NOT NULL,
|
||||
is_guest INTEGER NOT NULL DEFAULT 1,
|
||||
email TEXT UNIQUE,
|
||||
google_sub TEXT UNIQUE,
|
||||
pw_hash TEXT,
|
||||
pw_salt TEXT,
|
||||
device_id TEXT,
|
||||
created_at INTEGER,
|
||||
nickname_changed_at INTEGER
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS ratings (
|
||||
user_id TEXT PRIMARY KEY REFERENCES users(id),
|
||||
season INTEGER NOT NULL,
|
||||
glicko REAL NOT NULL,
|
||||
rd REAL NOT NULL,
|
||||
vol REAL NOT NULL,
|
||||
tr INTEGER NOT NULL DEFAULT 0,
|
||||
games INTEGER NOT NULL DEFAULT 0, -- 이번 시즌
|
||||
wins INTEGER NOT NULL DEFAULT 0, -- 이번 시즌
|
||||
total_games INTEGER NOT NULL DEFAULT 0, -- 누적 (배치 판정용)
|
||||
last_played INTEGER
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ratings_tr ON ratings(tr DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS matches (
|
||||
id TEXT NOT NULL,
|
||||
season INTEGER,
|
||||
mode TEXT NOT NULL, -- 'league' | 'custom'
|
||||
finished_at INTEGER,
|
||||
room_size INTEGER,
|
||||
p1 TEXT NOT NULL, -- 커스텀 FFA 는 p1 = 본인, score1 = 순위
|
||||
p2 TEXT,
|
||||
score1 INTEGER,
|
||||
score2 INTEGER,
|
||||
tr_delta1 INTEGER,
|
||||
tr_delta2 INTEGER,
|
||||
PRIMARY KEY (id, p1)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS matches_p1 ON matches(p1, finished_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS matches_p2 ON matches(p2, finished_at DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS solo_records (
|
||||
user_id TEXT NOT NULL,
|
||||
mode TEXT NOT NULL, -- 'sprint'(ms, 낮을수록 좋음) | 'time' | 'endless'(점수)
|
||||
best INTEGER NOT NULL,
|
||||
updated_at INTEGER,
|
||||
PRIMARY KEY (user_id, mode)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS solo_mode_best ON solo_records(mode, best);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
1454
server/package-lock.json
generated
Normal file
1454
server/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
14
server/package.json
Normal file
14
server/package.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "tetrig-server",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "node --test test/*.test.js",
|
||||
"dev": "wrangler dev --local",
|
||||
"deploy": "wrangler deploy"
|
||||
},
|
||||
"devDependencies": {
|
||||
"wrangler": "^4.40.0"
|
||||
}
|
||||
}
|
||||
128
server/scripts/e2e.mjs
Normal file
128
server/scripts/e2e.mjs
Normal file
@@ -0,0 +1,128 @@
|
||||
// 실서버(로컬 wrangler dev 또는 배포본) 대상 종단 테스트. node scripts/e2e.mjs [baseUrl]
|
||||
const BASE = process.argv[2] || "http://127.0.0.1:8799";
|
||||
const WS = BASE.replace(/^http/, "ws");
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
let fails = 0;
|
||||
const check = (cond, label) => { console.log(`${cond ? "✓" : "✗"} ${label}`); if (!cond) fails++; };
|
||||
|
||||
async function api(path, { method = "GET", token, body } = {}) {
|
||||
const res = await fetch(BASE + path, {
|
||||
method, headers: { "Content-Type": "application/json", ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
return { status: res.status, data: await res.json().catch(() => null) };
|
||||
}
|
||||
|
||||
function client(url, name) {
|
||||
const ws = new WebSocket(url);
|
||||
const inbox = [];
|
||||
const waiters = [];
|
||||
ws.onmessage = (e) => {
|
||||
const m = JSON.parse(e.data);
|
||||
inbox.push(m);
|
||||
for (const w of [...waiters]) if (w.pred(m)) { waiters.splice(waiters.indexOf(w), 1); w.res(m); }
|
||||
};
|
||||
const open = new Promise((res, rej) => { ws.onopen = res; ws.onerror = () => rej(new Error(name + " ws error")); });
|
||||
return {
|
||||
ws, inbox, open, name,
|
||||
send: (m) => ws.send(JSON.stringify(m)),
|
||||
wait(pred, ms = 8000) {
|
||||
const hit = inbox.find(pred);
|
||||
if (hit) { inbox.splice(inbox.indexOf(hit), 1); return Promise.resolve(hit); }
|
||||
return new Promise((res, rej) => {
|
||||
const w = { pred, res: (m) => { clearTimeout(to); inbox.splice(inbox.indexOf(m), 1); res(m); } };
|
||||
const to = setTimeout(() => rej(new Error(`${name}: timeout waiting`)), ms);
|
||||
waiters.push(w);
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const guests = [];
|
||||
for (let i = 0; i < 4; i++) guests.push((await api("/api/guest", { method: "POST", body: { deviceId: "dev" + i } })).data);
|
||||
check(guests.every((g) => g.token && g.user.guest), "게스트 4명 발급: " + guests.map((g) => g.user.nickname).join(", "));
|
||||
|
||||
// ── 커스텀 FFA ──
|
||||
const { data: room } = await api("/api/rooms", { method: "POST", token: guests[0].token, body: { rules: { ft: 1 } } });
|
||||
check(/^[A-HJ-NP-Z2-9]{6}$/.test(room.code), "방 코드 발급 " + room.code);
|
||||
check((await api(`/api/rooms/${room.code}`)).data.exists, "방 조회");
|
||||
check(!(await api(`/api/rooms/ZZZZZZ`)).data.exists, "없는 방은 exists=false");
|
||||
const cs = guests.map((g, i) => client(`${WS}/ws/room/${room.code}?token=${g.token}`, "p" + i));
|
||||
for (const c of cs) { await c.open; await c.wait((m) => m.t === "sync"); }
|
||||
const lobby = await cs[0].wait((m) => m.t === "lobby" && m.players.length === 4);
|
||||
check(lobby.host === guests[0].user.id && lobby.rules.ft === 1, "로비 4인, 호스트=p0, FT1");
|
||||
cs[0].send({ t: "start" });
|
||||
const rs = await Promise.all(cs.map((c) => c.wait((m) => m.t === "round_start")));
|
||||
check(rs.every((m) => m.seed > 0 && m.startIn === 3000), "4명 모두 round_start(seed) 수신");
|
||||
await sleep(3100);
|
||||
const ids = guests.map((g) => g.user.id);
|
||||
cs[0].send({ t: "target", id: ids[2] });
|
||||
cs[0].send({ t: "attack", lines: 4, pieces: 2 });
|
||||
const g2 = await cs[2].wait((m) => m.t === "garbage");
|
||||
check(g2.from === ids[0] && g2.lines === 4, "p0 → p2 가비지 4줄 (수동 타겟)");
|
||||
cs[1].send({ t: "board", grid: ".".repeat(190) + "GGGGGGGGG.", lock: true });
|
||||
const b = await cs[3].wait((m) => m.t === "board");
|
||||
check(b.id === ids[1], "보드 스냅샷 중계");
|
||||
cs[2].send({ t: "topout" });
|
||||
const ko = await cs[0].wait((m) => m.t === "ko" && m.who === ids[2]);
|
||||
check(ko.by === ids[0] && ko.place === 4, "KO 피드: p0 → p2 격추 (4위)");
|
||||
cs[1].send({ t: "topout" }); cs[3].send({ t: "topout" });
|
||||
const me = await cs[0].wait((m) => m.t === "match_end");
|
||||
check(me.winner === ids[0] && me.result[0].id === ids[0], "FT1 매치 종료, 우승 p0");
|
||||
cs[1].send({ t: "rematch", vote: true }); cs[2].send({ t: "rematch", vote: true }); cs[3].send({ t: "rematch", vote: true });
|
||||
check((await cs[0].wait((m) => m.t === "round_start")).n === 1, "리매치 과반 → 새 경기 1라운드");
|
||||
for (const c of cs) c.ws.close();
|
||||
|
||||
// ── 계정 ──
|
||||
const email = `t${Date.now()}@ex.com`;
|
||||
const sprint = await api("/api/solo", { method: "POST", token: guests[0].token, body: { mode: "sprint", value: 65000 } });
|
||||
check(sprint.data.improved, "게스트 솔로 기록 저장");
|
||||
const reg = await api("/api/register", { method: "POST", token: guests[0].token, body: { email, password: "password1", nickname: "테스터" + (Date.now() % 1000) } });
|
||||
check(reg.status === 200 && !reg.data.user.guest && reg.data.user.id === ids[0], "게스트 → 이메일 계정 승격(같은 ID)");
|
||||
const meRes = await api("/api/me", { token: reg.data.token });
|
||||
check(meRes.data.solo.sprint === 65000 && meRes.data.recent.some((m) => m.mode === "custom"), "승격 후 솔로 기록·커스텀 전적 유지");
|
||||
check((await api("/api/login", { method: "POST", body: { email, password: "wrong-pass" } })).status === 401, "틀린 비밀번호 401");
|
||||
await api("/api/solo", { method: "POST", token: guests[1].token, body: { mode: "sprint", value: 50000 } });
|
||||
const login = await api("/api/login", { method: "POST", token: guests[1].token, body: { email, password: "password1" } });
|
||||
check(login.status === 200 && login.data.user.id === ids[0], "로그인 성공");
|
||||
const me2 = await api("/api/me", { token: login.data.token });
|
||||
check(me2.data.solo.sprint === 50000, "로그인 시 게스트 기록 병합 (더 좋은 기록 50.000)");
|
||||
check((await api("/api/nickname", { method: "POST", token: login.data.token, body: { nickname: "다른닉" } })).status === 429, "닉 변경 30일 쿨다운");
|
||||
check((await api("/api/nickname/check?n=재빠른미노123")).data.ok === false, "게스트명 패턴 예약");
|
||||
|
||||
// ── 리그 ──
|
||||
const acct = [login.data];
|
||||
const reg2 = await api("/api/register", { method: "POST", body: { email: "b" + email, password: "password2" } });
|
||||
acct.push(reg2.data);
|
||||
const gq = client(`${WS}/ws/queue?token=${guests[2].token}`, "gq");
|
||||
const gqErr = await gq.open.then(() => "opened", () => "rejected");
|
||||
check(gqErr === "rejected", "게스트는 리그 큐 접속 거부");
|
||||
const qa = client(`${WS}/ws/queue?token=${acct[0].token}`, "qa");
|
||||
const qb = client(`${WS}/ws/queue?token=${acct[1].token}`, "qb");
|
||||
await qa.open; await qb.open;
|
||||
const [ma, mb] = await Promise.all([qa.wait((m) => m.t === "matched"), qb.wait((m) => m.t === "matched")]);
|
||||
check(ma.room === mb.room && ma.ft === 3, "매칭 성사 (FT3) " + ma.room.slice(0, 8));
|
||||
const la = client(`${WS}/ws/league/${ma.room}?token=${acct[0].token}`, "la");
|
||||
const lb = client(`${WS}/ws/league/${ma.room}?token=${acct[1].token}`, "lb");
|
||||
await la.open; await lb.open;
|
||||
for (let r = 1; r <= 3; r++) {
|
||||
await la.wait((m) => m.t === "round_start", 10000);
|
||||
await lb.wait((m) => m.t === "round_start", 10000);
|
||||
await sleep(3100);
|
||||
lb.send({ t: "topout" });
|
||||
await la.wait((m) => m.t === "round_end");
|
||||
}
|
||||
const [ea, eb] = await Promise.all([la.wait((m) => m.t === "match_end"), lb.wait((m) => m.t === "match_end")]);
|
||||
check(ea.winner === acct[0].user.id && ea.trDelta > 0 && eb.trDelta < 0, `리그 결과 TR 반영 (승 +${ea.trDelta} / 패 ${eb.trDelta})`);
|
||||
const meL = await api("/api/me", { token: acct[0].token });
|
||||
check(meL.data.league.placement === 1 && meL.data.league.tr === null && meL.data.recent[0].mode === "league", "배치 1/10, TR 비공개, 리그 전적 기록");
|
||||
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);
|
||||
99
server/src/auth.js
Normal file
99
server/src/auth.js
Normal file
@@ -0,0 +1,99 @@
|
||||
// 세션 토큰(HMAC), 비밀번호(PBKDF2), Google ID 토큰 검증. WebCrypto 만 사용.
|
||||
import { PBKDF2_ITER, TOKEN_TTL_MS } from "./rules.js";
|
||||
|
||||
const enc = new TextEncoder();
|
||||
|
||||
export function b64url(bytes) {
|
||||
let s = "";
|
||||
for (const b of new Uint8Array(bytes)) s += String.fromCharCode(b);
|
||||
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
||||
}
|
||||
export function unb64url(s) {
|
||||
s = s.replace(/-/g, "+").replace(/_/g, "/");
|
||||
while (s.length % 4) s += "=";
|
||||
const bin = atob(s);
|
||||
const out = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
||||
return out;
|
||||
}
|
||||
|
||||
async function hmacKey(secret) {
|
||||
return crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
|
||||
}
|
||||
|
||||
/** 토큰 = base64url(JSON{uid, exp}) + "." + base64url(HMAC). */
|
||||
export async function signToken(secret, uid, now = Date.now()) {
|
||||
const body = b64url(enc.encode(JSON.stringify({ uid, exp: now + TOKEN_TTL_MS })));
|
||||
const sig = await crypto.subtle.sign("HMAC", await hmacKey(secret), enc.encode(body));
|
||||
return `${body}.${b64url(sig)}`;
|
||||
}
|
||||
|
||||
export async function verifyToken(secret, token, now = Date.now()) {
|
||||
if (typeof token !== "string") return null;
|
||||
const [body, sig] = token.split(".");
|
||||
if (!body || !sig) return null;
|
||||
let ok = false;
|
||||
try {
|
||||
ok = await crypto.subtle.verify("HMAC", await hmacKey(secret), unb64url(sig), enc.encode(body));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!ok) return null;
|
||||
try {
|
||||
const p = JSON.parse(new TextDecoder().decode(unb64url(body)));
|
||||
if (typeof p.uid !== "string" || typeof p.exp !== "number" || p.exp < now) return null;
|
||||
return p;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function hashPassword(password, saltB64 = null) {
|
||||
const salt = saltB64 ? unb64url(saltB64) : crypto.getRandomValues(new Uint8Array(16));
|
||||
const key = await crypto.subtle.importKey("raw", enc.encode(password), "PBKDF2", false, ["deriveBits"]);
|
||||
const bits = await crypto.subtle.deriveBits({ name: "PBKDF2", hash: "SHA-256", salt, iterations: PBKDF2_ITER }, key, 256);
|
||||
return { hash: b64url(bits), salt: b64url(salt) };
|
||||
}
|
||||
|
||||
export function timingSafeEqual(a, b) {
|
||||
if (a.length !== b.length) return false;
|
||||
let d = 0;
|
||||
for (let i = 0; i < a.length; i++) d |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
||||
return d === 0;
|
||||
}
|
||||
|
||||
// ── Google ID 토큰 (RS256) ──
|
||||
let jwksCache = { at: 0, keys: [] };
|
||||
async function googleKeys(fetchFn = fetch) {
|
||||
if (Date.now() - jwksCache.at < 3600_000 && jwksCache.keys.length) return jwksCache.keys;
|
||||
const res = await fetchFn("https://www.googleapis.com/oauth2/v3/certs");
|
||||
const { keys } = await res.json();
|
||||
jwksCache = { at: Date.now(), keys };
|
||||
return keys;
|
||||
}
|
||||
|
||||
/** 검증되면 payload({sub, email, …}), 아니면 null. audiences = 허용할 OAuth 클라이언트 ID 목록. */
|
||||
export async function verifyGoogleIdToken(idToken, audiences, fetchFn = fetch) {
|
||||
if (!idToken || !audiences.length) return null;
|
||||
const parts = idToken.split(".");
|
||||
if (parts.length !== 3) return null;
|
||||
let header, payload;
|
||||
try {
|
||||
header = JSON.parse(new TextDecoder().decode(unb64url(parts[0])));
|
||||
payload = JSON.parse(new TextDecoder().decode(unb64url(parts[1])));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (header.alg !== "RS256") return null;
|
||||
const jwk = (await googleKeys(fetchFn)).find((k) => k.kid === header.kid);
|
||||
if (!jwk) return null;
|
||||
const key = await crypto.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]);
|
||||
const ok = await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key, unb64url(parts[2]), enc.encode(`${parts[0]}.${parts[1]}`));
|
||||
if (!ok) return null;
|
||||
const now = Date.now() / 1000;
|
||||
if (!["accounts.google.com", "https://accounts.google.com"].includes(payload.iss)) return null;
|
||||
if (!audiences.includes(payload.aud)) return null;
|
||||
if (typeof payload.exp !== "number" || payload.exp < now) return null;
|
||||
if (!payload.sub) return null;
|
||||
return payload;
|
||||
}
|
||||
162
server/src/db.js
Normal file
162
server/src/db.js
Normal file
@@ -0,0 +1,162 @@
|
||||
// D1 접근 헬퍼. Worker 와 DO 가 공유한다.
|
||||
import { glickoUpdate } from "./glicko.js";
|
||||
import {
|
||||
GLICKO, PLACEMENT_GAMES, RANK_VISIBLE_RD, RD_DECAY_IDLE_DAYS, RD_DECAY_PER_DAY, SEASON_LENGTH_DAYS,
|
||||
rankFor, trFor,
|
||||
} from "./rules.js";
|
||||
|
||||
const DAY = 24 * 3600 * 1000;
|
||||
|
||||
export async function getSeason(db, now = Date.now()) {
|
||||
const row = await db.prepare("SELECT value FROM meta WHERE key = 'season'").first();
|
||||
if (row) return JSON.parse(row.value);
|
||||
const s = { n: 1, startedAt: now, endsAt: now + SEASON_LENGTH_DAYS * DAY };
|
||||
await db.prepare("INSERT OR IGNORE INTO meta(key, value) VALUES ('season', ?)").bind(JSON.stringify(s)).run();
|
||||
return s;
|
||||
}
|
||||
|
||||
export async function getUser(db, uid) {
|
||||
return db.prepare("SELECT * FROM users WHERE id = ?").bind(uid).first();
|
||||
}
|
||||
|
||||
export function publicUser(u) {
|
||||
if (!u) return null;
|
||||
return {
|
||||
id: u.id, nickname: u.nickname, guest: !!u.is_guest, email: u.email ?? null,
|
||||
google: !!u.google_sub, nicknameChangedAt: u.nickname_changed_at ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getRating(db, uid) {
|
||||
const r = await db.prepare("SELECT * FROM ratings WHERE user_id = ?").bind(uid).first();
|
||||
if (r) return r;
|
||||
return {
|
||||
user_id: uid, season: 0, glicko: GLICKO.R, rd: GLICKO.RD, vol: GLICKO.VOL, tr: trFor(GLICKO.R, GLICKO.RD),
|
||||
games: 0, wins: 0, total_games: 0, last_played: null, _new: true,
|
||||
};
|
||||
}
|
||||
|
||||
/** 클라이언트 표시용 레이팅 요약 (배치 중이면 TR 비공개, RD<100 일 때만 랭크). */
|
||||
export function ratingView(r) {
|
||||
const placed = r.total_games >= PLACEMENT_GAMES;
|
||||
return {
|
||||
placed,
|
||||
placement: Math.min(r.total_games, PLACEMENT_GAMES),
|
||||
tr: placed ? r.tr : null,
|
||||
rank: placed && r.rd < RANK_VISIBLE_RD ? rankFor(r.tr) : null,
|
||||
rd: Math.round(r.rd),
|
||||
games: r.games,
|
||||
wins: r.wins,
|
||||
totalGames: r.total_games,
|
||||
};
|
||||
}
|
||||
|
||||
async function putRating(db, r) {
|
||||
await db
|
||||
.prepare(
|
||||
`INSERT INTO ratings(user_id, season, glicko, rd, vol, tr, games, wins, total_games, last_played)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
|
||||
ON CONFLICT(user_id) DO UPDATE SET season=?2, glicko=?3, rd=?4, vol=?5, tr=?6, games=?7, wins=?8,
|
||||
total_games=?9, last_played=?10`,
|
||||
)
|
||||
.bind(r.user_id, r.season, r.glicko, r.rd, r.vol, r.tr, r.games, r.wins, r.total_games, r.last_played)
|
||||
.run();
|
||||
}
|
||||
|
||||
/** 리그 경기 종료: 양측 Glicko-2 동시 갱신 + 전적 기록. 반환 {[uid]: {trDelta, before, after}} */
|
||||
export async function applyLeagueResult(db, { matchId, winner, loser, score }, now = Date.now()) {
|
||||
const season = (await getSeason(db, now)).n;
|
||||
const [w, l] = await Promise.all([getRating(db, winner), getRating(db, loser)]);
|
||||
const nw = glickoUpdate({ r: w.glicko, rd: w.rd, vol: w.vol }, [{ r: l.glicko, rd: l.rd, score: 1 }]);
|
||||
const nl = glickoUpdate({ r: l.glicko, rd: l.rd, vol: l.vol }, [{ r: w.glicko, rd: w.rd, score: 0 }]);
|
||||
const upd = (old, n, won) => ({
|
||||
...old, season, glicko: n.r, rd: n.rd, vol: n.vol, tr: trFor(n.r, n.rd),
|
||||
games: (old.season === season ? old.games : 0) + 1,
|
||||
wins: (old.season === season ? old.wins : 0) + (won ? 1 : 0),
|
||||
total_games: old.total_games + 1, last_played: now,
|
||||
});
|
||||
const W = upd(w, nw, true);
|
||||
const L = upd(l, nl, false);
|
||||
await putRating(db, W);
|
||||
await putRating(db, L);
|
||||
const dW = W.tr - w.tr;
|
||||
const dL = L.tr - l.tr;
|
||||
await db
|
||||
.prepare(
|
||||
`INSERT OR IGNORE INTO matches(id, season, mode, finished_at, room_size, p1, p2, score1, score2, tr_delta1, tr_delta2)
|
||||
VALUES (?, ?, 'league', ?, 2, ?, ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.bind(matchId, season, now, winner, loser, score[winner] ?? 0, score[loser] ?? 0, dW, dL)
|
||||
.run();
|
||||
return {
|
||||
[winner]: { trDelta: dW, before: ratingView(w), after: ratingView(W), won: true },
|
||||
[loser]: { trDelta: dL, before: ratingView(l), after: ratingView(L), won: false },
|
||||
};
|
||||
}
|
||||
|
||||
export async function recordCustom(db, { matchId, standings, size }, now = Date.now()) {
|
||||
const season = (await getSeason(db, now)).n;
|
||||
const stmts = standings.map((s) =>
|
||||
db
|
||||
.prepare(
|
||||
`INSERT OR IGNORE INTO matches(id, season, mode, finished_at, room_size, p1, score1, score2)
|
||||
VALUES (?, ?, 'custom', ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.bind(matchId, season, now, size, s.id, s.rank, s.wins),
|
||||
);
|
||||
if (stmts.length) await db.batch(stmts);
|
||||
}
|
||||
|
||||
/** 일일 Cron: RD 감쇠 + 시즌 마감. */
|
||||
export async function dailyMaintenance(db, now = Date.now()) {
|
||||
const idleBefore = now - RD_DECAY_IDLE_DAYS * DAY;
|
||||
await db
|
||||
.prepare("UPDATE ratings SET rd = MIN(?, rd + ?) WHERE last_played IS NOT NULL AND last_played < ?")
|
||||
.bind(GLICKO.RD_MAX, RD_DECAY_PER_DAY, idleBefore)
|
||||
.run();
|
||||
const s = await getSeason(db, now);
|
||||
if (now >= s.endsAt) {
|
||||
const next = { n: s.n + 1, startedAt: s.endsAt, endsAt: s.endsAt + SEASON_LENGTH_DAYS * DAY };
|
||||
await db.batch([
|
||||
db.prepare("UPDATE meta SET value = ? WHERE key = 'season'").bind(JSON.stringify(next)),
|
||||
// 시즌 소프트 리셋: R 유지, 불확실도(RD)를 최소 150 으로 올려 초반 변동폭을 키운다. 시즌 전적은 0부터.
|
||||
db.prepare("UPDATE ratings SET rd = MAX(rd, 150), games = 0, wins = 0, season = ?").bind(next.n),
|
||||
]);
|
||||
// TR 은 R/RD 에서 다시 계산
|
||||
const { results } = await db.prepare("SELECT user_id, glicko, rd FROM ratings").all();
|
||||
const stmts = results.map((r) => db.prepare("UPDATE ratings SET tr = ? WHERE user_id = ?").bind(trFor(r.glicko, r.rd), r.user_id));
|
||||
for (let i = 0; i < stmts.length; i += 50) await db.batch(stmts.slice(i, i + 50));
|
||||
return { rolled: true, season: next.n };
|
||||
}
|
||||
return { rolled: false, season: s.n };
|
||||
}
|
||||
|
||||
export const soloBetter = (mode, a, b) => (mode === "sprint" ? a < b : a > b);
|
||||
|
||||
/** 게스트 → 계정 기록 이전 (더 좋은 기록 우선). 게스트 행은 삭제해 닉네임을 반환한다. */
|
||||
export async function mergeGuestInto(db, guestId, userId) {
|
||||
if (!guestId || guestId === userId) return;
|
||||
const g = await getUser(db, guestId);
|
||||
if (!g || !g.is_guest) return;
|
||||
const { results } = await db.prepare("SELECT mode, best FROM solo_records WHERE user_id = ?").bind(guestId).all();
|
||||
for (const rec of results) await submitSolo(db, userId, rec.mode, rec.best);
|
||||
await db.batch([
|
||||
db.prepare("UPDATE OR IGNORE matches SET p1 = ? WHERE p1 = ? AND mode = 'custom'").bind(userId, guestId),
|
||||
db.prepare("DELETE FROM solo_records WHERE user_id = ?").bind(guestId),
|
||||
db.prepare("DELETE FROM matches WHERE p1 = ? AND mode = 'custom'").bind(guestId),
|
||||
db.prepare("DELETE FROM users WHERE id = ? AND is_guest = 1").bind(guestId),
|
||||
]);
|
||||
}
|
||||
|
||||
export async function submitSolo(db, uid, mode, value, now = Date.now()) {
|
||||
const cur = await db.prepare("SELECT best FROM solo_records WHERE user_id = ? AND mode = ?").bind(uid, mode).first();
|
||||
if (cur && !soloBetter(mode, value, cur.best)) return { improved: false, best: cur.best };
|
||||
await db
|
||||
.prepare(
|
||||
`INSERT INTO solo_records(user_id, mode, best, updated_at) VALUES (?1, ?2, ?3, ?4)
|
||||
ON CONFLICT(user_id, mode) DO UPDATE SET best = ?3, updated_at = ?4`,
|
||||
)
|
||||
.bind(uid, mode, value, now)
|
||||
.run();
|
||||
return { improved: true, best: value };
|
||||
}
|
||||
76
server/src/glicko.js
Normal file
76
server/src/glicko.js
Normal file
@@ -0,0 +1,76 @@
|
||||
// Glicko-2 (Glickman 2013, http://www.glicko.net/glicko/glicko2.pdf). 경기 1건 = 레이팅 기간 1개로 처리.
|
||||
import { GLICKO } from "./rules.js";
|
||||
|
||||
const SCALE = 173.7178;
|
||||
const EPS = 1e-6;
|
||||
|
||||
const g = (phi) => 1 / Math.sqrt(1 + (3 * phi * phi) / (Math.PI * Math.PI));
|
||||
const E = (mu, muj, phij) => 1 / (1 + Math.exp(-g(phij) * (mu - muj)));
|
||||
|
||||
/**
|
||||
* player = {r, rd, vol}, results = [{r, rd, score}] (score 1 승 / 0 패 / 0.5 무).
|
||||
* 반환: 새 {r, rd, vol}. RD 는 [RD_MIN, RD_MAX] 로 자른다.
|
||||
*/
|
||||
export function glickoUpdate(player, results, tau = GLICKO.TAU) {
|
||||
const mu = (player.r - 1500) / SCALE;
|
||||
const phi = player.rd / SCALE;
|
||||
const sigma = player.vol;
|
||||
|
||||
if (!results.length) {
|
||||
const phiStar = Math.sqrt(phi * phi + sigma * sigma);
|
||||
return clamp({ r: player.r, rd: phiStar * SCALE, vol: sigma });
|
||||
}
|
||||
|
||||
let vInv = 0;
|
||||
let deltaSum = 0;
|
||||
for (const o of results) {
|
||||
const muj = (o.r - 1500) / SCALE;
|
||||
const phij = o.rd / SCALE;
|
||||
const e = E(mu, muj, phij);
|
||||
const gj = g(phij);
|
||||
vInv += gj * gj * e * (1 - e);
|
||||
deltaSum += gj * (o.score - e);
|
||||
}
|
||||
const v = 1 / vInv;
|
||||
const delta = v * deltaSum;
|
||||
|
||||
// 변동성 σ' — Illinois 알고리즘
|
||||
const a = Math.log(sigma * sigma);
|
||||
const f = (x) => {
|
||||
const ex = Math.exp(x);
|
||||
return (ex * (delta * delta - phi * phi - v - ex)) / (2 * Math.pow(phi * phi + v + ex, 2)) - (x - a) / (tau * tau);
|
||||
};
|
||||
let A = a;
|
||||
let B;
|
||||
if (delta * delta > phi * phi + v) {
|
||||
B = Math.log(delta * delta - phi * phi - v);
|
||||
} else {
|
||||
let k = 1;
|
||||
while (f(a - k * tau) < 0) k++;
|
||||
B = a - k * tau;
|
||||
}
|
||||
let fA = f(A);
|
||||
let fB = f(B);
|
||||
for (let i = 0; i < 100 && Math.abs(B - A) > EPS; i++) {
|
||||
const C = A + ((A - B) * fA) / (fB - fA);
|
||||
const fC = f(C);
|
||||
if (fC * fB <= 0) {
|
||||
A = B;
|
||||
fA = fB;
|
||||
} else {
|
||||
fA /= 2;
|
||||
}
|
||||
B = C;
|
||||
fB = fC;
|
||||
}
|
||||
const sigmaNew = Math.exp(A / 2);
|
||||
|
||||
const phiStar = Math.sqrt(phi * phi + sigmaNew * sigmaNew);
|
||||
const phiNew = 1 / Math.sqrt(1 / (phiStar * phiStar) + 1 / v);
|
||||
const muNew = mu + phiNew * phiNew * deltaSum;
|
||||
return clamp({ r: muNew * SCALE + 1500, rd: phiNew * SCALE, vol: sigmaNew });
|
||||
}
|
||||
|
||||
function clamp(p) {
|
||||
return { r: p.r, rd: Math.min(GLICKO.RD_MAX, Math.max(GLICKO.RD_MIN, p.rd)), vol: p.vol };
|
||||
}
|
||||
322
server/src/index.js
Normal file
322
server/src/index.js
Normal file
@@ -0,0 +1,322 @@
|
||||
// TETRIG Worker — REST API + WebSocket 라우팅 + Cron.
|
||||
import { hashPassword, signToken, timingSafeEqual, verifyGoogleIdToken, verifyToken } from "./auth.js";
|
||||
import {
|
||||
dailyMaintenance, getRating, getSeason, getUser, mergeGuestInto, publicUser, ratingView, submitSolo,
|
||||
} from "./db.js";
|
||||
import {
|
||||
BRAND, NICK_COOLDOWN_MS, NICK_RE, SOLO_MODES, isRoomCode, looksLikeGuestName, randomGuestName, randomRoomCode,
|
||||
} from "./rules.js";
|
||||
|
||||
export { GameRoomDO } from "./room.js";
|
||||
export { MatchmakerDO } from "./matchmaker.js";
|
||||
|
||||
const CORS = {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
||||
};
|
||||
|
||||
const json = (data, status = 200) => Response.json(data, { status, headers: CORS });
|
||||
const err = (msg, status = 400) => json({ error: msg }, status);
|
||||
|
||||
async function body(req) {
|
||||
try {
|
||||
return await req.json();
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function secret(env) {
|
||||
if (!env.TOKEN_SECRET) throw new Error("TOKEN_SECRET 미설정");
|
||||
return env.TOKEN_SECRET;
|
||||
}
|
||||
|
||||
async function authUser(req, env, url) {
|
||||
const h = req.headers.get("Authorization") || "";
|
||||
const token = h.startsWith("Bearer ") ? h.slice(7) : url?.searchParams.get("token");
|
||||
const p = await verifyToken(secret(env), token);
|
||||
if (!p) return null;
|
||||
return getUser(env.DB, p.uid);
|
||||
}
|
||||
|
||||
async function issue(env, user) {
|
||||
return { token: await signToken(secret(env), user.id), user: publicUser(user) };
|
||||
}
|
||||
|
||||
async function uniqueGuestName(db) {
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const n = randomGuestName();
|
||||
const hit = await db.prepare("SELECT 1 FROM users WHERE nickname = ?").bind(n).first();
|
||||
if (!hit) return n;
|
||||
}
|
||||
return "게스트" + crypto.randomUUID().slice(0, 6);
|
||||
}
|
||||
|
||||
async function nicknameProblem(db, nick, selfId = null) {
|
||||
if (typeof nick !== "string" || !NICK_RE.test(nick)) return "닉네임은 2~12자의 한글·영문·숫자·_ 만 쓸 수 있습니다";
|
||||
if (looksLikeGuestName(nick)) return "게스트 이름 형식은 쓸 수 없습니다";
|
||||
const hit = await db.prepare("SELECT id FROM users WHERE nickname = ? COLLATE NOCASE").bind(nick).first();
|
||||
if (hit && hit.id !== selfId) return "이미 사용 중인 닉네임입니다";
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 유저 + 리그 요약 (WS 헤더로 DO 에 넘기는 정보). */
|
||||
async function playerInfo(env, u) {
|
||||
const r = await getRating(env.DB, u.id);
|
||||
const v = ratingView(r);
|
||||
return { nick: u.nickname, guest: !!u.is_guest, tr: v.tr, rank: v.rank, r: r.glicko, rd: r.rd };
|
||||
}
|
||||
|
||||
async function routeWs(req, env, url, u, ns, name, path = "/ws") {
|
||||
if (req.headers.get("Upgrade") !== "websocket") return err("websocket only", 426);
|
||||
const stub = ns.get(ns.idFromName(name));
|
||||
const headers = new Headers(req.headers);
|
||||
headers.set("x-uid", u.id);
|
||||
headers.set("x-info", encodeURIComponent(JSON.stringify(await playerInfo(env, u)))); // 헤더는 ASCII 만 안전
|
||||
return stub.fetch(new Request(`https://do${path}`, { headers }));
|
||||
}
|
||||
|
||||
async function handle(req, env) {
|
||||
const url = new URL(req.url);
|
||||
const path = url.pathname;
|
||||
if (req.method === "OPTIONS") return new Response(null, { headers: CORS });
|
||||
const db = env.DB;
|
||||
|
||||
if (path === "/" || path === "/api/health") {
|
||||
return json({ ok: true, name: BRAND, season: (await getSeason(db)).n });
|
||||
}
|
||||
|
||||
// ── 계정 ──
|
||||
if (path === "/api/guest" && req.method === "POST") {
|
||||
const b = await body(req);
|
||||
const id = crypto.randomUUID();
|
||||
const nickname = await uniqueGuestName(db);
|
||||
await db
|
||||
.prepare("INSERT INTO users(id, nickname, is_guest, device_id, created_at) VALUES (?, ?, 1, ?, ?)")
|
||||
.bind(id, nickname, typeof b.deviceId === "string" ? b.deviceId.slice(0, 64) : null, Date.now())
|
||||
.run();
|
||||
return json(await issue(env, await getUser(db, id)));
|
||||
}
|
||||
|
||||
if (path === "/api/register" && req.method === "POST") {
|
||||
const b = await body(req);
|
||||
const email = String(b.email || "").trim().toLowerCase();
|
||||
const password = String(b.password || "");
|
||||
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) return err("이메일 형식이 올바르지 않습니다");
|
||||
if (password.length < 8) return err("비밀번호는 8자 이상이어야 합니다");
|
||||
if (await db.prepare("SELECT 1 FROM users WHERE email = ?").bind(email).first()) return err("이미 가입된 이메일입니다", 409);
|
||||
const me = await authUser(req, env, url);
|
||||
let nickname = b.nickname ? String(b.nickname) : null;
|
||||
if (nickname) {
|
||||
const p = await nicknameProblem(db, nickname, me?.id);
|
||||
if (p) return err(p);
|
||||
}
|
||||
const { hash, salt } = await hashPassword(password);
|
||||
const now = Date.now();
|
||||
if (me && me.is_guest) {
|
||||
// 지금 쓰는 게스트 계정을 그대로 정식 계정으로 승격 → 기록이 자동으로 따라온다.
|
||||
await db
|
||||
.prepare("UPDATE users SET is_guest = 0, email = ?, pw_hash = ?, pw_salt = ?, nickname = COALESCE(?, nickname), nickname_changed_at = ? WHERE id = ?")
|
||||
.bind(email, hash, salt, nickname, nickname ? now : null, me.id)
|
||||
.run();
|
||||
return json(await issue(env, await getUser(db, me.id)));
|
||||
}
|
||||
const id = crypto.randomUUID();
|
||||
await db
|
||||
.prepare("INSERT INTO users(id, nickname, is_guest, email, pw_hash, pw_salt, created_at, nickname_changed_at) VALUES (?, ?, 0, ?, ?, ?, ?, ?)")
|
||||
.bind(id, nickname ?? (await uniqueGuestName(db)), email, hash, salt, now, nickname ? now : null)
|
||||
.run();
|
||||
return json(await issue(env, await getUser(db, id)));
|
||||
}
|
||||
|
||||
if (path === "/api/login" && req.method === "POST") {
|
||||
const b = await body(req);
|
||||
const email = String(b.email || "").trim().toLowerCase();
|
||||
const u = await db.prepare("SELECT * FROM users WHERE email = ?").bind(email).first();
|
||||
if (!u || !u.pw_hash) return err("이메일 또는 비밀번호가 맞지 않습니다", 401);
|
||||
const { hash } = await hashPassword(String(b.password || ""), u.pw_salt);
|
||||
if (!timingSafeEqual(hash, u.pw_hash)) return err("이메일 또는 비밀번호가 맞지 않습니다", 401);
|
||||
const me = await authUser(req, env, url);
|
||||
if (me && me.is_guest) await mergeGuestInto(db, me.id, u.id);
|
||||
return json(await issue(env, u));
|
||||
}
|
||||
|
||||
if (path === "/api/google" && req.method === "POST") {
|
||||
const auds = String(env.GOOGLE_CLIENT_IDS || "").split(",").map((s) => s.trim()).filter(Boolean);
|
||||
if (!auds.length) return err("Google 로그인이 아직 설정되지 않았습니다", 503);
|
||||
const b = await body(req);
|
||||
const g = await verifyGoogleIdToken(b.idToken, auds);
|
||||
if (!g) return err("Google 인증에 실패했습니다", 401);
|
||||
const me = await authUser(req, env, url);
|
||||
let u = await db.prepare("SELECT * FROM users WHERE google_sub = ?").bind(g.sub).first();
|
||||
if (!u && me && me.is_guest) {
|
||||
await db.prepare("UPDATE users SET is_guest = 0, google_sub = ? WHERE id = ?").bind(g.sub, me.id).run();
|
||||
u = await getUser(db, me.id);
|
||||
} else if (!u) {
|
||||
const id = crypto.randomUUID();
|
||||
await db
|
||||
.prepare("INSERT INTO users(id, nickname, is_guest, google_sub, created_at) VALUES (?, ?, 0, ?, ?)")
|
||||
.bind(id, await uniqueGuestName(db), g.sub, Date.now())
|
||||
.run();
|
||||
u = await getUser(db, id);
|
||||
} else if (me && me.is_guest) {
|
||||
await mergeGuestInto(db, me.id, u.id);
|
||||
}
|
||||
return json(await issue(env, u));
|
||||
}
|
||||
|
||||
if (path === "/api/nickname/check") {
|
||||
const p = await nicknameProblem(db, url.searchParams.get("n") || "");
|
||||
return json({ ok: !p, reason: p });
|
||||
}
|
||||
|
||||
// 이하 인증 필요
|
||||
const needAuth = path.startsWith("/api/me") || path === "/api/nickname" || path === "/api/solo" || path === "/api/rooms" || path.startsWith("/ws/");
|
||||
const me = needAuth ? await authUser(req, env, url) : null;
|
||||
if (needAuth && !me) return err("로그인이 필요합니다", 401);
|
||||
|
||||
if (path === "/api/me") {
|
||||
const r = await getRating(db, me.id);
|
||||
const { results: solo } = await db.prepare("SELECT mode, best FROM solo_records WHERE user_id = ?").bind(me.id).all();
|
||||
const { results: recent } = await db
|
||||
.prepare(
|
||||
`SELECT m.id, m.mode, m.finished_at, m.room_size, m.p1, m.p2, m.score1, m.score2, m.tr_delta1, m.tr_delta2,
|
||||
u1.nickname AS n1, u2.nickname AS n2
|
||||
FROM matches m LEFT JOIN users u1 ON u1.id = m.p1 LEFT JOIN users u2 ON u2.id = m.p2
|
||||
WHERE m.p1 = ?1 OR m.p2 = ?1 ORDER BY m.finished_at DESC LIMIT 20`,
|
||||
)
|
||||
.bind(me.id)
|
||||
.all();
|
||||
return json({
|
||||
user: publicUser(me),
|
||||
league: ratingView(r),
|
||||
season: await getSeason(db),
|
||||
solo: Object.fromEntries(solo.map((s) => [s.mode, s.best])),
|
||||
recent: recent.map((m) => {
|
||||
const mine = m.p1 === me.id;
|
||||
if (m.mode === "custom") return { id: m.id, mode: "custom", at: m.finished_at, size: m.room_size, place: m.score1, wins: m.score2 };
|
||||
return {
|
||||
id: m.id, mode: "league", at: m.finished_at, won: mine, opponent: mine ? m.n2 : m.n1,
|
||||
score: mine ? [m.score1, m.score2] : [m.score2, m.score1], trDelta: mine ? m.tr_delta1 : m.tr_delta2,
|
||||
};
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
// 계정 삭제 (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);
|
||||
const now = Date.now();
|
||||
if (me.nickname_changed_at && now - me.nickname_changed_at < NICK_COOLDOWN_MS) {
|
||||
const days = Math.ceil((me.nickname_changed_at + NICK_COOLDOWN_MS - now) / 86400000);
|
||||
return err(`닉네임은 30일에 한 번 바꿀 수 있습니다 (${days}일 남음)`, 429);
|
||||
}
|
||||
const p = await nicknameProblem(db, b.nickname, me.id);
|
||||
if (p) return err(p);
|
||||
await db.prepare("UPDATE users SET nickname = ?, nickname_changed_at = ? WHERE id = ?").bind(b.nickname, now, me.id).run();
|
||||
return json({ user: publicUser(await getUser(db, me.id)) });
|
||||
}
|
||||
|
||||
if (path === "/api/solo" && req.method === "POST") {
|
||||
const b = await body(req);
|
||||
if (!SOLO_MODES.includes(b.mode) || !Number.isInteger(b.value) || b.value <= 0) return err("잘못된 기록");
|
||||
// 최소 상식 검증: SPRINT 40줄 10초 미만은 불가능에 가깝다.
|
||||
if (b.mode === "sprint" && b.value < 10_000) return err("기록이 비정상입니다");
|
||||
return json(await submitSolo(db, me.id, b.mode, b.value));
|
||||
}
|
||||
|
||||
if (path.startsWith("/api/leaderboard")) {
|
||||
const board = url.searchParams.get("board") || "league";
|
||||
if (board === "league") {
|
||||
const { results } = await db
|
||||
.prepare(
|
||||
`SELECT u.id, u.nickname, r.tr, r.rd, r.games, r.wins, r.total_games FROM ratings r JOIN users u ON u.id = r.user_id
|
||||
WHERE u.is_guest = 0 AND r.total_games >= 10 ORDER BY r.tr DESC LIMIT 100`,
|
||||
)
|
||||
.all();
|
||||
return json({
|
||||
board,
|
||||
rows: results.map((r, i) => ({ pos: i + 1, id: r.id, nickname: r.nickname, ...ratingView({ ...r }) })),
|
||||
});
|
||||
}
|
||||
if (!SOLO_MODES.includes(board)) return err("unknown board");
|
||||
const order = board === "sprint" ? "ASC" : "DESC";
|
||||
const { results } = await db
|
||||
.prepare(
|
||||
`SELECT u.id, u.nickname, s.best FROM solo_records s JOIN users u ON u.id = s.user_id
|
||||
WHERE s.mode = ? AND u.is_guest = 0 ORDER BY s.best ${order} LIMIT 100`,
|
||||
)
|
||||
.bind(board)
|
||||
.all();
|
||||
return json({ board, rows: results.map((r, i) => ({ pos: i + 1, id: r.id, nickname: r.nickname, best: r.best })) });
|
||||
}
|
||||
|
||||
if (path === "/api/season") return json(await getSeason(db));
|
||||
|
||||
// ── 커스텀 방 ──
|
||||
if (path === "/api/rooms" && req.method === "POST") {
|
||||
const b = await body(req);
|
||||
for (let i = 0; i < 8; i++) {
|
||||
const code = randomRoomCode();
|
||||
const stub = env.ROOMS.get(env.ROOMS.idFromName(`custom:${code}`));
|
||||
const res = await stub.fetch("https://do/init", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ id: code, code, kind: "custom", rules: b.rules ?? {} }),
|
||||
});
|
||||
if (res.ok) return json({ code });
|
||||
}
|
||||
return err("방 코드를 만들지 못했습니다. 다시 시도해 주세요", 503);
|
||||
}
|
||||
|
||||
const roomInfo = /^\/api\/rooms\/([A-Z0-9]{6})$/.exec(path);
|
||||
if (roomInfo) {
|
||||
const code = roomInfo[1];
|
||||
if (!isRoomCode(code)) return json({ exists: false });
|
||||
const stub = env.ROOMS.get(env.ROOMS.idFromName(`custom:${code}`));
|
||||
return json(await (await stub.fetch("https://do/info")).json());
|
||||
}
|
||||
|
||||
// ── WebSocket ──
|
||||
const wsRoom = /^\/ws\/room\/([A-Z0-9]{6})$/.exec(path);
|
||||
if (wsRoom) {
|
||||
if (!isRoomCode(wsRoom[1])) return err("잘못된 코드", 404);
|
||||
const stub = env.ROOMS.get(env.ROOMS.idFromName(`custom:${wsRoom[1]}`));
|
||||
const info = await (await stub.fetch("https://do/info")).json();
|
||||
if (!info.exists) return err("없는 방입니다", 404);
|
||||
return routeWs(req, env, url, me, env.ROOMS, `custom:${wsRoom[1]}`);
|
||||
}
|
||||
const wsLeague = /^\/ws\/league\/([0-9a-f-]{36})$/.exec(path);
|
||||
if (wsLeague) return routeWs(req, env, url, me, env.ROOMS, `league:${wsLeague[1]}`);
|
||||
if (path === "/ws/queue") {
|
||||
if (me.is_guest) return err("리그전은 로그인 후 참가할 수 있습니다", 403);
|
||||
return routeWs(req, env, url, me, env.MATCHMAKER, "global", "/");
|
||||
}
|
||||
|
||||
return err("not found", 404);
|
||||
}
|
||||
|
||||
export default {
|
||||
async fetch(req, env) {
|
||||
try {
|
||||
return await handle(req, env);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return err("서버 오류", 500);
|
||||
}
|
||||
},
|
||||
async scheduled(_event, env) {
|
||||
await dailyMaintenance(env.DB);
|
||||
},
|
||||
};
|
||||
77
server/src/matchmaker.js
Normal file
77
server/src/matchmaker.js
Normal file
@@ -0,0 +1,77 @@
|
||||
// MatchmakerDO — 리그 대기열 싱글턴. 대기열 상태는 소켓 attachment 에만 둔다 (하이버네이션 안전).
|
||||
import { DurableObject } from "cloudflare:workers";
|
||||
import { findPairs } from "./matchmaking.js";
|
||||
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(decodeURIComponent(req.headers.get("x-info") || "%7B%7D"));
|
||||
for (const old of this.ctx.getWebSockets(uid)) {
|
||||
try {
|
||||
old.serializeAttachment({ ...old.deserializeAttachment(), gone: true });
|
||||
old.close(4000, "replaced");
|
||||
} catch {}
|
||||
}
|
||||
const [client, server] = Object.values(new WebSocketPair());
|
||||
this.ctx.acceptWebSocket(server, [uid]);
|
||||
server.serializeAttachment({ uid, r: info.r, rd: info.rd, tr: info.tr, nick: info.nick, rank: info.rank, joinedAt: Date.now() });
|
||||
server.send(JSON.stringify({ t: "queue", state: "waiting", waitMs: 0, hint: false }));
|
||||
await this.sweep();
|
||||
return new Response(null, { status: 101, webSocket: client });
|
||||
}
|
||||
|
||||
waiting() {
|
||||
return this.ctx
|
||||
.getWebSockets()
|
||||
.filter((ws) => ws.readyState === 1)
|
||||
.map((ws) => ({ ws, a: ws.deserializeAttachment() }))
|
||||
.filter((x) => x.a && !x.a.gone && !x.a.matched);
|
||||
}
|
||||
|
||||
async sweep() {
|
||||
const now = Date.now();
|
||||
const list = this.waiting();
|
||||
const byUid = new Map(list.map((x) => [x.a.uid, x]));
|
||||
const pairs = findPairs(list.map((x) => x.a), now);
|
||||
for (const [a, b] of pairs) {
|
||||
const roomId = crypto.randomUUID();
|
||||
const ft = leagueFt(a.tr ?? 0, b.tr ?? 0);
|
||||
const stub = this.env.ROOMS.get(this.env.ROOMS.idFromName(`league:${roomId}`));
|
||||
const res = await stub.fetch("https://room/init", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ id: roomId, kind: "league", allowed: [a.uid, b.uid], ft }),
|
||||
});
|
||||
if (!res.ok) continue;
|
||||
for (const [me, opp] of [[a, b], [b, a]]) {
|
||||
const x = byUid.get(me.uid);
|
||||
x.ws.serializeAttachment({ ...x.a, matched: true });
|
||||
x.ws.send(JSON.stringify({ t: "matched", room: roomId, ft, opponent: { id: opp.uid, nick: opp.nick, tr: opp.tr, rank: opp.rank } }));
|
||||
x.ws.close(1000, "matched");
|
||||
}
|
||||
}
|
||||
for (const x of this.waiting()) {
|
||||
const waitMs = now - x.a.joinedAt;
|
||||
x.ws.send(JSON.stringify({ t: "queue", state: "waiting", waitMs, hint: waitMs >= MM_HINT_AFTER_MS, size: this.waiting().length }));
|
||||
}
|
||||
if (this.waiting().length) await this.ctx.storage.setAlarm(now + SWEEP_MS);
|
||||
}
|
||||
|
||||
async alarm() {
|
||||
await this.sweep();
|
||||
}
|
||||
|
||||
async webSocketMessage(ws, data) {
|
||||
if (String(data).includes('"leave"')) ws.close(1000, "left");
|
||||
}
|
||||
|
||||
async webSocketClose() {}
|
||||
}
|
||||
38
server/src/matchmaking.js
Normal file
38
server/src/matchmaking.js
Normal file
@@ -0,0 +1,38 @@
|
||||
// 리그 매치메이킹 순수 로직 (§8.3). MatchmakerDO 가 대기열 스냅샷을 넘겨 짝을 받는다.
|
||||
import { MM_EXPAND_EVERY_MS, MM_EXPAND_FACTOR, MM_WINDOW_RD } from "./rules.js";
|
||||
|
||||
/** 대기 시간에 따라 넓어지는 탐색 반경 (R 기준 반폭). */
|
||||
export function windowFor(entry, now) {
|
||||
const steps = Math.floor(Math.max(0, now - entry.joinedAt) / MM_EXPAND_EVERY_MS);
|
||||
return MM_WINDOW_RD * entry.rd * Math.pow(MM_EXPAND_FACTOR, steps);
|
||||
}
|
||||
|
||||
/** 두 사람의 구간 [R-w, R+w] 가 겹치면 성사. */
|
||||
export function compatible(a, b, now) {
|
||||
return Math.abs(a.r - b.r) <= windowFor(a, now) + windowFor(b, now);
|
||||
}
|
||||
|
||||
/**
|
||||
* queue: [{uid, r, rd, joinedAt}] — 오래 기다린 순서로 우선 매칭, 그 안에서는 R 차이가 가장 작은 상대.
|
||||
* 반환: [[a, b], …]
|
||||
*/
|
||||
export function findPairs(queue, now) {
|
||||
const waiting = [...queue].sort((x, y) => x.joinedAt - y.joinedAt);
|
||||
const used = new Set();
|
||||
const pairs = [];
|
||||
for (const a of waiting) {
|
||||
if (used.has(a.uid)) continue;
|
||||
let best = null;
|
||||
for (const b of waiting) {
|
||||
if (b.uid === a.uid || used.has(b.uid)) continue;
|
||||
if (!compatible(a, b, now)) continue;
|
||||
if (!best || Math.abs(a.r - b.r) < Math.abs(a.r - best.r)) best = b;
|
||||
}
|
||||
if (best) {
|
||||
used.add(a.uid);
|
||||
used.add(best.uid);
|
||||
pairs.push([a, best]);
|
||||
}
|
||||
}
|
||||
return pairs;
|
||||
}
|
||||
490
server/src/room-logic.js
Normal file
490
server/src/room-logic.js
Normal file
@@ -0,0 +1,490 @@
|
||||
// 경기방 상태 기계 (리그 1:1 & 커스텀 N인 공용). 전송·저장과 분리된 순수 로직이라 node 로 테스트한다.
|
||||
// GameRoomDO(room.js)가 소켓 메시지를 handle() 로 넘기고, outbox/effects 를 비워 실제로 보낸다.
|
||||
import {
|
||||
AUTO_TARGET_MS, DEFAULT_RULES, MAX_ATTACK_PER_PIECE, MAX_PPS, RECONNECT_GRACE_MS,
|
||||
ROUND_COUNTDOWN_MS, ROUND_GAP_MS, overtimeMultiplier, sanitizeRules,
|
||||
} from "./rules.js";
|
||||
|
||||
const BOARD_W = 10;
|
||||
const BOARD_ROWS = 20;
|
||||
const BOARD_RE = /^[.IOTSZJLG]+$/;
|
||||
|
||||
export class RoomLogic {
|
||||
/**
|
||||
* opts: { id, kind: "custom"|"league", code?, allowed?: [uid, uid], ft?, now?, rand? }
|
||||
*/
|
||||
constructor(opts) {
|
||||
this.id = opts.id;
|
||||
this.kind = opts.kind;
|
||||
this.code = opts.code ?? null;
|
||||
this.allowed = opts.allowed ?? null;
|
||||
this.rules = { ...DEFAULT_RULES, ...(opts.kind === "league" ? { ft: opts.ft ?? 3 } : {}) };
|
||||
this.now = opts.now ?? (() => Date.now());
|
||||
this.rand = opts.rand ?? Math.random;
|
||||
|
||||
/** @type {Map<string, any>} uid -> player */
|
||||
this.players = new Map();
|
||||
this.order = [];
|
||||
this.host = null;
|
||||
this.phase = "lobby"; // lobby | countdown | playing | between | match_end
|
||||
this.round = 0;
|
||||
this.roundStartAt = 0;
|
||||
this.nextRoundAt = 0;
|
||||
this.matchId = null;
|
||||
this.finished = false;
|
||||
this.lastEnd = null; // 끊겼다 돌아온 사람에게 다시 보낼 match_end ({uid|"*": msg}) // 리그 경기 종료 후 방 폐기 표시
|
||||
|
||||
this.outbox = []; // {to: uid|null, except?: uid, msg}
|
||||
this.effects = []; // {type, ...}
|
||||
}
|
||||
|
||||
// ── 출력 ──
|
||||
send(to, msg) {
|
||||
this.outbox.push({ to, msg });
|
||||
}
|
||||
broadcast(msg, except = null) {
|
||||
this.outbox.push({ to: null, except, msg });
|
||||
}
|
||||
drain() {
|
||||
const o = this.outbox;
|
||||
const e = this.effects;
|
||||
this.outbox = [];
|
||||
this.effects = [];
|
||||
return { out: o, effects: e };
|
||||
}
|
||||
|
||||
// ── 직렬화 (DO 하이버네이션 대비) ──
|
||||
toJSON() {
|
||||
return {
|
||||
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, lastEnd: this.lastEnd,
|
||||
};
|
||||
}
|
||||
static fromJSON(j, deps = {}) {
|
||||
const r = new RoomLogic({ id: j.id, kind: j.kind, code: j.code, allowed: j.allowed, ...deps });
|
||||
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;
|
||||
}
|
||||
|
||||
// ── 조회 ──
|
||||
get connected() {
|
||||
return [...this.players.values()].filter((p) => p.connected);
|
||||
}
|
||||
get alive() {
|
||||
return [...this.players.values()].filter((p) => p.inRound && p.alive);
|
||||
}
|
||||
ftTarget() {
|
||||
return this.rules.ft;
|
||||
}
|
||||
|
||||
lobbyMsg() {
|
||||
return {
|
||||
t: "lobby",
|
||||
room: this.id,
|
||||
code: this.code,
|
||||
kind: this.kind,
|
||||
host: this.host,
|
||||
rules: this.rules,
|
||||
phase: this.phase,
|
||||
round: this.round,
|
||||
players: this.order.map((uid) => {
|
||||
const p = this.players.get(uid);
|
||||
return {
|
||||
id: p.uid, nick: p.nick, guest: p.guest, wins: p.wins, alive: p.alive, inRound: p.inRound,
|
||||
connected: p.connected, rematch: p.rematch, tr: p.tr ?? null, rank: p.rank ?? null,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
// ── 입장/퇴장 ──
|
||||
/** 반환: {ok:true} | {ok:false, reason} */
|
||||
join(uid, info = {}) {
|
||||
if (this.finished) return { ok: false, reason: "이미 끝난 경기입니다" };
|
||||
if (this.allowed && !this.allowed.includes(uid)) return { ok: false, reason: "이 경기의 참가자가 아닙니다" };
|
||||
const existing = this.players.get(uid);
|
||||
if (existing) {
|
||||
existing.connected = true;
|
||||
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 = [];
|
||||
}
|
||||
this.broadcast(this.lobbyMsg());
|
||||
return { ok: true, rejoined: true };
|
||||
}
|
||||
const p = {
|
||||
uid, nick: info.nick ?? "?", guest: !!info.guest, tr: info.tr ?? null, rank: info.rank ?? null,
|
||||
connected: true, disconnectedAt: 0,
|
||||
wins: 0, inRound: false, alive: false, place: 0,
|
||||
target: null, autoTarget: null, autoTargetAt: 0, lastAttacker: null,
|
||||
carry: 0, pieces: 0, lastBoardAt: 0, grid: null, rematch: false, pendingGarbage: [], flagged: 0,
|
||||
};
|
||||
this.players.set(uid, p);
|
||||
this.order.push(uid);
|
||||
if (!this.host) this.host = uid;
|
||||
this.send(uid, this.syncMsg(uid));
|
||||
this.broadcast(this.lobbyMsg());
|
||||
if (this.kind === "league" && this.phase === "lobby" && this.allowed.every((u) => this.players.get(u)?.connected)) {
|
||||
this.startRound();
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
syncMsg(uid) {
|
||||
const p = this.players.get(uid);
|
||||
return {
|
||||
...this.lobbyMsg(), t: "sync", you: uid,
|
||||
inRound: p.inRound, alive: p.alive,
|
||||
boards: Object.fromEntries([...this.players.values()].filter((o) => o.grid && o.uid !== uid).map((o) => [o.uid, o.grid])),
|
||||
};
|
||||
}
|
||||
|
||||
/** 소켓 종료. 리그·라운드 중이면 15초 유예 후 톱아웃 처리. */
|
||||
disconnect(uid) {
|
||||
const p = this.players.get(uid);
|
||||
if (!p) return;
|
||||
p.connected = false;
|
||||
p.disconnectedAt = this.now();
|
||||
this.broadcast(this.lobbyMsg());
|
||||
}
|
||||
|
||||
leave(uid) {
|
||||
const p = this.players.get(uid);
|
||||
if (!p) return;
|
||||
if (this.kind === "league" && !this.finished) {
|
||||
this.forfeit(uid);
|
||||
return;
|
||||
}
|
||||
if (p.inRound && p.alive) this.topout(uid);
|
||||
this.players.delete(uid);
|
||||
this.order = this.order.filter((u) => u !== uid);
|
||||
if (this.host === uid) this.host = this.order.find((u) => this.players.get(u).connected) ?? this.order[0] ?? null;
|
||||
if (this.phase !== "lobby" && this.phase !== "match_end" && this.participants().length < 2 && this.alive.length <= 1) {
|
||||
// 남은 인원으로 라운드를 이어갈 수 없으면 로비로
|
||||
if (this.phase === "between" || this.phase === "countdown") this.toLobby();
|
||||
}
|
||||
this.broadcast(this.lobbyMsg());
|
||||
}
|
||||
|
||||
participants() {
|
||||
return this.connected;
|
||||
}
|
||||
|
||||
// ── 라운드 ──
|
||||
startRound() {
|
||||
const ready = this.connected;
|
||||
if (ready.length < 2) return false;
|
||||
this.round += 1;
|
||||
this.phase = "countdown";
|
||||
const now = this.now();
|
||||
this.roundStartAt = now + ROUND_COUNTDOWN_MS;
|
||||
this.nextRoundAt = 0;
|
||||
const shared = this.randomSeed();
|
||||
for (const p of this.players.values()) {
|
||||
const inRound = p.connected;
|
||||
Object.assign(p, {
|
||||
inRound, alive: inRound, place: 0, target: null, autoTarget: null, autoTargetAt: 0,
|
||||
lastAttacker: null, carry: 0, pieces: 0, grid: null, rematch: false, pendingGarbage: [],
|
||||
});
|
||||
}
|
||||
for (const p of this.players.values()) {
|
||||
if (!p.inRound) continue;
|
||||
const seed = this.rules.sameBag ? shared : this.randomSeed();
|
||||
this.send(p.uid, { t: "round_start", n: this.round, startIn: ROUND_COUNTDOWN_MS, seed, rules: this.rules });
|
||||
}
|
||||
// 관전자에게도 라운드 시작 알림 (seed 없음)
|
||||
for (const p of this.players.values()) {
|
||||
if (!p.inRound) this.send(p.uid, { t: "round_start", n: this.round, startIn: ROUND_COUNTDOWN_MS, seed: null, rules: this.rules });
|
||||
}
|
||||
this.broadcast(this.lobbyMsg());
|
||||
return true;
|
||||
}
|
||||
|
||||
randomSeed() {
|
||||
return 1 + Math.floor(this.rand() * 0x7ffffffe);
|
||||
}
|
||||
|
||||
elapsed() {
|
||||
return Math.max(0, this.now() - this.roundStartAt);
|
||||
}
|
||||
|
||||
/** 시간 경과 처리. DO 알람에서 호출. */
|
||||
tick() {
|
||||
const now = this.now();
|
||||
if (this.phase === "countdown" && now >= this.roundStartAt) this.phase = "playing";
|
||||
if (this.phase === "between" && this.nextRoundAt && now >= this.nextRoundAt) {
|
||||
if (!this.startRound()) this.toLobby();
|
||||
}
|
||||
for (const p of [...this.players.values()]) {
|
||||
if (!p.connected && p.disconnectedAt && now - p.disconnectedAt >= RECONNECT_GRACE_MS) {
|
||||
if (this.kind === "league" && !this.finished) {
|
||||
this.forfeit(p.uid);
|
||||
} else if (p.inRound && p.alive) {
|
||||
this.topout(p.uid);
|
||||
p.disconnectedAt = 0;
|
||||
} else if (this.phase === "lobby" || this.phase === "match_end") {
|
||||
this.leave(p.uid);
|
||||
} else {
|
||||
p.disconnectedAt = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 다음에 tick() 이 필요한 시각 (없으면 null). */
|
||||
nextWake() {
|
||||
const t = [];
|
||||
if (this.phase === "countdown") t.push(this.roundStartAt);
|
||||
if (this.phase === "between" && this.nextRoundAt) t.push(this.nextRoundAt);
|
||||
for (const p of this.players.values()) if (!p.connected && p.disconnectedAt) t.push(p.disconnectedAt + RECONNECT_GRACE_MS);
|
||||
return t.length ? Math.min(...t) : null;
|
||||
}
|
||||
|
||||
ensurePlaying() {
|
||||
if (this.phase === "countdown" && this.now() >= this.roundStartAt) this.phase = "playing";
|
||||
return this.phase === "playing";
|
||||
}
|
||||
|
||||
// ── 메시지 처리 ──
|
||||
handle(uid, m) {
|
||||
const p = this.players.get(uid);
|
||||
if (!p || !m || typeof m.t !== "string") return;
|
||||
switch (m.t) {
|
||||
case "start":
|
||||
if (this.kind === "custom" && uid === this.host && (this.phase === "lobby" || this.phase === "match_end")) {
|
||||
if (this.phase === "match_end") this.resetWins();
|
||||
if (!this.startRound()) this.send(uid, { t: "error", msg: "2명 이상 있어야 시작할 수 있습니다" });
|
||||
}
|
||||
break;
|
||||
case "rules":
|
||||
if (this.kind === "custom" && uid === this.host && this.phase === "lobby") {
|
||||
this.rules = sanitizeRules(m.rules, this.rules);
|
||||
this.broadcast(this.lobbyMsg());
|
||||
}
|
||||
break;
|
||||
case "stop":
|
||||
if (this.kind === "custom" && uid === this.host) this.toLobby();
|
||||
break;
|
||||
case "attack":
|
||||
this.onAttack(p, m);
|
||||
break;
|
||||
case "board":
|
||||
this.onBoard(p, m);
|
||||
break;
|
||||
case "topout":
|
||||
if (p.inRound && p.alive && (this.phase === "playing" || this.ensurePlaying())) this.topout(uid);
|
||||
break;
|
||||
case "target":
|
||||
if (typeof m.id === "string" && m.id !== uid && this.players.has(m.id)) {
|
||||
p.target = m.id;
|
||||
this.send(uid, { t: "targeting", id: m.id, manual: true });
|
||||
} else if (m.id === null) {
|
||||
p.target = null;
|
||||
}
|
||||
break;
|
||||
case "rematch":
|
||||
this.onRematch(p, !!m.vote);
|
||||
break;
|
||||
case "leave":
|
||||
this.leave(uid);
|
||||
break;
|
||||
case "ping":
|
||||
this.send(uid, { t: "pong", ts: m.ts ?? null });
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
onAttack(p, m) {
|
||||
if (!p.inRound || !p.alive || !this.ensurePlaying()) return;
|
||||
const lines = m.lines;
|
||||
const pieces = m.pieces;
|
||||
if (!Number.isInteger(lines) || lines < 0 || lines > MAX_ATTACK_PER_PIECE) {
|
||||
p.flagged++;
|
||||
return;
|
||||
}
|
||||
if (Number.isInteger(pieces)) {
|
||||
const sec = this.elapsed() / 1000;
|
||||
if (pieces > MAX_PPS * sec + 3) {
|
||||
p.flagged++;
|
||||
return;
|
||||
}
|
||||
p.pieces = pieces;
|
||||
}
|
||||
if (lines === 0) return;
|
||||
const mul = this.rules.garbageMul * overtimeMultiplier(this.elapsed(), this.rules.overtime);
|
||||
p.carry += lines * mul;
|
||||
const send = Math.floor(p.carry + 1e-9);
|
||||
p.carry -= send;
|
||||
if (send <= 0) return;
|
||||
const target = this.pickTarget(p);
|
||||
if (!target) return;
|
||||
target.lastAttacker = p.uid;
|
||||
const msg = { t: "garbage", from: p.uid, lines: send };
|
||||
if (target.connected) this.send(target.uid, msg);
|
||||
else target.pendingGarbage.push(msg);
|
||||
this.broadcast({ t: "attack", from: p.uid, to: target.uid, lines: send }, target.uid);
|
||||
}
|
||||
|
||||
pickTarget(p) {
|
||||
const others = this.alive.filter((o) => o.uid !== p.uid);
|
||||
if (!others.length) return null;
|
||||
if (others.length === 1) return others[0];
|
||||
if (p.target) {
|
||||
const t = this.players.get(p.target);
|
||||
if (t && t.inRound && t.alive) return t;
|
||||
p.target = null;
|
||||
}
|
||||
const now = this.now();
|
||||
let t = p.autoTarget && this.players.get(p.autoTarget);
|
||||
if (!t || !t.alive || !t.inRound || now - p.autoTargetAt >= AUTO_TARGET_MS) {
|
||||
t = others[Math.floor(this.rand() * others.length)];
|
||||
p.autoTarget = t.uid;
|
||||
p.autoTargetAt = now;
|
||||
this.send(p.uid, { t: "targeting", id: t.uid, manual: false });
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
onBoard(p, m) {
|
||||
if (!p.inRound) return;
|
||||
const grid = m.grid;
|
||||
if (typeof grid !== "string" || grid.length !== BOARD_W * BOARD_ROWS || !BOARD_RE.test(grid)) return;
|
||||
p.grid = grid;
|
||||
const now = this.now();
|
||||
// 인원이 많을수록 브로드캐스트 주기를 늘린다 (§14.1).
|
||||
const minGap = 150 * Math.max(1, Math.ceil(this.connected.length / 6));
|
||||
if (now - p.lastBoardAt < minGap && !m.lock) return;
|
||||
p.lastBoardAt = now;
|
||||
this.broadcast({ t: "board", id: p.uid, grid, pending: m.pending ?? 0 }, p.uid);
|
||||
}
|
||||
|
||||
topout(uid) {
|
||||
const p = this.players.get(uid);
|
||||
if (!p || !p.alive) return;
|
||||
const aliveBefore = this.alive.length;
|
||||
p.alive = false;
|
||||
p.place = aliveBefore;
|
||||
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) {
|
||||
if (winner) {
|
||||
winner.wins += 1;
|
||||
winner.place = 1;
|
||||
}
|
||||
const score = Object.fromEntries(this.order.map((u) => [u, this.players.get(u).wins]));
|
||||
this.broadcast({ t: "round_end", n: this.round, winner: winner?.uid ?? null, score });
|
||||
const ft = this.ftTarget();
|
||||
if (ft > 0 && winner && winner.wins >= ft) {
|
||||
this.endMatch(winner.uid);
|
||||
return;
|
||||
}
|
||||
this.phase = "between";
|
||||
this.nextRoundAt = this.now() + ROUND_GAP_MS;
|
||||
this.broadcast(this.lobbyMsg());
|
||||
}
|
||||
|
||||
standings() {
|
||||
return [...this.players.values()]
|
||||
.filter((p) => p.wins > 0 || p.inRound)
|
||||
.sort((a, b) => b.wins - a.wins)
|
||||
.map((p, i) => ({ id: p.uid, nick: p.nick, wins: p.wins, rank: i + 1 }));
|
||||
}
|
||||
|
||||
endMatch(winnerUid) {
|
||||
this.phase = "match_end";
|
||||
this.nextRoundAt = 0;
|
||||
const standings = this.standings();
|
||||
if (this.kind === "league") {
|
||||
this.finished = true;
|
||||
const [a, b] = this.allowed;
|
||||
const loser = winnerUid === a ? b : a;
|
||||
this.effects.push({
|
||||
type: "league_end", winner: winnerUid, loser,
|
||||
score: { [a]: this.players.get(a)?.wins ?? 0, [b]: this.players.get(b)?.wins ?? 0 },
|
||||
});
|
||||
// match_end 메시지는 레이팅 반영 후 래퍼가 trDelta 를 붙여 보낸다.
|
||||
} else {
|
||||
this.effects.push({ type: "custom_end", standings, size: this.order.length });
|
||||
const msg = { t: "match_end", result: standings, winner: winnerUid };
|
||||
this.lastEnd = { "*": msg };
|
||||
this.broadcast(msg);
|
||||
this.broadcastRematch();
|
||||
}
|
||||
this.broadcast(this.lobbyMsg());
|
||||
}
|
||||
|
||||
forfeit(uid) {
|
||||
if (this.finished) return;
|
||||
const other = this.allowed.find((u) => u !== uid);
|
||||
const o = this.players.get(other);
|
||||
if (o) o.wins = Math.max(o.wins, this.rules.ft);
|
||||
const me = this.players.get(uid);
|
||||
if (me) me.alive = false;
|
||||
this.broadcast({ t: "ko", who: uid, by: null, place: 2, forfeit: true });
|
||||
this.endMatch(other);
|
||||
}
|
||||
|
||||
resetWins() {
|
||||
this.lastEnd = null;
|
||||
for (const p of this.players.values()) {
|
||||
p.wins = 0;
|
||||
p.rematch = false;
|
||||
}
|
||||
this.round = 0;
|
||||
}
|
||||
|
||||
toLobby() {
|
||||
this.phase = "lobby";
|
||||
this.nextRoundAt = 0;
|
||||
for (const p of this.players.values()) {
|
||||
p.inRound = false;
|
||||
p.alive = false;
|
||||
}
|
||||
this.broadcast(this.lobbyMsg());
|
||||
}
|
||||
|
||||
onRematch(p, vote) {
|
||||
if (this.kind !== "custom" || this.phase !== "match_end") return;
|
||||
p.rematch = vote;
|
||||
this.broadcastRematch();
|
||||
const conn = this.connected;
|
||||
const votes = conn.filter((x) => x.rematch).length;
|
||||
if (votes * 2 > conn.length && conn.length >= 2) {
|
||||
this.resetWins();
|
||||
this.startRound();
|
||||
}
|
||||
}
|
||||
|
||||
broadcastRematch() {
|
||||
const conn = this.connected;
|
||||
this.broadcast({
|
||||
t: "rematch_state",
|
||||
votes: conn.filter((x) => x.rematch).map((x) => x.uid),
|
||||
needed: Math.floor(conn.length / 2) + 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function pickInfo(info) {
|
||||
const o = {};
|
||||
for (const k of ["nick", "guest", "tr", "rank"]) if (k in info) o[k] = info[k];
|
||||
return o;
|
||||
}
|
||||
185
server/src/room.js
Normal file
185
server/src/room.js
Normal file
@@ -0,0 +1,185 @@
|
||||
// GameRoomDO — 경기당 1개 (리그 1:1 & 커스텀 N인 공용). WebSocket Hibernation 사용.
|
||||
import { DurableObject } from "cloudflare:workers";
|
||||
import { RoomLogic } from "./room-logic.js";
|
||||
import { DEFAULT_RULES, sanitizeRules } from "./rules.js";
|
||||
import { applyLeagueResult, recordCustom } from "./db.js";
|
||||
|
||||
const QUIET = new Set(["board", "attack", "ping"]);
|
||||
|
||||
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() {
|
||||
if (this.logic) return this.logic;
|
||||
const j = await this.ctx.storage.get("room");
|
||||
if (j) this.logic = RoomLogic.fromJSON(j);
|
||||
return this.logic;
|
||||
}
|
||||
|
||||
async save() {
|
||||
if (this.logic) await this.ctx.storage.put("room", this.logic.toJSON());
|
||||
}
|
||||
|
||||
async fetch(req) {
|
||||
const url = new URL(req.url);
|
||||
if (url.pathname === "/init") {
|
||||
const body = await req.json();
|
||||
const cur = await this.load();
|
||||
if (cur && cur.players.size > 0) return Response.json({ ok: false, reason: "exists" }, { status: 409 });
|
||||
this.logic = new RoomLogic({
|
||||
id: body.id, kind: body.kind, code: body.code ?? null, allowed: body.allowed ?? null, ft: body.ft,
|
||||
});
|
||||
if (body.kind === "custom") this.logic.rules = sanitizeRules(body.rules ?? {}, DEFAULT_RULES);
|
||||
this.logic.matchId = crypto.randomUUID();
|
||||
this.logic.createdAt = Date.now();
|
||||
await this.save();
|
||||
// 아무도 안 들어오면 10분 뒤 정리
|
||||
await this.ctx.storage.setAlarm(Date.now() + 10 * 60_000);
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
if (url.pathname === "/info") {
|
||||
const l = await this.load();
|
||||
if (!l || l.finished) return Response.json({ exists: false });
|
||||
return Response.json({ exists: true, kind: l.kind, players: l.players.size, phase: l.phase, rules: l.rules });
|
||||
}
|
||||
if (url.pathname === "/ws") {
|
||||
if (req.headers.get("Upgrade") !== "websocket") return new Response("websocket only", { status: 426 });
|
||||
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(decodeURIComponent(req.headers.get("x-info") || "%7B%7D"));
|
||||
const pair = new WebSocketPair();
|
||||
const [client, server] = Object.values(pair);
|
||||
// 같은 유저의 이전 소켓은 정리 (재접속)
|
||||
for (const old of this.ctx.getWebSockets(uid)) {
|
||||
try {
|
||||
old.serializeAttachment({ uid, replaced: true });
|
||||
old.close(4000, "replaced");
|
||||
} catch {}
|
||||
}
|
||||
this.ctx.acceptWebSocket(server, [uid]);
|
||||
server.serializeAttachment({ uid });
|
||||
const res = l.join(uid, info);
|
||||
if (!res.ok) {
|
||||
server.send(JSON.stringify({ t: "error", msg: res.reason, fatal: true }));
|
||||
server.close(4001, "rejected");
|
||||
}
|
||||
await this.flush();
|
||||
return new Response(null, { status: 101, webSocket: client });
|
||||
}
|
||||
return new Response("not found", { status: 404 });
|
||||
}
|
||||
|
||||
async webSocketMessage(ws, data) {
|
||||
const l = await this.load();
|
||||
const att = ws.deserializeAttachment();
|
||||
if (!l || !att || att.replaced) return;
|
||||
let m;
|
||||
try {
|
||||
m = JSON.parse(typeof data === "string" ? data : new TextDecoder().decode(data));
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
l.handle(att.uid, m);
|
||||
await this.flush(!QUIET.has(m.t));
|
||||
}
|
||||
|
||||
async webSocketClose(ws) {
|
||||
await this.onGone(ws);
|
||||
}
|
||||
|
||||
async webSocketError(ws) {
|
||||
await this.onGone(ws);
|
||||
}
|
||||
|
||||
async onGone(ws) {
|
||||
const l = await this.load();
|
||||
const att = ws.deserializeAttachment();
|
||||
if (!l || !att || att.replaced) return;
|
||||
const others = this.ctx.getWebSockets(att.uid).filter((s) => s !== ws && s.readyState === 1);
|
||||
if (!others.length) l.disconnect(att.uid);
|
||||
await this.flush();
|
||||
}
|
||||
|
||||
async alarm() {
|
||||
const l = await this.load();
|
||||
if (!l) return;
|
||||
if (l.players.size === 0) {
|
||||
await this.ctx.storage.deleteAll();
|
||||
this.logic = null;
|
||||
return;
|
||||
}
|
||||
l.tick();
|
||||
await this.flush();
|
||||
}
|
||||
|
||||
/** outbox 전송 + effects 처리 + 저장 + 다음 알람. */
|
||||
async flush(persist = true) {
|
||||
const l = this.logic;
|
||||
if (!l) return;
|
||||
// 효과를 먼저 처리해야 match_end(trDelta 포함)가 순서대로 나간다.
|
||||
for (let guard = 0; guard < 4; guard++) {
|
||||
const { out, effects } = l.drain();
|
||||
this.deliver(out);
|
||||
if (!effects.length) break;
|
||||
for (const e of effects) await this.applyEffect(l, e);
|
||||
}
|
||||
if (persist) await this.save();
|
||||
const wake = l.nextWake();
|
||||
if (l.players.size === 0) {
|
||||
await this.ctx.storage.setAlarm(Date.now() + 60_000);
|
||||
} else if (wake) {
|
||||
await this.ctx.storage.setAlarm(wake);
|
||||
}
|
||||
}
|
||||
|
||||
deliver(out) {
|
||||
if (!out.length) return;
|
||||
const sockets = this.ctx.getWebSockets();
|
||||
for (const o of out) {
|
||||
const payload = JSON.stringify(o.msg);
|
||||
for (const ws of sockets) {
|
||||
const att = ws.deserializeAttachment();
|
||||
if (!att || att.replaced) continue;
|
||||
if (o.to !== null && att.uid !== o.to) continue;
|
||||
if (o.except && att.uid === o.except) continue;
|
||||
try {
|
||||
ws.send(payload);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async applyEffect(l, e) {
|
||||
const db = this.env.DB;
|
||||
if (e.type === "league_end") {
|
||||
let result = null;
|
||||
try {
|
||||
result = await applyLeagueResult(db, { matchId: l.matchId, winner: e.winner, loser: e.loser, score: e.score });
|
||||
} catch (err) {
|
||||
console.error("league_end failed", err);
|
||||
}
|
||||
l.lastEnd = {};
|
||||
for (const uid of [e.winner, e.loser]) {
|
||||
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 {
|
||||
await recordCustom(db, { matchId: l.matchId, standings: e.standings, size: e.size });
|
||||
} catch (err) {
|
||||
console.error("custom_end failed", err);
|
||||
}
|
||||
l.matchId = crypto.randomUUID(); // 리매치는 새 경기
|
||||
}
|
||||
}
|
||||
}
|
||||
146
server/src/rules.js
Normal file
146
server/src/rules.js
Normal file
@@ -0,0 +1,146 @@
|
||||
// TETRIG 서버 공용 규칙·튜닝 상수 (명세서 §6~§9).
|
||||
// 튜닝 대상 수치는 전부 여기 모아 둔다. 클라이언트(Kotlin)의 Versus.kt 와 값이 같아야 한다.
|
||||
|
||||
export const BRAND = "TETRIG";
|
||||
export const BRAND_KO = "테트리그";
|
||||
|
||||
// ── 대전 (§6) ────────────────────────────────────────────────────
|
||||
export const ATTACK = {
|
||||
lines: [0, 0, 1, 2, 4], // Single/Double/Triple/Quad
|
||||
tspinMini: [0, 1], // Mini(0줄) / Mini Single
|
||||
tspin: [0, 2, 4, 6], // T-spin 0/Single/Double/Triple
|
||||
b2bBonus: 1,
|
||||
allClear: 5,
|
||||
combo: [1, 1, 2, 2, 3, 3, 4, 4, 4, 5], // 콤보 2부터(combo 인덱스 1부터), 이후 5 고정
|
||||
};
|
||||
export const GARBAGE_MAX_PER_INSERT = 8;
|
||||
export const GARBAGE_SAME_HOLE_CHANCE = 0.7;
|
||||
export const OVERTIME_START_MS = 90_000;
|
||||
export const OVERTIME_STEP_MS = 30_000;
|
||||
export const OVERTIME_STEP = 0.25;
|
||||
export const AUTO_TARGET_MS = 8_000;
|
||||
export const RECONNECT_GRACE_MS = 15_000;
|
||||
export const ROUND_COUNTDOWN_MS = 3_000;
|
||||
export const ROUND_GAP_MS = 4_000;
|
||||
|
||||
// 최소 안티치트 (§14.1)
|
||||
export const MAX_PPS = 5.0;
|
||||
// 한 피스로 낼 수 있는 이론상 최대치: T-spin Triple 6 + B2B 1 + AC 5 + 콤보 5 = 17
|
||||
export const MAX_ATTACK_PER_PIECE = 17;
|
||||
|
||||
/**
|
||||
* 한 번의 락 결과로 보낼 줄 수 (상쇄 전).
|
||||
* combo: 연속 클리어 인덱스 (0 = 첫 클리어, 1 = 콤보 2번째 …). b2b: 연속 어려운 클리어 인덱스.
|
||||
*/
|
||||
export function attackFor({ lines, tspin = "none", allClear = false, combo = -1, b2b = -1, difficult = false }) {
|
||||
if (lines <= 0) return 0;
|
||||
let n;
|
||||
if (tspin === "tspin") n = ATTACK.tspin[Math.min(lines, 3)];
|
||||
else if (tspin === "mini") n = ATTACK.tspinMini[Math.min(lines, 1)];
|
||||
else n = ATTACK.lines[Math.min(lines, 4)];
|
||||
if (difficult && b2b >= 1) n += ATTACK.b2bBonus;
|
||||
if (combo >= 1) n += ATTACK.combo[Math.min(combo - 1, ATTACK.combo.length - 1)];
|
||||
if (allClear) n += ATTACK.allClear;
|
||||
return n;
|
||||
}
|
||||
|
||||
/** 장기전 배율: 90초 후 30초마다 +25%. */
|
||||
export function overtimeMultiplier(elapsedMs, enabled = true) {
|
||||
if (!enabled || elapsedMs < OVERTIME_START_MS) return 1;
|
||||
return 1 + OVERTIME_STEP * (1 + Math.floor((elapsedMs - OVERTIME_START_MS) / OVERTIME_STEP_MS));
|
||||
}
|
||||
|
||||
// ── 커스텀 룸 (§7) ───────────────────────────────────────────────
|
||||
export const ROOM_CODE_CHARS = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // I/1/O/0 제외
|
||||
export const ROOM_CODE_LEN = 6;
|
||||
export const DEFAULT_RULES = Object.freeze({
|
||||
garbageMul: 1.0, // 0.5 ~ 2.0
|
||||
ft: 0, // 0 = 무제한, 1/3/5
|
||||
sameBag: false, // true = 동일 bag 공정전
|
||||
overtime: true,
|
||||
});
|
||||
|
||||
export function sanitizeRules(input = {}, base = DEFAULT_RULES) {
|
||||
const r = { ...base };
|
||||
if (typeof input.garbageMul === "number") r.garbageMul = Math.min(2, Math.max(0.5, Math.round(input.garbageMul * 4) / 4));
|
||||
if ([0, 1, 3, 5].includes(input.ft)) r.ft = input.ft;
|
||||
if (typeof input.sameBag === "boolean") r.sameBag = input.sameBag;
|
||||
if (typeof input.overtime === "boolean") r.overtime = input.overtime;
|
||||
return r;
|
||||
}
|
||||
|
||||
export function randomRoomCode(rand = Math.random) {
|
||||
let s = "";
|
||||
for (let i = 0; i < ROOM_CODE_LEN; i++) s += ROOM_CODE_CHARS[Math.floor(rand() * ROOM_CODE_CHARS.length)];
|
||||
return s;
|
||||
}
|
||||
|
||||
export function isRoomCode(s) {
|
||||
return typeof s === "string" && s.length === ROOM_CODE_LEN && [...s].every((c) => ROOM_CODE_CHARS.includes(c));
|
||||
}
|
||||
|
||||
// ── 리그 (§8) ────────────────────────────────────────────────────
|
||||
export const GLICKO = { R: 1500, RD: 350, VOL: 0.06, TAU: 0.5, RD_MIN: 58, RD_MAX: 350 };
|
||||
export const TR_MID = 1600;
|
||||
export const TR_SCALE = 300;
|
||||
export const PLACEMENT_GAMES = 10;
|
||||
export const RANK_VISIBLE_RD = 100;
|
||||
export const RD_DECAY_IDLE_DAYS = 7;
|
||||
export const RD_DECAY_PER_DAY = 1;
|
||||
export const SEASON_LENGTH_DAYS = 61; // 약 2개월 (§17 기본 제안값)
|
||||
|
||||
export const RANKS = [
|
||||
["D", 0], ["D+", 800], ["C-", 1400], ["C", 2000], ["C+", 2600], ["B-", 3300], ["B", 4000], ["B+", 4800],
|
||||
["A-", 5700], ["A", 6700], ["A+", 7800], ["S-", 9200], ["S", 10800], ["S+", 12400], ["SS", 14200],
|
||||
["U", 16500], ["X", 19500], ["X+", 22500],
|
||||
];
|
||||
|
||||
export function trFor(R, RD) {
|
||||
return Math.round(25000 / (1 + Math.pow(10, (TR_MID - (R - RD)) / TR_SCALE)));
|
||||
}
|
||||
|
||||
export function rankFor(tr) {
|
||||
let r = RANKS[0][0];
|
||||
for (const [name, cut] of RANKS) if (tr >= cut) r = name;
|
||||
return r;
|
||||
}
|
||||
|
||||
/** 경기 형식: 높은 쪽 랭크가 S- 이상이면 FT5, 아니면 FT3. */
|
||||
export function leagueFt(trA, trB) {
|
||||
const sMinus = RANKS.find(([n]) => n === "S-")[1];
|
||||
return Math.max(trA, trB) >= sMinus ? 5 : 3;
|
||||
}
|
||||
|
||||
// 매치메이킹 (§8.3)
|
||||
export const MM_WINDOW_RD = 2;
|
||||
export const MM_EXPAND_EVERY_MS = 30_000;
|
||||
export const MM_EXPAND_FACTOR = 1.2;
|
||||
export const MM_HINT_AFTER_MS = 120_000;
|
||||
|
||||
// ── 계정 (§9) ────────────────────────────────────────────────────
|
||||
export const GUEST_ADJ = [
|
||||
"재빠른", "용감한", "조용한", "빛나는", "날쌘", "느긋한", "단단한", "엉뚱한", "반짝이는", "졸린",
|
||||
"배고픈", "씩씩한", "수상한", "깜찍한", "똑똑한", "푸른", "붉은", "하얀", "검은", "노란",
|
||||
];
|
||||
export const GUEST_NOUN = [
|
||||
"미노", "블록", "벽돌", "큐브", "타일", "조각", "기둥", "탑", "망치", "번개",
|
||||
"여우", "고양이", "펭귄", "수달", "다람쥐", "부엉이", "판다", "고래", "참새", "두더지",
|
||||
];
|
||||
export function randomGuestName(rand = Math.random) {
|
||||
const a = GUEST_ADJ[Math.floor(rand() * GUEST_ADJ.length)];
|
||||
const n = GUEST_NOUN[Math.floor(rand() * GUEST_NOUN.length)];
|
||||
const d = String(Math.floor(rand() * 1000)).padStart(3, "0");
|
||||
return a + n + d;
|
||||
}
|
||||
/** 게스트명 패턴은 시스템 예약 — 로그인 유저가 이 모양의 닉으로 바꿀 수 없다. */
|
||||
export function looksLikeGuestName(s) {
|
||||
const m = /^(.+?)(\d{3})$/.exec(s);
|
||||
if (!m) return false;
|
||||
return GUEST_ADJ.some((a) => m[1].startsWith(a) && GUEST_NOUN.includes(m[1].slice(a.length)));
|
||||
}
|
||||
export const NICK_RE = /^[가-힣A-Za-z0-9_]{2,12}$/;
|
||||
export const NICK_COOLDOWN_MS = 30 * 24 * 3600 * 1000;
|
||||
export const TOKEN_TTL_MS = 30 * 24 * 3600 * 1000;
|
||||
export const PBKDF2_ITER = 100_000;
|
||||
|
||||
export const SOLO_MODES = ["sprint", "time", "endless"];
|
||||
192
server/test/room.test.js
Normal file
192
server/test/room.test.js
Normal file
@@ -0,0 +1,192 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { RoomLogic } from "../src/room-logic.js";
|
||||
|
||||
function mkRoom(kind = "custom", extra = {}) {
|
||||
let t = 1_000_000;
|
||||
const clock = { now: () => t, adv: (ms) => (t += ms) };
|
||||
let seed = 1;
|
||||
const rand = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
|
||||
const r = new RoomLogic({ id: "R", kind, code: "ABCDEF", now: clock.now, rand, ...extra });
|
||||
return { r, clock };
|
||||
}
|
||||
const msgs = (r, uid, type) => r.drain().out.filter((o) => (o.to === null ? o.except !== uid : o.to === uid) && (!type || o.msg.t === type)).map((o) => o.msg);
|
||||
const startPlaying = (r, clock) => { r.handle(r.host, { t: "start" }); clock.adv(3001); r.tick(); };
|
||||
|
||||
test("커스텀 1:1: 호스트 시작 → 가비지 → 톱아웃 → 라운드 승리", () => {
|
||||
const { r, clock } = mkRoom();
|
||||
r.join("a", { nick: "A" });
|
||||
r.join("b", { nick: "B" });
|
||||
assert.equal(r.host, "a");
|
||||
r.drain();
|
||||
r.handle("b", { t: "start" }); // 호스트 아님
|
||||
assert.equal(r.phase, "lobby");
|
||||
r.handle("a", { t: "start" });
|
||||
assert.equal(r.phase, "countdown");
|
||||
const starts = r.drain().out.filter((o) => o.msg.t === "round_start");
|
||||
assert.equal(starts.length, 2);
|
||||
assert.ok(starts.every((o) => o.msg.seed > 0));
|
||||
clock.adv(3001);
|
||||
r.tick();
|
||||
assert.equal(r.phase, "playing");
|
||||
r.handle("a", { t: "attack", lines: 4, pieces: 3 });
|
||||
const g = msgs(r, "b", "garbage");
|
||||
assert.deepEqual(g, [{ t: "garbage", from: "a", lines: 4 }]);
|
||||
r.handle("b", { t: "topout" });
|
||||
const out = r.drain().out.map((o) => o.msg);
|
||||
assert.ok(out.find((m) => m.t === "ko" && m.who === "b" && m.by === "a"));
|
||||
const end = out.find((m) => m.t === "round_end");
|
||||
assert.equal(end.winner, "a");
|
||||
assert.equal(end.score.a, 1);
|
||||
assert.equal(r.phase, "between"); // FT 무제한 → 다음 라운드 대기
|
||||
clock.adv(4001);
|
||||
r.tick();
|
||||
assert.equal(r.phase, "countdown");
|
||||
assert.equal(r.round, 2);
|
||||
});
|
||||
|
||||
test("가비지 배율 0.5× 는 소수 누적(carry)으로 공정하게", () => {
|
||||
const { r, clock } = mkRoom();
|
||||
r.join("a"); r.join("b");
|
||||
r.handle("a", { t: "rules", rules: { garbageMul: 0.5, overtime: false } });
|
||||
startPlaying(r, clock);
|
||||
r.drain();
|
||||
r.handle("a", { t: "attack", lines: 1, pieces: 1 });
|
||||
assert.equal(msgs(r, "b", "garbage").length, 0);
|
||||
r.handle("a", { t: "attack", lines: 1, pieces: 2 });
|
||||
assert.equal(msgs(r, "b", "garbage")[0].lines, 1);
|
||||
});
|
||||
|
||||
test("안티치트: 비정상 공격량·PPS 는 무시", () => {
|
||||
const { r, clock } = mkRoom();
|
||||
r.join("a"); r.join("b");
|
||||
startPlaying(r, clock);
|
||||
r.drain();
|
||||
r.handle("a", { t: "attack", lines: 40, pieces: 1 });
|
||||
r.handle("a", { t: "attack", lines: 4, pieces: 500 });
|
||||
assert.equal(msgs(r, "b", "garbage").length, 0);
|
||||
assert.equal(r.players.get("a").flagged, 2);
|
||||
});
|
||||
|
||||
test("FFA 4인: 타겟 수동 지정, KO 순위, 최후 생존자 승리, FT1 → match_end → 리매치 과반", () => {
|
||||
const { r, clock } = mkRoom();
|
||||
for (const u of ["a", "b", "c", "d"]) r.join(u, { nick: u.toUpperCase() });
|
||||
r.handle("a", { t: "rules", rules: { ft: 1 } });
|
||||
startPlaying(r, clock);
|
||||
r.drain();
|
||||
r.handle("a", { t: "target", id: "c" });
|
||||
r.handle("a", { t: "attack", lines: 2, pieces: 2 });
|
||||
assert.equal(msgs(r, "c", "garbage")[0].from, "a");
|
||||
r.handle("c", { t: "topout" });
|
||||
assert.equal(r.players.get("c").place, 4);
|
||||
r.handle("a", { t: "attack", lines: 2, pieces: 3 }); // 수동 타겟이 죽었으니 자동 타겟으로
|
||||
const atk = r.drain().out.find((o) => o.msg.t === "garbage");
|
||||
assert.ok(["b", "d"].includes(atk.to));
|
||||
r.handle("d", { t: "topout" });
|
||||
r.handle("b", { t: "topout" });
|
||||
assert.equal(r.phase, "match_end");
|
||||
const { effects } = r.drain();
|
||||
assert.equal(effects[0].type, "custom_end");
|
||||
assert.equal(effects[0].standings[0].id, "a");
|
||||
r.handle("a", { t: "rematch", vote: true });
|
||||
r.handle("b", { t: "rematch", vote: true });
|
||||
assert.equal(r.phase, "match_end"); // 2/4 는 과반 아님
|
||||
r.handle("c", { t: "rematch", vote: true });
|
||||
assert.equal(r.phase, "countdown");
|
||||
assert.equal(r.players.get("a").wins, 0);
|
||||
});
|
||||
|
||||
test("도중 입장은 관전 후 다음 라운드부터 참전", () => {
|
||||
const { r, clock } = mkRoom();
|
||||
r.join("a"); r.join("b");
|
||||
startPlaying(r, clock);
|
||||
r.join("c");
|
||||
assert.equal(r.players.get("c").inRound, false);
|
||||
r.handle("b", { t: "topout" });
|
||||
clock.adv(4001);
|
||||
r.tick();
|
||||
assert.equal(r.players.get("c").inRound, true);
|
||||
});
|
||||
|
||||
test("호스트 퇴장 시 다음 입장자에게 위임", () => {
|
||||
const { r } = mkRoom();
|
||||
r.join("a"); r.join("b"); r.join("c");
|
||||
r.handle("a", { t: "leave" });
|
||||
assert.equal(r.host, "b");
|
||||
});
|
||||
|
||||
test("재접속 유예 15초: 그 안에 돌아오면 유지, 넘기면 톱아웃", () => {
|
||||
const { r, clock } = mkRoom();
|
||||
r.join("a"); r.join("b"); r.join("c");
|
||||
startPlaying(r, clock);
|
||||
r.disconnect("b");
|
||||
clock.adv(10_000); r.tick();
|
||||
assert.equal(r.players.get("b").alive, true);
|
||||
r.handle("a", { t: "target", id: "b" });
|
||||
r.handle("a", { t: "attack", lines: 2, pieces: 2 });
|
||||
r.drain();
|
||||
r.join("b");
|
||||
const back = msgs(r, "b");
|
||||
assert.ok(back.find((m) => m.t === "sync"));
|
||||
assert.ok(back.find((m) => m.t === "garbage" && m.lines === 2)); // 끊긴 동안 받은 가비지 재전달
|
||||
r.disconnect("c");
|
||||
clock.adv(15_001); r.tick();
|
||||
assert.equal(r.players.get("c").alive, false);
|
||||
});
|
||||
|
||||
test("리그: 지정된 2명만 입장, 둘 다 오면 자동 시작, FT3, 이탈은 몰수패", () => {
|
||||
const { r, clock } = mkRoom("league", { allowed: ["a", "b"], ft: 3 });
|
||||
assert.equal(r.join("x").ok, false);
|
||||
r.join("a");
|
||||
assert.equal(r.phase, "lobby");
|
||||
r.join("b");
|
||||
assert.equal(r.phase, "countdown");
|
||||
for (let i = 0; i < 2; i++) {
|
||||
clock.adv(3001); r.tick();
|
||||
r.handle("b", { t: "topout" });
|
||||
clock.adv(4001); r.tick();
|
||||
}
|
||||
assert.equal(r.players.get("a").wins, 2);
|
||||
r.drain();
|
||||
r.disconnect("a");
|
||||
clock.adv(15_001); r.tick();
|
||||
assert.equal(r.phase, "match_end");
|
||||
const { effects } = r.drain();
|
||||
assert.deepEqual({ w: effects[0].winner, l: effects[0].loser }, { w: "b", l: "a" });
|
||||
assert.equal(r.finished, true);
|
||||
});
|
||||
|
||||
test("직렬화 왕복 (하이버네이션 복원)", () => {
|
||||
const { r } = mkRoom();
|
||||
r.join("a", { nick: "A" }); r.join("b", { nick: "B" });
|
||||
const j = JSON.parse(JSON.stringify(r.toJSON()));
|
||||
const r2 = RoomLogic.fromJSON(j);
|
||||
assert.equal(r2.players.get("a").nick, "A");
|
||||
assert.equal(r2.host, "a");
|
||||
});
|
||||
|
||||
test("보드 스냅샷 검증·중계", () => {
|
||||
const { r, clock } = mkRoom();
|
||||
r.join("a"); r.join("b");
|
||||
startPlaying(r, clock);
|
||||
r.drain();
|
||||
r.handle("a", { t: "board", grid: "x".repeat(200) });
|
||||
assert.equal(msgs(r, "b", "board").length, 0);
|
||||
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");
|
||||
});
|
||||
83
server/test/rules.test.js
Normal file
83
server/test/rules.test.js
Normal file
@@ -0,0 +1,83 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { attackFor, overtimeMultiplier, trFor, rankFor, leagueFt, randomRoomCode, isRoomCode, randomGuestName, looksLikeGuestName, sanitizeRules } from "../src/rules.js";
|
||||
import { glickoUpdate } from "../src/glicko.js";
|
||||
import { findPairs, compatible } from "../src/matchmaking.js";
|
||||
|
||||
test("가비지 전송 테이블 (§6)", () => {
|
||||
assert.equal(attackFor({ lines: 1 }), 0);
|
||||
assert.equal(attackFor({ lines: 2 }), 1);
|
||||
assert.equal(attackFor({ lines: 3 }), 2);
|
||||
assert.equal(attackFor({ lines: 4, difficult: true, b2b: 0 }), 4);
|
||||
assert.equal(attackFor({ lines: 4, difficult: true, b2b: 1 }), 5); // B2B +1
|
||||
assert.equal(attackFor({ lines: 1, tspin: "mini" }), 1);
|
||||
assert.equal(attackFor({ lines: 0, tspin: "mini" }), 0);
|
||||
assert.equal(attackFor({ lines: 2, tspin: "tspin", difficult: true, b2b: 0 }), 4);
|
||||
assert.equal(attackFor({ lines: 3, tspin: "tspin", difficult: true, b2b: 0 }), 6);
|
||||
assert.equal(attackFor({ lines: 1, combo: 1 }), 1); // 콤보 2번째 → +1
|
||||
assert.equal(attackFor({ lines: 1, combo: 20 }), 5); // 이후 5 고정
|
||||
assert.equal(attackFor({ lines: 4, allClear: true }), 9);
|
||||
});
|
||||
|
||||
test("장기전 배율", () => {
|
||||
assert.equal(overtimeMultiplier(89_999), 1);
|
||||
assert.equal(overtimeMultiplier(90_000), 1.25);
|
||||
assert.equal(overtimeMultiplier(120_000), 1.5);
|
||||
assert.equal(overtimeMultiplier(200_000, false), 1);
|
||||
});
|
||||
|
||||
test("TR·랭크·FT", () => {
|
||||
assert.ok(trFor(1500, 350) < 1000);
|
||||
assert.ok(trFor(2500, 60) > 24000);
|
||||
assert.equal(rankFor(0), "D");
|
||||
assert.equal(rankFor(7800), "A+");
|
||||
assert.equal(rankFor(9199), "A+");
|
||||
assert.equal(rankFor(9200), "S-");
|
||||
assert.equal(rankFor(25000), "X+");
|
||||
assert.equal(leagueFt(7000, 9199), 3);
|
||||
assert.equal(leagueFt(1000, 9200), 5);
|
||||
});
|
||||
|
||||
test("방 코드·게스트명·규칙", () => {
|
||||
for (let i = 0; i < 200; i++) {
|
||||
const c = randomRoomCode();
|
||||
assert.ok(isRoomCode(c), c);
|
||||
assert.ok(!/[I1O0]/.test(c));
|
||||
}
|
||||
const n = randomGuestName();
|
||||
assert.match(n, /\d{3}$/);
|
||||
assert.ok(looksLikeGuestName(n));
|
||||
assert.ok(!looksLikeGuestName("홍길동"));
|
||||
assert.deepEqual(sanitizeRules({ garbageMul: 9, ft: 7, sameBag: true }), { garbageMul: 2, ft: 0, sameBag: true, overtime: true });
|
||||
});
|
||||
|
||||
test("Glicko-2: Glickman 논문 예제", () => {
|
||||
const p = glickoUpdate({ r: 1500, rd: 200, vol: 0.06 }, [
|
||||
{ r: 1400, rd: 30, score: 1 },
|
||||
{ r: 1550, rd: 100, score: 0 },
|
||||
{ r: 1700, rd: 300, score: 0 },
|
||||
]);
|
||||
assert.ok(Math.abs(p.r - 1464.06) < 0.05, String(p.r));
|
||||
assert.ok(Math.abs(p.rd - 151.52) < 0.05, String(p.rd));
|
||||
assert.ok(Math.abs(p.vol - 0.05999) < 0.0001, String(p.vol));
|
||||
});
|
||||
|
||||
test("Glicko-2: 승자는 오르고 패자는 내려간다, RD 하한 58", () => {
|
||||
const w = glickoUpdate({ r: 1500, rd: 350, vol: 0.06 }, [{ r: 1500, rd: 350, score: 1 }]);
|
||||
const l = glickoUpdate({ r: 1500, rd: 350, vol: 0.06 }, [{ r: 1500, rd: 350, score: 0 }]);
|
||||
assert.ok(w.r > 1500 && l.r < 1500);
|
||||
const tight = glickoUpdate({ r: 1500, rd: 58, vol: 0.06 }, [{ r: 1500, rd: 58, score: 1 }]);
|
||||
assert.ok(tight.rd >= 58);
|
||||
});
|
||||
|
||||
test("매치메이킹: R±2RD 겹침, 대기 시간에 따라 확장", () => {
|
||||
const now = 1_000_000;
|
||||
const a = { uid: "a", r: 1500, rd: 50, joinedAt: now };
|
||||
const b = { uid: "b", r: 1750, rd: 50, joinedAt: now };
|
||||
assert.equal(compatible(a, b, now), false); // 250 > 100+100
|
||||
assert.equal(compatible({ ...a, joinedAt: now - 60_000 }, { ...b, joinedAt: now - 60_000 }, now), true); // ×1.44
|
||||
const c = { uid: "c", r: 1520, rd: 50, joinedAt: now };
|
||||
const pairs = findPairs([b, a, c], now);
|
||||
assert.equal(pairs.length, 1);
|
||||
assert.deepEqual(pairs[0].map((x) => x.uid).sort(), ["a", "c"]);
|
||||
});
|
||||
32
server/wrangler.toml
Normal file
32
server/wrangler.toml
Normal file
@@ -0,0 +1,32 @@
|
||||
name = "tetrig"
|
||||
main = "src/index.js"
|
||||
compatibility_date = "2026-09-01"
|
||||
workers_dev = true
|
||||
|
||||
[[d1_databases]]
|
||||
binding = "DB"
|
||||
database_name = "tetrig"
|
||||
database_id = "d08b6a47-4f54-43c1-9590-1fe61930216f"
|
||||
migrations_dir = "migrations"
|
||||
|
||||
[[durable_objects.bindings]]
|
||||
name = "ROOMS"
|
||||
class_name = "GameRoomDO"
|
||||
|
||||
[[durable_objects.bindings]]
|
||||
name = "MATCHMAKER"
|
||||
class_name = "MatchmakerDO"
|
||||
|
||||
# 무료 플랜은 SQLite 백엔드 DO 만 쓸 수 있다.
|
||||
[[migrations]]
|
||||
tag = "v1"
|
||||
new_sqlite_classes = ["GameRoomDO", "MatchmakerDO"]
|
||||
|
||||
[triggers]
|
||||
crons = ["0 18 * * *"] # 매일 03:00 KST — RD 감쇠·시즌 마감
|
||||
|
||||
[vars]
|
||||
# Google 로그인용 OAuth 클라이언트 ID (쉼표 구분). 비어 있으면 /api/google 은 503.
|
||||
GOOGLE_CLIENT_IDS = ""
|
||||
|
||||
# 비밀값: npx wrangler secret put TOKEN_SECRET
|
||||
@@ -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`
|
||||
|
||||
@@ -25,77 +25,83 @@
|
||||
<body>
|
||||
<main>
|
||||
<h1><span class="o">TET</span>RIG 개인정보처리방침</h1>
|
||||
<p class="meta">최종 수정일: 2026-09-24 · 앱 패키지: kr.tkrmagid.tetrig</p>
|
||||
<p class="meta">최종 수정일: 2026-11-04 · 앱 패키지: kr.tkrmagid.tetrig</p>
|
||||
|
||||
<div class="panel">
|
||||
<p><strong>요약: TETRIG은 개인정보를 일절 수집하지 않습니다.</strong> 앱에는 인터넷 접근 권한조차 없으며,
|
||||
모든 데이터는 기기 안에만 저장됩니다.</p>
|
||||
<p><strong>요약:</strong> 온라인 대전(커스텀 방·리그전)과 리더보드를 위해 게임 계정 정보와 경기 기록을 서버에 저장합니다.
|
||||
무료 운영을 위해 Google AdMob 광고를 표시하며, 이 과정에서 광고 ID 등 기기 정보가 Google 에 전송될 수 있습니다.
|
||||
솔로 모드는 계정 없이도 쓸 수 있고, 계정은 앱 안에서 언제든 삭제할 수 있습니다.</p>
|
||||
</div>
|
||||
|
||||
<h2>1. 수집하는 개인정보</h2>
|
||||
<p>없습니다. TETRIG은 이름, 이메일, 전화번호, 위치, 연락처, 사진, 기기 식별자 등
|
||||
어떤 개인정보도 수집·요청·전송하지 않습니다. 회원가입 절차가 없습니다.</p>
|
||||
|
||||
<h2>2. 기기에 저장되는 정보</h2>
|
||||
<p>아래 항목만 기기 내부 저장소(Android SharedPreferences)에 저장되며 외부로 전송되지 않습니다.</p>
|
||||
<h2>1. 수집하는 정보와 목적</h2>
|
||||
<ul>
|
||||
<li>솔로 모드 최고 기록 (SPRINT 최단 시간, TIME ATTACK / ENDLESS 최고 점수)</li>
|
||||
<li>게임 설정값 (고스트 표시, 왼손 배치, 큰 버튼)</li>
|
||||
<li><strong>게스트 계정</strong>: 앱이 처음 실행될 때 무작위 닉네임과 무작위 기기 식별값(앱이 직접 만든 값, 하드웨어 ID 아님)을 서버에 등록합니다. 온라인 대전 참가와 기록 저장에 씁니다.</li>
|
||||
<li><strong>이메일 계정(선택)</strong>: 이메일 주소, 비밀번호(PBKDF2 해시로만 저장, 원문 저장 안 함), 닉네임. 로그인과 기록 이전에 씁니다.</li>
|
||||
<li><strong>게임 기록</strong>: 솔로 최고 기록, 리그 레이팅(Glicko-2·TR)·전적, 커스텀 방 순위. 리더보드·프로필 표시와 매칭에 씁니다.</li>
|
||||
<li><strong>대전 중 데이터</strong>: 보드 상태, 공격량 등 경기 진행 신호. 실시간 중계와 부정행위 방지에만 쓰며 경기가 끝나면 결과만 남습니다.</li>
|
||||
</ul>
|
||||
<p>앱을 삭제하면 이 데이터도 함께 삭제됩니다.</p>
|
||||
|
||||
<h2>3. 권한</h2>
|
||||
<p>TETRIG은 인터넷, 저장소, 위치, 카메라, 마이크, 연락처 등 어떤 런타임 권한도 요청하지 않습니다.</p>
|
||||
<h2>2. 광고 (Google AdMob)</h2>
|
||||
<p>메인 화면·커스텀 로비 하단 배너, 결과 화면 광고, 그리고 3판에 한 번 결과 화면을 나갈 때 전면 광고를 표시합니다. 게임 플레이 중에는 광고가 나오지 않습니다.
|
||||
광고 제공을 위해 Google 이 광고 ID, IP 주소, 기기·앱 정보를 수집·처리할 수 있습니다. 유럽경제지역·영국 등에서는 처음 실행 시 동의 화면이 표시됩니다.
|
||||
Google 의 처리 방식: <a href="https://policies.google.com/technologies/partner-sites">https://policies.google.com/technologies/partner-sites</a>.
|
||||
기기 설정 > Google > 광고에서 광고 ID 를 재설정하거나 삭제할 수 있습니다.</p>
|
||||
|
||||
<h2>4. 제3자 제공 · 광고 · 분석</h2>
|
||||
<p>광고 SDK, 분석 SDK, 크래시 리포팅 도구를 일절 포함하지 않습니다.
|
||||
따라서 제3자에게 제공되는 데이터도 없습니다.</p>
|
||||
<h2>3. 보관과 처리 위치</h2>
|
||||
<p>서버는 Cloudflare(Workers·D1)에서 운영되며 전송 구간은 모두 HTTPS/WSS 로 암호화됩니다. 계정을 삭제하기 전까지 보관하고, 삭제하면 즉시 지웁니다.
|
||||
리그 경기 결과에는 상대 플레이어의 전적 보존을 위해 개인을 식별할 수 없는 내부 ID 와 점수만 남습니다.</p>
|
||||
|
||||
<h2>5. 아동 개인정보</h2>
|
||||
<p>어떤 이용자로부터도 개인정보를 수집하지 않으므로, 만 14세 미만 아동의 개인정보 역시 수집하지 않습니다.</p>
|
||||
<h2>4. 계정 삭제</h2>
|
||||
<p>앱 > 프로필 > <strong>계정 삭제</strong>를 누르면 계정, 이메일, 비밀번호 해시, 닉네임, 레이팅, 솔로 기록, 커스텀 전적이 즉시 삭제됩니다.
|
||||
앱을 쓸 수 없는 경우 가입한 이메일로 <a href="mailto:tkrmagid@gmail.com?subject=TETRIG%20계정%20삭제%20요청">tkrmagid@gmail.com</a> 에 삭제를 요청하면 7일 안에 처리합니다.</p>
|
||||
|
||||
<h2>6. 변경 고지</h2>
|
||||
<p>향후 온라인 대전 기능이 추가되어 수집 항목이 생기면, 이 문서를 갱신하고
|
||||
앱 업데이트 시점에 안내합니다.</p>
|
||||
<h2>5. 기기에 저장되는 정보</h2>
|
||||
<p>로그인 토큰, 솔로 최고 기록, 설정값(고스트·왼손 배치·큰 버튼)이 기기 안(SharedPreferences)에 저장되며 앱을 삭제하면 함께 지워집니다.</p>
|
||||
|
||||
<h2>7. 문의</h2>
|
||||
<p>개인정보 관련 문의: <a href="mailto:tkrmagid@gmail.com">tkrmagid@gmail.com</a></p>
|
||||
<h2>6. 권한</h2>
|
||||
<p>인터넷·네트워크 상태 권한만 사용합니다(온라인 대전과 광고). 위치·카메라·마이크·연락처 권한은 요청하지 않습니다.</p>
|
||||
|
||||
<h2>7. 제3자 제공</h2>
|
||||
<p>광고를 위한 Google AdMob 외에는 어떤 제3자에게도 정보를 판매·제공하지 않습니다. 분석·추적 SDK 는 쓰지 않습니다.</p>
|
||||
|
||||
<h2>8. 아동</h2>
|
||||
<p>만 14세 미만 아동을 대상으로 하지 않으며, 그 사실을 알게 되면 해당 계정을 삭제합니다.</p>
|
||||
|
||||
<h2>9. 문의</h2>
|
||||
<p><a href="mailto:tkrmagid@gmail.com">tkrmagid@gmail.com</a></p>
|
||||
|
||||
<hr>
|
||||
|
||||
<h1><span class="o">TET</span>RIG Privacy Policy</h1>
|
||||
<p class="meta">Last updated: 2026-09-24 · Package: kr.tkrmagid.tetrig</p>
|
||||
<p class="meta">Last updated: 2026-11-04 · Package: kr.tkrmagid.tetrig</p>
|
||||
|
||||
<div class="panel">
|
||||
<p><strong>Summary: TETRIG collects no personal data.</strong> The app does not even hold the
|
||||
INTERNET permission. All data stays on your device.</p>
|
||||
<p><strong>Summary:</strong> 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.</p>
|
||||
</div>
|
||||
|
||||
<h2>1. Data we collect</h2>
|
||||
<p>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.</p>
|
||||
|
||||
<h2>2. Data stored on your device</h2>
|
||||
<ul>
|
||||
<li>Solo mode personal bests (SPRINT time, TIME ATTACK / ENDLESS score)</li>
|
||||
<li>Gameplay settings (ghost piece, left-handed layout, large buttons)</li>
|
||||
<li><strong>Guest account</strong>: a random nickname and a random app-generated install ID (not a hardware ID), created on first launch.</li>
|
||||
<li><strong>Email account (optional)</strong>: email, password (stored only as a PBKDF2 hash), nickname.</li>
|
||||
<li><strong>Game records</strong>: solo bests, league rating and match history, custom room placements.</li>
|
||||
<li><strong>In-match signals</strong>: board state and attacks, used only to relay the live match and prevent cheating.</li>
|
||||
</ul>
|
||||
<p>Uninstalling the app removes this data.</p>
|
||||
|
||||
<h2>3. Permissions</h2>
|
||||
<p>TETRIG requests no runtime permissions and has no internet access.</p>
|
||||
<h2>2. Advertising (Google AdMob)</h2>
|
||||
<p>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 <a href="https://policies.google.com/technologies/partner-sites">https://policies.google.com/technologies/partner-sites</a>.</p>
|
||||
|
||||
<h2>4. Third parties, ads, analytics</h2>
|
||||
<p>No advertising SDK, no analytics SDK, no crash reporting. No data is shared with anyone.</p>
|
||||
<h2>3. Storage</h2>
|
||||
<p>The server runs on Cloudflare (Workers, D1); all traffic is encrypted (HTTPS/WSS). Data is kept until you delete your account.</p>
|
||||
|
||||
<h2>5. Children</h2>
|
||||
<p>Since no personal data is collected from any user, none is collected from children either.</p>
|
||||
<h2>4. Account deletion</h2>
|
||||
<p>In the app: Profile > <strong>계정 삭제 (Delete account)</strong> deletes your account, email, password hash, nickname, rating, solo records and custom history immediately.
|
||||
If you cannot use the app, email <a href="mailto:tkrmagid@gmail.com?subject=TETRIG%20account%20deletion">tkrmagid@gmail.com</a> from your registered address; requests are handled within 7 days.</p>
|
||||
|
||||
<h2>6. Changes</h2>
|
||||
<p>If online multiplayer is added later and data collection begins, this document will be updated
|
||||
and the change announced with the app update.</p>
|
||||
|
||||
<h2>7. Contact</h2>
|
||||
<h2>5. Contact</h2>
|
||||
<p><a href="mailto:tkrmagid@gmail.com">tkrmagid@gmail.com</a></p>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 59 KiB After Width: | Height: | Size: 60 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 61 KiB After Width: | Height: | Size: 60 KiB |
Reference in New Issue
Block a user