🇬🇧 English
🕉️ Moksha
“The only path to liberation is letting go (Tyaag).”
मोक्ष प्राप्ति का एकमात्र मार्ग — त्याग।
An HTML5 browser game rooted in Sanatan Shaashtra and Karmic Philosophy.
Control your chariot through the cosmic field, master your senses, burn your karma, and attain Moksha.
⚠️ Important Notice This game requires a keyboard or a gamepad. For the best experience, please open it on a desktop or laptop Chrome browser.
🎮 Play on itch.io |
💛 Support on PayPal
- For now, this game is only for Hindi-speaking players who deeply understand Hindu philosophy.
- You must control your senses to escape the cycle of reincarnation and attain Moksha.
- The challenge: how few reincarnations you need before you attain Moksha.
🕉️ Spiritual Philosophy (Sanatan Model)
The game is built on the chariot metaphor of the Katha Upanishad (Nachiketopakhyana):
| Symbol |
Game Element |
Meaning |
| 🐎 6 Horses |
The player’s six senses |
Indriyas (इंद्रियाँ) — the senses |
| 🪢 Reins |
Player control |
Mana (मन) — the mind |
| 🛻 Chariot |
Game entity |
Sharira (शरीर) — the body |
| 👁️ Passenger |
Soul (Aatma) |
Aatma (आत्मा) — the soul |
| ॐ Naam-Jaap |
SPACE / RT button |
Naam-smarana (नाम-स्मरण) — self-remembrance |
| 🌬️ Swaansa |
Ring of lotus petals |
Aayu-shesha (आयु-शेष) — remaining life |
Core Karma System
| Concept |
Variable |
Behaviour |
| Punya (पुण्य — Good Karma) |
shuvhaKarma |
Slows the chariot; binds automatically if not released in time |
| Paap (पाप — Bad Karma) |
ashuvhaKarma |
Slows the chariot and strikes it (vision distortion) |
| Prarabdha (प्रारब्ध — Past-Life Karma) |
prarabdha |
+1 per rebirth only (regardless of the amount of sanchita karma); endured over time — speeds up samaya decay ×1.15; 10 Naam accelerate bhog 2×; max 15 |
| Samarpita (समर्पित — Surrendered) |
samarpita |
≥50 triggers Chetana-Jaagriti (Awakening) |
| Chetana-Jaagriti (चेतना-जागृति — Awakening) |
chetanaaJaagrita |
The true gate for Moksha — also grants isKarmaImmune (Gita 4.37) |
| Kripa (कृपा — Grace) |
kripa |
Earned through surrender; frees you from karma-bondage |
| Shankha (शंख — Conch) |
shankha |
Dispels the chakravaata (storm) of Maya when Naam is unavailable (Yantra-marg) |
| Jyoti (ज्योति — Lamp) |
jyoti |
Restores vision in the darkness of bad karma |
🎮 Controls
| Action |
Keyboard |
Gamepad |
Spiritual Meaning |
| Steer Chariot |
A / D, ← / → |
DPAD L/R |
Indriya-niyantran — control of the senses |
| Naam-Jaap (Chant) |
SPACE |
RT (7) |
Naam-jaap burns Maya to ashes (bhasma) and turns it into samarpita (surrender). |
| Vairagya (Detach) |
S, ↓ |
X (2) |
Prevent good-karma bondage |
| Samarpana (Surrender) |
W, ↑ |
RB (5) |
Only in the final phase (samaya < 100) |
| Pralaya (Sacrifice) |
Q |
LB (4) |
Voluntary dissolution of the chariot |
| Pure Rebirth |
R |
LT (6) |
Zero karma → new life |
| Shaashtra (Knowledge) |
ESC |
BACK (8) |
Open the wisdom scroll |
| Pause |
F |
START (9) |
Stillness (Stambhana) |
| Shankha (Conch) |
Y |
Y (0) |
Dispel chakravaata (Yantra-marg, when Naam is unavailable) |
| Jyoti (Lamp) |
B |
B (1) |
Restore vision in the darkness of bad karma |
| Shaashtra Scroll |
↑ / ↓ (hold) |
DPAD U/D |
Navigate the wisdom text |
✨ Key Features
- 🕉️ Vedic Karma Engine — Real-time Punya/Paap/Prarabdha/Samarpita system
- 🌸 Lotus Petal Ring — 10 animated petals visualise the remaining swaansa
- 🌀 Chakravaata (Maya Tufaan — the storm of Maya) — Can only be dispelled by Naam-Jaap, or by Shankha if Naam-Jaap is unavailable
- 🎵 Layered Ambient Audio — 4 continuous loops (bgMusic, Shathendriya, SushuptiSwaansa, JaagritaSwaansa) with smooth duck/fade
- 🔮 Sci-Fi Yantra Visuals — CRT scanlines, gold scan-sweep, Yantra polygons, cyberGrid
- 🔱 Three End States — Moksha (liberation), Pralaya (dissolution), Punarjanma (rebirth)
- 🎮 Full Gamepad Support — Xbox/generic controller with deadzone handling
- 📱 Mobile Touch Controls — On-screen virtual button overlay; multi-touch safe; blocker-stack visibility system
- 🔄 Gyroscope Steering — Device tilt → chariot steering (gamma axis); iOS 13+ permission dialog; calibration support
- 🎓 Guru-Diksha Tutorial — 5-step Guru-Diksha system; slow-mode cards; forced maya spawn; praarabdha-wait gate
- ⚡ 60fps Performance — Pool-based architecture (no GC pressure), sprite caching, emoji sprite cache, gradient buckets
- 📜 In-Game Shaashtra — A full philosophical treatise accessible via ESC
- 🔔 Canvas Alert Queue — Contextual slide-in alert cards (top-right), category-coloured, auto-dismiss; de-duplicated (no per-second flood)
- ⚖️ Prarabdha Bhog System — Endure past karma over time; unit-break explosion; MAX 15 cap; samaya penalty ×1.15;
_praarabdhaSpeedMul carry-forward across janma (births)
- 👁️ Chetanaa Immunity — Chetana-Jaagriti grants karma immunity (Gita 4.37 — ज्ञानाग्निः सर्वकर्माणि भस्मसात् — “the fire of knowledge reduces all karma to ashes”)
- 🧩 ES6 Modular Architecture — KarmaEngine split into 4 mixins: KarmaMixin, PhysicsMixin, StateMixin + Renderer + Touch + Tutorial
- 🧘♀️ Bhakti-Marga Spawn Bias — Naama always spawns inside the tunnel (tunnelProb=1.0); other Maya objects spawn 85% outside and 15% inside — obstacles remain, but Naama stays dominant on the path
🚀 How to Run Locally
# 1. Clone the repository
git clone https://github.com/weirdcodesofficial/MOKSHA.git
cd MOKSHA
# 2. Serve locally (required for audio AND ES6 modules — file:// blocks both)
npx serve .
# OR
python -m http.server 8080
# 3. Open in browser
http://localhost:8080
⚠️ Do NOT open index.html directly — the file:// protocol blocks both audio loading AND ES6 module imports → the game will not start.
💻 System Requirements
Browser
- ✅ Recommended: Chrome (fully tested — smooth 60fps)
- ⚠️ Firefox: gamepad auto-detect, audio autoplay blocked
- ⚠️ Edge / Safari: untested
- Required APIs: HTML5 Canvas 2D, RequestAnimationFrame, Web Audio API, Fetch, ES6 Modules
High Mode vs Low Mode
gameReadinessMode = (audioLoadFailures.length === 0) ? 'high' : 'low'
High/Low Mode is determined by audio load success, not hardware specs.
| Factor |
High Mode |
Low Mode |
| Network |
All 28 mp3 files load in time |
Timeout exceeded → Low |
| Web Audio API |
Available |
Old browser → Low |
| Server/CDN |
HTTP 200 |
CORS / blocker → Low |
Hardware (for 60fps)
- CPU: Dual-core 2015+ (minimum), Quad-core (recommended)
- RAM: 4GB (minimum), 8GB+ (recommended)
- GPU: Integrated graphics sufficient
Browser Settings
- Hardware acceleration ON
- Run in a foreground tab (background RAF throttles the timer)
- Browser zoom at 100% (conflicts with
scaleGame())
- Disable aggressive extensions (they may block CDN audio/fonts → Low Mode)
- ⚠️ Smooth 60fps is not guaranteed on Firefox — Chrome strongly recommended
🛠️ Tech Stack
| Layer |
Technology |
| Rendering |
HTML5 Canvas 2D |
| Logic |
Vanilla JS (ES6 Modules) — no framework, no build tool |
| Audio |
Web Audio API (layered ambient + SFX duck system) |
| Input |
Keyboard + Gamepad API + Touch API + DeviceOrientation API |
| Visuals |
Pure Canvas — no sprites, no external assets except audio |
| Style |
External style.css (extracted from index.html) |
📁 File Structure
MOKSHA/
├── index.html — HTML shell + start screen + touch-controls overlay
├── style.css — All UI styles, extracted from index.html
├── audio/ — 28 .mp3 ambient & SFX files
└── src/
├── audio.js — AudioManager: 28-mp3 preload, ambient layers, duck system
├── engine.js — KarmaEngine: slim orchestrator, core loop, pools, state transitions
├── i18n.js — Language manager: hi/en keys, persistence, resolveAlert, tLines
├── shaashtra.js — Shaashtra treatise: 3 pages, structured blocks, shloka repository (language-independent)
├── karma.js — KarmaMixin: Vedic logic, maya spawn, kripa, forceSpawnMaya
├── physics.js — PhysicsMixin: glow-rings, particles, floating text, pool helpers
├── state.js — StateMixin: HUD updates, alert queue, triggerAlert, animations
├── render.js — Renderer: Canvas draw functions, alert cards, tutorial card, sprite caches
├── touch.js — TouchControls: on-screen buttons, blocker-stack; GyroscopeControls: tilt steering
├── tutorial.js — TutorialManager: 5-step Guru-Diksha, slow-mode, praarabdha-wait gate
└── main.js — Orchestrator: wires all modules, gameLoop, input, gamepad, gyro, tutorial
📖 Moksha — Project Reference Document (Developer Reference)
Purpose: This document is a permanent reference for the Moksha codebase.
Last-update basis: v0.0.9 — Touch controls + Gyroscope steering + Guru-Diksha tutorial + StateMixin split (~8312 lines across 11 src files + style.css)
Language/Stack: HTML5 Canvas, Vanilla JS ES6 Modules (no build tooling, no TypeScript, no framework), Web Audio API, Gamepad API, Touch API, DeviceOrientation API
1. The Spiritual Model (Shaastriya Model)
| Shastric concept |
Code variable/constant |
Meaning & behaviour |
| Punya (पुण्य — good karma) |
shuvhaKarma, pendingGoodKarma |
Slows speed; an alluring temptation — binds automatically if not renounced in time |
| Paap (पाप — bad karma) |
ashuvhaKarma |
Slows speed + strikes the chariot (vibration / vision distortion) |
| Prarabdha (प्रारब्ध) |
prarabdha |
+1 per rebirth only (regardless of how much sanchita karma there is); MAX_PRARABDHA=15 cap; decreases through bhog (×1.15 samaya penalty); 10 Naam give 2× speed |
| Samarpita (समर्पित — surrendered) |
samarpita |
When >= CHETANA_JAGRITI_THRESHOLD (50), Chetana-Jaagriti is triggered |
| Chetana-Jaagriti (चेतना-जागृति — awakening) |
chetanaaJaagrita (boolean) |
The authoritative condition for Moksha — triggered at samarpita >= 50; on awakening isKarmaImmune = true (Gita 4.37) |
| Naam (नाम) |
sanchitaNaama |
1 Naam = burns Punya, 5 = burns Paap |
| Kripa (कृपा — grace) |
kripa |
If bondage exists → kripa-- and the karma moves into samarpita; if no bondage → kripa++ |
| Shankha (शंख — conch) |
shankha |
Y/gamepad — for calming the chakravaata |
| Jyoti (ज्योति — lamp) |
jyoti |
B/gamepad — for vision in the darkness of Paap |
| Swaansa (श्वास — breath) |
swaansa, samaya |
Visualised by the lotus-petal ring (§2.8) |
| Cosmic Horizon (ब्रह्मांडीय क्षितिज) |
samaya <= 0 |
The moment of decision: Moksha or rebirth |
| Rebirth (पुनर्जन्म) |
punaraJanmaCount + isApavitra |
Time restarts from SAMAYA_PRAARAMBHIKA (2880) |
1.1 Symbolism
- 6 horses = 6 senses; reins = mind; chariot = body; charioteer = mind; passenger = soul
- ॐ Naam = self-remembrance; swaansa = remaining life — visualised by the lotus petals (§2.8)
1.2 Moksha Condition
if (shuvhaKarma === 0 && ashuvhaKarma === 0 && !pendingGoodKarma
&& prarabdha === 0 && chetanaaJaagrita && poornaSamarpana) { }
⚠️ Always use the chetanaaJaagrita boolean, never samarpita >= 50.
1.3 Rebirth — Pure vs Impure
let isApavitra = (shuvhaKarma > 0 || ashuvhaKarma > 0 || prarabdha > 0);
let earnsKripaOnRebirth = (sanchitaNaama >= 20 || samarpita >= 30 || chetanaaJaagrita);
A rebirth is “impure” (apavitra) only if karma-bondage remains — a lack of samarpita/Naam does not make it “impure”.
1.4 Kripa Logic (grantKripa) — Shastra-Consistent Behaviour
grantKripa(x, y, reason = null) {
let hadKarma = (shuvhaKarma + ashuvhaKarma) > 0;
if (hadKarma) {
if (kripa > 0) { kripa--; }
samarpita += freedKarma;
shuvhaKarma = 0; ashuvhaKarma = 0;
} else { kripa++; }
}
1.5 Chakravaata — Shastra-Consistent Behaviour
- The chakravaata pulls the player too (range: 220px) — the fearsome form of Maya
- The chakravaata also pulls shuvha/rikta Maya toward itself
- The naam-jaap ring burns the chakravaata to ashes (Naam-marg) — the Name is all-powerful
- The Shankha ring (Y) also burns the chakravaata (Yantra-marg) — when no Naam is accumulated
- If the player collides directly →
ashuvhaKarma++ — only Naam or Shankha is the defence
2. Core Game State — Variable Map
Properties of the KarmaEngine class (all accessed via engine.*):
engine.shuvhaKarma, engine.ashuvhaKarma, engine.sanchitaNaama — current active amounts
engine.prarabdha, engine.samarpita, engine.punaraJanmaCount — accumulated / lifetime counters
engine.kripa, engine.shankha, engine.jyoti — rare resource counters
engine.chetanaaJaagrita (boolean) — Moksha gate
engine.isKarmaImmune — temporary protection
engine.poornaSamarpana — all Naam surrendered in the final phase
engine._praarabdhaSpeedMul — accumulated speed burden from past lives (carry-forward)
engine._praarabdhaSpeedStack — FIFO stack — to undo the per-life multiplier
2.2 Time/Swaansa
SAMAYA_PRAARAMBHIKA = 2880 — the same value at the start and on every rebirth
engine.samaya — current time
engine.swaansa, engine.swaansaTimer — remaining breath (swaansa = samaya / 288)
2.3 Pool-Based Architecture — ⚠️ Mandatory Pattern
| Pool |
Size |
Use |
mayaPool |
50 |
Shuvha/ashuvha Maya |
particlePool |
50 |
Explosion particles |
glowEffectPool |
20 |
Expanding-and-fading attainment aura |
floatingTextPool |
25 |
Floating text (ॐ/🙏/+N etc.) — round glass-box + text-clamping + measureText() cache |
Rule: Find an active: false slot → reuse it → set active = false when done. Never resize the array.
2.4 Glow-Ring System (DRY)
engine.glowRings = {
jyoti: { active, radius, speed:18, maxRadius:420, strokeColor, lineWidthMul, shadowBlur, glowColor, fillColor },
shankha: { ...same... },
kripa: { ...same... }
};
- Shankha ring onTick: chakravaata-collision check
- Jyoti ring: the only thing that removes the vision distortion of Paap
2.5 Resource-Pickup Unification (DRY)
export const MAYA_SIZE_TABLE = { naama:{36,36}, kripa:{32,32}, chakravaata:{32,32}, shankha:{32,32}, jyoti:{32,32}, default:{20,24} };
export const RESOURCE_PICKUP_TABLE = {
shankha: { icon:"🐚", color:"#7dd3fc", sound:"shankhaPrapta", alert:"..." },
jyoti: { icon:"🪔", color:"#ffe932", sound:"jyotiPrapta", alert:"..." }
};
2.6 Named Constants (exported from engine.js)
export const SAMAYA_PRAARAMBHIKA = 2880;
export const CHETANA_JAGRITI_THRESHOLD = 50;
export const NAAMA_JAAP_GROWTH_SPEED = 22;
export const NAAMA_JAAP_MAX_RADIUS = 1000;
export const HORSE_PULL_RANGE = 160;
export const KRIPA_NAAM_MILESTONE = 20;
export const KRIPA_SAMARPITA_MILESTONE = 30;
export const PRARABDHA_BHOG_FRAMES = 600;
export const MAX_PRARABDHA = 15;
export const CHAKRAVAATA_PLAYER_PULL_RANGE = 160;
export const CHAKRAVAATA_PLAYER_PULL_FORCE = 0.8;
2.7 Speed/Time Rings and Karma Orbits (outerOrbits)
Ring radii:
let gateeRadius = (swaansaringSmoothSize / 2) + 5;
let samayRadius = gateeRadius + 12;
- Colour: neon-gold
#ffc83c — consistent with the yantra palette
- Head indicators: ⚡ (speed), ⏳ (time)
- Final phase (samaya<100): the time ring turns neon-red/pink
#ff005a
outerOrbits array — 9 entries (swaansa removed):
engine.outerOrbits = [
{ count:shuvhaKarma, emoji:"🌿", color:"#32ff32", speed:0.8 },
{ count:ashuvhaKarma, emoji:"🥀", color:"#ff3232", speed:-0.9 },
{ count:prarabdha, emoji:"📜", color:"#a78bfa", speed:0.6 },
{ count:sanchitaNaama, emoji:"ॐ", color:"#ffffff", speed:1.0, glowTimer:0 },
{ count:kripa, emoji:"✋", color:"#ffe9a8", speed:0.7 },
{ count:shankha, emoji:"🐚", color:"#7dd3fc", speed:0.5 },
{ count:jyoti, emoji:"🪔", color:"#ffe932", speed:-0.6 },
{ count:samarpita, emoji:"🙏", color:"#fb923c", speed:1.1 },
{ count:punaraJanmaCount, emoji:"♻️", color:"#f87171", speed:-0.5 },
];
⚠️ Swaansa (🌬️) is no longer in outerOrbits — it is visualised by the lotus-petal ring (§2.8).
Sorting: sorted by count ascending every frame; baseDist = pankhudiRadius + (pankhudiLength × 1.5) + 8
2.8 Lotus-Petal Ring (Visual Representation of Swaansa)
PANKHUDI_COUNT = 10;
pankhudiRadius = samayRadius + 3;
pankhudiLength = 22;
pankhudiRotation = frameNow / 4500;
swaansaBoost = Math.sin((swaansaTimer / 360) * Math.PI);
Three states — pre-rendered offscreen sprites (cached in render.js):
cachedPankhudiConsumed: spent — dim/thin
cachedPankhudiActive: the current breath — 1.5× longer, 1.4× wider, bright gold
cachedPankhudiInactive: future — normal gold
2.9 innerOrbit System (between the speed and time rings)
let innerOrbit = [
chetanaaJaagrita ? "👁️" : "😴",
ashuvhaKarma >= 3 ? "⚫" : "☀️",
poornaSamarpana ? "🙌" : "🤲"
];
2.10 Sci-Fi Visual Mechanisms
#scifi-scan-sweep → gold band top→bottom (7s CSS animation), z-index 3
#gameContainer::after → CRT scanlines (repeating gold gradient), z-index 4, bottom:60px
buildSciFiGridSprite(WIDTH, HEIGHT)
drawRingTicks(cx, cy, radius, count, color)
drawYantraPolygon(cx, cy, radius, sides, rotation, …)
getMayaSprite(type, bScale)
getEmojiSprite(emoji, fontSize)
| Action |
Keyboard |
Gamepad |
Touch |
Shastric meaning |
| Steer chariot |
A/D, ←/→ |
DPAD L/R (14/15) |
←/→ buttons |
Control of the senses |
| Naam-jaap |
SPACE |
RT (7) |
ॐ button |
Spends 1 Naam → expanding aura |
| Vairagya |
S, ↓ |
X (2) |
🌿 button |
Prevent Punya-bondage |
| Naam surrender |
W, ↑ |
RB (5) |
🙏 button |
Only in the final phase (samaya<100) |
| Pralaya |
Q |
LB (4) |
💀 button |
Voluntary renunciation of the chariot |
| Pure rebirth |
R |
LT (6) |
♻️ button |
Zero karma, new life |
| Shaashtra |
ESC |
BACK (8) |
— |
Gateway of knowledge |
| Stambhana (pause) |
F |
START (9) |
— |
Stillness |
| Shankha |
Y |
Y (0) |
🐚 button |
Chakravaata-calming ring |
| Jyoti |
B |
B (1) |
🪔 button |
Vision in the darkness of Paap |
| Shaashtra navigation |
↑↓ (held) |
DPAD U/D (12/13) |
— |
Scroll; DPAD = PageUp/Down |
⚠️ handleShaashtraGamepadNav() is now also called from pollGamepadOnStartScreen().
3.1 Gyroscope Steering (touch.js — GyroscopeControls)
gamma axis: left/right tilt in portrait mode (-90° to +90°)
deadzone: ±10° — the chariot stays straight in the neutral zone
iOS 13+: DeviceOrientationEvent.requestPermission() — a user gesture is required
Android: automatic — no dialog
calibrate(): the next event becomes the baseline (zero)
- Gyro and keyboard/touch work together — key-ownership safe
_setLeft/_setRight flags: only gyro-set keys are cleared; touch keys are safe
3.2 TouchControls Blocker Stack (touch.js)
touch.block('start');
touch.block('tutorial');
touch.block('shaashtra');
touch.unblock('start');
4. Audio Architecture (src/audio.js — AudioManager)
4.1 Layered Ambient (4 Continuous Loops)
bgMusic → BG_MUSIC_MP3_LAYER_VOLUME=0.01, constant
shathendriya → RUNNING_HORSES_VOLUME=0.16, constant (file: ./audio/shathendriya.mp3)
sushuptiSwaansa → SUSHUPTI_SWAANSA_VOLUME=1, swaansa-synced — from game start until chetanaaJaagrita
jaagritaSwaansa → JAAGRITA_SWAANSA_VOLUME=0.22, swaansa-synced — after chetanaaJaagrita
sushuptiSwaansa and jaagritaSwaansa never play together.
bgMusicVolume slider: 0–100 → 0.0–1.0 multiplier — applied to all layers.
4.2 Duck Reduction per Layer
BG_MUSIC_DUCK_REDUCTION = 0.75
JAAGRITA_SWAANSA_DUCK_REDUCTION = 0.55
SUSHUPTI_SWAANSA_DUCK_REDUCTION = 0.20 // previously 0.55 — it was being suppressed too much
RUNNING_HORSES_DUCK_REDUCTION = 0.15
4.3 Gating
isGameStarted && !gameOver && !won && !isPaused && !isShaashtraVisible
4.4 Readiness
isFontsReady + isAudioPreloadDone + isScaleGameDone → isGameFullyReady
gameReadinessMode = (audioLoadFailures.length === 0) ? 'high' : 'low'
4.5 Audio Files (28 total)
Eager load (22): naamaSamarpita, samarpita, punaraJanma, shathendriya,
sushuptiSwaansa, timer, prarabdhaBandhana, paapaBandhana,
punyaBandhana, bandhanaMukta, naamaDhwani, jaapaDhwani,
aakarshana, tyaaga, kripaDhwani, shankhaDhwani, jyotiDhwani,
shankhaPrapta, jyotiPrapta, poornaSamarpana, drishti, andhakaara
Deferred load (6): bgMusic, chetanaJaagrita, pralaya, jaagritaSwaansa,
moksha, antimaCharana
4.6 AudioManager Dependency Injection (in main.js)
Audio.setGameStateGetter(() => ({ isGameStarted, gameOver, won,
isPaused, isShaashtraVisible, chetanaaJaagrita }));
Audio.setVibrateCallback(vibrateGamepad);
Audio.setReadinessGetters({ getFontsReady: () => isFontsReady,
getScaleGameDone: () => isScaleGameDone });
Audio.init();
5. ES6 Module Architecture
5.1 Module Graph
index.html
└── src/main.js (type="module")
├── import { initLang, setLang, getLang, t, tLines } from './i18n.js'
├── import { Renderer } from './render.js'
├── import { KarmaEngine, SAMAYA_PRAARAMBHIKA } from './engine.js'
│ ├── import { KarmaMixin } from './karma.js'
│ │ └── import { ... } from './engine.js' (constants — safe circular)
│ ├── import { PhysicsMixin } from './physics.js'
│ ├── import { StateMixin } from './state.js'
│ │ └── import { CHETANA_JAGRITI_THRESHOLD } from './engine.js'
│ └── import { t } from './i18n.js'
├── import Audio (default) from './audio.js'
├── import { TutorialManager } from './tutorial.js'
│ └── import { t } from './i18n.js'
├── import { renderShaashtraPage } from './shaashtra.js'
└── import { TouchControls, GyroscopeControls } from './touch.js'
5.2 KarmaEngine — Public Interface
const engine = new KarmaEngine();
engine.setCallbacks({ playSound, vibrateGamepad, updateAmbientVolumes,
stopSushuptiSwaansaLayer, startJaagritaSwaansaLayer,
stopJaagritaSwaansaLayer, startSushuptiSwaansaLayer });
engine.setUI(UI);
engine.init(600, 680, TUNNEL_X, 180);
engine.update(dt, keys, frameNow);
5.3 Renderer — Public Interface
Renderer.init(ctx, WIDTH, HEIGHT);
Renderer.drawScene(state);
Renderer.drawTutorialCard(ctx, tutorial.getCurrentCard());
5.4 TutorialManager — Public Interface
const tutorial = new TutorialManager(
(...args) => engine._forceSpawnMaya?.(...args),
WIDTH, HEIGHT
);
tutorial.start(engine.player.x);
tutorial.checkCompletion({ player, sanchitaNaama, isNaamaJaapa,
playerInTunnel, praarabdha, antimaCharanaStarted });
touch.syncWithTutorial(tutorial.hasActiveCard());
if (tutorial.hasActiveCard()) Renderer.drawTutorialCard(ctx, tutorial.getCurrentCard());
tutorial.dismiss();
if (!tutorial.isDone()) { tutorial.skip(); return; }
5.5 TouchControls + GyroscopeControls — Public Interface
const touch = new TouchControls(keys);
const gyro = new GyroscopeControls(keys);
touch.unblock('start');
const granted = await gyro.requestPermission();
if (!granted) _enableTouchSteering();
touch.clearAll();
gyro.clearState();
touch.block('shaashtra');
touch.unblock('shaashtra');
5.6 AudioManager — Singleton (Default Export)
import Audio from './audio.js';
const AM = Audio;
AM.init();
AM.playSound('naamaDhwani');
AM.setSwaansaPulse(worldSwaansaPulse);
AM.updateDuckDecay();
AM.updateAmbientVolumes();
- Pool pattern (§2.3) — 4 pools, never push/splice
- Sprite caches —
mayaSpriteCache (shuvha/ashuvha), emojiSpriteCache (all orbits/innerOrbit), cachedPankhudiConsumed/Active/Inactive (3 states), sciFiGridSprite, cachedBuddhiSprite, cachedAtmanSprite
- Bucket-cached gradients —
cachedSwaansaGrad / cachedTunnelGrad
- DOM throttle — guards such as
lastPunyaAlertSecond
_updateStatWithPulse() — updates the UI only on change (_oldStats compare)
- HUD animation —
_uiScales / _uiGlows per-key lerp, DOM write via dirty-check
- Single RAF loop — dual-RAF removed (Issue #64); shaashtra scroll + audio updates run in the same
gameLoop()
- Visibility API —
cancelAnimationFrame() when the tab is hidden → saves battery/GPU; lastTime is reset on restore → prevents a dt spike
7. Guru-Diksha System (Tutorial Steps)
src/tutorial.js — TutorialManager — teaches new players the Vedic mechanics in 5 steps.
| Step |
id |
Shastric shloka |
Completion Trigger |
| 0 |
move |
उद्धरेदात्मनात्मानं नात्मानमवसादयेत्। (Gita 6.5 — “Let one uplift oneself by one’s own self; let one not degrade oneself.”) |
≥40px horizontal movement |
| 1 |
maya |
मायाजालमिदं विश्वं मोहयत्यखिलं जगत्। (“This universe is a web of Maya; it deludes the entire world.”) |
sanchitaNaama >= 1 (naama collected) |
| 2 |
jaapa |
नाम जपत मंगल दिसि दसहूँ। (“Chanting the Name brings auspiciousness in all ten directions.”) |
isNaamaJaapa === true (latch) |
| 3 |
tunnel |
भक्त्या मामभिजानाति यावान्यश्चास्मि तत्त्वतः। (Gita 18.55 — “Through devotion one truly knows Me — what and who I am in essence.”) |
playerInTunnel === true (after antimaCharana) |
| 4 |
praarabdha |
भोगेन क्षीयते पापं, तपसा क्षीयते मलः। (“Sin is exhausted by experiencing its fruit; impurity is exhausted by austerity.”) |
dismiss = complete (the card appears after prarabdha is received) |
- Slow-mode:
dt × 0.3 while a card is visible — so the player can read
- localStorage key:
'moksha_tutorial_seen' — once completed → skipped afterwards
_forceSpawnMaya(): forced naama spawn in steps 1 and 2 (at the canvas center)
_waitingForAntimaCharana: the card for step 3 is not shown immediately — only once antimaCharana begins
_waitingForPraarabdha: the card for step 4 is not shown immediately — only once the first prarabdha >= 1 occurs
8. Change Log Summary
| Area |
Change |
| 🆕 ES6 Modular Refactor (0.0.4) |
index.html (3835 lines) → audio.js + engine.js + render.js + main.js + style.css |
| 🆕 engine.js split (v0.0.6) |
engine.js (1449→1044 lines) → KarmaMixin (karma.js) + PhysicsMixin (physics.js); Object.assign mixin pattern |
| 🆕 StateMixin split (v0.0.9) |
HUD/alert methods → state.js; engine.js imports StateMixin; added to Object.assign |
| 🆕 touch.js (v0.0.9) |
TouchControls (on-screen buttons, blocker-stack) + GyroscopeControls (gamma-axis tilt steering, iOS permission) |
| 🆕 tutorial.js (v0.0.9) |
TutorialManager — 5-step Guru-Diksha; slow-mode; forceSpawn; antimaCharana-wait; praarabdha-wait |
| 🆕 KarmaEngine class |
All Vedic state + logic → src/engine.js ES6 class; setCallbacks() DI pattern |
| 🆕 AudioManager class |
All Web Audio logic → src/audio.js; setGameStateGetter() DI pattern |
| 🆕 Renderer module |
All draw functions → src/render.js; drawTutorialCard() added |
| 🆕 style.css |
All CSS → external file |
| 🆕 emojiSpriteCache |
orbit/innerOrbit emoji → offscreen canvas cache; per-frame text draw stopped |
| 🆕 cachedPankhudi* |
cachedPankhudiConsumed, cachedPankhudiActive, cachedPankhudiInactive — 3 cached states |
| 🆕 cachedBuddhiSprite / cachedAtmanSprite |
New player-body sprite caches |
| 🆕 _praarabdhaSpeedMul |
Past-life speed carry-over — ×= on punarjanma; _praarabdhaSpeedStack FIFO undo |
| 🆕 Single RAF loop |
dual-RAF removed (Issue #64); lastTime unconditional; Visibility API: rAF cancel on tab-hide |
| Glow rings |
6 variables → glowRings object + helpers |
| Maya render |
duplicate draw → drawPickupGlowIcon() |
| Resource collection |
duplicate → collectResource() + RESOURCE_PICKUP_TABLE |
| Moksha gate |
samarpita>=50 → chetanaaJaagrita boolean |
| poornaSamarpana |
purnaSamarpana → poornaSamarpana (variable rename — consistent across the code) |
| shuvhaKarma |
activeGoodKarma → shuvhaKarma |
| ashuvhaKarma |
activeBadKarma → ashuvhaKarma |
| outerOrbits 10→9 |
swaansa orbit removed → visualised by the lotus petals |
| Lotus-petal ring |
10 petals, shows swaansa, swaansaBoost animation |
| innerOrbit |
status icons between the speed↔time rings |
| Sci-fi visuals |
scan-sweep, CRT scanlines, drawRingTicks, drawYantraPolygon, cyberGrid |
| Ring colour |
violet/cyan → neon-gold #ffc83c |
| grantKripa() |
bondage present → kripa–, karma→samarpita; no bondage → kripa++ |
| chakravaata |
pulls the player; naam-ring burns it (Naam-marg); Shankha is the Yantra-marg; direct collision → ashuvhaKarma++ |
| bgMusicVolume |
fix: multiplier on all layers |
| SUSHUPTI duck |
0.55→0.20 |
| Audio eager/deferred |
22 eager + 6 deferred |
| mp3 count |
24 → 28 |
| Developer credit |
PS → Weired Codes |
| Line count |
3835 (single-file) → ~8312 (11 src files + style.css) |
| Bhakti-Marga spawn bias |
Added the _spawnXPos(tunnelProb) helper — naama tunnelProb=1.0 (always in the tunnel), other Maya tunnelProb=0.15 (85% outside, 15% in the tunnel) |
9. Working Method & Collaboration Rules (Permanent)
- Default: diff only — explicit
old_str/new_str — the full file only when asked.
- Confirmation before action — confirm scope → then the diff.
- Language — Devanagari Hindi, whatever language the question is in.
- Code style — modular, well-commented, no truncation.
- Guidance first — say what needs to change → confirmation → diff.
- Shastra-consistency first — every fix/feature must conform to shastric principles.
10. Open Questions
jaapaNaama = "राधा" — floating text on naam-jaap; shastra-consistent; unchanged.
11. Quick File Navigation
src/engine.js (~1220 lines) — Slim Orchestrator
| Line |
Function/Section |
| ~1 |
Imports: KarmaMixin, PhysicsMixin, StateMixin, t |
| ~49 |
Exported constants (SAMAYA_PRAARAMBHIKA, MAX_PRARABDHA, CHAKRAVAATA_PLAYER_PULL_RANGE, etc.) |
| ~106 |
KarmaEngine class constructor — all state properties |
| ~290 |
setCallbacks(), setUI() |
| ~318 |
init() — pool + stars initialization |
| ~378 |
update(dt, keys, frameNow) — main game-logic tick |
| ~968 |
toggleShaashtra() |
| ~1000 |
showEndScreen(reason) |
| ~1072 |
reset() — punahaPrarambha (restart) |
| ~1154 |
getState() — renderer snapshot |
| ~1220 |
Object.assign(KarmaEngine.prototype, PhysicsMixin, KarmaMixin, StateMixin) |
src/karma.js (~542 lines) — KarmaMixin
| Line |
Function/Section |
| ~1 |
import { SAMAYA_PRAARAMBHIKA, MAYA_SIZE_TABLE, RESOURCE_PICKUP_TABLE, ... } from engine.js |
| ~37 |
export const KarmaMixin |
| ~42 |
_syncOrbitCounts() |
| ~60 |
_checkMokhsha() — Moksha condition + rebirth |
| ~179 |
_spawnMaya() — type determination + pool slot |
| ~215 |
_spawnXPos(tunnelProb) — tunnel-biased xPos helper (1.0=naama/always tunnel, 0.15=others/mostly outside) |
| ~228 |
_forceSpawnMaya(type, x, y) — tutorial forced spawn |
| ~242 |
_handlePlayerMayaCollision() — Vedic collision logic |
| ~332 |
_grantKripa() — §1.4 |
| ~381 |
_collectResource() — Shankha/Jyoti DRY |
| ~400 |
actionNaamaJaapa() |
| ~427 |
actionShankha(), actionJyoti() |
| ~461 |
actionNaamaSamarpan() |
| ~490 |
actionVairaagya() |
| ~510 |
actionPralaya(), actionPause(), actionResume() |
src/physics.js (~203 lines) — PhysicsMixin
| Line |
Function/Section |
| ~1 |
export const PhysicsMixin |
| ~30 |
_isPlayerInsideTunnel() |
| ~40 |
_updateGlowRing(ring, dt, onTick) — DRY §2.4 |
| ~55 |
_resetAllGlowRings() |
| ~65 |
_createExplosion(x, y, color) |
| ~90 |
_createGainedGlow(x, y, color) |
| ~110 |
_addFloatingText(text, color, opts) — pool §2.3; overlap prevention; Y-stagger |
| ~185 |
_triggerGlow(color) |
| ~195 |
_triggerBlast(color) |
src/state.js (~202 lines) — StateMixin
| Line |
Function/Section |
| ~1 |
import { CHETANA_JAGRITI_THRESHOLD } from engine.js |
| ~10 |
export const StateMixin |
| ~15 |
triggerAlert({ icon, title, subtitle, titleKey, subtitleKey, params, category }) |
| ~50 |
_alertKey(name, icon, category, params, subtitleName) — i18n-key alert shorthand |
| ~60 |
_updateAlert(text, color) — legacy color→category wrapper |
| ~85 |
_updateStatWithPulse(el, key, newVal, icon, suffix) — dirty-check + pulse |
| ~100 |
_updateUIStats() — all HUD stats at once |
| ~150 |
_updateHUDAnimations(dt) — scale/glow lerp |
| ~195 |
setContainerBorderColor(color) — dirty-check |
src/touch.js (~344 lines)
| Line |
Function/Section |
| ~1 |
export class TouchControls |
| ~35 |
constructor(keys) — touch device detect; blocker set init |
| ~60 |
_isTouchDevice() |
| ~70 |
_bind() — touchstart/touchend/touchcancel on data-key buttons |
| ~115 |
block(reason), unblock(reason) — blocker-stack API |
| ~130 |
syncWithTutorial(cardVisible) — backward-compatible wrapper |
| ~140 |
_applyVisibility() — blocker.size === 0 → flex |
| ~155 |
clearAll() — clear stuck keys on blur |
| ~170 |
isActive() |
| ~185 |
export class GyroscopeControls |
| ~210 |
constructor(keys) — deadzone, calibration flags |
| ~230 |
isSupported(), requestPermission() — iOS permission dialog |
| ~260 |
calibrate(), stop(), clearState(), isActive() |
| ~300 |
_start() — attach deviceorientation listener |
| ~315 |
_onOrientation(e) — gamma → calibration → deadzone → key inject |
src/tutorial.js (~355 lines) — TutorialManager
| Line |
Function/Section |
| ~1 |
import { t } from i18n.js |
| ~15 |
TUTORIAL_STORAGE_KEY = 'moksha_tutorial_seen' |
| ~20 |
TUTORIAL_STEPS[] — 5 step definitions (id, shloka, forceSpawn, dismissToComplete) |
| ~55 |
export class TutorialManager |
| ~65 |
constructor(forceSpawnFn, canvasWidth, canvasHeight) |
| ~110 |
start(playerX) — localStorage check; first card show |
| ~130 |
dismiss() — card hide; forceSpawn trigger; dismissToComplete check |
| ~155 |
skip() — localStorage write; tutorial done |
| ~165 |
checkCompletion(state) — per-step action check; antima/praarabdha wait |
| ~220 |
isSlowMode(), hasActiveCard(), isDone() |
| ~240 |
getCurrentCard() — i18n card data for Renderer |
| ~255 |
resize(w, h) |
| ~265 |
_onStepComplete() — step++; antima-wait / praarabdha-wait gate |
src/audio.js (~1279 lines)
| Line |
Function/Section |
| ~53 |
Constants (volumes, duck reductions) |
| ~130 |
audioBuffers object (28 keys) |
| ~180 |
checkReadiness(), finalizeReadiness() |
| ~240 |
init() |
| ~320 |
loadAudioBuffer() |
| ~380 |
Eager audio batch (22 files) |
| ~450 |
Deferred audio batch (6 files) |
| ~500 |
startBgMusicMp3Layer() |
| ~530 |
startRunningHorsesLayer() (shathendriya) |
| ~560 |
startJaagritaSwaansaLayer() |
| ~600 |
startSushuptiSwaansaLayer() |
| ~680 |
playSound(name) — SFX dispatcher |
| ~950 |
duckBackgroundMusic(), updateDuckDecay() |
| ~1000 |
updateAmbientVolumes() |
| ~1050 |
isActiveGameplay() |
| ~1100 |
setGameStateGetter(), setVibrateCallback(), setReadinessGetters() |
src/render.js (~1452 lines)
| Line |
Function/Section |
| ~1 |
CanvasRenderingContext2D.prototype.roundRect polyfill |
| ~21 |
Sprite cache declarations (mayaSpriteCache, emojiSpriteCache) |
| ~38 |
buildSciFiGridSprite() |
| ~69 |
getMayaSprite() |
| ~108 |
getEmojiSprite() — emoji offscreen cache |
| ~125 |
drawRingTicks() |
| ~139 |
drawGlowRing() |
| ~152 |
drawPickupGlowIcon() |
| ~168 |
drawCenteredRow() |
| ~176 |
drawKarmaChain() |
| ~195 |
drawYantraPolygon() |
| ~220 |
drawAlerts(alertQueue, WIDTH) — slide-in alert cards |
| ~331 |
drawProximateAlerts(alertQueue, player, smoothSize, WIDTH) |
| ~413 |
export const Renderer |
| ~414 |
Renderer.init(context, WIDTH, HEIGHT) |
| ~419 |
Renderer.drawScene(state) — renders the entire frame |
| ~1172 |
Renderer.wrapText(ctx, text, maxWidth) |
| ~1194 |
Renderer.drawTutorialCard(context, card) — Guru-Diksha card |
src/main.js (~854 lines)
| Line |
Function/Section |
| ~1 |
imports (i18n, Renderer, KarmaEngine, Audio, TutorialManager, shaashtra, TouchControls, GyroscopeControls) |
| ~39 |
Canvas + game constants (WIDTH, HEIGHT, TUNNEL_X, TUNNEL_WIDTH) |
| ~48 |
UI DOM references |
| ~77 |
window._engine debug hook |
| ~94 |
tutorial init; touch init; gyro init |
| ~108 |
Gyro ↔ touch steering toggle logic |
| ~115 |
_syncSteeringUI(), _enableTouchSteering(), _enableGyroSteering(), _initDefaultGyroSteering() |
| ~169 |
Gamepad constants + GAMEPAD_BUTTON map |
| ~182 |
dispatchKey(), vibrateGamepad() |
| ~201 |
handleDiscreteButton(), handleShaashtraDirection(), handleShaashtraGamepadNav() |
| ~241 |
pollGamepad() — main gamepad poll (tutorial dismiss + gyro merge) |
| ~288 |
updateShaashtraPage() |
| ~317 |
toggleShaashtra() — touch block/unblock |
| ~343 |
debounce(), scaleGame() |
| ~574 |
draw() — engine state + Renderer.drawScene() + tutorial card |
| ~604 |
gameLoop(ts) — single RAF loop; tutorial check; audio; lastTime unconditional |
| ~650 |
Visibility API — tab-hide rAF cancel + restore |
| ~668 |
applyStartScreenLanguage() |
| ~746 |
pollGamepadOnStartScreen() |
src/i18n.js (~464 lines)
| Line |
Function/Section |
| ~1 |
LANG_STORAGE_KEY, SUPPORTED_LANGS, DEFAULT_LANG |
| ~5 |
Translation object (hi/en — all keys) |
| ~399 |
_readStoredLang(), _writeStoredLang(), _normalizeLang() |
| ~419 |
initLang() — language init at startup |
| ~424 |
getLang(), setLang(lang) |
| ~440 |
onLangChange(fn) — callback register |
| ~446 |
t(key, params) — translate with interpolation |
| ~455 |
tLines(key, params) — multiline translation |
| ~459 |
resolveAlert(a) — titleKey/subtitleKey → live-resolved text |
src/shaashtra.js (~268 lines)
| Line |
Function/Section |
| ~1 |
Shaashtra page data (3 pages, structured blocks) |
| ~50 |
Shloka repository (language-independent) |
| ~200 |
renderShaashtraPage(ctx, pageIndex, state) |
12. System Requirements & High/Low Mode
⚠️ High/Low Mode trigger — not a hardware check
gameReadinessMode = (audioLoadFailures.length === 0) ? 'high' : 'low';
| Factor |
High Mode |
Low Mode |
| Network |
All 28 mp3 files load within the timeout |
Timeout exceeded → Low |
| Web Audio API |
Available |
Old browser → Low |
| Server/CDN |
HTTP 200 |
CORS/blocker → Low |
Browser requirements
- ✅ Chrome — fully tested, smooth 60fps
- ⚠️ Firefox — no gamepad auto-detect, audio autoplay blocked
- ⚠️ Edge / Safari — untested
- HTML5 Canvas 2D, RAF, fetch, ES6 Modules — mandatory
- Web Audio API — required for High Mode
Hardware (60fps — not a mode determinant)
- CPU: dual-core 2015+ (minimum), quad-core (recommended)
- RAM: 4GB (minimum), 8GB+ (recommended)
- GPU: integrated is sufficient
Browser settings
- Hardware acceleration ON
- Foreground tab (background RAF throttling disturbs the timer)
- Zoom 100% (conflicts with scaleGame())
- Extensions: aggressive blockers → block CDN audio/fonts → Low Mode
This document is based on the audit of the ES6 Modular Refactor by Weired Codes.
Have it updated whenever a major refactor or a new feature is added.
🛠️ Transparency
Human-designed, AI-assisted.
The core concept, spiritual design, art direction, and gameplay vision of this game
are entirely human. AI (Claude by Anthropic) was used in code development to assist with
debugging, optimization, and refactoring.
All creative and shastric decisions have been made by Weired Codes.
⚠️ Important Notice
This game requires a keyboard or a gamepad. For the best experience, please open it on a desktop or laptop browser.
💛 Support the Project
If you like this spiritual and technical endeavour and wish to support it directly, you can contribute via PayPal.
(Note: the payment will be processed under the name PS.)
👤 Credits
Developed by Weired Codes
Inspired by the Katha Upanishad, the Bhagavad Gita, and Sanatan Dharma.
🔗 Links
评论