Files
o2o-weather/frontend/src/b/CloudMergePage.tsx
T
minaChoi 4fec164364 feat: 기념일 꾸밈 — 할로윈·빼빼로데이·크리스마스·추석 기간에만 이야기 주제와 구름 합치기 그림이 바뀜
frontend/src/b/holiday.ts 한 곳에 기간·주제·배경·게임 그림. ?holiday=<key> 로 미리 보기.
GA: game_start theme 추가, talk_post topic 6~9.
2026-10-30 09:15:53 +09:00

336 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<number | null>(null)
const [gain, setGain] = useState(0)
const baseRef = useRef<number | undefined>(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<HTMLCanvasElement>(null)
const gameRef = useRef<Game | null>(null)
const aimRef = useRef<number | null>(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<typeof setTimeout> | undefined
let ticket: Promise<string | undefined> = 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<HTMLCanvasElement>) => {
const rect = e.currentTarget.getBoundingClientRect()
return ((e.clientX - rect.left) / rect.width) * W
}
const onMove = (e: PointerEvent<HTMLCanvasElement>) => {
aimRef.current = toX(e)
}
const onUp = (e: PointerEvent<HTMLCanvasElement>) => {
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(
<div className="b-app fixed inset-0 z-[45] touch-none bg-[linear-gradient(#d9edff,#f5faff)]">
<div className="mx-auto flex h-full max-w-[440px] flex-col pt-[env(safe-area-inset-top,0px)] pb-[calc(10px+env(safe-area-inset-bottom,0px))] text-(--ink)">
<div className="flex items-center gap-1 px-3 pt-2">
<button type="button" onClick={back} aria-label="뒤로" className={cx('relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full bg-white/80 text-[22px] font-bold shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
‹
</button>
<div className="min-w-0 flex-1 px-1">
<h2 className="m-0 font-jua text-[22px] leading-tight font-normal">구름 합치기</h2>
<p className="m-0 flex items-center gap-1 text-[12px] font-extrabold opacity-75">
<Ic name="cloud" className="size-4" />
{region.short_name} {windText}
</p>
</div>
<button type="button" onClick={() => open({ type: 'gameHelp' })} aria-label="게임 방법" className={cx('relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full bg-white/80 text-[18px] font-extrabold text-(--ink2) shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
?
</button>
</div>
<div className="mx-3 mt-2.5 flex items-center gap-2.5 text-[13px] font-extrabold">
<span className="shrink-0 rounded-full bg-(--ink) px-3 py-1 text-white">{round}라운드</span>
<div className="min-w-0 flex-1">
<div className="h-2.5 overflow-hidden rounded-full bg-white/80">
<i className="block h-full rounded-full bg-(--orange) transition-[width]" style={{ width: `${Math.min(100, (roundGot / roundTarget(round)) * 100)}%` }} />
</div>
<p className="m-0 mt-0.5 text-[11px] font-bold opacity-75">
다음 라운드까지 {roundGot} / {roundTarget(round)}
</p>
</div>
<span className="flex shrink-0 items-center gap-1 opacity-75">
다음 <Ic name={LEVELS[next].icon} className="size-6" />
</span>
</div>
<p className="mx-3 mt-1 mb-0 flex justify-between text-[12px] font-bold">
<span>
점수 <b className="text-[16px] text-(--orange)">{score}</b> <span className="opacity-60">· 최고 {best}</span>
</span>
{loggedIn ? (
<span className="opacity-75">
오늘 게임 각 {todayGak} / {cap}
</span>
) : (
<button type="button" onClick={() => open({ type: 'login' })} className="cursor-pointer p-0 text-[12px] font-extrabold text-(--orange-deep) underline underline-offset-2">
로그인하면 라운드마다 +2각
</button>
)}
</p>
{/* 남은 높이를 다 쓰되 2:3 비율은 지킨다 */}
<div className="mt-2 grid min-h-0 flex-1 place-items-center px-3 [container-type:size]">
<div className="relative aspect-[2/3]" style={{ width: 'min(100cqw, 100cqh * 2 / 3)' }}>
<canvas
ref={canvasRef}
onPointerMove={onMove}
onPointerDown={onMove}
onPointerUp={onUp}
className="block size-full touch-none rounded-[22px] bg-gradient-to-b from-[#cfe8ff] to-[#f3f9ff] shadow-[0_4px_14px_rgb(40_48_74/0.08)]"
/>
{!today.isSuccess && <p className="absolute inset-0 m-0 grid place-items-center text-[14px] font-bold opacity-60">{today.isError ? '날씨를 불러오지 못했어요' : '오늘 바람 불러오는 중…'}</p>}
{flash && !over && (
<p className="pointer-events-none absolute inset-x-0 top-[30%] m-0 text-center font-jua text-[34px] leading-tight text-(--orange) drop-shadow-[0_2px_0_white]">
{round}라운드!
{gain > 0 && <span className="block text-[22px] text-(--ink)">+{gain}각</span>}
</p>
)}
{over && (
<div className="absolute inset-0 grid place-items-center rounded-[22px] bg-white/75">
<div className="text-center">
<p className="m-0 font-jua text-[28px]">넘쳤어요!</p>
<p className="m-0 mt-1 text-[15px] font-bold">
{round}라운드 · 총 {score}점{score >= best && score > 0 ? ' · 최고 기록' : ''}
</p>
{loggedIn && (
<p className="m-0 mt-1 text-[13px] font-bold opacity-75">
오늘 게임 각 {todayGak} / {cap}
</p>
)}
<button type="button" onClick={restart} className="mt-4 cursor-pointer rounded-full bg-(--orange) px-6 py-2.5 text-[15px] font-extrabold text-white">
다시 하기
</button>
</div>
</div>
)}
</div>
</div>
<div className="mx-3 mt-2 flex items-center justify-center gap-x-1 text-[12px] font-bold opacity-70">
{LEVELS.map((l, i) => (
<span key={l.icon} className="flex items-center gap-0.5">
<Ic name={l.icon} className="size-5" />
{i < LEVELS.length - 1 && '›'}
</span>
))}
</div>
</div>
</div>,
document.body,
)
}