feat: 날씨게임 구름 합치기 (/game) — 같은 날씨끼리 합쳐 해까지, 오늘 우리 구 풍속만큼 옆으로 밀림, 60초 라운드·목표 점수, 게임 방법 창
This commit is contained in:
1 parent
92206d82f0
commit
b2c46086a3
8 files changed
+444
-1
No files matched your search
@@ -351,3 +351,13 @@
|
||||
| [x] | `mobile/` 템플릿 예제 화면·`.vscode`·`LICENSE`·README 지움, `AGENTS.md`·`.claude`는 둠 | 사용자 결정 | `mobile/` |
|
||||
| [ ] | `frontend-dev` 개발 컨테이너 실제로 띄워 확인 (이미지 빌드만 확인, 5173이 사용 중이라 실행은 못 함) | 볼륨 경로 바뀜 | `compose.yaml` |
|
||||
| [ ] | 운영 서버가 git pull 뒤 루트 `package-lock.json`으로 빌드되는지 배포 때 확인 | 빌드 대상이 `./frontend` → `.` | `deploy.sh`, `compose.yaml` |
|
||||
|
||||
## 날씨게임 — 구름 합치기 (10/28)
|
||||
|
||||
| 상태 | 할 일 | 이유 | 관련 파일 |
|
||||
|---|---|---|---|
|
||||
| [ ] | 바람 방향 — API에 풍향이 없어 날짜 홀짝으로 왼쪽/오른쪽을 정함. 실제 풍향(기상청 VEC)을 내려줄지 결정 | 첫 구현 (10/28) | `frontend/src/b/cloudMerge.ts` `windDir`, `backend/router/v1/weather/protocol.py` |
|
||||
| [ ] | 오늘의 판(모두 같은 순서)·구별 순위·구 대항전·공유 카드·판 깨면 각 카드 열기 — 백엔드 필요, 재미 확인 뒤 | 기획 v2 DAU 장치 | — |
|
||||
| [ ] | **[결정 필요]** 앱인토스에 넣으면 게임물 등급분류·게임 카테고리 재등록 대상인지 토스에 확인 | 앱인토스 8월 공지 | — |
|
||||
| [ ] | 들어가는 길 — 지금은 `/game` 주소로만 열림. 피드 카드·메뉴 노출 여부 결정 | 사용자 선택 (10/28) | `frontend/src/App.tsx` |
|
||||
| [ ] | 라운드 목표 점수(200 + 라운드마다 80, 60초) — 아무 데나 1초에 1번 떨어뜨리는 시뮬레이션 4판으로만 정함(넘침 3판 4~6라운드, 시간 끝 1판 8라운드). 실제 사람 플레이 보고 조정 | 시간 제한 라운드 추가 (10/28) | `frontend/src/b/cloudMerge.ts` `roundTarget` |
|
||||
@@ -17,6 +17,7 @@
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@tanstack/react-query": "^5.104.0",
|
||||
"embla-carousel-react": "^8.6.0",
|
||||
"matter-js": "^0.20.0",
|
||||
"modern-screenshot": "^4.7.0",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
@@ -25,6 +26,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@hey-api/openapi-ts": "0.99.0",
|
||||
"@types/matter-js": "^0.20.2",
|
||||
"@types/node": "^24.13.3",
|
||||
"@types/react": "^19.2.18",
|
||||
"@types/react-dom": "^19.2.7",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { BrowserRouter, Route, Routes } from 'react-router'
|
||||
import { BLayout } from './b/BLayout'
|
||||
import { CloudMergePage } from './b/CloudMergePage'
|
||||
import { FoliagePage } from './b/FoliagePage'
|
||||
import { GakPage } from './b/GakPage'
|
||||
import { SeasonPage } from './b/SeasonPage'
|
||||
@@ -24,6 +25,7 @@ export default function App() {
|
||||
<Route path="foliage" element={<FoliagePage />} />
|
||||
<Route path="talk" element={<TalkPage />} />
|
||||
<Route path="shorts/:id?" element={<ShortsPage />} />
|
||||
<Route path="game" element={<CloudMergePage />} />
|
||||
<Route path="*" element={<TodayPage />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -39,6 +39,7 @@ import { MixSheet, MyGakSheet } from './myGak'
|
||||
import { ownPage, useRegion } from './regionContext'
|
||||
import { WeatherWhySheet } from './weatherWhy'
|
||||
import { useSky } from './skyContext'
|
||||
import { LEVELS } from './cloudMerge'
|
||||
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
|
||||
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
|
||||
import { HeartIcon } from './svg'
|
||||
@@ -85,7 +86,7 @@ export function SheetProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
}
|
||||
|
||||
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', install: '홈 화면에 추가', weatherWhy: '날씨 점수는 이렇게 나와요', talk: '이야기' } as const
|
||||
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', install: '홈 화면에 추가', weatherWhy: '날씨 점수는 이렇게 나와요', talk: '이야기', gameHelp: '구름 합치기 하는 법' } as const
|
||||
|
||||
/** 아래에서 올라오는 창: 네이티브 <dialog>라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */
|
||||
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
|
||||
@@ -173,6 +174,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
||||
{shown.type === 'install' && <InstallSheet />}
|
||||
{shown.type === 'weatherWhy' && <WeatherWhySheet d={shown.why} />}
|
||||
{shown.type === 'talk' && <TalkSheet talk={shown.talk} />}
|
||||
{shown.type === 'gameHelp' && <GameHelpSheet />}
|
||||
</div>
|
||||
)}
|
||||
{!shown && <RegionLinks />}
|
||||
@@ -514,6 +516,36 @@ function ArticleSheet({ articleId, onTitle }: { articleId: number; onTitle: (t:
|
||||
}
|
||||
|
||||
/* ---------- 이번 주 특집 ---------- */
|
||||
const GAME_STEPS = [
|
||||
'라운드마다 60초 안에 목표 점수를 채우면 다음 라운드로 넘어가요. 라운드가 오를수록 목표가 높아져요.',
|
||||
'손가락을 좌우로 움직여 떨어뜨릴 자리를 고르고, 손을 떼면 떨어져요.',
|
||||
'떨어지는 동안 오늘 우리 동네 바람만큼 옆으로 밀려요. 바람 방향을 보고 조금 비켜 떨어뜨리세요.',
|
||||
'같은 그림끼리 닿으면 한 단계 큰 그림으로 합쳐지고 점수가 올라요.',
|
||||
'해 둘이 만나면 사라지면서 보너스 점수!',
|
||||
'시간 안에 목표를 못 채우거나, 쌓인 그림이 위쪽 점선을 넘은 채로 잠깐 있으면 끝나요. 판은 다음 라운드로 그대로 이어져요.',
|
||||
]
|
||||
|
||||
function GameHelpSheet() {
|
||||
return (
|
||||
<Body>
|
||||
<ol className="m-0 flex list-decimal flex-col gap-2 pl-5 text-[15px] leading-[1.6]">
|
||||
{GAME_STEPS.map((t) => (
|
||||
<li key={t}>{t}</li>
|
||||
))}
|
||||
</ol>
|
||||
<p className="mt-4 mb-2 text-[13px] font-extrabold text-(--ink2)">합쳐지는 순서</p>
|
||||
<div className="grid grid-cols-4 gap-2 rounded-[16px] bg-[#f3f6fb] p-3">
|
||||
{LEVELS.map((l, i) => (
|
||||
<span key={l.icon} className="flex flex-col items-center gap-0.5 text-[12px] font-bold">
|
||||
<Ic name={l.icon} className="size-8" />
|
||||
{i + 1}. {l.name}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</Body>
|
||||
)
|
||||
}
|
||||
|
||||
function SeasonWeekSheet() {
|
||||
const { open } = useSheet()
|
||||
const q = useQuery(getSeasonWeekOptions())
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import Matter from 'matter-js'
|
||||
|
||||
/** 작은 것부터 큰 것 순서. 같은 단계 둘이 닿으면 다음 단계로 합쳐지고, 해 둘은 사라지며 보너스 */
|
||||
export const LEVELS = [
|
||||
{ icon: 'muggy', name: '물방울', r: 15, color: '#d9f0ff' },
|
||||
{ icon: 'snow', name: '눈송이', r: 21, color: '#e4ecff' },
|
||||
{ icon: 'cloud', name: '구름', r: 28, color: '#f1f3f8' },
|
||||
{ icon: 'rain', name: '비구름', r: 36, color: '#dcdcff' },
|
||||
{ icon: 'umbrella', name: '우산', r: 45, color: '#eadcff' },
|
||||
{ icon: 'sun_cloud', name: '해구름', r: 55, color: '#fff1c9' },
|
||||
{ icon: 'moon', name: '달', r: 66, color: '#ffe6b3' },
|
||||
{ icon: 'sun', name: '해', r: 78, color: '#ffd2a1' },
|
||||
] as const
|
||||
|
||||
export const W = 360
|
||||
export const H = 540
|
||||
/** 이 선 위에 쌓인 채로 LOSE_MS 넘게 있으면 끝 */
|
||||
export const LINE_Y = 96
|
||||
export const DROP_Y = 46
|
||||
const LOSE_MS = 1600
|
||||
const WALL = 40
|
||||
/** 떨어지는 중에만 바람을 받는다. 초속 1m 당 가로 힘 */
|
||||
const WIND_FORCE = 0.000045
|
||||
const MAX_WIND = 12
|
||||
/** 처음 떨어뜨리는 건 작은 4단계 중에서 */
|
||||
const SPAWN_MAX = 3
|
||||
const SUN_BONUS = 66
|
||||
/** 라운드마다 주어지는 시간. 그 안에 목표 점수를 넘기면 다음 라운드, 못 넘기면 끝 */
|
||||
export const ROUND_MS = 60_000
|
||||
export const roundTarget = (round: number) => 200 + 80 * (round - 1)
|
||||
|
||||
export const pointsFor = (level: number) => ((level + 1) * (level + 2)) / 2
|
||||
|
||||
export type Piece = Matter.Body & { level: number; falling: boolean; merged: boolean; overSince: number | null }
|
||||
|
||||
export type GameEvents = { onScore: (score: number) => void; onOver: () => void }
|
||||
|
||||
/** 바람 방향은 날짜마다 정해 하루 동안 같게: 홀수 날은 오른쪽, 짝수 날은 왼쪽 */
|
||||
export const windDir = (day: number) => (day % 2 ? 1 : -1)
|
||||
|
||||
export const randomLevel = () => Math.floor(Math.random() * (SPAWN_MAX + 1))
|
||||
|
||||
export function createGame(windMs: number, dir: number, ev: GameEvents) {
|
||||
const engine = Matter.Engine.create({ gravity: { x: 0, y: 1, scale: 0.0012 } })
|
||||
const wind = Math.min(Math.max(windMs, 0), MAX_WIND) * dir
|
||||
const opts = { isStatic: true, friction: 0.6 }
|
||||
Matter.Composite.add(engine.world, [
|
||||
Matter.Bodies.rectangle(W / 2, H + WALL / 2, W + WALL * 2, WALL, opts),
|
||||
Matter.Bodies.rectangle(-WALL / 2, H / 2, WALL, H * 2, opts),
|
||||
Matter.Bodies.rectangle(W + WALL / 2, H / 2, WALL, H * 2, opts),
|
||||
])
|
||||
let score = 0
|
||||
let over = false
|
||||
|
||||
const make = (level: number, x: number, y: number) => {
|
||||
const b = Matter.Bodies.circle(x, y, LEVELS[level].r, { restitution: 0.15, friction: 0.4, frictionAir: 0.012, density: 0.0016 }) as Piece
|
||||
b.level = level
|
||||
b.falling = false
|
||||
b.merged = false
|
||||
b.overSince = null
|
||||
Matter.Composite.add(engine.world, b)
|
||||
return b
|
||||
}
|
||||
|
||||
const pieces = () => engine.world.bodies.filter((b): b is Piece => 'level' in b)
|
||||
|
||||
Matter.Events.on(engine, 'beforeUpdate', () => {
|
||||
for (const p of pieces()) if (p.falling) Matter.Body.applyForce(p, p.position, { x: p.mass * wind * WIND_FORCE, y: 0 })
|
||||
})
|
||||
|
||||
Matter.Events.on(engine, 'collisionStart', (e) => {
|
||||
for (const { bodyA, bodyB } of e.pairs) {
|
||||
const a = bodyA as Piece
|
||||
const b = bodyB as Piece
|
||||
if ('level' in a) a.falling = false
|
||||
if ('level' in b) b.falling = false
|
||||
if (!('level' in a) || !('level' in b) || a.level !== b.level || a.merged || b.merged) continue
|
||||
a.merged = b.merged = true
|
||||
Matter.Composite.remove(engine.world, [a, b])
|
||||
const last = a.level === LEVELS.length - 1
|
||||
score += last ? SUN_BONUS : pointsFor(a.level + 1)
|
||||
if (!last) {
|
||||
const c = make(a.level + 1, (a.position.x + b.position.x) / 2, (a.position.y + b.position.y) / 2)
|
||||
Matter.Body.setVelocity(c, { x: 0, y: -1 })
|
||||
}
|
||||
ev.onScore(score)
|
||||
}
|
||||
})
|
||||
|
||||
const step = (dt: number, now: number) => {
|
||||
if (over) return
|
||||
Matter.Engine.update(engine, Math.min(dt, 1000 / 30))
|
||||
for (const p of pieces()) {
|
||||
const above = !p.falling && p.position.y - LEVELS[p.level].r < LINE_Y
|
||||
p.overSince = above ? (p.overSince ?? now) : null
|
||||
if (p.overSince != null && now - p.overSince > LOSE_MS) {
|
||||
over = true
|
||||
ev.onOver()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const drop = (level: number, x: number) => {
|
||||
if (over) return
|
||||
const r = LEVELS[level].r
|
||||
const p = make(level, Math.min(Math.max(x, r), W - r), DROP_Y)
|
||||
p.falling = true
|
||||
}
|
||||
|
||||
/** 위험선 근처에 있는지: 선을 빨갛게 보여 줄 때 */
|
||||
const danger = () => pieces().some((p) => !p.falling && p.position.y - LEVELS[p.level].r < LINE_Y + 40)
|
||||
|
||||
const end = () => {
|
||||
over = true
|
||||
}
|
||||
|
||||
return { step, drop, end, isOver: () => over, pieces, danger, wind, destroy: () => Matter.Engine.clear(engine) }
|
||||
}
|
||||
|
||||
export type Game = ReturnType<typeof createGame>
|
||||
|
||||
const BEST_KEY = 'cloudMerge.best'
|
||||
export const loadBest = () => Number(localStorage.getItem(BEST_KEY)) || 0
|
||||
export const saveBest = (v: number) => localStorage.setItem(BEST_KEY, String(v))
|
||||
@@ -21,6 +21,7 @@ export type SheetState =
|
||||
| { type: 'install' }
|
||||
| { type: 'weatherWhy'; why: WeatherWhyPayload }
|
||||
| { type: 'talk'; talk: TalkData }
|
||||
| { type: 'gameHelp' }
|
||||
| null
|
||||
|
||||
export type SheetApi = { open: (s: Exclude<SheetState, null>) => void; close: () => void }
|
||||
|
||||
Generated
+15
@@ -19,6 +19,7 @@
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@tanstack/react-query": "^5.104.0",
|
||||
"embla-carousel-react": "^8.6.0",
|
||||
"matter-js": "^0.20.0",
|
||||
"modern-screenshot": "^4.7.0",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
@@ -27,6 +28,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@hey-api/openapi-ts": "0.99.0",
|
||||
"@types/matter-js": "^0.20.2",
|
||||
"@types/node": "^24.13.3",
|
||||
"@types/react": "^19.2.18",
|
||||
"@types/react-dom": "^19.2.7",
|
||||
@@ -4459,6 +4461,13 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/matter-js": {
|
||||
"version": "0.20.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/matter-js/-/matter-js-0.20.2.tgz",
|
||||
"integrity": "sha512-3PPKy3QxvZ89h9+wdBV2488I1JLVs7DEpIkPvgO8JC1mUdiVSO37ZIvVctOTD7hIq8OAL2gJ3ugGSuUip6DhCw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "24.19.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz",
|
||||
@@ -10376,6 +10385,12 @@
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/matter-js": {
|
||||
"version": "0.20.0",
|
||||
"resolved": "https://registry.npmjs.org/matter-js/-/matter-js-0.20.0.tgz",
|
||||
"integrity": "sha512-iC9fYR7zVT3HppNnsFsp9XOoQdQN2tUyfaKg4CHLH8bN+j6GT4Gw7IH2rP0tflAebrHFw730RR3DkVSZRX8hwA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/mdn-data": {
|
||||
"version": "2.0.14",
|
||||
"resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.0.14.tgz",
|
||||
|
||||
Reference in new issue
Block a user