From b661385a00b630c52b0cdedc96a919187300131b Mon Sep 17 00:00:00 2001 From: "soroush.asadi" Date: Fri, 5 Jun 2026 09:52:28 +0330 Subject: [PATCH] Celebration animations for purchases, XP gains & achievement unlocks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - New global celebration system: celebration-store (queue) + CelebrationOverlay (animated: count-up XP, filling bar, level-up pop, achievement cards; plays levelUp/award sounds; tap or auto-dismiss). Rendered in page.tsx. - Shop: every purchase now celebrates — XP packs animate XP gain + level-up, cosmetics show a "purchased!" pop. Newly-unlocked achievements (diffed from the profile before/after) animate too. - XP purchases now actually evaluate achievements: gamification.evaluateAchievements (client) + Gamification.EvaluateAchievements (server, called in ShopBuy xp path) unlock level milestones + grant their coins. Verified live: buying XP took L1→L5, unlocked level_5 server-side and credited its reward. tsc + dotnet + next build clean; images rebuilt :1500/:1505. Co-Authored-By: Claude Opus 4.8 --- .../src/Hokm.Server/Profiles/Gamification.cs | 19 ++ .../Hokm.Server/Profiles/ProfileService.cs | 1 + src/app/page.tsx | 2 + src/components/online/CelebrationOverlay.tsx | 165 ++++++++++++++++++ src/components/screens/ShopScreen.tsx | 35 +++- src/lib/celebration-store.ts | 45 +++++ src/lib/i18n.tsx | 2 + src/lib/online/gamification.ts | 34 ++++ src/lib/online/mock-service.ts | 6 +- 9 files changed, 306 insertions(+), 3 deletions(-) create mode 100644 src/components/online/CelebrationOverlay.tsx create mode 100644 src/lib/celebration-store.ts diff --git a/server/src/Hokm.Server/Profiles/Gamification.cs b/server/src/Hokm.Server/Profiles/Gamification.cs index 28f1d09..caac5ea 100644 --- a/server/src/Hokm.Server/Profiles/Gamification.cs +++ b/server/src/Hokm.Server/Profiles/Gamification.cs @@ -148,6 +148,25 @@ public static class Gamification p.Xp = r.xp; } + /// Re-evaluate achievements vs current state (outside a match), unlock new + /// ones + grant their coins, and return the newly-unlocked list. + public static List EvaluateAchievements(ProfileDto p) + { + var list = new List(); + foreach (var d in Achs) + { + int prog = AchProgress(d, p.Stats, p.Rating, p.Level); + p.Achievements[d.Id] = prog; + if (prog >= d.Goal && !p.Unlocked.Contains(d.Id)) + { + p.Unlocked.Add(d.Id); + p.Coins += d.Coin; + list.Add(new() { Id = d.Id, NameFa = d.NameFa, NameEn = d.NameEn, Icon = d.Icon, CoinReward = d.Coin }); + } + } + return list; + } + private static (int level, int xp, bool up) AddXp(int level, int xp, int gain) { bool up = false; diff --git a/server/src/Hokm.Server/Profiles/ProfileService.cs b/server/src/Hokm.Server/Profiles/ProfileService.cs index cf3ab17..497c547 100644 --- a/server/src/Hokm.Server/Profiles/ProfileService.cs +++ b/server/src/Hokm.Server/Profiles/ProfileService.cs @@ -131,6 +131,7 @@ public class ProfileService if (p.Coins < pk.Price) return (false, p, "insufficient"); p.Coins -= pk.Price; Gamification.GrantXp(p, pk.Xp); + Gamification.EvaluateAchievements(p); // unlock any level milestones reached await Save(p); await Ledger(uid, "xp", -pk.Price, id); return (true, p, ""); diff --git a/src/app/page.tsx b/src/app/page.tsx index 1459111..fa95271 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -18,6 +18,7 @@ import { AuthScreen } from "@/components/screens/AuthScreen"; import { DailyRewardModal } from "@/components/online/DailyRewardModal"; import { NotificationToaster } from "@/components/online/NotificationToaster"; import { ResumeGameBar } from "@/components/online/ResumeGameBar"; +import { CelebrationOverlay } from "@/components/online/CelebrationOverlay"; import { CapacitorBack } from "@/components/CapacitorBack"; import { useSessionStore } from "@/lib/session-store"; import { useGameStore } from "@/lib/game-store"; @@ -141,6 +142,7 @@ export default function Page() { + {loading && null} diff --git a/src/components/online/CelebrationOverlay.tsx b/src/components/online/CelebrationOverlay.tsx new file mode 100644 index 0000000..c31bac2 --- /dev/null +++ b/src/components/online/CelebrationOverlay.tsx @@ -0,0 +1,165 @@ +"use client"; + +import { AnimatePresence, motion } from "framer-motion"; +import { Coins, Sparkles, Star, TrendingUp } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; +import { useCelebrationStore } from "@/lib/celebration-store"; +import { useI18n } from "@/lib/i18n"; +import { sound } from "@/lib/sound"; + +function useCountUp(target: number, ms = 900, run = true) { + const [v, setV] = useState(0); + const raf = useRef(null); + useEffect(() => { + if (!run) return; + const start = performance.now(); + const tick = (now: number) => { + const p = Math.min(1, (now - start) / ms); + // ease-out + setV(Math.round(target * (1 - Math.pow(1 - p, 3)))); + if (p < 1) raf.current = requestAnimationFrame(tick); + }; + raf.current = requestAnimationFrame(tick); + return () => { if (raf.current) cancelAnimationFrame(raf.current); }; + }, [target, ms, run]); + return v; +} + +/** Global animated celebration for purchases / XP gains / achievement unlocks. */ +export function CelebrationOverlay() { + const current = useCelebrationStore((s) => s.current); + const dismiss = useCelebrationStore((s) => s.dismiss); + + useEffect(() => { + if (!current) return; + const leveled = (current.levelAfter ?? 0) > (current.levelBefore ?? 0); + const cue = setTimeout(() => { + if (leveled) sound.play("levelUp"); + else if (current.achievements?.length) sound.play("award"); + }, 350); + const auto = setTimeout(() => dismiss(), current.achievements?.length ? 5200 : 3600); + return () => { clearTimeout(cue); clearTimeout(auto); }; + }, [current, dismiss]); + + return ( + + {current && } + + ); +} + +function Card() { + const { t, locale } = useI18n(); + const current = useCelebrationStore((s) => s.current)!; + const dismiss = useCelebrationStore((s) => s.dismiss); + const leveled = (current.levelAfter ?? 0) > (current.levelBefore ?? 0); + const xp = useCountUp(current.xpGained ?? 0, 900, current.variant === "xp"); + + return ( + + e.stopPropagation()} + className="glass rounded-3xl p-7 w-full max-w-xs text-center relative overflow-hidden" + > + {/* radiating glow */} +
+ + + {current.icon ?? (current.variant === "xp" ? "⚡" : "🛍️")} + + + {current.title && ( +

{current.title}

+ )} + + {/* XP gain */} + {current.variant === "xp" && (current.xpGained ?? 0) > 0 && ( +
+
+ + +{xp.toLocaleString()} XP +
+ + + +
+ )} + + {/* level up */} + {leveled && ( + + + {t("reward.levelUp")} → {current.levelAfter} + + )} + + {/* achievements */} + {current.achievements && current.achievements.length > 0 && ( +
+ {current.achievements.map((a, i) => ( + + {a.icon} + + {t("reward.newAchievement")} + + {locale === "fa" ? a.nameFa : a.nameEn} + + + + +{a.coinReward} + + + + ))} +
+ )} + + {current.variant === "purchase" && !current.achievements?.length && ( +

+ + {t("celebrate.purchased")} +

+ )} + + + + + ); +} diff --git a/src/components/screens/ShopScreen.tsx b/src/components/screens/ShopScreen.tsx index 0356663..3739ef0 100644 --- a/src/components/screens/ShopScreen.tsx +++ b/src/components/screens/ShopScreen.tsx @@ -9,7 +9,9 @@ import { useSessionStore } from "@/lib/session-store"; import { useI18n } from "@/lib/i18n"; import { getService } from "@/lib/online/service"; import { sound } from "@/lib/sound"; -import { ShopItem } from "@/lib/online/types"; +import { achievementById } from "@/lib/online/gamification"; +import { celebrate } from "@/lib/celebration-store"; +import { AchievementUnlock, ShopItem } from "@/lib/online/types"; import { cn } from "@/lib/cn"; /** The product artwork, used on the card and (bigger) in the detail sheet. */ @@ -75,11 +77,40 @@ export function ShopScreen() { }; const buy = async (item: ShopItem) => { + const before = profile; const res = await getService().buyItem(item.id); if (res.ok && res.profile) { - setProfile(res.profile); + const after = res.profile; + setProfile(after); sound.play("purchase"); setDetail(null); + + // newly-unlocked achievements (e.g. an XP pack crossing a level milestone) + const newAch: AchievementUnlock[] = after.unlocked + .filter((id) => !before.unlocked.includes(id)) + .map((id) => achievementById(id)) + .filter((d): d is NonNullable => !!d) + .map((d) => ({ id: d.id, nameFa: d.nameFa, nameEn: d.nameEn, icon: d.icon, coinReward: d.coinReward })); + + if (item.kind === "xp") { + celebrate({ + variant: "xp", + icon: "⚡", + title: locale === "fa" ? "امتیاز تجربه" : "Experience", + xpGained: item.xp ?? 0, + levelBefore: before.level, + levelAfter: after.level, + achievements: newAch.length ? newAch : undefined, + }); + } else { + celebrate({ + variant: "purchase", + // avatar/reaction previews are emojis; others fall back to the default glyph + icon: item.kind === "avatar" || item.kind === "reactionpack" ? item.preview : undefined, + title: locale === "fa" ? item.nameFa : item.nameEn, + achievements: newAch.length ? newAch : undefined, + }); + } } else { setMsg(locale === "fa" ? res.messageFa : res.messageEn); setTimeout(() => setMsg(""), 1800); diff --git a/src/lib/celebration-store.ts b/src/lib/celebration-store.ts new file mode 100644 index 0000000..2fadcc9 --- /dev/null +++ b/src/lib/celebration-store.ts @@ -0,0 +1,45 @@ +"use client"; + +import { create } from "zustand"; +import { AchievementUnlock } from "./online/types"; + +/** A queued celebration shown by . */ +export interface Celebration { + id: number; + variant: "xp" | "purchase"; + title?: string; + /** emoji/glyph shown big at the top */ + icon?: string; + xpGained?: number; + levelBefore?: number; + levelAfter?: number; + achievements?: AchievementUnlock[]; +} + +interface CelebrationStore { + current: Celebration | null; + queue: Celebration[]; + celebrate: (c: Omit) => void; + dismiss: () => void; +} + +let _id = 1; + +export const useCelebrationStore = create((set, get) => ({ + current: null, + queue: [], + celebrate: (c) => { + const item: Celebration = { ...c, id: _id++ }; + if (get().current) set({ queue: [...get().queue, item] }); + else set({ current: item }); + }, + dismiss: () => { + const [next, ...rest] = get().queue; + set({ current: next ?? null, queue: rest }); + }, +})); + +/** Convenience helper usable from anywhere (no hook needed). */ +export function celebrate(c: Omit) { + useCelebrationStore.getState().celebrate(c); +} diff --git a/src/lib/i18n.tsx b/src/lib/i18n.tsx index fd0fcb4..b0f6617 100644 --- a/src/lib/i18n.tsx +++ b/src/lib/i18n.tsx @@ -33,6 +33,7 @@ const fa: Dict = { "resume.cta": "بازگشت به بازی", "resume.matchEnded": "بازی به پایان رسید", "resume.matchEndedBody": "نتیجه و جایزه را ببینید", + "celebrate.purchased": "خرید با موفقیت انجام شد!", "achv.title": "دستاوردها", "achv.unlocked": "باز شده", @@ -299,6 +300,7 @@ const en: Dict = { "resume.cta": "Return to game", "resume.matchEnded": "Match ended", "resume.matchEndedBody": "See the result and reward", + "celebrate.purchased": "Purchase complete!", "achv.title": "Achievements", "achv.unlocked": "Unlocked", diff --git a/src/lib/online/gamification.ts b/src/lib/online/gamification.ts index fe2fdc0..a067222 100644 --- a/src/lib/online/gamification.ts +++ b/src/lib/online/gamification.ts @@ -298,6 +298,40 @@ export function achievementById(id: string): AchievementDef | undefined { return ACHIEVEMENTS.find((a) => a.id === id); } +/** + * Re-evaluate all achievements against the profile's current state (used outside + * matches, e.g. after an XP-pack purchase crosses a level milestone). Unlocks new + * ones, grants their coin rewards, and returns the newly-unlocked list. + */ +export function evaluateAchievements(profile: UserProfile): { + profile: UserProfile; + newAchievements: AchievementUnlock[]; +} { + const achievements = { ...profile.achievements }; + const unlocked = [...profile.unlocked]; + const newAchievements: AchievementUnlock[] = []; + let coins = 0; + for (const def of ACHIEVEMENTS) { + const prog = achievementProgress(def, profile.stats, profile.rating, profile.level); + achievements[def.id] = prog; + if (prog >= def.goal && !unlocked.includes(def.id)) { + unlocked.push(def.id); + coins += def.coinReward; + newAchievements.push({ + id: def.id, + nameFa: def.nameFa, + nameEn: def.nameEn, + icon: def.icon, + coinReward: def.coinReward, + }); + } + } + return { + profile: { ...profile, achievements, unlocked, coins: profile.coins + coins }, + newAchievements, + }; +} + /** The sticker pack (if any) that unlocking this achievement grants. */ export function stickerPackForAchievement(achId: string): StickerPackDef | undefined { return STICKER_PACKS.find((p) => p.unlockAchievement === achId); diff --git a/src/lib/online/mock-service.ts b/src/lib/online/mock-service.ts index 663fd40..f665121 100644 --- a/src/lib/online/mock-service.ts +++ b/src/lib/online/mock-service.ts @@ -11,6 +11,7 @@ import { addXp, applyMatchResult, dailyRewardFor, + evaluateAchievements, faNum, xpNeededForLevel, } from "./gamification"; @@ -898,7 +899,10 @@ export class MockOnlineService implements OnlineService { return { ok: false, messageFa: "سکه کافی نیست", messageEn: "Not enough coins" }; const pack = XP_PACKS.find((x) => x.id === id)!; const lvl = addXp(p.level, p.xp, pack.xp); - this.profile = { ...p, coins: p.coins - item.price, level: lvl.level, xp: lvl.xp }; + const leveled = { ...p, coins: p.coins - item.price, level: lvl.level, xp: lvl.xp }; + // unlock any level milestones the new level reaches + const { profile: evaluated } = evaluateAchievements(leveled); + this.profile = evaluated; this.saveProfile(); return { ok: true, profile: this.profile, messageFa: "امتیاز اضافه شد", messageEn: "XP added" }; }