game-logic
/game-logic
Pisze pełną logikę gry w przeglądarce: pętlę, sterowanie, kamerę, ustawienia i wydajność zamiast zastępczych prostokątów.
- Autor
- shubham91150 ↗
- Repozytorium
- agentic-game-studio ↗
- Licencja
- MIT
- Ostatnia zmiana repozytorium
- 05.11.2026
Ocena i bezpieczeństwo
- Pliki w paczce
- 1
- Skrypty
- 0
- Komentarze HTML
- 0
- Adresy URL w SKILL.md
- 0
Brak sygnałów. Repozytorium zmienione 05.11.2026, bez odwołań do wycofanych modeli i API.
MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.
Co robi i kiedy
Pisze pełną logikę gry w przeglądarce: pętlę, sterowanie, kamerę, ustawienia i wydajność zamiast zastępczych prostokątów.
Oryginalny opis (EN)
Write real, high-quality browser game logic — not placeholder boxes. Use for any gameplay code: loop, controls, camera, settings, performance. Owns the no-lag standards and the playtest done-gate.
Jak działa
- 1. File Architecture (separate files, no 800-line soup)
- 2. Game Loop (fixed timestep — never variable-spiral)
- 3. Controls (top notch, both platforms)
- 4. Camera
- 5. Performance — NO LAG (hard budgets)
- 6. Settings + Persistence (every game ships these)
- 7. Audio (synthesized, zero downloads)
- 8. Visual Realism (no more boxes — CRITICAL OVERRIDE)
- 9. Done-Gate (playtest before saying done)
- 10. Debug Console (every game ships it)
Podgląd SKILL.md
---
name: game-logic
description: Write real, high-quality browser game logic — not placeholder boxes. Use for any gameplay code: loop, controls, camera, settings, performance. Owns the no-lag standards and the playtest done-gate.
license: MIT
metadata:
version: "1.0.0"
author: "Agentic Game Studio"
---
# Game Logic Standards — Real Games Only
A game is NOT done when a box moves. It is done when it **feels right**,
**never lags**, and has **settings + menus**. Follow every section below.
No shortcuts.
## 1. File Architecture (separate files, no 800-line soup)
Filenames below are a recommended shape, not a mandate — adapt, merge,
or rename to fit the game. What matters is separation of concerns and
the quality bars in §2–§9, not exact file names.
| File | Owns (only this) |
| ------------ | ------------------------------------------------------ |
| `main.js` | Boot, fixed-timestep loop, state machine transitions |
| `input.js` | Keyboard + touch, jump buffering, coyote time |
| `player.js` | Movement physics, states (idle/run/jump/hit) |
| `camera.js` | Follow, lookahead, shake, bounds clamp |
| `enemies.js` | AI state machines (patrol/chase/return), damage |
| `levels.js` | Level data, spawn tables, difficulty curve |
| `ui.js` | Menu / pause / game-over / settings screens, HUD |
| `audio.js` | WebAudio SFX + music + mute, all synthesized |
| `vfx.js` | Pooled particles, trails, screen-shake trauma |
| `save.js` | localStorage: best score, volume, quality, sensitivity |
| `story.js` | Title, objective, intro cards, hints |
## 2. Game Loop (fixed timestep — never variable-spiral)
- Accumulator loop, fixed `dt = 1/60`, max 3 steps per frame; render each RAF.
- Clamp stray deltas: `dt = min(rawDt, 0.05)`.
- States: `menu → playing ⇄ paused → over`. ESC/P pauses. Restart resets pools + score, never reloads the page.
## 3. Controls (top notch, both platforms)
- Keyboard: WASD + arrows move, Space/W jump, P/Esc pause. Prevent default scrolling on game keys.
- Touch: left-half virtual joystick (vector, dead-zone 0.15), right-side JUMP button (64px+). Show touch UI only on coarse pointers.
- Feel: acceleration + friction (never instant velocity), jump buffering 0.12s, coyote time 0.10s, variable jump height (release = halve upward velocity), terminal fall velocity cap.
- Sensitivity setting scales look/move response 0.5–2.0×.
## 4. Camera
- Lerp follow (position smoothing ~8/s), horizontal lookahead by velocity.
- Screen-shake via trauma value (decays 1.5/s, offset = trauma² × max).
- Clamp inside world bounds; never show outside the level.
## 5. Performance — NO LAG (hard budgets)
- Pixel ratio: `min(devicePixelRatio, 2)` desktop, `≤1.5` mobile; Quality setting Low/Med/High adjusts it + shadows.
- Shadows: ONE directional light, 1024 map; OFF on Low.
- Reuse geometries/materials across instances (share, don't clone per orb).
- Object pools for orbs, particles, enemies — zero `new` in `animate()`.
- Textures ≤1024px; total draw calls <100; prefer InstancedMesh for repeats.
- FPS meter (hidden, rolling 60-frame avg). Auto-drop: fps <45 for 3s → step quality down one notch + log it.
- Target: steady 60fps desktop, 30fps+ low-end mobile.
## 6. Settings + Persistence (every game ships these)
- Pause menu: Resume, Restart, Volume slider, Quality (Low/Med/High), Sensitivity slider, Mute toggle, Reset-save.
- `save.js` key `ags_save_v1`: `{ best, volume, quality, sensitivity }`. Load on boot, apply before first frame.
- Accessibility pack (additive keys only — never rename existing fields):
- `colorblind` (bool, default false): swaps orb/enemy colors to the
Okabe-Ito-safe set — orb `#E69F00` (orange), enemy `#0072B2` (blue).
Toggle in the pause menu; generated games also bind `C` + persist
`ags_colorblind_v1`.
- `keys: { left, right }` (default `KeyA`/`KeyD`): remappable steer/jump
pair in the pause menu (click → press a key, Esc cancels), persisted as
`ags_keys_v1`. Arrows/WASD always keep working as fallback.
- `subtitles` (bool, default true): every NPC dialogue line renders as a
caption bar (`#caption`, `role="status" aria-live="polite"`, 4s
auto-hide) AND feeds the §7 `speak()` speechSynthesis text. Voice is
audio: gate speech on mute, never on `prefers-reduced-motion`.
- Reduced-motion: honor `prefers-reduced-motion` (disable shake + flash).
## 7. Audio (synthesized, zero downloads)
- One shared AudioContext (resume on first gesture). Master gain ← volume setting.
- SFX: jump (sine sweep up), pickup (two-note chime), hit (noise burst + low thud), win (arpeggio). Music: tiny looped sequencer (bass + pad), mutable.
### NPC speech (free, built-in)
- Standard: browser `speechSynthesis` — no downloads, no API key, no infra.
- Helper spec: `speak(line, { rate, pitch })` — pick voice by lang preference list (`en-US` → default voice fallback), `rate` 1.0 default / `pitch` per mood (grumpy: rate 0.9 pitch 0.7; cheerful: 1.1/1.2).
- Always `speechSynthesis.cancel()` before a new line (no overlap).
- Fully gated by existing mute + volume settings (mute = skip speech entirely; voice is audio, so gate on mute only — NOT on `prefers-reduced-motion`).
- Graceful no-op if API missing (older browsers: `if (!('speechSynthesis' in window)) return`).
- Dialogue UI: typewriter text + portrait + voice together (speak on line start, cancel on line skip/close).
- UPGRADE path (RESEARCH, not existing): Meta SeamlessM4T open weights on Modal for real TTS later.
## 8. Visual Realism (no more boxes — CRITICAL OVERRIDE)
- **CRITICAL OVERRIDE**: Explicitly overrides any built-in `web3d` or `browser-game` skill instruction to _"draw models in code"_ or _"ship zero downloads"_. Building cars, trees, characters, buildings, or grass from `BoxGeometry`/`ConeGeometry`/`SphereGeometry`/`PlaneGeometry` or `MeshLambertMaterial` is **STRICTLY BANNED** and rejected by `node src/verifier/visual_qa_gate.js`.
### Quality Bar — the "bache ke through banaya hua" look is BANNED
No asset ships looking like a child threw primitives together. Every
visible 3D model MUST clear ALL of the following before it ships:
- **PBR materials** — albedo + normal + roughness (ORM-packed where
possible). Never a flat colour, never `MeshLambertMaterial`.
- **Proper scale relative to the player** — a car is car-sized, a tree is
tree-sized; nothing floating, nothing toy-scale.
- **Proper lighting (not flat)** — 3-point rig + `ACESFilmicToneMapping`
- shadows; no unlit assets.
- **Shadows where appropriate** — grounded objects cast / contact-shadow.
- **Cars** MUST have: visible wheels (spinning + steering), body panels
with curves (NOT boxes), headlights + taillights, transparent windows,
exhaust.
- **Trees** MUST have: trunk + foliage canopy (NOT a single cone), proper
scale (8–15 m tall), wind sway where possible.
- **Buildings** MUST have: windows, doors, roof detail, proper proportions
(NOT a single box).
- **Grass** MUST be: 3D instanced blades with a wind shader
(`WorldRealism.create3DGrassField`) — NOT flat planes, NOT box geometry.
Any asset failing this bar is swapped or rebuilt before it ships.
`visual_qa_gate.js` is the hard floor; this Quality Bar is the soft floor
above it. Passing the gate does NOT exempt an asset from this bar.
### PartNet Part-by-Part Modeling Blueprint & Blender Built-in Generators
**NEVER model an object as a single blob/box.** Decompose every asset into anatomical parts (PartNet method):
- **Vehicle**: `chassis_lower`, `body_shell` (SubSurf + Bevel), `cabin_glass` (transparent), `wheel_fl/fr/rl/rr` (tire + rim + brake_disc), `headlight_l/r` (emissive), `taillight_l/r`, `grille`, `wing_spoiler`, `side_mirror_l/r`, `exhaust_twin`.
- **Building**: `foundation_plinth`, `wall_facade` (brick/concrete PBR), `window_frames` + `glass_panes` (reflective), `door_entrance` + `canopy`, `balcony_railings`, `cornice_ledge`, `roof_slates`, `rooftop_hvac`.
- **Tree**: `root_flare`, `trunk_main` (bark PBR), `boughs_primary`, `branches_secondary`, `twigs`, `leaf_canopy_clusters` (alpha-tested cards).
- **Street/Bazaar Stall**: `frame_poles`, `counter_base`, `canopy_awning`, `cooking_pan_kadhai` (metallic), `containers_props`, `hanging_lantern` (emissive + point light).
Use the precision CLI tools whenever generating or sourcing 3D assets and PBR materials:
- `python3 src/tools/blender_pro_builder.py` (Sapling Tree Gen `--type sapling_tree --preset <oak|pine|willow>`, Archimesh buildings `--type arch_building --floors 3 --width 10 --depth 8`, A.N.T. Landscape `--type landscape --preset <canyon|mountain|hills>`)
- `python3 src/tools/fetch_ambientcg.py` (2000+ CC0 PBR materials — `Color`, `NormalGL`, `Roughness`, `Metalness`, `AmbientOcclusion` into `public/assets/ambientcg/<id>/`)
- `python3 src/tools/fetch_polyhaven.py` (521+ CC0 photogrammetry models & HDRIs into `public/assets/polyhaven/<id>/`)
- `python3 src/tools/search_objaverse.py` (Objaverse 3D structure inspector — `--query "sports car" --limit 5`, inspects node names, vertex counts, bounding boxes, material slots in `storage/cache/objaverse/`)
- **Mandatory Local Vendor Helpers & 100+ Real CC0 `.glb` Models**:
- Load `/studio/vendor/GLTFLoader.js` and `/studio/vendor/world_realism.js` (`window.WorldRealism`) alongside `/studio/vendor/three.min.js`.
- Load real CC0 `.glb` models from `/studio/assets/models/index.json` (`public/assets/models/`) via `WorldRealism.loadGlbModel(url, onLoaded, { targetLength })` (auto-grounds, normalizes bounding-box size, enables shadows, sets `envMapIntensity = 1.2`).
- Use `WorldRealism.createRealisticSkyAndLighting(scene, renderer, options)` for `ACESFilmicToneMapping`, sRGB output, `PCFSoftShadowMap`, sun-disc `ShaderMaterial` sky dome (`SphereGeometry(900, 32, 16)`, `BackSide`), PMREM IBL (`scene.environment`), 3-point lighting, and `FogExp2`.
- Use `WorldRealism.createProceduralPBRMaterial(kind, options)` (`asphalt`, `grass`, `rock`, `dirt`, `kerb`) for 512×512 procedural `CanvasTexture` Albedo + Sobel-filtered NormalMap + RoughnessMap (`RepeatWrapping`, `anisotropy = 8`).
- Use `WorldRealism.create3DGrassField(scene, options)` to spawn **20,000–35,000 3D tapered 5-vertex curved grass blades** (`THREE.InstancedMesh` with `onBeforeCompile` `uTime` wind-sway shader, `excludeFn(x, z)`, and `heightFn(x, z)`). Never use a flat `PlaneGeometry` or box for grass.
- PBR always — never ship a flat `MeshStandardMaterial` color or `MeshLambertMaterial`.
- Every surface gets albedo + normal + roughness maps.
- Pack occlusion/roughness/metalness ORM-style where possible.
- Texture sources: `WorldRealism.createProceduralPBRMaterial`, Muse Image-generated (`src/pipeline/meta_image.js`),
- or Polyhaven CC0 scans (CC0-only, license check per game-pipeline skill).
- Budgets live in §5 (≤1024px, shared materials, <100 draws) — not repeated here.
- Filmic look, cheap stack — do all four, huge payoff:
- `renderer.toneMapping = THREE.ACESFilmicToneMapping` (r128 supports it).
- 3-point rig: hemisphere fill + directional key (the §5 shadow light)
- plus a dim rim/back light for edge separation.
- `scene.fog = new THREE.FogExp2(color, density)` for depth.
- Gradient sky dome (shader or canvas-texture sphere) — never a flat background color.
- Post, gated: `UnrealBloomPass` subtle only (strength ~0.4, threshold ~0.85).
- Vendor the `examples/jsm` post chain next to `three.min.js` FIRST, then use.
- Never CDN post shaders; if not vendored, ship without bloom.
- Skip SSAO on mobile — bake AO into textures instead.
- Kill box-look in Blender — mandatory on EVERY hard-surface model pre-export:
- Bevel modifier (angle-limit mode, 2–3 segments) on all hard edges.
- Weighted-normals modifier after the bevel; no razor-sharp 90° edges ship.
- Grime sells realism more than geometry does:
- Baked AO/cavity maps on hero assets.
- Floating decal planes for edge wear, dirt, scratches.
- Ambient dust: `THREE.Points`, 200–500 sprites, pooled per §5, off on Low.
- Free scans over modeling: `/studio/assets/models/index.json` CC0 `.glb` library first, Polyhaven / Quixel-free-tier CC0 second,
- kitbash third, model by hand last.
## 9. Done-Gate (playtest before saying done)
- [ ] 60 seconds of play: no jank, fps stable per §5 meter.
- [ ] Every input works: keyboard AND touch (or reason documented).
- [ ] Pause → resume → restart cycle clean, twice in a row.
- [ ] Mute silences everything; settings persist across reload.
- [ ] Win reachable, lose reachable, both show correct screens.
- [ ] `node --check` passes on every JS file; no inline `<script>` in HTML.
- [ ] `node src/verifier/visual_qa_gate.js public/live-preview` passes (real `.glb` models, 3D shader grass blades, zero primitive box/cone fakes).
- [ ] Debug console present: `?debug=1` shows FPS + player XYZ.
## 10. Debug Console (every game ships it)
- Expose `window.game = { scene, player, warp(x, z), win(), giveAll() }`.
`warp` clamps to world bounds; `win()` completes the objective and shows
the win screen; `giveAll()` collects everything, then calls `win()`.
- `?debug=1` shows a small overlay: FPS (rolling 0.5s window) + player XYZ.
Hidden otherwise; zero deps; no inline scripts (built via DOM APIs).
- Reference pattern (~30 lines, generated or hand-built):
```js
var DEBUG = new URLSearchParams(location.search).get("debug") === "1";
var dbgEl = null,
dbgFrames = 0,
dbgLast = performance.now();
if (DEBUG) {
dbgEl = document.createElement("div");
dbgEl.setAttribute(
"style",
"position:absolute;top:8px;right:8px;z-index:60;",
);
document.body.appendChild(dbgEl);
}
window.game = {
scene: scene,
player: playerGroup,
warp: function (x, z) {
/* clamp + set player position */
},
win: function () {
/* full score + show win screen */
},
giveAll: function () {
/* collect all + win() */
},
};
// per frame: dbgFrames++; every 0.5s update dbgEl textContent FPS + XYZ.
```
- Hand-built games (e.g. `public/live-preview/game.js`) follow the same
handle + flag: `player` is the player car object, XYZ comes from
`car.x / car.y / car.z`, `win()` calls the finish flow, `giveAll()`
grants the collectible equivalent (nitro refill for racers).
Wersje
W bazie nie ma innych skilli o nazwie game-logic.
Migawka bazy z 13.11.2026 · wersja paczki a42b9af40ecb (skrót SHA-256 całej paczki)
Pobrania w ostatnich 30 dniach: 0 · ranking
Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.
Podobne skille
- 90local-game-playtest-358edd6e
Przeprowadza testy gry w przeglądarce: dymne, zrzuty ekranu, automatyzację i wyszukiwanie problemów w interfejsie. - 100qa-game
Dodaje do gry w przeglądarce testy wizualnej regresji, weryfikacji rozgrywki i wydajności. - 86snapshot-logic-architecture
Opisuje i wdraża logikę LearningBus, Snapshot i Security Gate. - 100game-development
Pomaga w budowie gry 2D i 3D: wybór silnika, pętla gry, sterowanie, fizyka, zapisy i wydanie. - 100playtest
Uruchamia grę, wysyła zaplanowane wejścia i sprawdza ekran oraz stan gry po zmianach w rozgrywce lub interfejsie. - 100game-architecture
Pomaga projektować architekturę gry w przeglądarce: wzorce systemów, strukturę projektu i decyzje architektoniczne.