앱 - 전면 광고: 판 수를 기기에 저장해 앱을 다시 켜도 이어 센다. 규칙은 "마지막 전면 뒤 3판 이상 + 세션 첫 판 제외" - 보상형 광고: 30분 전면 끄기, TIME ATTACK 이어하기(1판 1회, 기록·리더보드 미반영), 리소 스킨·흑연 보드 해금 - Play Billing 9.1: remove_ads / supporter_pack(비소모) / season_pass(소모). 승인 즉시, 시즌 패스는 서버 적용 뒤 소비, 실행 때마다 복원 - 상점 탭: 시즌 패스 트랙, 블록 스킨 7종·보드 테마 5종, 배지 장착, 상품, 구매 복원 - 광고 제거 구매 시 배너·결과·전면 끔 (보상형은 선택지로 유지) - AdMob 미디에이션 어댑터: AppLovin, Pangle - 커스텀 방 초대 링크 https://tetrig.pages.dev/r/CODE (앱 링크) + 공유, 결과 카드 PNG 공유 - 로비·리더보드·프로필에 배지 표시 서버 - 0002_shop 마이그레이션: season_xp, user_items, purchases, users.badge - 시즌 패스 XP(솔로 10/커스텀 20+10/리그 25+15), 30레벨 무료·프리미엄 트랙 - /api/pass, /api/purchase(Google Play Developer API 검증, PLAY_SA_KEY), /api/badge - 게스트 병합·계정 삭제 시 패스·아이템·구매 이전/삭제 웹 - /r/<코드> 초대 안내 페이지, scripts/build-pages.sh, 개인정보처리방침·스토어 문구 갱신 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
173 lines
7.6 KiB
JavaScript
173 lines
7.6 KiB
JavaScript
// D1 접근 헬퍼. Worker 와 DO 가 공유한다.
|
|
import { glickoUpdate } from "./glicko.js";
|
|
import { PASS, awardXp, mergeShopStatements } from "./shop.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, badge: u.badge ?? 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();
|
|
// 시즌 패스 XP (실패해도 경기 결과에는 영향 없음)
|
|
await Promise.all([
|
|
awardXp(db, winner, PASS.LEAGUE_XP + PASS.LEAGUE_WIN_XP, now),
|
|
awardXp(db, loser, PASS.LEAGUE_XP, now),
|
|
]).catch((e) => console.error("xp", e));
|
|
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);
|
|
for (const st of standings) {
|
|
await awardXp(db, st.id, PASS.CUSTOM_XP + (st.rank === 1 ? PASS.CUSTOM_WIN_XP : 0), now).catch((e) => console.error("xp", e));
|
|
}
|
|
}
|
|
|
|
/** 일일 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([
|
|
...mergeShopStatements(db, guestId, userId),
|
|
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 };
|
|
}
|