feat: 날씨게임 구름 합치기 (/game) — 같은 날씨끼리 합쳐 해까지, 오늘 우리 구 풍속만큼 옆으로 밀림, 60초 라운드·목표 점수, 게임 방법 창
This commit is contained in:
1 parent
92206d82f0
commit
b2c46086a3
8 files changed
+444
-1
No files matched your search
@@ -0,0 +1,256 @@
|
||||
import { useEffect, useRef, useState, type PointerEvent } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||
import { kst } from '@nalssigak/shared/lib'
|
||||
import { slotAt } from '@nalssigak/shared/lib/weatherText'
|
||||
import { cx } from '../lib/utils'
|
||||
import { createGame, DROP_Y, H, LEVELS, LINE_Y, loadBest, randomLevel, ROUND_MS, roundTarget, saveBest, W, windDir, type Game } from './cloudMerge'
|
||||
import { iconSrc } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Ic, TAP44 } from './ui'
|
||||
|
||||
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 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)
|
||||
const [score, setScore] = useState(0)
|
||||
const [best, setBest] = useState(loadBest)
|
||||
const [over, setOver] = useState<'full' | 'time' | null>(null)
|
||||
const [play, setPlay] = useState(0)
|
||||
const [round, setRound] = useState(1)
|
||||
const [roundGot, setRoundGot] = useState(0)
|
||||
const [leftSec, setLeftSec] = useState(ROUND_MS / 1000)
|
||||
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 base = 0
|
||||
let left = ROUND_MS
|
||||
let flashTimer: ReturnType<typeof setTimeout> | undefined
|
||||
const game = createGame(windMs, dir, {
|
||||
onScore: (s) => {
|
||||
setScore(s)
|
||||
if (s - base >= roundTarget(roundNo)) {
|
||||
roundNo += 1
|
||||
base = s
|
||||
left = ROUND_MS
|
||||
setRound(roundNo)
|
||||
setLeftSec(ROUND_MS / 1000)
|
||||
setFlash(true)
|
||||
clearTimeout(flashTimer)
|
||||
flashTimer = setTimeout(() => setFlash(false), 1200)
|
||||
}
|
||||
setRoundGot(s - base)
|
||||
if (s > loadBest()) {
|
||||
saveBest(s)
|
||||
setBest(s)
|
||||
}
|
||||
},
|
||||
onOver: () => setOver('full'),
|
||||
})
|
||||
gameRef.current = game
|
||||
let last = performance.now()
|
||||
let raf = 0
|
||||
const loop = (t: number) => {
|
||||
game.step(t - last, t)
|
||||
if (left > 0 && !game.isOver()) {
|
||||
const sec = Math.ceil(left / 1000)
|
||||
left -= t - last
|
||||
if (left <= 0) {
|
||||
game.end()
|
||||
setLeftSec(0)
|
||||
setOver((o) => o ?? 'time')
|
||||
} else if (Math.ceil(left / 1000) !== sec) setLeftSec(Math.ceil(left / 1000))
|
||||
}
|
||||
last = t
|
||||
draw(ctx, game, aimRef.current, nextRef.current, game.danger())
|
||||
raf = requestAnimationFrame(loop)
|
||||
}
|
||||
raf = requestAnimationFrame(loop)
|
||||
return () => {
|
||||
cancelAnimationFrame(raf)
|
||||
clearTimeout(flashTimer)
|
||||
game.destroy()
|
||||
gameRef.current = null
|
||||
}
|
||||
}, [today.isSuccess, windMs, dir, play])
|
||||
|
||||
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
|
||||
game.drop(nextRef.current, toX(e))
|
||||
coolRef.current = performance.now() + 450
|
||||
nextRef.current = randomLevel()
|
||||
setNext(nextRef.current)
|
||||
}
|
||||
|
||||
const restart = () => {
|
||||
setScore(0)
|
||||
setOver(null)
|
||||
setRound(1)
|
||||
setRoundGot(0)
|
||||
setLeftSec(ROUND_MS / 1000)
|
||||
setPlay((n) => n + 1)
|
||||
}
|
||||
const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/'))
|
||||
const windText = windMs < 0.5 ? '바람 없음' : `${dir > 0 ? '→' : '←'} 초속 ${windMs.toFixed(1)}m`
|
||||
|
||||
return (
|
||||
<div className="pb-6">
|
||||
<div className="flex items-start gap-1 px-3 pt-1">
|
||||
<button type="button" onClick={back} aria-label="뒤로" className={cx('relative mt-0.5 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">
|
||||
<p className="m-0 flex items-center gap-1 text-[13px] font-extrabold opacity-75">
|
||||
<Ic name="cloud" className="size-4" />
|
||||
날씨게임 · {region.short_name} {windText}
|
||||
</p>
|
||||
<h2 className="m-0 mt-0.5 font-jua text-[26px] leading-tight font-normal">구름 합치기</h2>
|
||||
</div>
|
||||
<button type="button" onClick={() => open({ type: 'gameHelp' })} aria-label="게임 방법" className={cx('relative mt-0.5 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-3 flex items-center justify-between text-[14px] font-extrabold">
|
||||
<span className="rounded-full bg-(--ink) px-3 py-1 text-[13px] text-white">{round}라운드</span>
|
||||
<span className={cx('font-jua text-[26px] leading-none font-normal tabular-nums', leftSec <= 10 ? 'text-[#e5484d]' : 'text-(--ink)')}>
|
||||
{Math.floor(leftSec / 60)}:{String(leftSec % 60).padStart(2, '0')}
|
||||
</span>
|
||||
<span className="flex items-center gap-1 opacity-75">
|
||||
다음 <Ic name={LEVELS[next].icon} className="size-6" />
|
||||
</span>
|
||||
</div>
|
||||
<div className="mx-3 mt-2">
|
||||
<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-1 flex justify-between text-[12px] font-bold opacity-75">
|
||||
<span>
|
||||
목표 {roundGot} / {roundTarget(round)}
|
||||
</span>
|
||||
<span>
|
||||
총점 {score} · 최고 {best}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 하단 탭에 가리지 않게 화면 높이에 맞춰 폭을 줄인다 (위 머리말 약 210px + 아래 순서·탭 약 120px) */}
|
||||
<div className="relative mx-auto mt-2" style={{ width: 'min(100% - 24px, (100dvh - 330px) * 2 / 3)' }}>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
onPointerMove={onMove}
|
||||
onPointerDown={onMove}
|
||||
onPointerUp={onUp}
|
||||
className="block aspect-[360/540] w-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] text-(--orange) drop-shadow-[0_2px_0_white]">{round}라운드!</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]">{over === 'time' ? '시간 끝!' : '넘쳤어요!'}</p>
|
||||
<p className="m-0 mt-1 text-[15px] font-bold">
|
||||
{round}라운드 · 총 {score}점{score >= best && score > 0 ? ' · 최고 기록' : ''}
|
||||
</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 className="mx-3 mt-3 flex flex-wrap items-center justify-center gap-x-1 gap-y-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>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user