import { useEffect, useRef, useState, type PointerEvent } from 'react' import { createPortal } from 'react-dom' import { useNavigate } from 'react-router' import { useQuery, useQueryClient } from '@tanstack/react-query' import { getWeatherTodayOptions, myLevelQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' import { gameRound, gameStart } from '@nalssigak/shared/api/client/sdk.gen' import type { ResLevel } from '@nalssigak/shared/api/client/types.gen' import { kst } from '@nalssigak/shared/lib' import { slotAt } from '@nalssigak/shared/lib/weatherText' import { track } from '../lib/analytics' import { cx } from '../lib/utils' import { useAuth } from './authContext' import { createGame, DROP_Y, H, HOLIDAY, LEVELS, LINE_Y, loadBest, randomLevel, roundTarget, saveBest, W, windDir, type Game } from './cloudMerge' import { useLevel } from './level' import { iconSrc } from './lib' import { useRegion } from './regionContext' import { useSheet } from './sheetContext' import { Ic, TAP44 } from './ui' const gameEarned = (l: ResLevel | undefined) => l?.today?.find((a) => a.action === 'game') /** 라운드를 깨면 서버에 알려 각을 받는다. 내 레벨은 판이 끝날 때 한 번에 바꿔, 게임 중에 레벨업 창이 뜨지 않게 한다 */ async function claimRound(play: string, round: number) { try { const { data } = await gameRound({ body: { play, round } }) return data.result?.success ? data : undefined } catch (e) { console.warn('[game] 라운드 각을 받지 못함', e) return undefined } } const images = LEVELS.map((l) => { const img = new Image() img.src = iconSrc(l.icon) ?? '' return img }) /** 부딪히는 원이 보이게 동그란 방울을 그리고 그 안에 그림 */ function bubble(ctx: CanvasRenderingContext2D, level: number, x: number, y: number, angle = 0) { const { r, color } = LEVELS[level] ctx.save() ctx.translate(x, y) ctx.beginPath() ctx.arc(0, 0, r, 0, Math.PI * 2) ctx.fillStyle = color ctx.fill() ctx.lineWidth = 2 ctx.strokeStyle = 'rgb(255 255 255 / 0.9)' ctx.stroke() ctx.rotate(angle) const s = r * 1.5 ctx.drawImage(images[level], -s / 2, -s / 2, s, s) ctx.restore() } function draw(ctx: CanvasRenderingContext2D, game: Game, aimX: number | null, next: number, danger: boolean) { ctx.clearRect(0, 0, W, H) ctx.setLineDash([6, 6]) ctx.strokeStyle = danger ? '#e5484d' : 'rgb(40 48 74 / 0.18)' ctx.lineWidth = 2 ctx.beginPath() ctx.moveTo(0, LINE_Y) ctx.lineTo(W, LINE_Y) ctx.stroke() if (aimX != null) { const r = LEVELS[next].r const x = Math.min(Math.max(aimX, r), W - r) ctx.strokeStyle = 'rgb(40 48 74 / 0.12)' ctx.beginPath() ctx.moveTo(x, DROP_Y) ctx.lineTo(x, H) ctx.stroke() ctx.globalAlpha = 0.85 bubble(ctx, next, x, DROP_Y) ctx.globalAlpha = 1 } ctx.setLineDash([]) for (const p of game.pieces()) { bubble(ctx, p.level, p.position.x, p.position.y, p.angle) } } /** 구름 합치기: 같은 날씨끼리 합쳐 해까지. 지금 고른 구의 풍속만큼 떨어지는 동안 옆으로 밀린다 */ export function CloudMergePage() { const navigate = useNavigate() const { region } = useRegion() const { open } = useSheet() const { loggedIn } = useAuth() const queryClient = useQueryClient() const level = useLevel().data const [earned, setEarned] = useState(null) const [gain, setGain] = useState(0) const baseRef = useRef(undefined) useEffect(() => { baseRef.current = gameEarned(level)?.earned }, [level]) const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } })) const [now] = useState(() => kst(new Date())) const slots = today.data?.slots ?? [] const windMs = slots.length ? (slotAt(slots, now.h).wind_ms ?? 0) : 0 const dir = windDir(now.d) const canvasRef = useRef(null) const gameRef = useRef(null) const aimRef = useRef(W / 2) const [next, setNext] = useState(randomLevel) const nextRef = useRef(next) const coolRef = useRef(0) // 이번 판에 떨어뜨린 횟수: 0 이면 아직 시작 전(첫 그림에서 game_start) const dropsRef = useRef(0) const [score, setScore] = useState(0) const [best, setBest] = useState(loadBest) const [over, setOver] = useState(false) const [play, setPlay] = useState(0) const [round, setRound] = useState(1) const [roundGot, setRoundGot] = useState(0) const [flash, setFlash] = useState(false) useEffect(() => { if (!today.isSuccess) return const canvas = canvasRef.current const ctx = canvas?.getContext('2d') if (!canvas || !ctx) return const ratio = window.devicePixelRatio || 1 canvas.width = W * ratio canvas.height = H * ratio ctx.scale(ratio, ratio) let roundNo = 1 let total = 0 dropsRef.current = 0 let base = 0 let flashTimer: ReturnType | undefined let ticket: Promise = Promise.resolve(undefined) let lastLevel: ResLevel | undefined let gotSoFar = baseRef.current const settle = () => { if (lastLevel) queryClient.setQueryData(myLevelQueryKey(), lastLevel) lastLevel = undefined } if (loggedIn) { ticket = gameStart() .then(({ data }) => data.play ?? undefined) .catch((e: unknown) => { console.warn('[game] 판을 열지 못함', e) return undefined }) } const claim = async (round: number) => { const token = await ticket if (!token) return const res = await claimRound(token, round) const now = gameEarned(res)?.earned if (!res || now == null) return lastLevel = res if (gotSoFar != null && now > gotSoFar) setGain(now - gotSoFar) gotSoFar = now setEarned(now) } const game = createGame(windMs, dir, { onScore: (s) => { total = s setScore(s) if (s - base >= roundTarget(roundNo)) { roundNo += 1 base = s setRound(roundNo) setFlash(true) setGain(0) clearTimeout(flashTimer) flashTimer = setTimeout(() => setFlash(false), 1400) void claim(roundNo - 1) track('game_round', { round: roundNo - 1, score: s, logged_in: loggedIn }) } setRoundGot(s - base) if (s > loadBest()) { saveBest(s) setBest(s) } }, onOver: () => { setOver(true) track('game_over', { round: roundNo, score: total, best: total > 0 && total >= loadBest(), drops: dropsRef.current }) settle() }, }) gameRef.current = game let last = performance.now() let raf = 0 const loop = (t: number) => { game.step(t - last, t) last = t draw(ctx, game, aimRef.current, nextRef.current, game.danger()) raf = requestAnimationFrame(loop) } raf = requestAnimationFrame(loop) return () => { cancelAnimationFrame(raf) clearTimeout(flashTimer) game.destroy() settle() gameRef.current = null } }, [today.isSuccess, windMs, dir, play, loggedIn, queryClient]) const toX = (e: PointerEvent) => { const rect = e.currentTarget.getBoundingClientRect() return ((e.clientX - rect.left) / rect.width) * W } const onMove = (e: PointerEvent) => { aimRef.current = toX(e) } const onUp = (e: PointerEvent) => { const game = gameRef.current if (!game || over || performance.now() < coolRef.current) return if (dropsRef.current === 0) track('game_start', { again: play > 0, logged_in: loggedIn, wind_ms: windMs, theme: HOLIDAY?.key ?? 'basic' }) dropsRef.current += 1 game.drop(nextRef.current, toX(e)) coolRef.current = performance.now() + 450 nextRef.current = randomLevel() setNext(nextRef.current) } const restart = () => { setScore(0) setOver(false) setRound(1) setRoundGot(0) setPlay((n) => n + 1) } const cap = gameEarned(level)?.cap ?? 20 const todayGak = earned ?? gameEarned(level)?.earned ?? 0 const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/')) const windText = windMs < 0.5 ? '바람 없음' : `${dir > 0 ? '→' : '←'} 초속 ${windMs.toFixed(1)}m` // 스택 화면: 머리줄·탭을 덮게 body 로 띄운다(main 이 쌓임 순서를 가둬서). b-app 의 낮 색을 그대로 써 밤에도 밝은 바탕 return createPortal(

구름 합치기

{region.short_name} {windText}

{round}라운드

다음 라운드까지 {roundGot} / {roundTarget(round)}

다음

점수 {score} · 최고 {best} {loggedIn ? ( 오늘 게임 각 {todayGak} / {cap} ) : ( )}

{/* 남은 높이를 다 쓰되 2:3 비율은 지킨다 */}
{!today.isSuccess &&

{today.isError ? '날씨를 불러오지 못했어요' : '오늘 바람 불러오는 중…'}

} {flash && !over && (

{round}라운드! {gain > 0 && +{gain}각}

)} {over && (

넘쳤어요!

{round}라운드 · 총 {score}점{score >= best && score > 0 ? ' · 최고 기록' : ''}

{loggedIn && (

오늘 게임 각 {todayGak} / {cap}

)}
)}
{LEVELS.map((l, i) => ( {i < LEVELS.length - 1 && '›'} ))}
, document.body, ) }