Download app.js from hwihwalab/mujoco-physics-playengine: direct link, hf CLI and curl.
- Browser
- Download file 96.5 kB
-
https://huggingface.co/spaces/hwihwalab/mujoco-physics-playengine/resolve/main/app.js
- Command line
-
hf download hf://spaces/hwihwalab/mujoco-physics-playengine/app.js
-
curl -L -o app.js https://huggingface.co/spaces/hwihwalab/mujoco-physics-playengine/resolve/main/app.js
96.5 kB
/**
* MuJoCo PlayEngine: Interactive Cockpit & Game Loop Controller
* Style: Fall Guys & Party Animals Jelly Bean Pop Edition
* Features:
* - Real-time DeepMind MuJoCo v3.3.0 WebAssembly Physics (60 FPS WebGL)
* - 3-Way Camera Perspective Switcher ('cam_front', 'cam_quarter', 'cam_topdown') + [C] shortcut
* - Kawaii 8-Bit Chiptune Procedural BGM (0 Bytes asset, pure Web Audio API)
* - Victory & Goal Clear Banners across all 10 Mini-Games
* - Coin Collection Sound FX & Star Coin Tracker (5/5)
* - Full 10 Games Contextual Action Buttons & Keypad Visualizer
* - 100% English Default with Korean Toggle
*/
// โ
ROOT-CAUSE FIX (HF Private Space): NO static import here.
// A static import chain (app.js โ mujoco_wasm_player.js โ mujoco.js) means that if ANY
// sub-module fails to load (e.g. private-Space auth token `__sign` not forwarded to
// sub-resource requests), the browser aborts app.js entirely โ empty game list & dead
// START button. The physics engine is now lazily imported inside initWasmEngine().
let MujocoWasmPlayer = null;
// Forward HF private-Space auth query (`__sign`) to every sub-resource URL.
function withSign(url) {
try {
const sign = new URLSearchParams(window.location.search).get("__sign");
if (!sign) return url;
return url + (url.includes("?") ? "&" : "?") + "__sign=" + encodeURIComponent(sign);
} catch (e) {
return url;
}
}
window.__withSign = withSign;
const I18N = {
en: {
brand_subtitle: "๐ฌ Physical AI Sandbox & Arcade | HWIHWA LAB",
menu_title: "10 Jelly Bricks",
menu_desc: "Select a jelly brick to play in the sweet bouncy arena!",
hud_score: "Survival Time",
hud_best: "Best Record",
hud_angle: "Pole Angle",
hud_coins: "Star Coins",
hud_demo: "Demolition Rate",
hud_race: "Race Leader",
hud_swing: "Swing Angle",
hud_beans: "Beans Landed",
hud_pinball: "Pinball Score",
hud_domino: "Target Status",
hud_acro: "Backflip Combo",
hud_claw: "Rescue Height",
keypad_title: "๐ฎ Real-time Keyboard Visualizer",
cam_label: "๐ฅ View:",
cam_front: "๐ฅ Front",
cam_quarter: "๐ 45ยฐ Quarter",
cam_topdown: "๐ Top-Down",
cam_tip: "Press <strong>[C]</strong> to switch view",
control_title: "Control Deck",
control_mode_label: "Controller Mode",
mode_manual: "๐ฎ Human Play",
mode_ai: "๐ค Smart AI",
mode_help_manual: "Use โ and โ arrow keys to balance the lollipop! (Survive 15s to Win ๐)",
mode_help_ai: "AI PD Controller automatically maintains balance.",
action_btn_label: "Quick Actions",
cannon_power_label: "๐ฃ Cannon Power",
cannon_preset_soft: "Soft (0.6x)",
cannon_preset_normal: "Normal (1.0x)",
cannon_preset_heavy: "Heavy (1.6x)",
cannon_preset_mega: "MEGA (2.0x)",
gravity_label: "Bouncy Gravity",
gravity_zero: "Floating (0G)",
gravity_moon: "Moon (-1.6)",
gravity_earth: "Earth (-9.8)",
gravity_heavy: "Heavy (-24.8)",
btn_start_game: "โถ START GAME (SPACE)",
btn_playing: "โธ PLAYING (R to Reset)",
btn_retry: "๐ RETRY (R)",
btn_play_again: "๐ PLAY AGAIN (R)",
btn_reset_toy: "๐ RESET TOY (R)",
btn_export_code: "๐ COPY PYTHON / XML CODE",
ready_title: "READY TO PLAY!",
ready_sub: "Press [SPACE] or Click [START] to Play!",
overlay_btn_start: "โถ START GAME",
gameover_title: "OOPS! TOPPLED!",
gameover_sub: "Oops! Toppled! Press [R] key to Retry",
label_survived: "SURVIVED:",
label_grade: "GRADE:",
overlay_btn_retry: "๐ RETRY (R)",
overlay_btn_watch_ai: "๐ค WATCH SMART AI",
overlay_btn_play_again: "๐ PLAY AGAIN (R)",
overlay_btn_next: "โฉ NEXT GAME",
mentor_quote: "๐ข ENGINE LIVE ยท MuJoCo v3.3.0 (500Hz) ยท 30 FPS Stream ยท Zero Assets (100% Procedural) ยท Built with โค๏ธ by HWIHWA LAB",
banner_badge: "ENGINE LIVE",
modal_desc: "This code is a 100% standalone executable MuJoCo brick. Copy and paste it into Antigravity or Python to build games and AI agents!",
modal_tab_py: "Python Script",
modal_tab_xml: "MuJoCo XML (Blueprint)",
modal_btn_copy: "๐ Copy to Clipboard",
modal_btn_close: "Close",
engine_loading_msg: "๐ฌ Loading 3D Physics Engine... Please wait!"
},
ko: {
brand_subtitle: "๐ฌ Physical AI Sandbox & Arcade | HWIHWA LAB",
menu_title: "10๋ ์ ค๋ฆฌ ๋ฌผ๋ฆฌ ์์",
menu_desc: "ํด๋ฆญํ์ฌ ํตํต ํ๋ ์ค์ํธ ์๋ ๋์์ ํ๋ ์ดํ์ธ์.",
hud_score: "๋ฒํด ์๊ฐ (์ ์)",
hud_best: "์ต๊ณ ๊ธฐ๋ก",
hud_angle: "๊ธฐ์ธ๊ธฐ ๊ฐ๋",
hud_coins: "ํฉ๊ธ ์ฝ์ธ",
hud_demo: "ํ์ ๋ถ๊ดด์จ",
hud_race: "์ ๋ ์ฃผ์",
hud_swing: "์ค์ ๊ฐ๋",
hud_beans: "์์ฐฉํ ์ ค๋ฆฌ",
hud_pinball: "ํ๋ณผ ์ ์",
hud_domino: "ํฉ๊ธ๋ณ ์ํ",
hud_acro: "๋ฐฑํ
๋ธ๋ง ์ฝค๋ณด",
hud_claw: "์ธํ ๊ตฌ์ถ ๋์ด",
keypad_title: "๐ฎ ์ค์๊ฐ ํค๋ณด๋ ์
๋ ฅ ์๊ฐํ",
cam_label: "๐ฅ ์นด๋ฉ๋ผ ๋ทฐ:",
cam_front: "๐ฅ ์ ๋ฉด ๋ทฐ",
cam_quarter: "๐ 45ยฐ ์ฟผํฐ ๋ทฐ",
cam_topdown: "๐ ํ๋ค์ด ๋ทฐ",
cam_tip: "<strong>[C]</strong> ํค๋ก ์นด๋ฉ๋ผ ๋ทฐ ์ฆ์ ์ ํ",
control_title: "์ปจํธ๋กค ๋ฐํฌ",
control_mode_label: "์กฐ์ ๋ชจ๋ ์ ํ",
mode_manual: "๐ฎ ์ธ๊ฐ ํ๋ ์ด",
mode_ai: "๐ค ์ค๋งํธ AI",
mode_help_manual: "โ, โ ๋ฐฉํฅํค๋ก ์นดํธ๋ฅผ ๋ฐ์ด ๋กค๋ฆฌํ์ ๊ท ํ์ ์ธ์๋ณด์ธ์! (15์ด ์์กด ์ ๐ ๊ณจ๋ ๋ฐธ๋ฐ์ ์น๋ฆฌ)",
mode_help_ai: "AI(PD ์ปจํธ๋กค๋ฌ)๊ฐ ๋ชจํฐ๋ฅผ ์๋ ์ ์ดํ์ฌ ์๋ฒฝํ ๊ท ํ์ ์ ์งํฉ๋๋ค.",
action_btn_label: "์ฆ๊ฐ ์คํ ์ก์
",
cannon_power_label: "๐ฃ ๋ํฌ ํ๋ ฅ ํ์",
cannon_preset_soft: "์ฝํ๊ฒ (0.6x)",
cannon_preset_normal: "๋ณดํต (1.0x)",
cannon_preset_heavy: "๊ฐํ๊ฒ (1.6x)",
cannon_preset_mega: "์ด๊ฐ๋ ฅ MEGA (2.0x)",
gravity_label: "์ค๋ ฅ ๊ฐ์๋ ์กฐ์ (Gravity)",
gravity_zero: "๋ฌด์ค๋ ฅ (0G)",
gravity_moon: "๋ฌ ํ๋ฉด (-1.6)",
gravity_earth: "์ง๊ตฌ (-9.8)",
gravity_heavy: "์ด์ค๋ ฅ (-24.8)",
btn_start_game: "โถ ๊ฒ์ ์์ (SPACE)",
btn_playing: "โธ ํ๋ ์ด ์ค (Rํค๋ก ๋ฆฌ์
)",
btn_retry: "๐ ์ฌ๋์ ํ๊ธฐ (Rํค)",
btn_play_again: "๐ ๋ค์ ํ๋ ์ด (Rํค)",
btn_reset_toy: "๐ ์์์น ๋ฆฌ์
(R)",
btn_export_code: "๐ ํ์ด์ฌ / XML ์ฝ๋ ๋ณต์ฌ",
ready_title: "ํ๋ ์ด ์ค๋น ์๋ฃ!",
ready_sub: "[SPACE] ํค ๋๋ [์์] ๋ฒํผ์ ๋๋ฌ ํ๋ ์ดํ์ธ์!",
overlay_btn_start: "โถ ๊ฒ์ ์์",
gameover_title: "์๋ฅด๋ฅด! ์ฐ๋ฌ์ก์ต๋๋ค!",
gameover_sub: "์๋ฅด๋ฅด ์ฐ๋ฌ์ก์ต๋๋ค! [R] ํค๋ก ์ฌ๋์ ํ์ธ์.",
label_survived: "๋ฒํด ์๊ฐ:",
label_grade: "๋์ ๋ฑ๊ธ:",
overlay_btn_retry: "๐ ์ฌ๋์ (R)",
overlay_btn_watch_ai: "๐ค ๋๋ํ AI ๊ด์ ํ๊ธฐ",
overlay_btn_play_again: "๐ ๋ค์ ํ๋ ์ด (R)",
overlay_btn_next: "โฉ ๋ค์ ๊ฒ์",
mentor_quote: "๐ข ENGINE LIVE ยท MuJoCo v3.3.0 (500Hz) ยท 30 FPS Stream ยท Zero Assets (100% Procedural) ยท Built with โค๏ธ by HWIHWA LAB",
banner_badge: "์์ง ๊ตฌ๋ ์ค",
modal_desc: "์ด ์ฝ๋๋ ์์ ํ ๋
๋ฆฝ ์คํ ๊ฐ๋ฅํ MuJoCo ๋ฌผ๋ฆฌ ๋ฒฝ๋์
๋๋ค. ๋ณต์ฌํด์ ์ํฐ๊ทธ๋๋นํฐ๋ ๋ก์ปฌ ํ์ด์ฌ์ ๋ถ์ฌ๋ฃ์ด ๋๋ง์ ์น๊ฒ์์ด๋ AI ์๋ฎฌ๋ ์ดํฐ๋ก ํ์ฅํ์ธ์!",
modal_tab_py: "ํ์ด์ฌ ์คํ ์คํฌ๋ฆฝํธ",
modal_tab_xml: "MuJoCo XML ์ค๊ณ๋",
modal_btn_copy: "๐ ํด๋ฆฝ๋ณด๋์ ๋ณต์ฌ",
modal_btn_close: "๋ซ๊ธฐ",
engine_loading_msg: "๐ฌ 3D ๋ฌผ๋ฆฌ ์์ง ๋ก๋ฉ ์ค... ์ ์๋ง ๊ธฐ๋ค๋ ค ์ฃผ์ธ์!"
}
};
// 10๋ ๋ฏธ๋๊ฒ์๋ณ ๋ง์ถคํ ์ธ๊ฐ ์๋ vs ์ค๋งํธ AI ์๋ด ๋ฌธ๊ตฌ
const GAME_MODE_HELP = {
1: {
ko: {
manual: "์คํ์ด์ค๋ฐ๋ฅผ ๋๋ฌ ์ ค๋ฆฌ๋น์ ํ์ด๋ฐ์ ๋ง์ถฐ ๋ฐ๋ฅ ๋งคํธ๋ก ์์ ํ๊ฒ ๋ํ์ํค์ธ์!",
ai: "์ค๋งํธ AI๊ฐ 1.6์ด๋ง๋ค ์ต์ ์ ๋ฆฌ๋ฌ์ผ๋ก ์ ค๋ฆฌ๋น์ ๊ณต์ค ํฌํํ์ฌ ๋งคํธ ํํฐ๋ฅผ ์์ฑํฉ๋๋ค!"
},
en: {
manual: "Press [Space] to drop cute jelly beans safely onto the bouncy foam pit!",
ai: "Smart AI drops jelly beans in a rhythmic sequence every 1.6s to create a sweet pile!"
}
},
2: {
ko: {
manual: "A / D ํค๋ก ์ข์ฐ ํ๋ฆฌํผ๋ฅผ ์ณ์ฌ๋ ค ์ ค๋ฆฌ๋ณผ๋ค์ด ๋ฐ๋ฅ์ผ๋ก ๋จ์ด์ง์ง ์๊ฒ ํ๊ฒจ๋ด์ธ์!",
ai: "์ค๋งํธ AI๊ฐ 10๊ฐ ๊ตฌ์ฌ์ ์ค์๊ฐ ๊ถค์ ์ ์ถ์ ํ์ฌ ํ๋ฆฌํผ ๋ํ ๊ตฌ์ญ ์ง์
์ ์ด๊ณ ์ ๋ฐ์ฌ ๋ฐ๊ฒฉํฉ๋๋ค!"
},
en: {
manual: "Press [A] / [D] to flap left and right flippers and keep the gumballs bouncing!",
ai: "Smart AI tracks all gumballs in real time and triggers reflex flaps whenever a ball enters the danger zone!"
}
},
3: {
ko: {
manual: "์คํ์ด์ค๋ฐ๋ฅผ ๋๋ฌ ์ ค๋ฆฌ๋น ์คํธ๋ผ์ด์ปค๋ก 1๋ฒ ๋๋ฏธ๋
ธ๋ฅผ ํ๊ฒฉํ๊ณ ํฉ๊ธ๋ณ์ ์ฐ๋ฌ๋จ๋ฆฌ์ธ์!",
ai: "์ค๋งํธ AI๊ฐ ๋ฌผ๋ฆฌ ์์ง ์ฐ์ ๋ฐ๊ฒฝ์ ๊ณ์ฐํ์ฌ ๋๋ฏธ๋
ธ ์ฐ์ ์ ๋๋ฅผ ์ผ์ผํค๋ ์ํ์ค ๋์ง์ ์๋ ์งํํฉ๋๋ค!"
},
en: {
manual: "Press [Space] to launch the jelly striker, topple the sweet dominoes, and hit the Gold Star!",
ai: "Smart AI calculates optimal impulse physics to trigger a domino chain reaction toppling the Gold Star!"
}
},
4: {
ko: {
manual: "W ๋๋ โ ํค๋ฅผ ์ค์ ํ์ด๋ฐ์ ๋ง์ถฐ ๋๋ฌ ๋ฐ๋์ ๊ฐ์ํ๊ณ 360๋ ํ์ ์ ๋ฌ์ฑํ์ธ์!",
ai: "์ค๋งํธ AI๊ฐ ๊ฐ์๋ ๋ถํธ์ ๋๊ธฐํ๋ ์ต์ ๊ณต์ง ํํ(Resonance Pumping) ํ ํฌ๋ฅผ ์๋ ์ธ๊ฐํฉ๋๋ค!"
},
en: {
manual: "Press [W] / [โ] in sync with the swing rhythm to pump momentum and achieve a 360ยฐ full loop!",
ai: "Smart AI applies optimal resonance pumping torque synchronized with angular velocity to conquer the 360ยฐ loop!"
}
},
5: {
ko: {
manual: "์คํ์ด์ค๋ฐ๋ก 2๋จ ๊ด์ ์ ์์ธก ๋ถ๊ฐ๋ฅํ ์นด์ค์ค ํ ํฌ๋ฅผ ์ฃผ์
ํ์ฌ 3ํ์ ๊ณต์ค์ ๋น๋ฅผ ์ฑ๊ณต์ํค์ธ์!",
ai: "์ค๋งํธ AI๊ฐ ์ด์ค ์ง์์ ๋น์ ํ ์์ ๊ณต๊ฐ์ ๋ถ์ํ์ฌ ํ๋ คํ ๊ณต์ค์ ๋น ์ฝค๋ณด๋ฅผ ์ ๋ํ๋ ์์ ๊ฒฐํฉ ํ ํฌ๋ฅผ ๋ถ์ฌํฉ๋๋ค!"
},
en: {
manual: "Press [Space] to inject chaotic torque into the double pendulum and complete 3 acrobatic somersaults!",
ai: "Smart AI drives non-linear phase-coupled sinusoidal torques to execute thrilling multi-rotation somersault combos!"
}
},
6: {
ko: {
manual: "์คํ์ด์ค๋ฐ๋ก ํํฌ๋น๊ณผ ๋ฏผํธ๋น์ ๋ ์ธ๋ณด์ฐ ์ํฐ์ฌ๋ผ์ด๋ ๋ ์ด์ค๋ฅผ ์์ํ์ธ์!",
ai: "์ค๋งํธ AI๊ฐ ์ ๋ ์ด์ ๊ฐ์ ๊ฑฐ๋ฆฌ ์ฐจ์ด๋ฅผ ๊ฐ์งํ์ฌ ๋ค์ฒ์ง ์ฃผ์์๊ฒ ์ฌ๋ฆฝ์คํธ๋ฆผ ๋ถ์คํธ๋ฅผ ์ฃผ์ด ๊ทน์ ์ธ ๋ฐ๋น ์น๋ถ๋ฅผ ์ฐ์ถํฉ๋๋ค!"
},
en: {
manual: "Press [Space] to unleash the thrilling rainbow water slide race between Pink Bean and Mint Bean!",
ai: "Smart AI monitors the lead gap and applies dynamic slipstream catch-up boost for a thrilling photo-finish showdown!"
}
},
7: {
ko: {
manual: "โ, โ ๋ฐฉํฅํค๋ก ์นดํธ๋ฅผ ๋ฐ์ด ๋กค๋ฆฌํ์ ๊ท ํ์ ์ธ์๋ณด์ธ์! (15์ด ์์กด ์ ๐ ๊ณจ๋ ๋ฐธ๋ฐ์ ์น๋ฆฌ)",
ai: "[์ด์ ์จ ์ฌ๋ ์์ปค์ค AI] ๋ฏธํ์ ํ๋ค๋ฆฌ๋ ๋กค๋ฆฌํ์ ์ค์๊ฐ LQR ์ ์ด๋ก ์ข์ฐ 3~4cm์ฉ ํก! ํก! ์น๋ฉฐ ์ค์ ๊ท ํ์ ์ ์งํฉ๋๋ค."
},
en: {
manual: "Use โ and โ arrow keys to balance the lollipop! (Survive 15s to Win ๐)",
ai: "[Living Circus AI] Performs real-time LQR balancing, dynamically micro-tapping 3~4cm to hold the center against carnival breezes."
}
},
8: {
ko: {
manual: "W / A / S / D ํค๋ก ๋ฌ์ฝคํ ๋ฒํผ์นด๋ฅผ ์กฐ์ข
ํ์ฌ ์๋ ๋ ๊ณณ๊ณณ์ 5๋ ํฉ๊ธ ๋ง์นด๋กฑ ๋ณ ์ฝ์ธ์ ๋ชจ๋ ์์งํ์ธ์!",
ai: "์ค๋งํธ AI๊ฐ Pure Pursuit ์์จ์ฃผํ๊ณผ ์ฅ์ ๋ฌผ ํ์ถ ๋ฆฌํ๋ ์ค๋ก ๊ฐ์ฅ ๊ฐ๊น์ด ๋ฏธ์์ง ํฉ๊ธ ์ฝ์ธ์ ์์ฐจ ํ์ํ์ฌ ์๋ฒฝ ์ฃผํํฉ๋๋ค!"
},
en: {
manual: "Drive the sweet bumper car with W / A / S / D to collect all 5 Golden Macaron Star Coins across the arena!",
ai: "Smart AI executes a Pure Pursuit autonomous waypoint navigation algorithm with obstacle avoidance to hunt all 5 coins!"
}
},
9: {
ko: {
manual: "W / S (์ด๊นจ), A / D (ํ๊ฟ์น), ์คํ์ด์ค๋ฐ (์์ ์จ/์คํ)๋ก ์ ค๋ฆฌ๋น ์ธํ์ ์กฐ์คํ์ฌ ๊ตฌ์ถํ์ธ์!",
ai: "์ค๋งํธ AI๊ฐ ์ญ๊ธฐ๊ตฌํ 3๋จ๊ณ ์ํ์ค(์ ๊ทผ โ ํ๊ฐ & ์์ ํก์ฐฉ โ ์์น)๋ฅผ ์ํํ์ฌ ์ ค๋ฆฌ๋น ์ธํ์ ์๋ ๊ตฌ์ถํฉ๋๋ค!"
},
en: {
manual: "Control shoulder (W/S), elbow (A/D), and spacebar (magnet toggle) to rescue the Jelly Bean plushie!",
ai: "Smart AI executes a 3-stage Inverse Kinematics pick-and-place sequence (approach โ descend & magnet on โ lift) to rescue the plushie!"
}
},
10: {
ko: {
manual: "์ฐ์ธก ์ฌ๋ผ์ด๋๋ก ๋ํฌ ํ์๋ฅผ ์กฐ์ ํ๊ณ , ์คํ์ด์ค๋ฐ๋ฅผ ๋๋ฌ 9๋จ ๋ง์นด๋กฑ ํ์๋ฅผ ์ผ๊ฒฉ์ ๋ถ๊ดด์ํค์ธ์!",
ai: "์ค๋งํธ AI๊ฐ ๋ง์นด๋กฑ ํ์์ ์ง๋ ์ค์ฌ(CoM)๊ณผ ํ๋ํ์ ๊ณ์ฐํ์ฌ 80% ์ด์ ์ ๋ณต์ ์ ๋ํ๋ ์ต์ ์ ์ ๊ฒฉ ์ฌ๊ฒฉ์ ๊ฐํฉ๋๋ค!"
},
en: {
manual: "Adjust cannon power with the right slider, then press [Space] to demolish the 9-story macaron tower in one shot!",
ai: "Smart AI computes tower center-of-mass and projectile ballistics, automatically firing an optimal sniper shot for total demolition!"
}
}
};
function updateModeHelpText() {
const modeHelp = document.getElementById("modeHelpText");
if (!modeHelp) return;
const gameHelp = GAME_MODE_HELP[currentExampleId];
if (gameHelp && gameHelp[currentLang] && gameHelp[currentLang][currentControlMode]) {
modeHelp.textContent = gameHelp[currentLang][currentControlMode];
} else {
modeHelp.textContent = currentControlMode === "ai"
? (I18N[currentLang]?.mode_help_ai || I18N.en.mode_help_ai)
: (I18N[currentLang]?.mode_help_manual || I18N.en.mode_help_manual);
}
}
// ์ ์ญ ์ํ ๋ณ์: ๊ธ๋ก๋ฒ ํ๊น
ํ์ด์ค(Hugging Face) ๋ฐ ํด์ธ ์ฌ์ฉ์ ํ์ค 100% ์๋ฌธ(en) ๊ธฐ๋ณธ ์์
let currentLang = (function() {
try {
const urlParams = new URLSearchParams(window.location.search);
const paramLang = urlParams.get("lang");
if (paramLang && (paramLang === "ko" || paramLang === "en")) {
return paramLang;
}
// ๊ณผ๊ฑฐ ๋ก์ปฌ์คํ ๋ฆฌ์ง์ ko๊ฐ ๋จ์์๋๋ผ๋ ํ๋ก๊ทธ๋จ ์ฒซ ์คํ์ ํญ์ ์๋ฌธ ๊ธฐ๋ณธ์ผ๋ก ์์
// ํ์ฌ ๋ธ๋ผ์ฐ์ ํญ ์ธ์
๋ด์์๋ง ํ ๊ธ ์ํ ์ ์ง
const sess = sessionStorage.getItem("jelly_lang_sess");
if (sess && (sess === "ko" || sess === "en")) {
return sess;
}
} catch (e) {}
return "en";
})();
let currentExampleId = 7;
let currentControlMode = "manual";
let currentGameState = "ready";
let currentCamera = "cam_front";
let currentCodeData = null;
let currentCodeTab = "py";
let examplesData = (typeof window !== "undefined" && window.EMBEDDED_EXAMPLES) ? window.EMBEDDED_EXAMPLES : {};
let activeKeySet = new Set();
let soundEnabled = true;
let bgmEnabled = false;
let audioCtx = null;
let bgmTimer = null;
let bgmStep = 0;
// WebAssembly Physics Engine (1st-Class Core Engine for Static Space & Web)
let wasmPlayer = null;
let useWasm = true;
// 10๋ ๋ฏธ๋๊ฒ์ ์น๋ฆฌ ์ถํ ๋ฐฐ๋ ํ
์คํธ ํ๋ฆฌ์
const VICTORY_BANNERS = {
1: { icon: "๐", title: "SKYDIVING PARTY CLEARED!", sub: "All Jelly Beans landed safely on the carnival floor!" },
2: { icon: "๐", title: "PINBALL JACKPOT!", sub: "Gumballs cascade through candy bumpers in high-score style!" },
3: { icon: "๐", title: "DOMINO CLEARED!", sub: "All 7 Dominos Knocked Down & Golden Star Hit! (0.83s)" },
4: { icon: "๐ก", title: "360ยฐ SWING COMPLETED!", sub: "Full kinetic somersault loop achieved in carnival sky!" },
5: { icon: "๐คธ", title: "ACROBATIC COMBO!", sub: "Twin Gymnast Beans performed 3 consecutive backflips!" },
6: { icon: "๐", title: "PINK BEAN WINS! ๐", sub: "Champion of the Rainbow Waterpark Slide! Splash pool reached!" },
7: { icon: "โญ", title: "GOLDEN BALANCER MASTER!", sub: "15 seconds balanced on pudding cart! Flawless control!" },
8: { icon: "๐", title: "COIN DASH MASTER!", sub: "All 5 Golden Star Coins Collected! Master Bumper Driver!" },
9: { icon: "๐งธ", title: "PLUSHIE RESCUED!", sub: "Magnetic Crane lifted the plushie bean safely out of the box!" },
10: { icon: "๐ฅ", title: "TOWER ANNIHILATED!", sub: "9-Story Macaron Tower 100% Demolished! Direct cannon hit!" }
};
const VICTORY_BANNERS_KR = {
1: { icon: "๐", title: "์ค์นด์ด๋ค์ด๋น ํํฐ ์ฑ๊ณต!", sub: "๋ชจ๋ ์ ค๋ฆฌ๋น์ด ํญ์ ํ ์ถ์ ๋ฐ๋ฅ์ ์์ ํ๊ฒ ์ฐฉ์งํ์ต๋๋ค!" },
2: { icon: "๐", title: "ํ๋ณผ ์ญํ ๋ฌ์ฑ!", sub: "๋ฌ์ฝคํ ์บ๋ ๋ฒํผ๋ฅผ ํต๊ณผํ๋ฉฐ ์ ค๋ฆฌ๋ณผ ํญํฌ์๊ฐ ์์์ง๋๋ค!" },
3: { icon: "๐", title: "๋๋ฏธ๋
ธ ์ ๋ ์๋ฒฝ ์ฑ๊ณต!", sub: "7์ฐ์ ๋๋ฏธ๋
ธ ์ ๋ & ํฉ๊ธ๋ณ ๋ช
์ค! 0.83์ด ํด๋ฆฌ์ด" },
4: { icon: "๐ก", title: "360๋ ์์ด์ธํธ ์ค์ ์ฑ๊ณต!", sub: "์ถ์ ํ๋์ ๊ฐ๋ฅด๋ ์๋ฒฝํ 360๋ ๊ณต์ง ํ์ ๋ฃจํ ๋ฌ์ฑ!" },
5: { icon: "๐คธ", title: "์ํฌ๋ก๋ฐํฑ 3์ฐ์ ํฅ!", sub: "์๋ฅ์ด ์ ค๋ฆฌ๋น์ ๊ณต์ค 3์ฐ์ ๋ฐฑํ
๋ธ๋ง ์์ปค์ค ์ฑ๊ณต!" },
6: { icon: "๐", title: "ํํฌ๋น 1์ ๊ณจ์ธ! ๐", sub: "๋ฌด์ง๊ฐ ์ํฐ ์ฌ๋ผ์ด๋ ์ ํจ! ์ฒจ๋ฒ ํ์ฅ ๊ณจ์ธ ์ฑ๊ณต!" },
7: { icon: "โญ", title: "15์ด ๊ณจ๋ ๋ฐธ๋ฐ์ ๋ฌ์ฑ!", sub: "ํธ๋ฉ ์นดํธ ์์์ ์์ฌ์์ฌ 15์ด ๊ท ํ ์ ์ง ์ฑ๊ณต!" },
8: { icon: "๐", title: "5๋ ํฉ๊ธ ์ฝ์ธ ์ ์ฒด ์์ง!", sub: "์ถ์ ๋ฒํผ์นด ๋ง์คํฐ ๋๋ผ์ด๋ฒ ๋ฑ๊ทน! ๋ชจ๋ ์คํ ์ฝ์ธ ํ๋!" },
9: { icon: "๐งธ", title: "์ ค๋ฆฌ๋น ์ธํ ๊ตฌ์ถ ์ฑ๊ณต!", sub: "์์ ํฌ๋ ์ธ ํก์ฐฉ์ผ๋ก ํน์ ํ ์ธํ๋น์ ์์ ํ๊ฒ ๊ตฌ์ถํ์ต๋๋ค!" },
10: { icon: "๐ฅ", title: "๋ง์นด๋กฑ ํ์ 100% ์ํ!", sub: "9์ธต ๋ง์นด๋กฑ ํ์ ํต์พํ ์ ๋ ์ํ ์ฑ๊ณต! ๋ํฌ์ ๋ช
์ค!" }
};
// ์คํ ๋์ผ๋ก / ์คํ์ด์ค ์ธํฐ๋ํฐ๋ธ ์ํ ๋จธ์ ์ ์ด ํ์ด๋จธ & ์ค์ฝ์ด ์นด์ดํฐ
let staticLifecycleTimer = null;
let staticBalanceInterval = null;
let staticBeanCounter = 0;
let staticPinballScore = 0;
let staticSwingLoops = 0;
let staticAcroCombo = 0;
let staticCoinCounter = 0;
let staticClawMagnet = false;
let staticSurvivalTime = 0.0;
// ============================================================================
// ๐ WASM Real-Time Physics Engine Controller (Singleton Promise)
// ============================================================================
class EngineLoadingManager {
constructor() {
this.currentVal = 6;
this.targetVal = 20;
this.isSceneStable = false;
this.isUiReady = false;
this.isFontsReady = false;
this.isReady = false;
this.isDismissed = false;
this.startTime = performance.now();
this.minDurationMs = 1600; // Pacing so users can comfortably perceive milestones
this.holdDurationMs = 500; // Hold at 100% for 500ms so user clearly perceives completion
this.timer = null;
this.overlay = null;
// Web Fonts loading check
if (typeof document !== "undefined" && document.fonts && document.fonts.ready) {
document.fonts.ready.then(() => {
this.isFontsReady = true;
this._checkReadiness();
}).catch(() => {
this.isFontsReady = true;
this._checkReadiness();
});
} else {
this.isFontsReady = true;
}
this._startTicker();
}
getOverlay() {
if (!this.overlay) this.overlay = document.getElementById("engineLoadingOverlay");
return this.overlay;
}
setMessage(msgKo, msgEn) {
const el = document.getElementById("engineLoadingMsg");
if (!el) return;
const isKo = (typeof currentLang !== "undefined" ? currentLang : "ko") === "ko";
el.textContent = isKo ? msgKo : msgEn;
}
setProgress(target, msgKo = null, msgEn = null) {
if (this.isReady) return;
this.targetVal = Math.max(this.targetVal, Math.min(95, target));
if (msgKo && msgEn) {
this.setMessage(msgKo, msgEn);
}
}
notifyUiReady() {
this.isUiReady = true;
this.setProgress(70, "๐จ UI ๋ฐ ๊ฒ์ ํ๋ผ๋ฏธํฐ ๋ก๋ฉ ์๋ฃ", "๐จ UI & Parameters Initialized");
this._checkReadiness();
}
notifySceneStable() {
this.isSceneStable = true;
this.setProgress(96, "โจ 3D ๊ทธ๋ํฝ ๋ฐ ๋ฌผ๋ฆฌ ๋ ๋๋ง ๊ฒ์ฆ ์๋ฃ", "โจ 3D Graphics & Physics Verified");
this._checkReadiness();
}
_checkReadiness() {
if (this.isReady) return;
// Check all physical and visual DOM criteria
const listEl = document.getElementById("brickList");
const hasGameList = listEl && listEl.children.length >= 10;
const titleEl = document.getElementById("activeTitle");
const hasHeader = titleEl && titleEl.textContent.trim().length > 0;
const canvas = document.querySelector(".screen-wrapper canvas.wasm-canvas");
const hasCanvas = canvas && canvas.clientWidth > 0 && canvas.clientHeight > 0;
const isPlayerReady = typeof wasmPlayer !== "undefined" && wasmPlayer && wasmPlayer.isReady && wasmPlayer.isGameLoaded && wasmPlayer.geomMeshes && wasmPlayer.geomMeshes.length > 0;
// All screen elements, web fonts, and 3D frames must be 100% verified!
if (this.isSceneStable && this.isFontsReady && hasGameList && hasHeader && hasCanvas && isPlayerReady) {
this.complete();
}
}
_startTicker() {
if (this.timer) return;
this.timer = setInterval(() => {
const elapsed = performance.now() - this.startTime;
const timeRatio = Math.min(1.0, elapsed / this.minDurationMs);
// Desired progress based on minimum pacing and actual milestone
let desired = this.targetVal;
if (!this.isReady) {
// Smoothly pace progress up to 88% while WASM module downloads and compiles
desired = Math.min(88, Math.max(this.targetVal, timeRatio * 85));
} else {
// Once engine and all elements are ready, glide smoothly all the way to 100%
desired = 100;
}
if (this.currentVal < desired) {
// Steady, comfortable step so numbers are clearly readable (never jump wildly)
const step = Math.min(1.8, Math.max(0.4, (desired - this.currentVal) * 0.12));
this.currentVal = Math.min(desired, this.currentVal + step);
}
const bar = document.getElementById("miniProgressBar");
const pct = document.getElementById("loadingPercent");
const rounded = Math.round(this.currentVal);
if (bar) bar.style.width = `${rounded}%`;
if (pct) pct.textContent = `${rounded}%`;
// When reaching 100% after readiness signal
if (this.isReady && this.currentVal >= 99.5) {
this.currentVal = 100;
if (bar) bar.style.width = "100%";
if (pct) {
pct.textContent = "100%";
pct.style.color = "#10b981"; // Vibrant Emerald Green
pct.style.transform = "scale(1.12)";
}
this.setMessage("๐ 100% ์ค๋น ์๋ฃ! ๊ฒ์์ ์์ํฉ๋๋ค!", "๐ 100% Ready! Starting 3D Arena!");
clearInterval(this.timer);
this.timer = null;
this._dismissWithHold();
}
}, 25);
}
complete() {
if (this.isReady) return;
this.isReady = true;
this.targetVal = 100;
this._startTicker();
}
_dismissWithHold() {
if (this.isDismissed) return;
this.isDismissed = true;
// Hold at 100% for 500ms so user perceives completion before fade-out begins
setTimeout(() => {
const ov = this.getOverlay();
if (!ov) return;
// Step 1: Smooth opacity fade-out (0.4s ease)
ov.classList.add("fade-out");
// Step 2: Clean DOM removal after fade-out transition finishes
setTimeout(() => {
ov.classList.add("is-hidden");
ov.style.setProperty("display", "none", "important");
ov.style.setProperty("opacity", "0", "important");
ov.style.setProperty("visibility", "hidden", "important");
ov.style.setProperty("pointer-events", "none", "important");
try { ov.remove(); } catch (e) {}
// Ensure 3D canvas and viewport dimensions are perfectly synchronized
if (typeof wasmPlayer !== "undefined" && wasmPlayer && typeof wasmPlayer.handleResize === "function") {
wasmPlayer.handleResize();
}
}, 420);
}, this.holdDurationMs);
}
}
const engineLoadingMgr = new EngineLoadingManager();
window.__engineLoadingMgr = engineLoadingMgr;
function dismissEngineLoadingOverlay() {
engineLoadingMgr.complete();
}
window.__dismissLoadingOverlay = dismissEngineLoadingOverlay;
// ============================================================================
// ๐ Kawaii Web Audio API Synthesizer (0 ๋ฐ์ดํธ ๋ค์ด๋ก๋, ๋ธ๋ผ์ฐ์ ์์ ํฉ์ฑ์)
// ============================================================================
function initAudio() {
if (!audioCtx) {
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
if (AudioContextClass) {
audioCtx = new AudioContextClass();
}
}
if (audioCtx && audioCtx.state === "suspended") {
audioCtx.resume();
}
}
function playBoing() {
if (!soundEnabled) return;
initAudio();
if (!audioCtx) return;
try {
const now = audioCtx.currentTime;
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.type = "sine";
osc.frequency.setValueAtTime(220, now);
osc.frequency.exponentialRampToValueAtTime(560, now + 0.12);
osc.frequency.exponentialRampToValueAtTime(280, now + 0.24);
gain.gain.setValueAtTime(0.3, now);
gain.gain.exponentialRampToValueAtTime(0.01, now + 0.24);
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.start(now);
osc.stop(now + 0.24);
} catch (e) {}
}
function playPop() {
if (!soundEnabled) return;
initAudio();
if (!audioCtx) return;
try {
const now = audioCtx.currentTime;
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.type = "sine";
osc.frequency.setValueAtTime(540, now);
osc.frequency.exponentialRampToValueAtTime(140, now + 0.08);
gain.gain.setValueAtTime(0.25, now);
gain.gain.exponentialRampToValueAtTime(0.01, now + 0.08);
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.start(now);
osc.stop(now + 0.08);
} catch (e) {}
}
function playCoinSound() {
if (!soundEnabled) return;
initAudio();
if (!audioCtx) return;
try {
const now = audioCtx.currentTime;
const notes = [987.77, 1318.51]; // B5 -> E6 ์พํํ 1-up ์ฝ์ธ ํ๋์
notes.forEach((freq, idx) => {
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
const t = now + idx * 0.08;
osc.type = "sine";
osc.frequency.setValueAtTime(freq, t);
gain.gain.setValueAtTime(0.25, t);
gain.gain.exponentialRampToValueAtTime(0.01, t + 0.18);
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.start(t);
osc.stop(t + 0.18);
});
} catch (e) {}
}
function playStart() {
if (!soundEnabled) return;
initAudio();
if (!audioCtx) return;
try {
const notes = [261.63, 329.63, 392.00, 523.25]; // C4 -> E4 -> G4 -> C5
notes.forEach((freq, idx) => {
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
const now = audioCtx.currentTime + idx * 0.07;
osc.type = "triangle";
osc.frequency.setValueAtTime(freq, now);
gain.gain.setValueAtTime(0.2, now);
gain.gain.exponentialRampToValueAtTime(0.01, now + 0.18);
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.start(now);
osc.stop(now + 0.18);
});
} catch (e) {}
}
function playGameOver() {
if (!soundEnabled) return;
initAudio();
if (!audioCtx) return;
try {
const notes = [440.00, 392.00, 349.23, 261.63]; // A4 -> G4 -> F4 -> C4
notes.forEach((freq, idx) => {
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
const now = audioCtx.currentTime + idx * 0.11;
osc.type = "sawtooth";
osc.frequency.setValueAtTime(freq, now);
gain.gain.setValueAtTime(0.18, now);
gain.gain.exponentialRampToValueAtTime(0.01, now + 0.22);
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.start(now);
osc.stop(now + 0.22);
});
} catch (e) {}
}
function playCheer() {
if (!soundEnabled) return;
initAudio();
if (!audioCtx) return;
try {
const notes = [523.25, 659.25, 783.99, 1046.50, 1318.51]; // C5 -> E5 -> G5 -> C6 -> E6
notes.forEach((freq, idx) => {
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
const now = audioCtx.currentTime + idx * 0.07;
osc.type = "triangle";
osc.frequency.setValueAtTime(freq, now);
gain.gain.setValueAtTime(0.28, now);
gain.gain.exponentialRampToValueAtTime(0.01, now + 0.28);
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.start(now);
osc.stop(now + 0.28);
});
} catch (e) {}
}
// ============================================================================
// ๐ต Procedural 8-Bit Chiptune Kawaii BGM (์์ Web Audio API ์ฝ๋ ์์ฑ)
// ============================================================================
const MELODY = [
523.25, 659.25, 783.99, 1046.50, 880.00, 783.99, 659.25, 523.25,
587.33, 659.25, 783.99, 880.00, 783.99, 659.25, 587.33, 523.25
];
const BASS = [
130.81, 130.81, 164.81, 164.81, 220.00, 220.00, 174.61, 196.00
];
function startBgm() {
initAudio();
if (!audioCtx) return;
if (bgmTimer) clearInterval(bgmTimer);
bgmStep = 0;
const stepInterval = 140; // ~107 BPM 16๋นํธ
bgmTimer = setInterval(() => {
if (!bgmEnabled || !audioCtx) return;
try {
const now = audioCtx.currentTime;
// 1. ๋ฉ๋ก๋ (๋ฆฌ๋ ์ฌ๊ฐํ)
const noteFreq = MELODY[bgmStep % MELODY.length];
if (noteFreq) {
const lead = audioCtx.createOscillator();
const leadGain = audioCtx.createGain();
lead.type = "square";
lead.frequency.setValueAtTime(noteFreq, now);
leadGain.gain.setValueAtTime(0.035, now);
leadGain.gain.exponentialRampToValueAtTime(0.002, now + 0.12);
lead.connect(leadGain);
leadGain.connect(audioCtx.destination);
lead.start(now);
lead.stop(now + 0.12);
}
// 2. ๋ฒ ์ด์ค (ํตํต ํ๋ ์ผ๊ฐํ)
if (bgmStep % 2 === 0) {
const bassFreq = BASS[(bgmStep / 2) % BASS.length];
const bass = audioCtx.createOscillator();
const bassGain = audioCtx.createGain();
bass.type = "triangle";
bass.frequency.setValueAtTime(bassFreq, now);
bassGain.gain.setValueAtTime(0.08, now);
bassGain.gain.exponentialRampToValueAtTime(0.005, now + 0.22);
bass.connect(bassGain);
bassGain.connect(audioCtx.destination);
bass.start(now);
bass.stop(now + 0.22);
}
bgmStep++;
} catch (e) {}
}, stepInterval);
}
function stopBgm() {
if (bgmTimer) {
clearInterval(bgmTimer);
bgmTimer = null;
}
}
function toggleBgm() {
initAudio();
bgmEnabled = !bgmEnabled;
const btn = document.getElementById("bgmToggleBtn");
const txt = document.getElementById("bgmText");
if (btn) btn.classList.toggle("playing", bgmEnabled);
if (txt) txt.textContent = bgmEnabled ? "BGM ON" : "BGM OFF";
if (bgmEnabled) {
playPop();
startBgm();
} else {
stopBgm();
}
}
// ============================================================================
// ๐ Confetti Particle System
// ============================================================================
function triggerConfetti() {
const canvas = document.getElementById("confettiCanvas");
if (!canvas) return;
const ctx = canvas.getContext("2d");
canvas.width = canvas.clientWidth || 640;
canvas.height = canvas.clientHeight || 480;
const colors = ["#ff477e", "#06d6a0", "#ffd166", "#118ab2", "#9d4edd", "#ff7b00"];
const particles = [];
for (let i = 0; i < 60; i++) {
particles.push({
x: canvas.width * 0.5 + (Math.random() - 0.5) * 80,
y: canvas.height * 0.45,
vx: (Math.random() - 0.5) * 16,
vy: -Math.random() * 12 - 6,
size: Math.random() * 9 + 4,
color: colors[Math.floor(Math.random() * colors.length)],
rot: Math.random() * 360,
vrot: (Math.random() - 0.5) * 15,
alpha: 1.0
});
}
let start = null;
function render(ts) {
if (!start) start = ts;
const progress = ts - start;
ctx.clearRect(0, 0, canvas.width, canvas.height);
let active = false;
particles.forEach(p => {
p.x += p.vx;
p.y += p.vy;
p.vy += 0.38;
p.rot += p.vrot;
p.alpha = Math.max(0, 1 - progress / 1500);
if (p.alpha > 0) {
active = true;
ctx.save();
ctx.translate(p.x, p.y);
ctx.rotate((p.rot * Math.PI) / 180);
ctx.fillStyle = p.color;
ctx.globalAlpha = p.alpha;
ctx.fillRect(-p.size / 2, -p.size / 2, p.size, p.size * 0.6);
ctx.restore();
}
});
if (active && progress < 1600) {
requestAnimationFrame(render);
} else {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
}
requestAnimationFrame(render);
}
// ============================================================================
// ๐ DOM Initialization
// ============================================================================
// CRITICAL FIX: <script type="module"> is deferred โ DOMContentLoaded may have
// already fired before module evaluation. Use readyState check to guarantee init.
function safeStep(name, fn) {
try {
return fn();
} catch (e) {
console.error(`[initApp] step '${name}' failed:`, e);
if (window.__bootError) window.__bootError(`${name}: ${e && e.message ? e.message : e}`);
}
}
let __appInitStarted = false;
async function initApp() {
if (__appInitStarted) return;
__appInitStarted = true;
// Each step isolated: one failure can never block the game list from rendering.
safeStep("language", setupLanguageToggle);
safeStep("sound", setupSoundToggle);
safeStep("bgm", setupBgmToggle);
safeStep("fullscreen", setupFullscreenToggle);
safeStep("keyboard", setupKeyboardListeners);
safeStep("widescreen", setupAutoWidescreen);
try {
await loadExamples();
} catch (e) {
console.error("[initApp] loadExamples failed:", e);
if (window.__bootError) window.__bootError("loadExamples: " + (e && e.message ? e.message : e));
}
safeStep("translations", applyTranslations);
safeStep("actionButtons", updateActionButtons);
safeStep("gameStateUI", () => updateGameStateUI());
if (typeof window !== 'undefined' && window.__engineLoadingMgr) {
window.__engineLoadingMgr.notifyUiReady();
}
// Catastrophic 40s timeout: warn user rather than abruptly hiding loading screen while elements are missing
setTimeout(() => {
if (typeof window !== 'undefined' && window.__engineLoadingMgr && !window.__engineLoadingMgr.isReady) {
console.warn("[initApp] 40s timeout reached without stable scene rendering.");
engineLoadingMgr.setMessage("โ ๏ธ ๋คํธ์ํฌ ๋ก๋ฉ ์ง์ฐ ์ค... ์ ์ ํ ๋ค์ ์๋ํด ์ฃผ์ธ์.", "โ ๏ธ Network delay... Please refresh if needed.");
}
}, 40000);
}
window.__jellyInitApp = initApp;
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initApp);
} else {
// DOM already parsed (module deferred execution) โ init immediately
initApp();
}
function setupAutoWidescreen() {
try {
if (window.resizeTo && screen.availWidth && screen.availHeight) {
if (window.outerWidth < screen.availWidth * 0.8) {
window.moveTo(0, 0);
window.resizeTo(screen.availWidth, screen.availHeight);
}
}
} catch (e) {}
}
function setupFullscreenToggle() {
const fsBtn = document.getElementById("fullscreenBtn");
const fsText = document.getElementById("fsText");
if (!fsBtn) return;
function updateFsText() {
if (document.fullscreenElement) {
if (fsText) fsText.textContent = "NORMAL";
fsBtn.title = currentLang === "ko" ? "์ผ๋ฐ ํ๋ฉด์ผ๋ก ๋ณต๊ท [F]" : "Exit Widescreen Fullscreen [F]";
} else {
if (fsText) fsText.textContent = "WIDE";
fsBtn.title = currentLang === "ko" ? "16:9 ์์ด๋ ์ ์ฒดํ๋ฉด ์ ํ [F]" : "Toggle 16:9 Widescreen Fullscreen [F]";
}
}
fsBtn.addEventListener("click", () => {
playPop();
if (!document.fullscreenElement) {
if (document.documentElement.requestFullscreen) {
document.documentElement.requestFullscreen().catch(() => {});
}
} else {
if (document.exitFullscreen) {
document.exitFullscreen().catch(() => {});
}
}
});
document.addEventListener("fullscreenchange", updateFsText);
updateFsText();
}
function setupLanguageToggle() {
const toggleBtn = document.getElementById("langToggleBtn");
if (!toggleBtn) return;
const langText = document.getElementById("langText");
if (langText) langText.textContent = currentLang.toUpperCase();
toggleBtn.title = currentLang === "en" ? "ํ๊ตญ์ด๋ก ๋ณ๊ฒฝ (Switch to Korean)" : "Switch to English";
toggleBtn.addEventListener("click", () => {
currentLang = currentLang === "en" ? "ko" : "en";
try {
sessionStorage.setItem("jelly_lang_sess", currentLang);
localStorage.removeItem("jelly_lang"); // ๊ธฐ์กด ko ๊ณ ์ ์บ์ ์ ๋ฆฌ
} catch (e) {}
if (langText) langText.textContent = currentLang.toUpperCase();
toggleBtn.title = currentLang === "en" ? "ํ๊ตญ์ด๋ก ๋ณ๊ฒฝ (Switch to Korean)" : "Switch to English";
applyTranslations();
renderExampleList();
updateUIHeader();
updateActionButtons();
updateGameStateUI();
playPop();
});
}
function setupSoundToggle() {
const toggleBtn = document.getElementById("soundToggleBtn");
if (!toggleBtn) return;
toggleBtn.addEventListener("click", () => {
initAudio();
soundEnabled = !soundEnabled;
toggleBtn.classList.toggle("muted", !soundEnabled);
toggleBtn.innerHTML = soundEnabled ? '๐ <span id="soundText">SFX ON</span>' : '๐ <span id="soundText">SFX OFF</span>';
if (soundEnabled) playPop();
});
}
function setupBgmToggle() {
const toggleBtn = document.getElementById("bgmToggleBtn");
if (!toggleBtn) return;
toggleBtn.addEventListener("click", () => {
toggleBgm();
});
}
function applyTranslations() {
const dict = I18N[currentLang] || I18N.en;
document.querySelectorAll("[data-i18n]").forEach(elem => {
const key = elem.getAttribute("data-i18n");
if (dict[key]) {
if (dict[key].includes("<")) {
elem.innerHTML = dict[key];
} else {
elem.textContent = dict[key];
}
}
});
// ๋ชจ๋ ๋์๋ง ๋ฐ ์ธ๋์ผ์ดํฐ ์ฆ์ ๊ฐฑ์ (๋จ์ผ ์ด๋ชจ์ง ์์ด์ฝ ์ ์ฉ)
updateModeHelpText();
const indicatorIcon = document.getElementById("indicatorIcon");
const indicatorText = document.getElementById("indicatorText");
if (indicatorIcon) {
indicatorIcon.textContent = currentControlMode === "ai" ? "๐ค" : "๐ฎ";
}
if (indicatorText) {
indicatorText.textContent = currentControlMode === "ai"
? (currentLang === "ko" ? "AI ์์จ ์ ์ด ๋ชจ๋" : "Autonomous AI Mode")
: (currentLang === "ko" ? "์ธ๊ฐ ์๋ ์กฐ์ ๋ชจ๋" : "Human Manual Mode");
}
}
// ============================================================================
// ๐ฅ 3-Way Camera Controller
// ============================================================================
async function setCamera(camName) {
playPop();
currentCamera = camName;
document.getElementById("btnCamFront")?.classList.toggle("active", camName === "cam_front");
document.getElementById("btnCamQuarter")?.classList.toggle("active", camName === "cam_quarter");
document.getElementById("btnCamTopdown")?.classList.toggle("active", camName === "cam_topdown");
if (useWasm && wasmPlayer) {
wasmPlayer.setCamera(camName);
return;
}
try {
await fetch("/api/camera", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ camera: camName })
});
} catch (err) {
console.error("Camera switch error:", err);
}
}
function cycleCamera() {
const order = ["cam_front", "cam_quarter", "cam_topdown"];
const curIdx = order.indexOf(currentCamera);
const nextCam = order[(curIdx + 1) % order.length];
setCamera(nextCam);
}
// ============================================================================
// ๐ WASM Real-Time Physics Engine Controller (Singleton Promise)
// ============================================================================
let wasmInitPromise = null;
async function initWasmEngine() {
if (wasmPlayer && wasmPlayer.isReady) {
return wasmPlayer;
}
if (wasmInitPromise) return wasmInitPromise;
wasmInitPromise = (async () => {
const container = document.querySelector('.screen-wrapper');
const streamImg = document.getElementById("mjpegStream");
if (streamImg) streamImg.style.display = "none";
const statusLabel = document.getElementById("streamStatus");
if (statusLabel) statusLabel.textContent = "WASM 60FPS";
engineLoadingMgr.setProgress(25, "๐ฌ 3D ๋ฌผ๋ฆฌ ์์ง ์ปค๋ ์ด๊ธฐํ ์ค...", "๐ฌ Initializing 3D Physics Engine...");
try {
if (!MujocoWasmPlayer) {
engineLoadingMgr.setProgress(50, "๐ฆ MuJoCo WebAssembly ๋ชจ๋ ๋ก๋ฉ ์ค...", "๐ฆ Loading MuJoCo WASM Module...");
const mod = await import(withSign("./mujoco_wasm_player.js?v=20261107_v30"));
MujocoWasmPlayer = mod.MujocoWasmPlayer;
}
wasmPlayer = new MujocoWasmPlayer(container);
engineLoadingMgr.setProgress(75, "โ๏ธ 60FPS ๋ฌผ๋ฆฌ ์ฐ์ฐ ์ฝ์ด ์ปดํ์ผ ์ค...", "โ๏ธ Compiling 60FPS Physics Core...");
await wasmPlayer.init();
engineLoadingMgr.setProgress(92, "๐จ 3D ์นด๋๋ฐ ํ
๋งํํฌ ํ๊ฒฝ ๋น๋ ์ค...", "๐จ Building 3D Carnival Arena...");
wasmPlayer.onTelemetryUpdate = (t) => {
updateHUD(t);
if (t.victory_banner && currentGameState !== "victory") {
currentGameState = "victory";
playCheer();
triggerConfetti();
updateGameStateUI(t);
}
};
wasmPlayer.onCoinCollected = (coins) => {
playCoinSound();
triggerConfetti();
const el = document.getElementById("hudCoins");
if (el) el.textContent = coins;
};
wasmPlayer.onStateChange = (state, data) => {
currentGameState = state;
updateGameStateUI(data);
if (state === "victory") {
playCheer();
triggerConfetti();
} else if (state === "gameover") {
playGameOver();
}
};
console.log("๐ MujocoWasmPlayer successfully initialized!");
return wasmPlayer;
} catch (err) {
console.error("โ Failed to initialize MujocoWasmPlayer:", err);
if (window.__bootError) window.__bootError("Physics engine: " + (err && err.message ? err.message : err));
throw err;
}
})();
return wasmInitPromise;
}
function updateHUD(t) {
if (!t) return;
if (t.survival_time !== undefined) {
const el = document.getElementById("hudScore");
if (el) el.textContent = `${t.survival_time.toFixed(2)}s`;
}
if (t.best_score !== undefined) {
const el = document.getElementById("hudBest");
if (el) el.textContent = `${t.best_score.toFixed(2)}s`;
}
if (t.pole_angle_deg !== undefined) {
const el = document.getElementById("hudAngle");
if (el) el.textContent = `${t.pole_angle_deg}ยฐ`;
}
if (t.coins_collected !== undefined) {
const el = document.getElementById("hudCoins");
if (el) el.textContent = t.coins_collected;
}
if (t.demolition_rate !== undefined) {
const el = document.getElementById("hudDemo");
if (el) el.textContent = t.demolition_rate.toFixed(1);
}
if (t.beans_landed !== undefined) {
const el = document.getElementById("hudBeansLanded");
if (el) el.textContent = `${t.beans_landed} (${t.beans_dropped || 4} drops)`;
}
if (t.pinball_score !== undefined) {
const el = document.getElementById("hudPinballScore");
if (el) el.textContent = t.pinball_score;
}
if (t.domino_cleared !== undefined) {
const el = document.getElementById("hudDominoStatus");
if (el) el.textContent = t.domino_cleared ? "Cleared! (0.83s) ๐" : "Standing ๐";
}
if (t.swing_angle_deg !== undefined) {
const el = document.getElementById("hudSwingAngle");
if (el) el.textContent = `${t.swing_angle_deg}ยฐ (Loops: ${t.swing_loops || 0})`;
}
if (t.somersault_count !== undefined) {
const el = document.getElementById("hudAcroCombo");
if (el) el.textContent = `${Math.min(3, t.somersault_count)} / 3 ๐คธ`;
}
if (t.race_leader !== undefined) {
const el = document.getElementById("hudRaceLeader");
if (el) el.textContent = t.race_winner ? `${t.race_winner} Won! ๐` : t.race_leader;
}
if (t.claw_height !== undefined) {
const el = document.getElementById("hudClawHeight");
if (el) el.textContent = `${t.claw_height.toFixed(2)}m`;
}
}
// ============================================================================
// ๐ฎ ์์ ๊ด๋ฆฌ & ์ ํ (100% ๋ก์ปฌ ๋๋ฑ ๋ฌผ๋ฆฌ ์๋ฎฌ๋ ์ด์
์ง๊ฒฐ)
// ============================================================================
async function loadExamples() {
// 1. EMBEDDED_EXAMPLES ๋๊ธฐ ๋ก๋ ๋ฐ ์ด๊ธฐ UI ์ธํ
if (typeof window.EMBEDDED_EXAMPLES !== "undefined" && Object.keys(window.EMBEDDED_EXAMPLES).length > 0) {
examplesData = window.EMBEDDED_EXAMPLES;
}
// ๊ธฐ๋ณธ ๊ฒ์ ID ๊ฒฐ์ (์ ์ ํด๋ฆญ ๋๊ธฐ๊ฐ ๋๋ ํ๋๊ทธ์ญ 7๋ฒ)
const pending = Number(window.__pendingSelect) || 7;
currentExampleId = pending;
// ์ข์ธก ๊ฒ์ ๋ฆฌ์คํธ ๋ฐ UI ํค๋ ๋๊ธฐ ์ฆ๊ฐ ๋ ๋๋ง
renderExampleList();
updateUIHeader();
updateActionButtons();
updateGameStateUI();
if (typeof window !== 'undefined' && window.__engineLoadingMgr) {
window.__engineLoadingMgr.notifyUiReady();
}
// 2. ๐ MuJoCo WebAssembly ์ค์๊ฐ ๋ฌผ๋ฆฌ ์์ง ์ฆ์ ๊ฐ๋
useWasm = true;
try {
await initWasmEngine();
if (wasmPlayer) {
wasmPlayer.loadGame(currentExampleId);
}
} catch (err) {
console.error("WASM startup error:", err);
if (window.__engineLoadingMgr) {
window.__engineLoadingMgr.setMessage("โ ๏ธ WASM ๋ฌผ๋ฆฌ ์์ง ๋ก๋ฉ ์ค๋ฅ", "โ ๏ธ WASM Loading Error");
window.__engineLoadingMgr.complete();
}
}
}
function renderExampleList() {
const listEl = document.getElementById("brickList");
if (!listEl) return;
listEl.innerHTML = "";
for (let i = 1; i <= 10; i++) {
const meta = examplesData[i];
if (!meta) continue;
const item = document.createElement("div");
item.className = `brick-item ${i === currentExampleId ? "active" : ""}`;
item.onclick = () => {
playPop();
selectExample(i);
};
const title = currentLang === "ko" ? meta.title_kr : `${i.toString().padStart(2, "0")} ยท ${meta.title}`;
item.innerHTML = `
<div class="brick-item-top">
<span class="brick-num">#${i.toString().padStart(2, "0")}</span>
<span class="brick-category-tag">${meta.badge}</span>
</div>
<div class="brick-title">${title}</div>
`;
listEl.appendChild(item);
}
}
async function selectExample(id) {
currentExampleId = id;
renderExampleList();
updateUIHeader();
updateActionButtons();
currentGameState = "ready";
currentControlMode = "manual";
document.getElementById("btnModeManual")?.classList.add("active");
document.getElementById("btnModeAI")?.classList.remove("active");
const indicatorIcon = document.getElementById("indicatorIcon");
const indicatorText = document.getElementById("indicatorText");
if (indicatorIcon) indicatorIcon.textContent = "๐ฎ";
if (indicatorText) {
indicatorText.textContent = currentLang === "ko" ? "์ธ๊ฐ ์๋ ์กฐ์ ๋ชจ๋" : "Human Manual Mode";
}
updateModeHelpText();
updateGameStateUI();
// ๐ WASM ๋ฌผ๋ฆฌ ์์ง์ผ๋ก ์ง๊ฒฐ (์ง์ฐ ์ ๋ก, 10๋ ๋ฏธ๋๊ฒ์ 3D ๋ฌผ๋ฆฌ ์ฆ์ ๋ก๋)
if (useWasm) {
if (wasmPlayer && wasmPlayer.isReady) {
wasmPlayer.loadGame(id);
} else {
initWasmEngine().then(player => {
if (player && player.isReady) player.loadGame(id);
}).catch(err => {
console.error("selectExample wasm load error:", err);
});
}
return;
}
}
function nextExample() {
const nextId = currentExampleId >= 10 ? 1 : currentExampleId + 1;
selectExample(nextId);
}
function updateUIHeader() {
const meta = examplesData[currentExampleId];
if (!meta) return;
const title = currentLang === "ko" ? meta.title_kr : `${currentExampleId.toString().padStart(2, "0")} ยท ${meta.title}`;
document.getElementById("activeTitle").textContent = title;
document.getElementById("activeBadge").textContent = meta.badge;
// 10๋ ๋ฏธ๋๊ฒ์ ์ ์ฉ HUD ์์ ฏ ๊ฐ์์ฑ ์ ์ด
const setHudDisplay = (id, show) => {
const el = document.getElementById(id);
if (el) el.style.display = show ? "flex" : "none";
};
const isCartpole = currentExampleId === 7;
setHudDisplay("scoreHud", isCartpole);
setHudDisplay("bestHud", isCartpole);
setHudDisplay("angleHud", isCartpole);
setHudDisplay("beanHud", currentExampleId === 1);
setHudDisplay("pinballHud", currentExampleId === 2);
setHudDisplay("dominoHud", currentExampleId === 3);
setHudDisplay("swingHud", currentExampleId === 4);
setHudDisplay("acroHud", currentExampleId === 5);
setHudDisplay("raceHud", currentExampleId === 6);
setHudDisplay("coinHud", currentExampleId === 8);
setHudDisplay("clawHud", currentExampleId === 9);
setHudDisplay("demoHud", currentExampleId === 10);
// ๋ชจ๋ ์นด๋ ์์ ํ์ฑํ (10๋ ๋ฏธ๋๊ฒ์ ์ ์ฒด ์ค๋งํธ AI ์์จ์ฃผํ/์คํ ํ๋ ์ด ์ง์)
document.getElementById("modeCard").style.display = "flex";
document.getElementById("cannonCard").style.display = currentExampleId === 10 ? "flex" : "none";
updateModeHelpText();
}
// ============================================================================
// ๐๏ธ ์ํฉ๋ณ 10๋ ๋ฏธ๋๊ฒ์ ์กฐ์ ๋ฒํผ ๋ฐ์ธ๋
// ============================================================================
function updateActionButtons() {
const grid = document.getElementById("actionBtnGrid");
if (!grid) return;
grid.innerHTML = "";
const isKo = currentLang === "ko";
if (currentExampleId === 1) {
grid.innerHTML = `
<button class="btn-action-trigger" onclick="sendAction('drop_bean')">
๐ ${isKo ? "์ ค๋ฆฌ๋น ๊ณต์ค ํฌํ! (์คํ์ด์ค๋ฐ)" : "Drop Extra Bean! (Space)"}
</button>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px; margin-top: 6px;">
<button class="btn-action-trigger" onclick="sendAction('bounce_cushion', -1)">
โ ${isKo ? "์ข์ธก ํ๊ธฐ๊ธฐ (โ / A)" : "Bounce Left (โ / A)"}
</button>
<button class="btn-action-trigger" onclick="sendAction('bounce_cushion', 1)">
${isKo ? "์ฐ์ธก ํ๊ธฐ๊ธฐ โถ (โ / D)" : "Bounce Right โถ (โ / D)"}
</button>
</div>
`;
} else if (currentExampleId === 2) {
grid.innerHTML = `
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px;">
<button class="btn-action-trigger" onmousedown="sendAction('flip_left')" onmouseup="sendAction('flip_stop')">
โ ${isKo ? "์ข์ธก ํ๋ฆฌํผ (A)" : "Left Flipper (A)"}
</button>
<button class="btn-action-trigger" onmousedown="sendAction('flip_right')" onmouseup="sendAction('flip_stop')">
${isKo ? "์ฐ์ธก ํ๋ฆฌํผ โถ (D)" : "Right Flipper โถ (D)"}
</button>
</div>
<button class="btn-action-trigger" style="margin-top: 6px;" onclick="sendAction('ball_rain')">
โ ${isKo ? "์ ค๋ฆฌ๋ณผ ํญํฌ์ (์คํ์ด์ค๋ฐ)" : "Gumball Rain (Space)"}
</button>
`;
} else if (currentExampleId === 3) {
grid.innerHTML = `
<button class="btn-action-trigger" onclick="sendAction('push_domino')">
๐ ${isKo ? "1๋ฒ ๋๋ฏธ๋
ธ ๋ฐ๊ธฐ! (์คํ์ด์ค๋ฐ)" : "Strike 1st Domino! (Space)"}
</button>
`;
} else if (currentExampleId === 4) {
grid.innerHTML = `
<button class="btn-action-trigger" onclick="sendAction('swing_pump')">
๐ก ${isKo ? "๊ทธ๋ค ๋ฐ๋ ๊ฐ์ (W / โ / ์คํ์ด์ค๋ฐ)" : "Pump Momentum (W / โ / Space)"}
</button>
`;
} else if (currentExampleId === 5) {
grid.innerHTML = `
<button class="btn-action-trigger" onclick="sendAction('acrobatic_flip')">
๐คธ ${isKo ? "์ํฌ๋ก๋ฐํฑ ํฅ (์คํ์ด์ค๋ฐ)" : "Acrobatic Kick (Space)"}
</button>
`;
} else if (currentExampleId === 6) {
grid.innerHTML = `
<button class="btn-action-trigger" onclick="sendAction('start_race')">
๐ ${isKo ? "์ํฐ ์ฌ๋ผ์ด๋ ์ถ๋ฐ! (์คํ์ด์ค๋ฐ)" : "Start Slide Race! (Space)"}
</button>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px; margin-top: 6px;">
<button class="btn-action-trigger" onclick="sendAction('slide_boost_pink')">${isKo ? "๐ ํํฌ๋น ๋ถ์คํฐ (A / โ)" : "๐ Pink Turbo Boost (A / โ)"}</button>
<button class="btn-action-trigger" onclick="sendAction('slide_boost_mint')">${isKo ? "๐ ๋ฏผํธ๋น ๋ถ์คํฐ (D / โ)" : "๐ Mint Turbo Boost (D / โ)"}</button>
</div>
`;
} else if (currentExampleId === 7) {
grid.innerHTML = `
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px;">
<button class="btn-action-trigger" onmousedown="sendAction('cart_left')" onmouseup="sendAction('cart_stop')">
โ ${isKo ? "์ข์ธก ์ด๋ (A / โ)" : "Push Left (A / โ)"}
</button>
<button class="btn-action-trigger" onmousedown="sendAction('cart_right')" onmouseup="sendAction('cart_stop')">
${isKo ? "์ฐ์ธก ์ด๋ โถ (D / โ)" : "Push Right โถ (D / โ)"}
</button>
</div>
`;
} else if (currentExampleId === 8) {
grid.innerHTML = `
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px;">
<button class="btn-action-trigger" onmousedown="sendAction('car_forward')" onmouseup="sendAction('car_stop')">
โฒ ${isKo ? "์ ์ง (W / โ)" : "Throttle (W / โ)"}
</button>
<button class="btn-action-trigger" onmousedown="sendAction('car_backward')" onmouseup="sendAction('car_stop')">
โผ ${isKo ? "ํ์ง (S / โ)" : "Reverse (S / โ)"}
</button>
<button class="btn-action-trigger" onmousedown="sendAction('car_left')" onmouseup="sendAction('car_stop')">
โ ${isKo ? "์ขํ์ (A / โ)" : "Steer Left (A / โ)"}
</button>
<button class="btn-action-trigger" onmousedown="sendAction('car_right')" onmouseup="sendAction('car_stop')">
${isKo ? "์ฐํ์ โถ (D / โ)" : "Steer Right โถ (D / โ)"}
</button>
</div>
<p style="font-size: 11px; color: var(--candy-yellow); font-weight: 700; margin-top: 6px; text-align: center;">
โญ ${isKo ? "5๋ ํฉ๊ธ ์ฝ์ธ์ ๋ชจ๋ ํ๋ํ์ธ์!" : "Collect all 5 Golden Star Coins!"}
</p>
`;
} else if (currentExampleId === 9) {
grid.innerHTML = `
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px;">
<button class="btn-action-trigger" onclick="sendAction('arm_shoulder_up')">${isKo ? "์ด๊นจ ๊ด์ โ (W / โ)" : "Shoulder โ (W / โ)"}</button>
<button class="btn-action-trigger" onclick="sendAction('arm_shoulder_down')">${isKo ? "์ด๊นจ ๊ด์ โ (S / โ)" : "Shoulder โ (S / โ)"}</button>
<button class="btn-action-trigger" onclick="sendAction('arm_elbow_up')">${isKo ? "ํ๊ฟ์น โ (D / โ)" : "Elbow โ (D / โ)"}</button>
<button class="btn-action-trigger" onclick="sendAction('arm_elbow_down')">${isKo ? "ํ๊ฟ์น โ (A / โ)" : "Elbow โ (A / โ)"}</button>
</div>
<button class="btn-action-trigger" style="margin-top: 6px;" onclick="sendAction('claw_magnet_toggle')">
๐งฒ ${isKo ? "์์ ํฌ๋ ์ธ ํก์ฐฉ ON/OFF (์คํ์ด์ค๋ฐ)" : "Magnet Grip Suction (Space)"}
</button>
`;
} else if (currentExampleId === 10) {
grid.innerHTML = `
<button class="btn-action-trigger" onclick="sendAction('fire_cannon')">
๐ ${isKo ? "์ ค๋ฆฌ๋น ๋ํฌ ๋ฐ์ฌ! (์คํ์ด์ค๋ฐ)" : "FIRE CANNONBALL! (Space)"}
</button>
`;
} else {
grid.innerHTML = `
<button class="btn-action-trigger" onclick="sendAction('start')">
โถ ${isKo ? "๋ฌผ๋ฆฌ ์๋ฎฌ๋ ์ด์
์์ (์คํ์ด์ค๋ฐ)" : "Trigger Physics (Space)"}
</button>
`;
}
}
function triggerStaticVictory(exampleId) {
currentGameState = "victory";
playCheer();
triggerConfetti();
const banner = (currentLang === "ko" ? VICTORY_BANNERS_KR[exampleId] : VICTORY_BANNERS[exampleId]) || {
icon: "๐",
title: "VICTORY!",
sub: "Stage Cleared!"
};
const iconEl = document.getElementById("vicIcon");
const titleEl = document.getElementById("vicTitle");
const subEl = document.getElementById("vicSub");
if (iconEl) iconEl.textContent = banner.icon;
if (titleEl) titleEl.textContent = banner.title;
if (subEl) subEl.textContent = banner.sub;
updateGameStateUI();
}
function startStaticAISimulation(exampleId) {
if (staticLifecycleTimer) {
clearTimeout(staticLifecycleTimer);
staticLifecycleTimer = null;
}
if (staticBalanceInterval) {
clearInterval(staticBalanceInterval);
staticBalanceInterval = null;
}
const screenImg = document.getElementById("mjpegStream");
// 01 ์ค์นด์ด๋ค์ด๋น AI ๋ฆฌ๋ฌ ํฌํ ์๋ฎฌ๋ ์ด์
(1.2์ด ๊ฐ๊ฒฉ 4ํ ํฌํ ํ ์น๋ฆฌ)
if (exampleId === 1) {
let aiLanded = 0;
staticBalanceInterval = setInterval(() => {
if (currentGameState !== "playing" || currentControlMode !== "ai" || currentExampleId !== 1) {
clearInterval(staticBalanceInterval);
return;
}
aiLanded++;
const beanEl = document.getElementById("hudBeansLanded");
if (beanEl) beanEl.textContent = `${aiLanded} / 4 ๐`;
playBoing();
if (aiLanded >= 4) {
clearInterval(staticBalanceInterval);
triggerStaticVictory(1);
}
}, 700);
}
// 02 ์บ๋ ํ๋ณผ ๋ณผํ์ฅ AI ์๋ ํ๋ฆฌํ ๋ฐ 1000์ ๋ํ
else if (exampleId === 2) {
staticPinballScore = 0;
staticBalanceInterval = setInterval(() => {
if (currentGameState !== "playing" || currentControlMode !== "ai" || currentExampleId !== 2) {
clearInterval(staticBalanceInterval);
return;
}
staticPinballScore += Math.floor(Math.random() * 60) + 120;
const pinEl = document.getElementById("hudPinballScore");
if (pinEl) pinEl.textContent = staticPinballScore;
playBoing();
if (staticPinballScore >= 1000) {
clearInterval(staticBalanceInterval);
triggerStaticVictory(2);
}
}, 320);
}
// 03 ๋๋ฏธ๋
ธ ์คํธ๋ผ์ดํฌ AI ํ๋ ์ํ์ค ๊ฒฉ๋ฐ
else if (exampleId === 3) {
staticLifecycleTimer = setTimeout(() => {
if (currentGameState !== "playing" || currentExampleId !== 3) return;
if (screenImg && typeof EMBEDDED_CLEARED !== "undefined" && EMBEDDED_CLEARED[3]) {
screenImg.src = EMBEDDED_CLEARED[3];
}
const domEl = document.getElementById("hudDominoStatus");
if (domEl) domEl.textContent = "AI Cleared! (0.83s) ๐";
triggerStaticVictory(3);
}, 2400);
}
// 04 ์์ด์ธํธ ๊ทธ๋ค AI ๊ณต์ง ํํ 360๋ ๋ฃจํ
else if (exampleId === 4) {
let aiAngle = 0.0;
staticBalanceInterval = setInterval(() => {
if (currentGameState !== "playing" || currentControlMode !== "ai" || currentExampleId !== 4) {
clearInterval(staticBalanceInterval);
return;
}
aiAngle += 72.0;
const swingEl = document.getElementById("hudSwingAngle");
if (swingEl) swingEl.textContent = `${aiAngle.toFixed(1)}ยฐ (${Math.min(1, Math.floor(aiAngle / 360))} loop)`;
playBoing();
if (aiAngle >= 360.0) {
clearInterval(staticBalanceInterval);
triggerStaticVictory(4);
}
}, 550);
}
// 05 ํธ์ ์ํฌ๋ก๋ฐํฑ ์ค์ AI 3์ฐ์ ํ
๋ธ๋ง ํฅ
else if (exampleId === 5) {
let aiCombos = 0;
staticBalanceInterval = setInterval(() => {
if (currentGameState !== "playing" || currentControlMode !== "ai" || currentExampleId !== 5) {
clearInterval(staticBalanceInterval);
return;
}
aiCombos++;
const acroEl = document.getElementById("hudAcroCombo");
if (acroEl) acroEl.textContent = `${aiCombos} / 3 ๐คธ`;
playBoing();
if (aiCombos >= 3) {
clearInterval(staticBalanceInterval);
triggerStaticVictory(5);
}
}, 800);
}
// 06 ์ฌ๋ผ์ด๋ ๋ ์ด์ค AI ์ฌ๋ฆฝ์คํธ๋ฆผ ์ถ์ ์ญ์ ์น
else if (exampleId === 6) {
staticLifecycleTimer = setTimeout(() => {
if (currentGameState !== "playing" || currentExampleId !== 6) return;
if (screenImg && typeof EMBEDDED_CLEARED !== "undefined" && EMBEDDED_CLEARED[6]) {
screenImg.src = EMBEDDED_CLEARED[6];
}
const leaderEl = document.getElementById("hudRaceLeader");
if (leaderEl) leaderEl.textContent = "Pink Bean Won! ๐";
triggerStaticVictory(6);
}, 2400);
}
// 07 ์นดํธํด LQR AI ํผํํธ ๋ฐธ๋ฐ์ฑ (3.5์ด ๋ฐ๋ชจ ํ ์น๋ฆฌ)
else if (exampleId === 7) {
staticSurvivalTime = 0.0;
staticBalanceInterval = setInterval(() => {
if (currentGameState !== "playing" || currentExampleId !== 7) {
clearInterval(staticBalanceInterval);
return;
}
staticSurvivalTime += 0.5;
const scoreEl = document.getElementById("hudScore");
const angleEl = document.getElementById("hudAngle");
if (scoreEl) scoreEl.textContent = `${staticSurvivalTime.toFixed(2)}s`;
if (angleEl) {
const sway = (Math.sin(staticSurvivalTime * 3.5) * 0.8).toFixed(1);
angleEl.textContent = `${sway > 0 ? "+" : ""}${sway}ยฐ`;
}
if (staticSurvivalTime >= 3.5) {
clearInterval(staticBalanceInterval);
triggerStaticVictory(7);
}
}, 250);
}
// 08 ๋ฒํผ์นด Pure Pursuit AI ์ฝ์ธ ์์ฐจ 5/5 ์์ง
else if (exampleId === 8) {
let aiCoins = 0;
staticBalanceInterval = setInterval(() => {
if (currentGameState !== "playing" || currentControlMode !== "ai" || currentExampleId !== 8) {
clearInterval(staticBalanceInterval);
return;
}
aiCoins++;
const coinEl = document.getElementById("hudCoins");
if (coinEl) coinEl.textContent = aiCoins;
playBoing();
if (aiCoins >= 5) {
clearInterval(staticBalanceInterval);
triggerStaticVictory(8);
}
}, 650);
}
// 09 ์ธํ๋ฝ๊ธฐ 3๋จ๊ณ IK ์์ ํฌ๋ ์ธ ๊ตฌ์ถ
else if (exampleId === 9) {
const clawEl = document.getElementById("hudClawHeight");
if (clawEl) clawEl.textContent = "0.25m (Targeting ๐ฏ)";
staticLifecycleTimer = setTimeout(() => {
if (currentGameState !== "playing" || currentExampleId !== 9) return;
if (clawEl) clawEl.textContent = "0.45m (Grip ON ๐งฒ)";
playBoing();
staticLifecycleTimer = setTimeout(() => {
if (currentGameState !== "playing" || currentExampleId !== 9) return;
if (clawEl) clawEl.textContent = "Rescued! ๐งธ";
triggerStaticVictory(9);
}, 1200);
}, 1000);
}
// 10 ๋ง์นด๋กฑ ๋ฉ๊ฐํ์ ํ๋ํ CoM ์ ๊ฒฉ ์ํ
else if (exampleId === 10) {
staticLifecycleTimer = setTimeout(() => {
if (currentGameState !== "playing" || currentExampleId !== 10) return;
if (screenImg && typeof EMBEDDED_CLEARED !== "undefined" && EMBEDDED_CLEARED[10]) {
screenImg.src = EMBEDDED_CLEARED[10];
}
const demoEl = document.getElementById("hudDemo");
if (demoEl) demoEl.textContent = "100.0";
triggerStaticVictory(10);
}, 2300);
}
}
// ============================================================================
// ๐ก ์๋ฒ ์ก์
์ ์ก & ์คํ์ด์ค ์ธํฐ๋ํฐ๋ธ ์ํ ๋จธ์
// ============================================================================
async function sendAction(actionType, value = 0.0) {
const isStatic = (typeof IS_STATIC_SPACE !== "undefined" && IS_STATIC_SPACE) || (typeof EMBEDDED_ANIMATIONS !== "undefined");
const screenImg = document.getElementById("mjpegStream");
// ๐ค ์ ์ ์ธํฐ๋ํฐ๋ธ ์กฐ์ ์ ์ค๋งํธ AI ๋ชจ๋ โ ์ธ๊ฐ ์๋ ๋ชจ๋๋ก ์๋ ์ ํ (Human Takeover)
if (currentControlMode === "ai" && actionType !== "start" && actionType !== "reset") {
setControlMode("manual");
}
// ๐ Client-Side MuJoCo WebAssembly Engine Handler (Instant Response)
if (useWasm) {
if (!wasmPlayer || !wasmPlayer.isReady) {
await initWasmEngine();
}
if (wasmPlayer) {
if (actionType === "start") {
playStart();
} else if (actionType === "reset") {
playPop();
} else {
playBoing();
}
try {
wasmPlayer.applyAction(actionType, value);
} catch (err) {
console.warn("wasmPlayer.applyAction suppressed error:", err);
}
currentGameState = wasmPlayer.gameState;
updateGameStateUI();
return;
}
}
if (actionType === "start" || actionType === "fire_cannon" || actionType === "push_domino" || actionType === "start_race") {
playStart();
currentGameState = "playing";
updateGameStateUI();
if (isStatic && screenImg) {
if (staticLifecycleTimer) clearTimeout(staticLifecycleTimer);
if (staticBalanceInterval) clearInterval(staticBalanceInterval);
// ๋ชจ๋์ ๋ฐ๋ผ ์์ ํ ๋ถ๋ฆฌ๋ ๊ฒ์ ๋ฃจํ ์คํ!
if (currentControlMode === "ai") {
// [๐ค ์ค๋งํธ AI ๋ชจ๋]: ์์จ ์ฃผํ ๋ฌผ๋ฆฌ ์ ๋๋ฉ์ด์
๊ฐ๋ ๋ฐ ์ 10๋ ๋ฏธ๋๊ฒ์ 100% ํด๋ฆฌ์ด ์์ฐ!
if (typeof EMBEDDED_ANIMATIONS !== "undefined" && EMBEDDED_ANIMATIONS[currentExampleId]) {
screenImg.src = EMBEDDED_ANIMATIONS[currentExampleId] + "?t=" + Date.now();
}
startStaticAISimulation(currentExampleId);
} else {
// [๐ฎ ์ธ๊ฐ ์๋ ์กฐ์ ๋ชจ๋]:
// ์ ์ ๊ฐ ํค๋ฅผ ์ง์ ๋๋ฅด๊ธฐ ์ ๊น์ง๋ ์ ์ง ์คํธ์ปท(Still)์ ์ ์งํ์ฌ ํผ์ ์คํ๋๋ ํ์ ์์ฒ ์ฐจ๋จ!
if (actionType === "fire_cannon" || (currentExampleId === 10 && actionType === "start" && value === 1.0)) {
// 10๋ฒ ๋ํฌ: ์ ์ ๊ฐ ์คํ์ด์ค๋ฐ๋ ๋ฐ์ฌ ๋ฒํผ์ ๋๋ ์ ๋๋ง ๊ฒฉ๋ฐ ์ ๋๋ฉ์ด์
์ฌ์ ๋ฐ ํด๋ฆฌ์ด!
if (typeof EMBEDDED_ANIMATIONS !== "undefined" && EMBEDDED_ANIMATIONS[10]) {
screenImg.src = EMBEDDED_ANIMATIONS[10] + "?t=" + Date.now();
}
staticLifecycleTimer = setTimeout(() => {
if (screenImg && typeof EMBEDDED_CLEARED !== "undefined" && EMBEDDED_CLEARED[10]) {
screenImg.src = EMBEDDED_CLEARED[10];
}
const demoEl = document.getElementById("hudDemo");
if (demoEl) demoEl.textContent = "100.0";
triggerStaticVictory(10);
}, 2300);
} else if (actionType === "push_domino" || (currentExampleId === 3 && actionType === "start" && value === 1.0)) {
// 03๋ฒ ๋๋ฏธ๋
ธ: ์ ์ ๊ฐ ์คํ์ด์ค๋ฐ๋ ๋๋ฏธ๋
ธ ๋ฐ๊ธฐ ๋ฒํผ์ ๋๋ ์ ๋๋ง ์ฐ์ ์ ๋ ์ ๋๋ฉ์ด์
์ฌ์ ๋ฐ ํด๋ฆฌ์ด!
if (typeof EMBEDDED_ANIMATIONS !== "undefined" && EMBEDDED_ANIMATIONS[3]) {
screenImg.src = EMBEDDED_ANIMATIONS[3] + "?t=" + Date.now();
}
staticLifecycleTimer = setTimeout(() => {
if (screenImg && typeof EMBEDDED_CLEARED !== "undefined" && EMBEDDED_CLEARED[3]) {
screenImg.src = EMBEDDED_CLEARED[3];
}
const domEl = document.getElementById("hudDominoStatus");
if (domEl) domEl.textContent = "Cleared! (0.83s) ๐";
triggerStaticVictory(3);
}, 2400);
} else if (actionType === "start_race" || (currentExampleId === 6 && actionType === "start" && value === 1.0)) {
// 06๋ฒ ์ฌ๋ผ์ด๋: ๋ ์ด์ค ์ถ๋ฐ ์ ํธ ์ ์ฌ๋ผ์ด๋ ๋ค์ด ์ ๋๋ฉ์ด์
์ฌ์ ๋ฐ ํด๋ฆฌ์ด!
if (typeof EMBEDDED_ANIMATIONS !== "undefined" && EMBEDDED_ANIMATIONS[6]) {
screenImg.src = EMBEDDED_ANIMATIONS[6] + "?t=" + Date.now();
}
staticLifecycleTimer = setTimeout(() => {
if (screenImg && typeof EMBEDDED_CLEARED !== "undefined" && EMBEDDED_CLEARED[6]) {
screenImg.src = EMBEDDED_CLEARED[6];
}
const leaderEl = document.getElementById("hudRaceLeader");
if (leaderEl) leaderEl.textContent = "Pink Bean Won! ๐";
triggerStaticVictory(6);
}, 2400);
} else if (currentExampleId === 7) {
// 07๋ฒ ์นดํธํด: 15์ด ์์กด ๋์ ์นด์ดํธ๋ค์ด
staticSurvivalTime = 0.0;
if (typeof EMBEDDED_ANIMATIONS !== "undefined" && EMBEDDED_ANIMATIONS[7]) {
screenImg.src = EMBEDDED_ANIMATIONS[7] + "?t=" + Date.now();
}
staticBalanceInterval = setInterval(() => {
if (currentGameState !== "playing" || currentExampleId !== 7) {
clearInterval(staticBalanceInterval);
return;
}
staticSurvivalTime += 0.1;
const scoreEl = document.getElementById("hudScore");
const angleEl = document.getElementById("hudAngle");
if (scoreEl) scoreEl.textContent = `${staticSurvivalTime.toFixed(2)}s`;
if (angleEl) {
const sway = (Math.sin(staticSurvivalTime * 3.5) * 1.2).toFixed(1);
angleEl.textContent = `${sway > 0 ? "+" : ""}${sway}ยฐ`;
}
if (staticSurvivalTime >= 15.0) {
clearInterval(staticBalanceInterval);
triggerStaticVictory(7);
}
}, 100);
} else {
// 01, 02, 04, 05, 08, 09๋ฒ: ๊ฒ์ ์์ ์ ์ ์ง ์คํธ์ปท(Still)์ ์ ์งํ์ฌ ํผ์ ์คํ๋๋ ํ์ ์ฐจ๋จ!
if (typeof EMBEDDED_STILLS !== "undefined" && EMBEDDED_STILLS[currentExampleId]) {
screenImg.src = EMBEDDED_STILLS[currentExampleId];
}
}
}
}
} else if (actionType === "reset") {
playPop();
currentGameState = "ready";
if (staticLifecycleTimer) {
clearTimeout(staticLifecycleTimer);
staticLifecycleTimer = null;
}
if (staticBalanceInterval) {
clearInterval(staticBalanceInterval);
staticBalanceInterval = null;
}
staticBeanCounter = 0;
staticPinballScore = 0;
staticSwingLoops = 0;
staticAcroCombo = 0;
staticCoinCounter = 0;
staticClawMagnet = false;
staticSurvivalTime = 0.0;
// ๋๊ธฐ ์ํ์ ๊นจ๋ํ ์ ์ง ์คํธ์ปท์ผ๋ก ๋ณต๊ท
if (isStatic && screenImg && typeof EMBEDDED_STILLS !== "undefined" && EMBEDDED_STILLS[currentExampleId]) {
screenImg.src = EMBEDDED_STILLS[currentExampleId];
}
updateGameStateUI();
// 10๋ ๋ฏธ๋๊ฒ์ ์ ์ฒด HUD ์์น ๋ฆฌ์
const scoreEl = document.getElementById("hudScore");
if (scoreEl) scoreEl.textContent = "0.00s";
const angleEl = document.getElementById("hudAngle");
if (angleEl) angleEl.textContent = "0.0ยฐ";
const coinEl = document.getElementById("hudCoins");
if (coinEl) coinEl.textContent = "0";
const demoEl = document.getElementById("hudDemo");
if (demoEl) demoEl.textContent = "0.0";
const beanEl = document.getElementById("hudBeansLanded");
if (beanEl) beanEl.textContent = "0 / 4 ๐";
const pinEl = document.getElementById("hudPinballScore");
if (pinEl) pinEl.textContent = "0";
const domEl = document.getElementById("hudDominoStatus");
if (domEl) domEl.textContent = "Ready ๐";
const acroEl = document.getElementById("hudAcroCombo");
if (acroEl) acroEl.textContent = "0 / 3 ๐คธ";
const clawEl = document.getElementById("hudClawHeight");
if (clawEl) clawEl.textContent = "0.12m ๐งธ";
const leaderEl = document.getElementById("hudRaceLeader");
if (leaderEl) leaderEl.textContent = "Ready to Race ๐";
const swingEl = document.getElementById("hudSwingAngle");
if (swingEl) swingEl.textContent = "0.0ยฐ";
} else {
playBoing();
}
if (useWasm && wasmPlayer) {
wasmPlayer.applyAction(actionType, value);
currentGameState = wasmPlayer.gameState;
updateGameStateUI();
return;
}
try {
const res = await fetch("/api/action", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action_type: actionType, value: value })
});
if (res.ok) {
const data = await res.json();
if (data.game_state) {
currentGameState = data.game_state;
updateGameStateUI(data);
}
}
} catch (err) {
if (!useWasm) {
useWasm = true;
await initWasmEngine();
if (wasmPlayer) {
wasmPlayer.loadGame(currentExampleId);
wasmPlayer.applyAction(actionType, value);
}
}
}
}
function handleMainStartClick() {
if (currentGameState === "playing") {
sendAction("reset");
} else {
sendAction("start");
}
}
function updateGameStateUI(telemetry = null) {
const readyOverlay = document.getElementById("readyOverlay");
const gameoverOverlay = document.getElementById("gameoverOverlay");
const victoryOverlay = document.getElementById("victoryOverlay");
const mainStartBtn = document.getElementById("mainStartBtn");
const dict = I18N[currentLang] || I18N.en;
if (currentGameState === "ready") {
if (readyOverlay) readyOverlay.style.display = "flex";
if (gameoverOverlay) gameoverOverlay.style.display = "none";
if (victoryOverlay) victoryOverlay.style.display = "none";
if (mainStartBtn) mainStartBtn.textContent = dict.btn_start_game;
} else if (currentGameState === "playing") {
if (readyOverlay) readyOverlay.style.display = "none";
if (gameoverOverlay) gameoverOverlay.style.display = "none";
if (victoryOverlay) victoryOverlay.style.display = "none";
if (mainStartBtn) mainStartBtn.textContent = dict.btn_playing;
} else if (currentGameState === "gameover") {
if (readyOverlay) readyOverlay.style.display = "none";
if (gameoverOverlay) gameoverOverlay.style.display = "flex";
if (victoryOverlay) victoryOverlay.style.display = "none";
if (mainStartBtn) mainStartBtn.textContent = dict.btn_retry;
if (telemetry) {
const resSurv = document.getElementById("resSurvival");
if (resSurv) resSurv.textContent = `${(telemetry.survival_time || 0).toFixed(2)}s`;
const resRnk = document.getElementById("resRank");
if (resRnk) resRnk.textContent = telemetry.rank || "B";
}
} else if (currentGameState === "victory") {
if (readyOverlay) readyOverlay.style.display = "none";
if (gameoverOverlay) gameoverOverlay.style.display = "none";
if (victoryOverlay) victoryOverlay.style.display = "flex";
if (mainStartBtn) mainStartBtn.textContent = dict.btn_play_again;
if (telemetry && telemetry.victory_banner) {
const iconEl = document.getElementById("vicIcon");
const titleEl = document.getElementById("vicTitle");
const subEl = document.getElementById("vicSub");
if (iconEl) iconEl.textContent = telemetry.victory_banner.icon || "๐";
if (titleEl) titleEl.textContent = telemetry.victory_banner.title || "VICTORY!";
if (subEl) subEl.textContent = telemetry.victory_banner.sub || "Great job!";
} else {
const banner = (currentLang === "ko" ? VICTORY_BANNERS_KR[currentExampleId] : VICTORY_BANNERS[currentExampleId]);
if (banner) {
const iconEl = document.getElementById("vicIcon");
const titleEl = document.getElementById("vicTitle");
const subEl = document.getElementById("vicSub");
if (iconEl) iconEl.textContent = banner.icon;
if (titleEl) titleEl.textContent = banner.title;
if (subEl) subEl.textContent = banner.sub;
}
}
}
}
// ============================================================================
// ๐ค ์กฐ์ ๋ชจ๋ ๋ฐ ํ๋ผ๋ฏธํฐ ์กฐ์
// ============================================================================
async function setControlMode(mode) {
playPop();
currentControlMode = mode;
document.getElementById("btnModeManual").classList.toggle("active", mode === "manual");
document.getElementById("btnModeAI").classList.toggle("active", mode === "ai");
const indicatorIcon = document.getElementById("indicatorIcon");
const indicatorText = document.getElementById("indicatorText");
if (indicatorIcon) {
indicatorIcon.textContent = mode === "ai" ? "๐ค" : "๐ฎ";
}
if (indicatorText) {
indicatorText.textContent = mode === "ai"
? (currentLang === "ko" ? "AI ์์จ ์ ์ด ๋ชจ๋" : "Autonomous AI Mode")
: (currentLang === "ko" ? "์ธ๊ฐ ์๋ ์กฐ์ ๋ชจ๋" : "Human Manual Mode");
}
updateModeHelpText();
if (useWasm && wasmPlayer) {
wasmPlayer.setMode(mode);
return;
}
if (mode === "ai" && currentGameState === "ready") {
sendAction("start");
}
try {
await fetch("/api/set_mode", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ mode: mode })
});
} catch (err) {
// offline
}
}
async function updateGravity(val) {
const g = parseFloat(val);
document.getElementById("gravityVal").textContent = `${g.toFixed(2)} m/sยฒ`;
if (useWasm && wasmPlayer && wasmPlayer.model) {
wasmPlayer.model.opt.gravity[2] = g;
return;
}
try {
await fetch("/api/set_gravity", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ gravity: g })
});
} catch (err) {}
}
function setGravityPreset(g) {
playPop();
document.getElementById("gravitySlider").value = g;
updateGravity(g);
document.querySelectorAll(".preset-pill").forEach(btn => {
btn.classList.toggle("active", parseFloat(btn.textContent.match(/-?\d+\.?\d*/)?.[0] || 0) === g);
});
}
async function updateCannonPower(val) {
const p = parseFloat(val);
document.getElementById("cannonPowerVal").textContent = `${p.toFixed(1)}x`;
if (useWasm && wasmPlayer) {
wasmPlayer.cannonPower = p;
return;
}
try {
await fetch("/api/cannon_power", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ power: p })
});
} catch (err) {}
}
function setCannonPowerPreset(p) {
playPop();
document.getElementById("cannonSlider").value = p;
updateCannonPower(p);
}
// ============================================================================
// โจ๏ธ ํค๋ณด๋ ์
๋ ฅ ๋ฐ ์๊ฐํ
// ============================================================================
function setupKeyboardListeners() {
window.addEventListener("keydown", (e) => {
if (e.repeat) return;
const code = e.code;
activeKeySet.add(code);
highlightKeyBox(code, true);
// ๊ณตํต ๋ฆฌ์
if (code === "KeyR") {
sendAction("reset");
return;
}
// ์นด๋ฉ๋ผ ์ ํ ๋จ์ถํค [C]
if (code === "KeyC") {
cycleCamera();
return;
}
// ์์ด๋ ์ ์ฒดํ๋ฉด ์ ํ ๋จ์ถํค [F]
if (code === "KeyF") {
const fsBtn = document.getElementById("fullscreenBtn");
if (fsBtn) fsBtn.click();
return;
}
// ๋ชจ๋ ํ ๊ธ [M]
if (code === "KeyM") {
setControlMode(currentControlMode === "manual" ? "ai" : "manual");
return;
}
// ์คํ์ด์ค ํค
if (code === "Space") {
e.preventDefault();
if (currentGameState === "ready" || currentGameState === "gameover") {
if (currentExampleId === 3) {
sendAction("push_domino");
} else if (currentExampleId === 6) {
sendAction("start_race");
} else if (currentExampleId === 10) {
sendAction("fire_cannon");
} else {
sendAction("start");
}
} else if (currentExampleId === 1) {
sendAction("drop_bean");
} else if (currentExampleId === 2) {
sendAction("ball_rain");
} else if (currentExampleId === 3) {
sendAction("push_domino");
} else if (currentExampleId === 4) {
sendAction("swing_pump");
} else if (currentExampleId === 5) {
sendAction("acrobatic_flip");
} else if (currentExampleId === 6) {
sendAction("start_race");
} else if (currentExampleId === 9) {
sendAction("claw_magnet_toggle");
} else if (currentExampleId === 10) {
sendAction("fire_cannon");
}
return;
}
// ๊ฒ์ 01 ์ค์นด์ด๋ค์ด๋น (A/D ๋ฐ ์ข์ฐ ๋ฐฉํฅํค๋ก ์ฟ ์
ํ๊ธฐ๊ธฐ)
if (currentExampleId === 1) {
if (code === "KeyA" || code === "ArrowLeft") sendAction("bounce_cushion", -1);
if (code === "KeyD" || code === "ArrowRight") sendAction("bounce_cushion", 1);
}
// ๊ฒ์ 02 ํ๋ณผ (A/D ๋ฐ ์ข์ฐ ๋ฐฉํฅํค ๋์ ์ง์)
else if (currentExampleId === 2) {
if (code === "KeyA" || code === "ArrowLeft") sendAction("flip_left");
if (code === "KeyD" || code === "ArrowRight") sendAction("flip_right");
}
// ๊ฒ์ 04 ๊ทธ๋ค ํํ (W, Up, Space)
else if (currentExampleId === 4) {
if (code === "KeyW" || code === "ArrowUp") sendAction("swing_pump");
}
// ๊ฒ์ 05 ์ํฌ๋ก๋ฐํฑ ๊ด์ ์ ์ด (W/S: ๊ด์ 1, A/D: ๊ด์ 2)
else if (currentExampleId === 5) {
if (code === "KeyW" || code === "ArrowUp") sendAction("acrobatic_j1_up");
if (code === "KeyS" || code === "ArrowDown") sendAction("acrobatic_j1_down");
if (code === "KeyA" || code === "ArrowLeft") sendAction("acrobatic_j2_up");
if (code === "KeyD" || code === "ArrowRight") sendAction("acrobatic_j2_down");
}
// ๊ฒ์ 06 ์ฌ๋ผ์ด๋ ๋ถ์คํฐ (A/Left: ํํฌ๋น, D/Right: ๋ฏผํธ๋น)
else if (currentExampleId === 6) {
if (code === "KeyA" || code === "ArrowLeft") sendAction("slide_boost_pink");
if (code === "KeyD" || code === "ArrowRight") sendAction("slide_boost_mint");
}
// ๊ฒ์ 07 ์นดํธํด ๋ฐธ๋ฐ์ (A/D ๋ฐ ๋ฐฉํฅํค ์ข์ฐ ๋์ ์ง์)
else if (currentExampleId === 7) {
if (code === "KeyA" || code === "ArrowLeft") sendAction("cart_left");
if (code === "KeyD" || code === "ArrowRight") sendAction("cart_right");
}
// ๊ฒ์ 08 ๋ฒํผ์นด ๋๋ผ์ด๋ธ (WASD ๋ฐ ๋ฐฉํฅํค ์ํ์ข์ฐ ๋์ ์ง์)
else if (currentExampleId === 8) {
if (code === "KeyW" || code === "ArrowUp") sendAction("car_forward");
if (code === "KeyS" || code === "ArrowDown") sendAction("car_backward");
if (code === "KeyA" || code === "ArrowLeft") sendAction("car_left");
if (code === "KeyD" || code === "ArrowRight") sendAction("car_right");
}
// ๊ฒ์ 09 ๋ก๋ดํ ํฌ๋ ์ธ (WASD ๋ฐ ๋ฐฉํฅํค ๋์ ์ง์)
else if (currentExampleId === 9) {
if (code === "ArrowUp" || code === "KeyW") sendAction("arm_shoulder_up");
if (code === "ArrowDown" || code === "KeyS") sendAction("arm_shoulder_down");
if (code === "ArrowRight" || code === "KeyD") sendAction("arm_elbow_up");
if (code === "ArrowLeft" || code === "KeyA") sendAction("arm_elbow_down");
}
// ๊ฒ์ 10 ๋ง์นด๋กฑ ๋ํฌ ํ์ ์กฐ์ (W/โ: ํ์ ์ฆํญ, S/โ: ํ์ ๊ฐ์ )
else if (currentExampleId === 10) {
const slider = document.getElementById("cannonSlider");
if (slider) {
if (code === "ArrowUp" || code === "KeyW") {
const newVal = Math.min(2.5, +(parseFloat(slider.value) + 0.1).toFixed(1));
slider.value = newVal;
updateCannonPower(newVal);
} else if (code === "ArrowDown" || code === "KeyS") {
const newVal = Math.max(0.4, +(parseFloat(slider.value) - 0.1).toFixed(1));
slider.value = newVal;
updateCannonPower(newVal);
}
}
}
});
window.addEventListener("keyup", (e) => {
const code = e.code;
activeKeySet.delete(code);
highlightKeyBox(code, false);
// 02 ํ๋ณผ
if (currentExampleId === 2) {
const leftHeld = activeKeySet.has("KeyA") || activeKeySet.has("ArrowLeft");
const rightHeld = activeKeySet.has("KeyD") || activeKeySet.has("ArrowRight");
if (!leftHeld && !rightHeld) sendAction("flip_stop");
else if (leftHeld) sendAction("flip_left");
else if (rightHeld) sendAction("flip_right");
}
// 05 ์ํฌ๋ก๋ฐํฑ
else if (currentExampleId === 5) {
sendAction("acrobatic_stop");
}
// 07 ์นดํธํด (A/D ๋ฐ ์ข์ฐ ๋ฐฉํฅํค ๋์ ์ง์)
else if (currentExampleId === 7) {
const leftHeld = activeKeySet.has("KeyA") || activeKeySet.has("ArrowLeft");
const rightHeld = activeKeySet.has("KeyD") || activeKeySet.has("ArrowRight");
if (!leftHeld && !rightHeld) sendAction("cart_stop");
else if (leftHeld) sendAction("cart_left");
else if (rightHeld) sendAction("cart_right");
}
// 08 ๋ฒํผ์นด (๋ณตํฉ ์
๋ ฅ ํ๋ ๋ณด์กด)
else if (currentExampleId === 8) {
const upHeld = activeKeySet.has("KeyW") || activeKeySet.has("ArrowUp");
const downHeld = activeKeySet.has("KeyS") || activeKeySet.has("ArrowDown");
const leftHeld = activeKeySet.has("KeyA") || activeKeySet.has("ArrowLeft");
const rightHeld = activeKeySet.has("KeyD") || activeKeySet.has("ArrowRight");
if (upHeld) sendAction("car_forward");
else if (downHeld) sendAction("car_backward");
else if (leftHeld) sendAction("car_left");
else if (rightHeld) sendAction("car_right");
else sendAction("car_stop");
}
});
}
function highlightKeyBox(code, isActive) {
const keyMap = {
KeyW: "keyW", ArrowUp: "keyW",
KeyA: "keyA", ArrowLeft: "keyLeft",
KeyS: "keyS", ArrowDown: "keyS",
KeyD: "keyD", ArrowRight: "keyRight",
Space: "keySpace", KeyR: "keyR", KeyC: "keyC"
};
const elemId = keyMap[code];
if (elemId) {
const el = document.getElementById(elemId);
if (el) el.classList.toggle("active", isActive);
}
}
// ============================================================================
// ๐ ์ค์๊ฐ ํ
๋ ๋ฉํธ๋ฆฌ ํด๋ง ๋ฃจํ
// ============================================================================
function startTelemetryLoop() {
setInterval(async () => {
if (useWasm) return;
if ((typeof IS_STATIC_SPACE !== "undefined" && IS_STATIC_SPACE) || (typeof EMBEDDED_ANIMATIONS !== "undefined")) {
return;
}
try {
const res = await fetch("/api/telemetry");
if (!res.ok) return;
const data = await res.json();
// ์ํ ๋ณํ ๊ฐ์ง
if (data.game_state !== currentGameState) {
const prevState = currentGameState;
currentGameState = data.game_state;
if (currentGameState === "gameover" && prevState !== "gameover") {
playGameOver();
} else if (currentGameState === "victory" && prevState !== "victory") {
playCheer();
triggerConfetti();
} else if (currentGameState === "playing" && prevState === "ready") {
playStart();
triggerConfetti();
}
updateGameStateUI(data);
}
// ์ฌ์ด๋ FX ์๋ฆผ (์ฝ์ธ ํ๋ ๋ฑ)
if (data.new_coin_sound) {
playCoinSound();
triggerConfetti();
}
// 1. ์ค์นด์ด๋ค์ด๋น
if (data.example_id === 1) {
const beanEl = document.getElementById("hudBeansLanded");
if (beanEl) beanEl.textContent = `${data.beans_landed} (${data.beans_dropped} drops)`;
}
// 2. ์บ๋ ํ๋ณผ
else if (data.example_id === 2) {
const pinEl = document.getElementById("hudPinballScore");
if (pinEl) pinEl.textContent = data.pinball_score || 0;
}
// 3. ๋๋ฏธ๋
ธ ์คํธ๋ผ์ดํฌ
else if (data.example_id === 3) {
const domEl = document.getElementById("hudDominoStatus");
if (domEl) {
domEl.textContent = data.domino_cleared
? "Cleared! (0.83s) ๐"
: (data.survival_time > 0 ? `${data.survival_time.toFixed(2)}s ๐` : "Ready ๐");
}
}
// 4. ์์ด์ธํธ ๊ทธ๋ค
else if (data.example_id === 4) {
const swingEl = document.getElementById("hudSwingAngle");
if (swingEl) swingEl.textContent = `${data.swing_angle_deg}ยฐ (Loops: ${data.swing_loops})`;
}
// 5. ์ํฌ๋ก๋ฐํฑ ํธ์
else if (data.example_id === 5) {
const acroEl = document.getElementById("hudAcroCombo");
if (acroEl) acroEl.textContent = `${data.somersault_count} / 3 ๐คธ`;
}
// 6. ์ฌ๋ผ์ด๋ ๋ ์ด์ค
else if (data.example_id === 6) {
const leaderEl = document.getElementById("hudRaceLeader");
if (leaderEl) {
leaderEl.textContent = data.race_winner ? `${data.race_winner} Won! ๐` : (data.race_leader || "Racing downhill...");
}
}
// 7. ์นดํธํด ๋ฐธ๋ฐ์
else if (data.example_id === 7) {
const scoreEl = document.getElementById("hudScore");
if (scoreEl) scoreEl.textContent = `${data.survival_time.toFixed(2)}s`;
const bestEl = document.getElementById("hudBest");
if (bestEl) bestEl.textContent = `${data.best_score.toFixed(2)}s`;
const angleEl = document.getElementById("hudAngle");
if (angleEl) angleEl.textContent = `${data.pole_angle_deg}ยฐ`;
}
// 8. ๋ฒํผ์นด ์ฝ์ธ ๋์
else if (data.example_id === 8) {
const coinsEl = document.getElementById("hudCoins");
if (coinsEl) coinsEl.textContent = data.coins_collected;
}
// 9. ์ธํ๋ฝ๊ธฐ ํฌ๋ ์ธ
else if (data.example_id === 9) {
const clawEl = document.getElementById("hudClawHeight");
if (clawEl) {
clawEl.textContent = data.plushie_grabbed
? "Rescued! ๐งธ"
: (data.claw_magnet_on ? `${(data.plushie_z || 0.12).toFixed(2)}m (Grip ON ๐งฒ)` : `${(data.plushie_z || 0.12).toFixed(2)}m ๐ฏ`);
}
}
// 10. ๋ง์นด๋กฑ ํ์ ๋ํฌ
else if (data.example_id === 10) {
const demoEl = document.getElementById("hudDemo");
if (demoEl) demoEl.textContent = data.demolition_rate.toFixed(1);
}
} catch (e) {
// ignore
}
}, 80);
}
// ============================================================================
// ๐ ์ฝ๋ ๋ด๋ณด๋ด๊ธฐ ๋ชจ๋ฌ
// ============================================================================
async function openCodeModal() {
playPop();
const modal = document.getElementById("codeModal");
modal.style.display = "flex";
document.getElementById("modalBrickTitle").textContent = `Brick #${currentExampleId.toString().padStart(2, "0")} Code Export`;
if (typeof EMBEDDED_CODES !== "undefined" && EMBEDDED_CODES[String(currentExampleId)]) {
currentCodeData = EMBEDDED_CODES[String(currentExampleId)];
renderModalCode();
return;
}
if (typeof window !== "undefined" && window.PREMIUM_GAME_XMLS && window.PREMIUM_GAME_XMLS[String(currentExampleId)]) {
const rawXml = window.PREMIUM_GAME_XMLS[String(currentExampleId)];
currentCodeData = {
xml: rawXml,
python: `# MuJoCo Standalone Executable Brick #${currentExampleId}\nimport mujoco\nimport mujoco.viewer\n\nxml = """${rawXml}"""\n\nmodel = mujoco.MjModel.from_xml_string(xml)\ndata = mujoco.MjData(model)\nmujoco.viewer.launch(model, data)\n`
};
renderModalCode();
return;
}
}
function closeCodeModal() {
playPop();
document.getElementById("codeModal").style.display = "none";
}
function switchCodeTab(tab) {
playPop();
currentCodeTab = tab;
document.getElementById("tabPy").classList.toggle("active", tab === "py");
document.getElementById("tabXml").classList.toggle("active", tab === "xml");
renderModalCode();
}
function renderModalCode() {
if (!currentCodeData) return;
const viewer = document.getElementById("codeViewer");
viewer.textContent = currentCodeTab === "py" ? currentCodeData.python : currentCodeData.xml;
}
function copyCurrentCode() {
playCheer();
triggerConfetti();
const text = document.getElementById("codeViewer").textContent;
navigator.clipboard.writeText(text).then(() => {
alert(currentLang === "ko" ? "๐ ์ฝ๋๊ฐ ํด๋ฆฝ๋ณด๋์ ๋ณต์ฌ๋์์ต๋๋ค!" : "๐ Code copied to clipboard! Paste it into Antigravity.");
});
}
// Expose all interactive functions to window for HTML onclick / onchange handlers
if (typeof window !== "undefined") {
window.setCamera = setCamera;
window.selectExample = selectExample;
window.nextExample = nextExample;
window.sendAction = sendAction;
window.setControlMode = setControlMode;
window.setGravityPreset = setGravityPreset;
window.updateGravity = updateGravity;
window.setCannonPowerPreset = setCannonPowerPreset;
window.updateCannonPower = updateCannonPower;
window.handleMainStartClick = handleMainStartClick;
window.openCodeModal = openCodeModal;
window.closeCodeModal = closeCodeModal;
window.switchCodeTab = switchCodeTab;
window.copyCurrentCode = copyCurrentCode;
window.toggleBgm = toggleBgm;
}
/**
* MuJoCo PlayEngine: Interactive Cockpit & Game Loop Controller
* Style: Fall Guys & Party Animals Jelly Bean Pop Edition
* Features:
* - Real-time DeepMind MuJoCo v3.3.0 WebAssembly Physics (60 FPS WebGL)
* - 3-Way Camera Perspective Switcher ('cam_front', 'cam_quarter', 'cam_topdown') + [C] shortcut
* - Kawaii 8-Bit Chiptune Procedural BGM (0 Bytes asset, pure Web Audio API)
* - Victory & Goal Clear Banners across all 10 Mini-Games
* - Coin Collection Sound FX & Star Coin Tracker (5/5)
* - Full 10 Games Contextual Action Buttons & Keypad Visualizer
* - 100% English Default with Korean Toggle
*/
// โ
ROOT-CAUSE FIX (HF Private Space): NO static import here.
// A static import chain (app.js โ mujoco_wasm_player.js โ mujoco.js) means that if ANY
// sub-module fails to load (e.g. private-Space auth token `__sign` not forwarded to
// sub-resource requests), the browser aborts app.js entirely โ empty game list & dead
// START button. The physics engine is now lazily imported inside initWasmEngine().
let MujocoWasmPlayer = null;
// Forward HF private-Space auth query (`__sign`) to every sub-resource URL.
function withSign(url) {
try {
const sign = new URLSearchParams(window.location.search).get("__sign");
if (!sign) return url;
return url + (url.includes("?") ? "&" : "?") + "__sign=" + encodeURIComponent(sign);
} catch (e) {
return url;
}
}
window.__withSign = withSign;
const I18N = {
en: {
brand_subtitle: "๐ฌ Physical AI Sandbox & Arcade | HWIHWA LAB",
menu_title: "10 Jelly Bricks",
menu_desc: "Select a jelly brick to play in the sweet bouncy arena!",
hud_score: "Survival Time",
hud_best: "Best Record",
hud_angle: "Pole Angle",
hud_coins: "Star Coins",
hud_demo: "Demolition Rate",
hud_race: "Race Leader",
hud_swing: "Swing Angle",
hud_beans: "Beans Landed",
hud_pinball: "Pinball Score",
hud_domino: "Target Status",
hud_acro: "Backflip Combo",
hud_claw: "Rescue Height",
keypad_title: "๐ฎ Real-time Keyboard Visualizer",
cam_label: "๐ฅ View:",
cam_front: "๐ฅ Front",
cam_quarter: "๐ 45ยฐ Quarter",
cam_topdown: "๐ Top-Down",
cam_tip: "Press <strong>[C]</strong> to switch view",
control_title: "Control Deck",
control_mode_label: "Controller Mode",
mode_manual: "๐ฎ Human Play",
mode_ai: "๐ค Smart AI",
mode_help_manual: "Use โ and โ arrow keys to balance the lollipop! (Survive 15s to Win ๐)",
mode_help_ai: "AI PD Controller automatically maintains balance.",
action_btn_label: "Quick Actions",
cannon_power_label: "๐ฃ Cannon Power",
cannon_preset_soft: "Soft (0.6x)",
cannon_preset_normal: "Normal (1.0x)",
cannon_preset_heavy: "Heavy (1.6x)",
cannon_preset_mega: "MEGA (2.0x)",
gravity_label: "Bouncy Gravity",
gravity_zero: "Floating (0G)",
gravity_moon: "Moon (-1.6)",
gravity_earth: "Earth (-9.8)",
gravity_heavy: "Heavy (-24.8)",
btn_start_game: "โถ START GAME (SPACE)",
btn_playing: "โธ PLAYING (R to Reset)",
btn_retry: "๐ RETRY (R)",
btn_play_again: "๐ PLAY AGAIN (R)",
btn_reset_toy: "๐ RESET TOY (R)",
btn_export_code: "๐ COPY PYTHON / XML CODE",
ready_title: "READY TO PLAY!",
ready_sub: "Press [SPACE] or Click [START] to Play!",
overlay_btn_start: "โถ START GAME",
gameover_title: "OOPS! TOPPLED!",
gameover_sub: "Oops! Toppled! Press [R] key to Retry",
label_survived: "SURVIVED:",
label_grade: "GRADE:",
overlay_btn_retry: "๐ RETRY (R)",
overlay_btn_watch_ai: "๐ค WATCH SMART AI",
overlay_btn_play_again: "๐ PLAY AGAIN (R)",
overlay_btn_next: "โฉ NEXT GAME",
mentor_quote: "๐ข ENGINE LIVE ยท MuJoCo v3.3.0 (500Hz) ยท 30 FPS Stream ยท Zero Assets (100% Procedural) ยท Built with โค๏ธ by HWIHWA LAB",
banner_badge: "ENGINE LIVE",
modal_desc: "This code is a 100% standalone executable MuJoCo brick. Copy and paste it into Antigravity or Python to build games and AI agents!",
modal_tab_py: "Python Script",
modal_tab_xml: "MuJoCo XML (Blueprint)",
modal_btn_copy: "๐ Copy to Clipboard",
modal_btn_close: "Close",
engine_loading_msg: "๐ฌ Loading 3D Physics Engine... Please wait!"
},
ko: {
brand_subtitle: "๐ฌ Physical AI Sandbox & Arcade | HWIHWA LAB",