Turn timer + auto-play, disconnect/reconnect, cosmetics, queue & paid plan

- Turn timer (20s) for play/trump; system auto-plays a smart move on timeout
- Disconnect handling (mock): wait-for-return countdown, system covers turns
- Cosmetics: titles, card-back styles, custom profile-image upload, badges;
  pickers in Profile; shop sells card styles; reward modal shows new titles
- Paid plan (pro): free players queue when server busy, pro skips; upgrade flow
- OnlineService extended (upgradePlan, richer profile patch); mock implements
  queue + plans; gamification adds TITLES + CARD_STYLES

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
soroush.asadi
2026-06-04 10:49:54 +03:30
parent 5776036d78
commit 13ec0d4300
16 changed files with 682 additions and 61 deletions
+67
View File
@@ -4,12 +4,15 @@
import {
AchievementDef,
AchievementUnlock,
CardStyleDef,
LeagueInfo,
MatchSummary,
PlayerStats,
RankTier,
RankTierId,
RewardResult,
TitleDef,
TitleUnlock,
UserProfile,
} from "./types";
@@ -176,6 +179,55 @@ export function achievementProgress(
}
}
/* ------------------------------ Titles ------------------------------- */
export const TITLES: TitleDef[] = [
{ id: "novice", nameFa: "تازه‌کار", nameEn: "Novice", hintFa: "پیش‌فرض", hintEn: "Default" },
{ id: "winner", nameFa: "برنده", nameEn: "Winner", hintFa: "۱۰ برد", hintEn: "10 wins" },
{ id: "kot_master", nameFa: "استاد کُت", nameEn: "Kot Master", hintFa: "۱۰ کُت", hintEn: "10 kots" },
{ id: "veteran", nameFa: "کهنه‌کار", nameEn: "Veteran", hintFa: "سطح ۲۰", hintEn: "Level 20" },
{ id: "champion", nameFa: "قهرمان", nameEn: "Champion", hintFa: "لیگ طلا", hintEn: "Gold league" },
{ id: "legend", nameFa: "اسطوره", nameEn: "Legend", hintFa: "لیگ استاد", hintEn: "Master league" },
];
export function titleUnlocked(
id: string,
stats: PlayerStats,
rating: number,
level: number
): boolean {
switch (id) {
case "novice":
return true;
case "winner":
return stats.wins >= 10;
case "kot_master":
return stats.kotsFor >= 10;
case "veteran":
return level >= 20;
case "champion":
return rating >= tierById("gold").floor;
case "legend":
return rating >= tierById("master").floor;
default:
return false;
}
}
/* ---------------------------- Card styles ---------------------------- */
export const CARD_STYLES: CardStyleDef[] = [
{ id: "classic", nameFa: "کلاسیک", nameEn: "Classic", c1: "#14274f", c2: "#0a142e", accent: "#d4af37", price: 0 },
{ id: "sapphire", nameFa: "یاقوت کبود", nameEn: "Sapphire", c1: "#0b3a82", c2: "#06173a", accent: "#6aa6ff", price: 800 },
{ id: "ruby", nameFa: "یاقوت", nameEn: "Ruby", c1: "#7f1d2e", c2: "#2b0a12", accent: "#ff7a90", price: 800 },
{ id: "emerald", nameFa: "زمرد", nameEn: "Emerald", c1: "#0d6b5e", c2: "#062420", accent: "#2dd4bf", price: 1000 },
{ id: "royal", nameFa: "سلطنتی", nameEn: "Royal", c1: "#4a1d7f", c2: "#1a0a2e", accent: "#c77dff", price: 1500 },
];
export function cardStyleById(id: string): CardStyleDef {
return CARD_STYLES.find((c) => c.id === id) ?? CARD_STYLES[0];
}
/* ---------------------- Apply a match result ------------------------- */
function applyStats(stats: PlayerStats, summary: MatchSummary): PlayerStats {
@@ -239,6 +291,19 @@ export function applyMatchResult(
const coinsAfter = Math.max(0, coinsBefore + cDelta + achievementCoins);
// Titles unlocked by the new state.
const ownedTitles = [...(profile.ownedTitles ?? [])];
const newTitles: TitleUnlock[] = [];
for (const tdef of TITLES) {
if (
titleUnlocked(tdef.id, stats, ratingAfter, lvl.level) &&
!ownedTitles.includes(tdef.id)
) {
ownedTitles.push(tdef.id);
newTitles.push({ id: tdef.id, nameFa: tdef.nameFa, nameEn: tdef.nameEn });
}
}
const leagueBefore = getLeagueInfo(ratingBefore);
const leagueAfter = getLeagueInfo(ratingAfter);
const tierIndex = (id: RankTierId) => RANK_TIERS.findIndex((t) => t.id === id);
@@ -256,6 +321,7 @@ export function applyMatchResult(
stats,
achievements,
unlocked,
ownedTitles,
};
const reward: RewardResult = {
@@ -270,6 +336,7 @@ export function applyMatchResult(
levelAfter: lvl.level,
leveledUp: lvl.level > levelBefore,
newAchievements,
newTitles,
promoted,
demoted,
};
+95 -22
View File
@@ -2,7 +2,7 @@
// Simulates remote players, friends presence, room invites and matchmaking
// with timers, and computes rewards via gamification.ts.
import { applyMatchResult, dailyRewardFor } from "./gamification";
import { CARD_STYLES, applyMatchResult, dailyRewardFor } from "./gamification";
import {
CreateRoomOptions,
MatchmakingOptions,
@@ -94,7 +94,7 @@ function defaultProfile(session: AuthSession): UserProfile {
username: "player_" + session.userId.slice(-4),
displayName: "بازیکن",
avatar: AVATARS[0].id,
phone: session.method === "phone" ? undefined : undefined,
plan: "free",
level: 1,
xp: 0,
coins: 1000,
@@ -110,13 +110,29 @@ function defaultProfile(session: AuthSession): UserProfile {
currentWinStreak: 0,
},
ownedAvatars: [AVATARS[0].id, AVATARS[1].id],
ownedThemes: ["royal"],
ownedCardStyles: ["classic"],
ownedTitles: ["novice"],
title: "novice",
cardStyle: "classic",
achievements: {},
unlocked: [],
createdAt: Date.now(),
};
}
/** Backfill fields on older persisted profiles so the app never crashes. */
function migrateProfile(p: UserProfile): UserProfile {
return {
...p,
plan: p.plan ?? "free",
ownedAvatars: p.ownedAvatars ?? [AVATARS[0].id],
ownedCardStyles: p.ownedCardStyles ?? ["classic"],
ownedTitles: p.ownedTitles ?? ["novice"],
title: p.title ?? "novice",
cardStyle: p.cardStyle ?? "classic",
};
}
function makeFriend(status?: PresenceStatus): Friend {
return {
id: rid("fr"),
@@ -147,6 +163,7 @@ export class MockOnlineService implements OnlineService {
| null = null;
private currentOppRating = 1000;
private lastOtp = "";
private mmOpts: MatchmakingOptions | null = null;
private messages: Record<string, ChatMessage[]> = {};
private unread: Record<string, number> = {};
@@ -159,7 +176,8 @@ export class MockOnlineService implements OnlineService {
constructor() {
this.session = load<AuthSession>(LS.session);
this.profile = load<UserProfile>(LS.profile);
const loaded = load<UserProfile>(LS.profile);
this.profile = loaded ? migrateProfile(loaded) : null;
this.messages = load<Record<string, ChatMessage[]>>(LS.chats) ?? {};
this.seedFriends();
}
@@ -282,27 +300,40 @@ export class MockOnlineService implements OnlineService {
async getProfile() {
if (!this.profile) {
// guest fallback profile (not persisted as session)
this.profile =
load<UserProfile>(LS.profile) ??
defaultProfile({
userId: rid("guest"),
token: "",
method: "guest",
createdAt: Date.now(),
});
const loaded = load<UserProfile>(LS.profile);
this.profile = loaded
? migrateProfile(loaded)
: defaultProfile({
userId: rid("guest"),
token: "",
method: "guest",
createdAt: Date.now(),
});
this.saveProfile();
}
return this.profile;
}
async updateProfile(patch: Partial<Pick<UserProfile, "displayName" | "avatar">>) {
async updateProfile(
patch: Partial<
Pick<UserProfile, "displayName" | "avatar" | "avatarImage" | "title" | "cardStyle">
>
) {
const p = await this.getProfile();
this.profile = { ...p, ...patch };
this.saveProfile();
return this.profile;
}
async upgradePlan(): Promise<UserProfile> {
const p = await this.getProfile();
this.profile = { ...p, plan: "pro", planUntil: Date.now() + 30 * 864e5 };
this.saveProfile();
// pro players skip the queue immediately
if (this.matchmaking.phase === "queued") this.beginSearch();
return this.profile;
}
/* ----------------------------- friends ----------------------------- */
async listFriends() {
@@ -536,6 +567,44 @@ export class MockOnlineService implements OnlineService {
async startMatchmaking(opts: MatchmakingOptions) {
await this.getProfile();
this.mmOpts = opts;
const me = this.profile!;
const pro = me.plan === "pro";
const busy = Math.random() < 0.7;
if (!pro && busy) {
// server is busy and the player is on the free plan → queue them
let pos = randInt(3, 8);
this.matchmaking = {
phase: "queued",
players: [{ id: me.id, displayName: me.displayName, avatar: me.avatar, level: me.level, rating: me.rating }],
elapsedMs: 0,
ranked: opts.ranked,
stake: opts.stake,
queuePosition: pos,
};
this.emitMM();
const tick = () =>
this.after(1100, () => {
if (this.matchmaking.phase !== "queued") return;
pos -= 1;
if (pos <= 0) {
this.beginSearch();
} else {
this.matchmaking.queuePosition = pos;
this.emitMM();
tick();
}
});
tick();
return;
}
this.beginSearch();
}
private beginSearch() {
const opts = this.mmOpts!;
const me = this.profile!;
this.matchmaking = {
phase: "searching",
@@ -646,12 +715,15 @@ export class MockOnlineService implements OnlineService {
price: 500 + i * 150,
preview: a.emoji,
}));
const themes: ShopItem[] = [
{ id: "midnight", kind: "theme", nameFa: "تم نیمه‌شب", nameEn: "Midnight", price: 1200, preview: "#0a142e" },
{ id: "emerald", kind: "theme", nameFa: "تم زمرد", nameEn: "Emerald", price: 1500, preview: "#0d6b6b" },
{ id: "crimson", kind: "theme", nameFa: "تم یاقوت", nameEn: "Crimson", price: 1800, preview: "#7f1d2e" },
];
return [...avatarItems, ...themes];
const cardItems: ShopItem[] = CARD_STYLES.filter((c) => c.price > 0).map((c) => ({
id: c.id,
kind: "cardstyle",
nameFa: c.nameFa,
nameEn: c.nameEn,
price: c.price,
preview: c.accent,
}));
return [...avatarItems, ...cardItems];
}
async buyItem(id: string) {
@@ -660,7 +732,7 @@ export class MockOnlineService implements OnlineService {
const item = items.find((i) => i.id === id);
if (!item) return { ok: false, messageFa: "آیتم یافت نشد", messageEn: "Item not found" };
const owned =
item.kind === "avatar" ? p.ownedAvatars.includes(id) : p.ownedThemes.includes(id);
item.kind === "avatar" ? p.ownedAvatars.includes(id) : p.ownedCardStyles.includes(id);
if (owned) return { ok: false, messageFa: "قبلاً خریداری شده", messageEn: "Already owned" };
if (p.coins < item.price)
return { ok: false, messageFa: "سکه کافی نیست", messageEn: "Not enough coins" };
@@ -669,7 +741,8 @@ export class MockOnlineService implements OnlineService {
...p,
coins: p.coins - item.price,
ownedAvatars: item.kind === "avatar" ? [...p.ownedAvatars, id] : p.ownedAvatars,
ownedThemes: item.kind === "theme" ? [...p.ownedThemes, id] : p.ownedThemes,
ownedCardStyles:
item.kind === "cardstyle" ? [...p.ownedCardStyles, id] : p.ownedCardStyles,
};
this.saveProfile();
return { ok: true, profile: this.profile, messageFa: "خرید انجام شد", messageEn: "Purchased" };
+6 -1
View File
@@ -44,7 +44,12 @@ export interface OnlineService {
/* ----- profile ----- */
getProfile(): Promise<UserProfile>;
updateProfile(patch: Partial<Pick<UserProfile, "displayName" | "avatar">>): Promise<UserProfile>;
updateProfile(
patch: Partial<
Pick<UserProfile, "displayName" | "avatar" | "avatarImage" | "title" | "cardStyle">
>
): Promise<UserProfile>;
upgradePlan(): Promise<UserProfile>;
/* ----- friends ----- */
listFriends(): Promise<Friend[]>;
+46 -2
View File
@@ -28,22 +28,35 @@ export interface PlayerStats {
currentWinStreak: number;
}
export type PlanId = "free" | "pro";
export interface UserProfile {
id: string;
username: string;
displayName: string;
avatar: string; // avatar id (see AVATARS)
avatarImage?: string; // custom uploaded image (data URL); overrides avatar
phone?: string;
email?: string;
plan: PlanId;
/** epoch ms when a pro plan expires (mock: far future) */
planUntil?: number;
level: number;
xp: number; // xp within the current level
coins: number;
rating: number; // competitive rating
stats: PlayerStats;
// cosmetics
ownedAvatars: string[];
ownedThemes: string[];
ownedCardStyles: string[];
ownedTitles: string[];
title: string | null; // equipped title id
cardStyle: string; // equipped card-back style id
achievements: Record<string, number>; // achievementId -> progress count
unlocked: string[]; // achievementId list already unlocked
@@ -98,6 +111,27 @@ export interface AchievementView extends AchievementDef {
unlocked: boolean;
}
/* ----------------------- Titles & card styles ------------------------ */
export interface TitleDef {
id: string;
nameFa: string;
nameEn: string;
/** how it's unlocked (for display) */
hintFa: string;
hintEn: string;
}
export interface CardStyleDef {
id: string;
nameFa: string;
nameEn: string;
c1: string; // back gradient start
c2: string; // back gradient end
accent: string; // pattern/border accent
price: number; // 0 = free/default
}
/* ------------------------------ Friends ------------------------------ */
export type PresenceStatus = "online" | "offline" | "in-game";
@@ -152,6 +186,7 @@ export interface Room {
export type MatchmakingPhase =
| "idle"
| "queued" // server busy, free plan waiting in line
| "searching"
| "found"
| "ready"
@@ -170,6 +205,8 @@ export interface MatchmakingState {
elapsedMs: number;
ranked: boolean;
stake: number;
/** position in the queue when phase === "queued" */
queuePosition?: number;
}
/* ------------------------- Match + Rewards --------------------------- */
@@ -193,6 +230,12 @@ export interface AchievementUnlock {
coinReward: number;
}
export interface TitleUnlock {
id: string;
nameFa: string;
nameEn: string;
}
export interface RewardResult {
ratingBefore: number;
ratingAfter: number;
@@ -205,6 +248,7 @@ export interface RewardResult {
levelAfter: number;
leveledUp: boolean;
newAchievements: AchievementUnlock[];
newTitles: TitleUnlock[];
promoted: boolean;
demoted: boolean;
}
@@ -223,7 +267,7 @@ export interface LeaderboardEntry {
/* ------------------------------- Shop -------------------------------- */
export type ShopItemKind = "avatar" | "theme";
export type ShopItemKind = "avatar" | "cardstyle";
export interface ShopItem {
id: string;