<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
<meta name="theme-color" content="#7cc8ff">
<title>Бублик и Золотая косточка</title>
<style>
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{margin:0;height:100%;overflow:hidden;background:#1b2a4a;font-family:'Nunito',system-ui,sans-serif;color:#fff;user-select:none;-webkit-user-select:none;touch-action:none;overscroll-behavior:none}
#c{position:fixed;inset:0;width:100%;height:100%;display:block}
.hidden{display:none!important}
.screen{position:fixed;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:10px;text-align:center;z-index:20;animation:fade .35s ease;gap:1.2vh}
@keyframes fade{from{opacity:0;transform:scale(.97)}to{opacity:1;transform:none}}
.panel{background:rgba(255,255,255,.93);color:#33406b;border-radius:24px;padding:clamp(10px,2.4vh,20px) clamp(14px,3vh,24px);box-shadow:0 8px 0 rgba(30,50,110,.28),0 18px 40px rgba(0,0,0,.25);max-width:min(600px,94vw);max-height:92vh;overflow:auto;display:flex;flex-direction:column;gap:1.6vh;align-items:center}
.panel h2{margin:0;font-weight:900;font-size:clamp(20px,5vh,32px);color:#e9742a}
.panel p{margin:0;font-weight:800;font-size:clamp(14px,3.3vh,19px);line-height:1.35}
.row{display:flex;gap:10px;flex-wrap:wrap;justify-content:center;align-items:center}
.btn{font:inherit;font-weight:900;font-size:clamp(16px,3.8vh,22px);color:#fff;background:#ff8a3d;border:0;border-radius:18px;padding:.55em 1.4em;box-shadow:0 6px 0 #c9591a;cursor:pointer;transition:transform .08s,box-shadow .08s;touch-action:manipulation}
.btn:active{transform:translateY(5px);box-shadow:0 1px 0 #c9591a}
.btn.blue{background:#4aa8ff;box-shadow:0 6px 0 #2370c4}.btn.blue:active{box-shadow:0 1px 0 #2370c4}
.btn.green{background:#43c767;box-shadow:0 6px 0 #1f8f40}.btn.green:active{box-shadow:0 1px 0 #1f8f40}
.btn.small{font-size:clamp(13px,2.8vh,16px);padding:.45em 1em}
.btn.red{background:#ff5d73;box-shadow:0 6px 0 #c22a40}.btn.red:active{box-shadow:0 1px 0 #c22a40}
.logo{margin:0}
.l1{font-weight:900;font-size:clamp(36px,12vh,78px);line-height:1;text-shadow:0 4px 0 #e9742a,0 9px 0 rgba(0,0,0,.22);letter-spacing:1px}
.l2{font-weight:900;font-size:clamp(16px,4.8vh,32px);color:#ffe27a;text-shadow:0 3px 0 #b8551a;margin-top:.6vh}
.nm{font-weight:900;font-size:clamp(13px,3vh,17px);display:flex;flex-direction:column;gap:4px;align-items:center}
.nm input{font:inherit;font-weight:900;text-align:center;border:3px solid #9fc5ff;border-radius:14px;padding:.3em .6em;width:min(260px,70vw);color:#33406b;outline:none;font-size:clamp(16px,3.6vh,22px);user-select:text;-webkit-user-select:text}
.bankPill{display:flex;gap:8px;align-items:center;background:#fff1d0;color:#a8660a;border:3px solid #ffd98a;border-radius:99px;padding:4px 16px;font-weight:900;font-size:clamp(15px,3.6vh,21px)}
.bankPill svg{width:clamp(20px,4.6vh,30px);height:clamp(20px,4.6vh,30px)}
/* гардероб */
.wardPanel{max-width:min(800px,97vw);gap:1vh}
.wardBody{display:flex;gap:14px;align-items:center;justify-content:center;width:100%}
.pv{display:flex;flex-direction:column;align-items:center;gap:4px;font-weight:800;font-size:12px;color:#6a769c;flex:none}
.pv canvas{width:clamp(120px,40vh,230px);height:auto;aspect-ratio:220/190;border-radius:18px;border:3px solid #cfe0ff;cursor:pointer;display:block}
.wardR{display:flex;flex-direction:column;gap:6px;align-items:center;flex:1;min-width:0}
.tabs{display:flex;flex-wrap:wrap;gap:5px;justify-content:center}
.tab{font:inherit;font-weight:900;font-size:clamp(12px,2.8vh,15px);border:0;border-radius:12px;padding:.35em .8em;background:#dfe8fb;color:#4a5a8a;cursor:pointer;touch-action:manipulation}
.tab.on{background:#4aa8ff;color:#fff}
.opts{display:flex;flex-wrap:wrap;gap:5px;justify-content:center;max-height:30vh;overflow:auto;width:100%;padding:2px}
.chip{font:inherit;font-weight:800;font-size:clamp(11px,2.6vh,14px);border:3px solid #cfd8f0;background:#eaf3ff;color:#33406b;border-radius:12px;padding:.3em .7em;cursor:pointer;display:inline-flex;align-items:center;gap:3px;touch-action:manipulation}
.chip.on{border-color:#ff8a3d;background:#fff1e0}
.chip.lock{background:#f6ecd8;border-color:#e8d4a8;color:#a8660a}
.chip svg{width:13px;height:13px}
.palrow{display:flex;gap:5px;align-items:center;flex-wrap:wrap;justify-content:center;font-weight:800;font-size:clamp(11px,2.6vh,14px)}
.sw{width:clamp(22px,5.5vh,30px);height:clamp(22px,5.5vh,30px);border-radius:50%;border:3px solid #fff;box-shadow:0 0 0 2px #cfd8f0;cursor:pointer;padding:0;font:inherit;font-weight:900;font-size:10px;color:#33406b;background:#fff;touch-action:manipulation}
.sw.on{box-shadow:0 0 0 3px #ff8a3d}
.colin{display:flex;align-items:center;gap:4px;font-weight:800}
.colin input{width:40px;height:30px;border:0;padding:0;background:none;cursor:pointer}
#hud{position:fixed;top:max(8px,env(safe-area-inset-top));left:max(10px,env(safe-area-inset-left));right:max(10px,env(safe-area-inset-right));display:flex;gap:8px;align-items:center;z-index:10;pointer-events:none}
.pill{display:flex;align-items:center;gap:6px;background:rgba(20,30,70,.55);border-radius:999px;padding:4px 12px;font-weight:900;font-size:clamp(14px,3.6vh,20px);backdrop-filter:blur(4px)}
.pill svg{width:clamp(16px,4vh,24px);height:clamp(16px,4vh,24px)}
#pauseBtn{pointer-events:auto;margin-left:auto;width:clamp(38px,9vh,48px);height:clamp(38px,9vh,48px);border-radius:50%;border:3px solid rgba(255,255,255,.7);background:rgba(20,30,70,.55);display:grid;place-items:center;color:#fff;cursor:pointer;padding:0}
#bossBar{position:fixed;top:max(56px,calc(env(safe-area-inset-top) + 50px));left:50%;transform:translateX(-50%);width:min(320px,50vw);height:16px;border-radius:99px;background:rgba(0,0,0,.5);border:3px solid #fff;z-index:10;overflow:hidden}
#bossFill{height:100%;background:linear-gradient(#ff7a7a,#e12a4a);width:100%;transition:width .3s}
#banner{position:fixed;top:30%;left:0;right:0;text-align:center;z-index:15;pointer-events:none;opacity:0}
#banner.on{animation:ban 2.8s ease both}
@keyframes ban{0%{opacity:0;transform:translateY(20px) scale(.9)}12%,80%{opacity:1;transform:none}100%{opacity:0;transform:translateY(-14px)}}
#banner b{display:block;font-size:clamp(26px,9vh,56px);font-weight:900;text-shadow:0 4px 0 #e9742a,0 7px 14px rgba(0,0,0,.35)}
#banner i{display:block;font-style:normal;font-size:clamp(14px,4vh,24px);font-weight:800;color:#ffe27a;text-shadow:0 2px 6px #000}
#toast{position:fixed;top:max(56px,calc(env(safe-area-inset-top) + 48px));left:50%;transform:translate(-50%,-10px);background:rgba(20,30,70,.8);padding:6px 16px;border-radius:99px;font-weight:900;font-size:clamp(13px,3.2vh,18px);opacity:0;transition:.25s;z-index:30;pointer-events:none;white-space:nowrap}
#toast.on{opacity:1;transform:translate(-50%,0)}
#tip{position:fixed;bottom:34%;left:50%;transform:translate(-50%,10px);max-width:min(520px,80vw);background:#fff;color:#33406b;border-radius:18px;padding:8px 16px;font-weight:900;font-size:clamp(13px,3.3vh,18px);box-shadow:0 5px 0 rgba(0,0,0,.2);opacity:0;transition:.25s;z-index:12;pointer-events:none;text-align:center}
#tip.on{opacity:1;transform:translate(-50%,0)}
#touch{position:fixed;left:0;right:0;bottom:0;height:45%;pointer-events:none;z-index:9;--u:clamp(62px,19vh,96px)}
.tb{position:absolute;bottom:max(12px,env(safe-area-inset-bottom));pointer-events:auto;touch-action:none;background:rgba(255,255,255,.26);border:3px solid rgba(255,255,255,.6);color:#fff;display:flex;align-items:center;justify-content:center;font-weight:900}
.tb svg{width:50%;height:50%;opacity:.9;pointer-events:none}
#dpad{left:max(14px,env(safe-area-inset-left));width:calc(var(--u)*2.2);height:var(--u);border-radius:99px;justify-content:space-between;padding:0 calc(var(--u)*.2)}
#dpad svg{width:34%;height:50%;opacity:.55}
#dpad[data-d=l] .aL,#dpad[data-d=r] .aR{opacity:1}
#bJump{right:max(14px,env(safe-area-inset-right));width:calc(var(--u)*1.3);height:calc(var(--u)*1.3);border-radius:50%}
#bBark{right:calc(max(14px,env(safe-area-inset-right)) + var(--u)*1.3 + 14px);width:var(--u);height:var(--u);border-radius:50%;background:rgba(255,160,70,.45);font-size:calc(var(--u)*.26)}
.tb.on{background:rgba(255,255,255,.55)}
#rotate{position:fixed;inset:0;background:#24376b;z-index:100;display:none;flex-direction:column;align-items:center;justify-content:center;gap:18px;font-weight:900;font-size:22px;text-align:center;padding:20px}
@media (orientation:portrait){#rotate{display:flex}}
#rotate svg{width:90px;height:90px;animation:rot 2.2s ease-in-out infinite}
@keyframes rot{0%,20%{transform:rotate(0)}60%,100%{transform:rotate(-90deg)}}
#mapBox{position:relative;width:min(80vw,780px);height:min(58vh,360px)}
#mapBox svg{position:absolute;inset:0;width:100%;height:100%}
.node{position:absolute;transform:translate(-50%,-50%);background:var(--c,#62c85a);border:4px solid #fff;border-radius:50%;width:clamp(48px,13vh,76px);height:clamp(48px,13vh,76px);color:#fff;font:inherit;font-weight:900;font-size:clamp(18px,5vh,30px);cursor:pointer;box-shadow:0 6px 0 rgba(0,0,0,.28);display:grid;place-items:center;padding:0;touch-action:manipulation}
.node:active{transform:translate(-50%,-47%)}
.node.locked{background:#8a93ad;filter:saturate(.4)}
.node.boss{border-color:#ffd93d;box-shadow:0 6px 0 rgba(0,0,0,.28),0 0 0 4px rgba(255,217,61,.55)}
.node .nmx{position:absolute;top:100%;margin-top:6px;font-size:clamp(10px,2.7vh,15px);white-space:nowrap;text-shadow:0 2px 4px #000;line-height:1.1}
.node .sts{position:absolute;bottom:calc(100% + 2px);display:flex;gap:1px}
.node .sts svg{width:clamp(12px,3.2vh,18px);height:clamp(12px,3.2vh,18px)}
.big-stars{display:flex;gap:8px}
.big-stars svg{width:clamp(36px,11vh,64px);height:clamp(36px,11vh,64px);animation:pop .5s cubic-bezier(.3,1.6,.5,1) both}
@keyframes pop{from{transform:scale(0) rotate(-90deg)}to{transform:none}}
.stat{display:flex;gap:14px;font-weight:900;font-size:clamp(14px,3.4vh,20px);align-items:center;flex-wrap:wrap;justify-content:center}
.stat span{display:flex;align-items:center;gap:6px}
.stat svg{width:22px;height:22px}
.mapTitle{font-weight:900;font-size:clamp(20px,6vh,34px);text-shadow:0 3px 0 #e9742a,0 5px 10px rgba(0,0,0,.35);margin:0}
.mapSub{font-weight:900;font-size:clamp(12px,3vh,17px);color:#fff;text-shadow:0 2px 5px rgba(0,0,0,.6);margin-top:-.6vh}
.dots{display:flex;gap:6px}
.dots i{width:12px;height:12px;border-radius:50%;background:rgba(255,255,255,.4);border:2px solid #fff}
.dots i.on{background:#ffd93d}
.arrow{position:absolute;top:50%;transform:translateY(-50%);width:clamp(46px,12vh,66px);height:clamp(46px,12vh,66px);border-radius:50%;border:4px solid #fff;background:#ff8a3d;box-shadow:0 6px 0 #c9591a;display:grid;place-items:center;padding:0;cursor:pointer;z-index:25;touch-action:manipulation}
.arrow:active{transform:translateY(-46%)}
.arrow svg{width:50%;height:50%}
.arrow.l{left:max(8px,env(safe-area-inset-left))}.arrow.r{right:max(8px,env(safe-area-inset-right))}
.arrow.dim{background:#8a93ad;box-shadow:0 6px 0 #5d6580}
@media (min-aspect-ratio:3/2){#title{flex-direction:row;gap:4vw}}
/* диалоги и сцены */
#dlg{justify-content:flex-end;padding-bottom:max(10px,2vh);background:rgba(10,20,50,.3)}
.dlgPanel{flex-direction:row;max-width:min(800px,97vw);gap:14px;align-items:center;padding:clamp(8px,2vh,16px)}
#dlgC{height:clamp(90px,34vh,190px);width:auto;aspect-ratio:360/170;border-radius:16px;border:3px solid #cfe0ff;flex:none;display:block}
.dlgR{display:flex;flex-direction:column;gap:1vh;align-items:stretch;text-align:left;flex:1;min-width:0}
#dlgName{font-weight:900;font-size:clamp(16px,4vh,22px);color:#e9742a}
#dlgTxt{min-height:3.6em}
.dlgR .btn{align-self:flex-end}
#cut{justify-content:flex-end;padding-bottom:max(8px,2vh);background:radial-gradient(120% 120% at 50% 0%,#1c2a52 0%,#0a0f26 100%);gap:1vh;z-index:40}
#cutC{width:min(94vw,880px);height:auto;max-height:52vh;aspect-ratio:640/300;border-radius:16px;border:4px solid rgba(255,255,255,.25);box-shadow:0 14px 40px rgba(0,0,0,.5);display:block}
#cutPanel{max-width:min(720px,94vw);gap:1vh;padding:clamp(10px,2vh,18px) clamp(14px,3vh,22px)}
#cutName{font-weight:900;font-size:clamp(15px,3.6vh,21px);color:#e9742a;text-align:left;width:100%}
#cutTxt{min-height:3.4em;text-align:left;width:100%}
#cutNext{align-self:flex-end}
/* обновления */
.updBox{text-align:left;width:min(560px,86vw);max-height:56vh;overflow:auto;display:flex;flex-direction:column;gap:1.4vh;padding-right:4px}
.ver{background:#eef4ff;border:3px solid #cfe0ff;border-radius:16px;padding:8px 14px}
.ver.new{border-color:#ff8a3d;background:#fff4e6}
.ver h3{margin:0 0 4px;font-weight:900;font-size:clamp(15px,3.6vh,20px);color:#e9742a;display:flex;gap:8px;align-items:center;flex-wrap:wrap}
.ver h3 em{font-style:normal;font-size:.7em;background:#43c767;color:#fff;border-radius:99px;padding:1px 10px}
.ver ul{margin:0;padding-left:1.2em;font-weight:800;font-size:clamp(12px,2.9vh,16px);line-height:1.35}
/* настройки */
.setBox{display:flex;flex-direction:column;gap:10px;width:min(380px,84vw)}
</style>
</head>
<body>
<canvas id="c"></canvas>
<div id="hud" class="hidden">
<div class="pill" id="hearts"></div>
<div class="pill"><svg viewBox="-12 -8 24 16"><g id="hudBone"></g></svg><span id="boneN">0</span></div>
<div class="pill" id="starsHud"></div>
<button id="pauseBtn" aria-label="Пауза"><svg width="22" height="22" viewBox="0 0 24 24" fill="#fff"><rect x="5" y="4" width="5" height="16" rx="2"/><rect x="14" y="4" width="5" height="16" rx="2"/></svg></button>
</div>
<div id="bossBar" class="hidden"><div id="bossFill"></div></div>
<div id="banner"><b id="banB"></b><i id="banI"></i></div>
<div id="toast"></div>
<div id="tip"></div>
<div id="touch" class="hidden">
<div class="tb" id="dpad"><svg class="aL" viewBox="0 0 24 24" fill="#fff"><path d="M16 3 6 12l10 9z"/></svg><svg class="aR" viewBox="0 0 24 24" fill="#fff"><path d="m8 3 10 9-10 9z"/></svg></div>
<div class="tb" id="bBark">ГАВ</div>
<div class="tb" id="bJump"><svg viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"><path d="m5 15 7-8 7 8M5 21l7-8 7 8" opacity=".9"/></svg></div>
</div>
<div id="title" class="screen">
<div class="logo"><div class="l1">Бублик</div><div class="l2">и Золотая косточка</div></div>
<div class="panel">
<div class="bankPill"><svg viewBox="-12 -8 24 16"><g id="menuBone"></g></svg><span id="bankN">0</span> костей</div>
<label class="nm">Как зовут твою собаку?<input id="nameIn" maxlength="12" autocomplete="off" spellcheck="false"></label>
<button class="btn" id="playBtn">Играть</button>
<button class="btn blue" id="wardBtn">Гардероб</button>
<div class="row"><button class="btn small blue" id="updBtn">Обновления · v1.2</button><button class="btn small blue" id="setBtn">Настройки</button><button class="btn small blue" id="fsBtn">Во весь экран</button></div>
</div>
</div>
<div id="upd" class="screen hidden"><div class="panel">
<h2>Обновления</h2>
<div class="updBox">
<div class="ver new"><h3>Версия 1.2 <em>новое</em></h3><ul>
<li>Сюжет понятнее: кинематографичные сцены показывают кражу косточки и то, как боссы передают её друг другу прямо перед боем.</li>
<li>Добавлены настройки: звук, музыка, вибрация, полный экран и сброс сохранения.</li>
<li>Гардероб теперь за кости, а не за звёзды. Кости копятся, и их не мало!</li>
<li>Счётчик костей на главном экране и в гардеробе. За каждую собранную косточку начисляется 10.</li>
<li>Боссы стали крепче — прыгать до победы не выйдет!</li>
<li>Дружок после спасения дарит костомагнит, который притягивает кости рядом с тобой.</li>
<li>У каждой части своя музыка.</li>
<li>3 новые части: «Провалившийся путь», «Подземелье Барона» и «Солёное море» — теперь 48 миров и 8 частей.</li>
<li>В 8 части — подводное приключение: без скафандра-шлема там находиться нельзя.</li>
<li>В финале 6-й части 7-й — клетка пуста, пол проваливается. Дальше — подземелье.</li>
<li>На 3-м уровне подземелья экран дрожит. В 6-м ждёт Барон с косточкой в зубах…</li>
<li>Барон превращается в Пса-поедателя и призывает духов прошлых боссов!</li>
<li>После спасения Золотой косточки она появляется у героя на спине — маленькая тайна в главном меню.</li>
</ul></div>
<div class="ver"><h3>Версия 1.1</h3><ul>
<li>Добавлены 2 новые части: «Ледяное царство» и «Страна теней».</li>
<li>5 боссов с разными аренами: Кот-Король, Дракон Жар, Мехакот, Йети Мороз и Тёмный Маг Мурзик.</li>
<li>После победы из сундука выпадает ключ — им открывается клетка с собакой.</li>
<li>5 собак-друзей со своими диалогами: Шарик, Тузик, Дружок, Снежка и Барон.</li>
<li>Новый враг — грибочек, 11 новых тематических миров и новые окрасы.</li>
</ul></div>
<div class="ver"><h3>Версия 1.0 <em style="background:#4aa8ff">первый релиз</em></h3><ul>
<li>Три части и 18 миров с тремя большими звёздами в каждом.</li>
<li>Три босса: Кот-Король, Дракон Жар и Мехакот.</li>
<li>Двойной прыжок, лай «ГАВ», суперсосиска и контрольные точки.</li>
<li>Гардероб: окрасы, шапки, кофты, аксессуары и цвет ошейника.</li>
<li>Сенсорное и клавиатурное управление, звуки и музыка.</li>
</ul></div>
</div>
<button class="btn green" id="updBack">Назад</button>
</div></div>
<div id="set" class="screen hidden"><div class="panel">
<h2>Настройки</h2>
<div class="setBox">
<button class="btn blue" id="setSnd">Звук: вкл</button>
<button class="btn blue" id="setMus">Музыка: вкл</button>
<button class="btn blue" id="setVib">Вибрация: вкл</button>
<button class="btn blue" id="setFs">Во весь экран</button>
<button class="btn red" id="setReset">Стереть сохранение</button>
</div>
<button class="btn green" id="setBack">Готово</button>
</div></div>
<div id="ward" class="screen hidden"><div class="panel wardPanel">
<h2>Гардероб</h2>
<div class="bankPill"><svg viewBox="-12 -8 24 16"><g id="wardBone"></g></svg><span id="wardBankN">0</span> костей</div>
<div class="wardBody">
<div class="pv"><canvas id="pvC" width="220" height="190"></canvas><span>Нажми на собаку — побежит!</span></div>
<div class="wardR"><div class="tabs" id="tabs"></div><div class="opts" id="opts"></div><div id="cols" class="row"></div></div>
</div>
<button class="btn green" id="wardOk">Готово</button>
</div></div>
<div id="map" class="screen hidden">
<h3 class="mapTitle" id="mapTitle"></h3>
<div class="mapSub" id="mapSub"></div>
<div id="mapBox"><svg viewBox="0 0 100 100" preserveAspectRatio="none"><path id="mapPath" fill="none" stroke="rgba(255,255,255,.85)" stroke-width="1.6" stroke-dasharray="3 3" stroke-linecap="round" vector-effect="non-scaling-stroke"/></svg><div id="mapNodes"></div></div>
<div class="dots" id="dots"></div>
<button class="btn small blue" id="mapBack">Назад</button>
<button class="arrow l" id="partPrev" aria-label="Предыдущая часть"><svg viewBox="0 0 24 24" fill="#fff"><path d="M16 3 6 12l10 9z"/></svg></button>
<button class="arrow r" id="partNext" aria-label="Следующая часть"><svg viewBox="0 0 24 24" fill="#fff"><path d="m8 3 10 9-10 9z"/></svg></button>
</div>
<div id="pause" class="screen hidden"><div class="panel"><h2>Пауза</h2>
<button class="btn green" id="pResume">Продолжить</button>
<div class="row"><button class="btn small" id="pRestart">Сначала</button><button class="btn small blue" id="pMap">К карте</button><button class="btn small blue" id="pSnd">Звук</button></div></div></div>
<div id="dlg" class="screen hidden"><div class="panel dlgPanel">
<canvas id="dlgC" width="360" height="170"></canvas>
<div class="dlgR"><div id="dlgName"></div><p id="dlgTxt"></p><button class="btn green" id="dlgNext">Дальше</button></div>
</div></div>
<div id="cut" class="screen hidden">
<canvas id="cutC" width="640" height="300"></canvas>
<div class="panel" id="cutPanel"><div id="cutName">…</div><p id="cutTxt"></p><button class="btn green" id="cutNext">Дальше</button></div>
</div>
<div id="win" class="screen hidden"><div class="panel"><h2 id="winH">Уровень пройден!</h2><div class="big-stars" id="winStars"></div>
<div class="stat" id="winStat"></div><p id="winMsg"></p>
<div class="row"><button class="btn green" id="wNext">Дальше</button><button class="btn small" id="wAgain">Ещё раз</button><button class="btn small blue" id="wMap">К карте</button></div></div></div>
<div id="lose" class="screen hidden"><div class="panel"><h2>Ой, не получилось!</h2><p>Ничего страшного! Продолжим с последней контрольной точки.</p>
<div class="row"><button class="btn green" id="lRetry">Попробовать снова</button><button class="btn small blue" id="lMap">К карте</button></div></div></div>
<div id="rotate"><svg viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="2" width="10" height="20" rx="2.5"/><path d="M11 18h2"/></svg>Поверни телефон набок,
чтобы играть!</div>
<script>
'use strict';
const TILE=32,ROWS=12,VH=384,STEP=1/90,TAU=Math.PI*2;
const $=id=>document.getElementById(id);
const cvs=$('c');let ctx=cvs.getContext('2d');
let VW=683,SC=1;
const clamp=(v,a,b)=>Math.max(a,Math.min(b,v));
const lerp=(a,b,t)=>a+(b-a)*t;
function hash(n){n=n|0;n=Math.imul((n^61)^(n>>>16),9);n^=n>>>4;n=Math.imul(n,0x27d4eb2d);n^=n>>>15;return n>>>0}
function mkRng(s){return()=>{s|=0;s=s+0x6D2B79F5|0;let t=Math.imul(s^s>>>15,1|s);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296}}
const BONE_VALUE=10;
let save={name:'Бублик',skin:0,hat:0,shirt:0,face:0,collar:0,hatC:-1,shirtC:-1,cBody:'#e39a42',cEar:'#a8601f',unlocked:0,stars:{},sound:true,music:true,vibe:true,story:false,dogs:[],bank:120,owned:[],magnet:false,bone:false};
try{const old=JSON.parse(localStorage.getItem('bublik-v2')||localStorage.getItem('bublik-v1')||'{}');Object.assign(save,old);if(!Array.isArray(save.dogs))save.dogs=[];if(save.bank===undefined)save.bank=120;if(!Array.isArray(save.owned))save.owned=[]}catch(e){}
const persist=()=>{try{localStorage.setItem('bublik-v2',JSON.stringify(save))}catch(e){}};
const vib=ms=>{try{if(save.vibe&&navigator.vibrate)navigator.vibrate(ms)}catch(e){}};
/* ---------- тематика миров ---------- */
const THEMES={
meadow:{sky:['#7cc8ff','#e6f8ff'],sun:'#fff6b0',cloud:1,d1:'round',d2:'tree',far:'#a9dfae',mid:'#77c97c',grass:'#62c85a',grass2:'#46a94a',dirt:'#a3703f',dirt2:'#85582f',plank:'#d79a58',plank2:'#a56d34',spike:'#a8b0c0',node:'#62c85a'},
forest:{sky:['#1f5d57','#a8dba0'],sun:'#e8ffd0',d1:'pine',d2:'pine',far:'#2f7d63',mid:'#1f6149',grass:'#4fa04a',grass2:'#397d3b',dirt:'#6e4a2c',dirt2:'#573820',plank:'#b98450',plank2:'#8a5c32',spike:'#7a4a2a',node:'#3f9a62'},
beach:{sky:['#4cc2ff','#fff1c9'],sun:'#fff2a0',cloud:1,sea:1,d1:'palm',d2:'round',far:'#67d1d8',mid:'#f2d58d',grass:'#f8dc8b',grass2:'#e8c26d',dirt:'#dba95e',dirt2:'#c18c45',plank:'#e0a768',plank2:'#b57b3c',spike:'#8a8ea0',node:'#f2b84c'},
snow:{sky:['#8fb4f0','#f2f8ff'],sun:'#ffffff',cloud:1,snow:1,d1:'peak',d2:'pine',far:'#b6cdf0',mid:'#8fb0d8',grass:'#ffffff',grass2:'#d3e6fa',dirt:'#7b9cc4',dirt2:'#5f80aa',plank:'#bfe4ff',plank2:'#86bfe8',spike:'#9fe4ff',node:'#7ec8ff'},
cave:{sky:['#150b30','#3d2370'],d1:'stal',d2:'crys',far:'#2b1a55',mid:'#3a2672',grass:'#8f7df0',grass2:'#6b59cf',dirt:'#4b3a86',dirt2:'#392b6b',plank:'#7a6fd0',plank2:'#5649a8',spike:'#ff6ec7',dark:1,node:'#9b7cff'},
castle:{sky:['#1b1250','#a14fae'],sun:'#fff0c9',stars:1,d1:'tower',d2:'round',far:'#3c2670',mid:'#2c1b56',grass:'#bba6ea',grass2:'#8f7ac9',dirt:'#5c4a8a',dirt2:'#463670',plank:'#9d8bd8',plank2:'#6f5db0',spike:'#d9d9ee',node:'#e86bc2'},
/* часть 2 */
desert:{sky:['#ffb35c','#fff0c0'],sun:'#fffbd0',d1:'dune',d2:'cactus',far:'#e8b86a',mid:'#d49c4f',grass:'#f3cf7a',grass2:'#dcb257',dirt:'#c68a48',dirt2:'#a86f33',plank:'#c9955a',plank2:'#9a6a34',spike:'#7a8a50',node:'#f0a43c'},
jungle:{sky:['#2e8b57','#c8f0a0'],sun:'#f4ffc8',cloud:1,d1:'palm',d2:'tree',far:'#2c8a4c',mid:'#1f6d3a',grass:'#3fb54a',grass2:'#2a8f36',dirt:'#7a4f2a',dirt2:'#5e3a1c',plank:'#b98450',plank2:'#8a5c32',spike:'#6a4a2a',node:'#2faa55'},
swamp:{sky:['#3b4a2f','#b7c98a'],d1:'tree',d2:'pine',far:'#4d5f3a',mid:'#3a4a2c',grass:'#7ca43c',grass2:'#5f8a2c',dirt:'#5a4a2a',dirt2:'#463820',plank:'#9a7a4a',plank2:'#6e5430',spike:'#b6e04a',node:'#8cb040'},
volcano:{sky:['#2a0a0a','#ff7a30'],ember:1,d1:'volc',d2:'round',far:'#4a1a14',mid:'#36110e',grass:'#8a4a3a',grass2:'#ff6a20',dirt:'#3e2420',dirt2:'#2e1a16',plank:'#8a6a5a',plank2:'#5a4036',spike:'#ff5a20',node:'#ff6a30'},
ruins:{sky:['#5a3a7a','#ffd29a'],sun:'#fff0c0',d1:'tower',d2:'round',far:'#6a4a7a',mid:'#523a66',grass:'#d8c08a',grass2:'#b89c64',dirt:'#8a7050',dirt2:'#6e5a40',plank:'#c8aa70',plank2:'#9a8050',spike:'#c0c0d0',node:'#c08a5a'},
lair:{sky:['#1a0505','#7a1a10'],ember:1,d1:'volc',d2:'stal',far:'#3a0f0c',mid:'#2a0a08',grass:'#9a5a4a',grass2:'#ff6a20',dirt:'#4a2420',dirt2:'#331816',plank:'#7a5a50',plank2:'#4a3430',spike:'#ff4a20',node:'#e8402a'},
/* часть 3 */
sky:{sky:['#5fb0ff','#ffffff'],sun:'#fff6b0',cloud:1,d1:'round',d2:'round',far:'#d8ecff',mid:'#b8d8f8',grass:'#8ae68a',grass2:'#5cc45c',dirt:'#e8e0f0',dirt2:'#c8c0d8',plank:'#ffffff',plank2:'#b8c8e8',spike:'#8aa0c8',node:'#5fb0ff'},
candy:{sky:['#ff9ad5','#fff0fa'],sun:'#fff6b0',cloud:1,d1:'lolli',d2:'round',far:'#ffc0e0',mid:'#ff9ad0',grass:'#7be0c3',grass2:'#4cc4a4',dirt:'#c07a50',dirt2:'#8a5230',plank:'#ffd0e8',plank2:'#e078b0',spike:'#ff3a7a',node:'#ff6ab8'},
space:{sky:['#02020a','#2a2a6a'],stars:1,d1:'planet',d2:'crys',far:'#4a4a8a',mid:'#1c1c44',grass:'#b8b8d0',grass2:'#8888a8',dirt:'#5a5a78',dirt2:'#444460',plank:'#8aa0c8',plank2:'#5a6a98',spike:'#ff5a5a',node:'#7a7aff'},
factory:{sky:['#2a3040','#6a7a90'],d1:'gear',d2:'tower',far:'#4a5468',mid:'#38425a',grass:'#8a98b0',grass2:'#ffb020',dirt:'#4a5266',dirt2:'#363c4e',plank:'#a0aab8',plank2:'#6a7488',spike:'#ffcc20',node:'#8a98b8'},
neon:{sky:['#0a0030','#ff2a9a'],stars:1,d1:'city',d2:'city',far:'#2a1060',mid:'#1a0848',grass:'#2affd0',grass2:'#10a090',dirt:'#2a2060',dirt2:'#1e1648',plank:'#7a5aff',plank2:'#4a2ac0',spike:'#ff2a9a',node:'#ff2ad0'},
lab:{sky:['#10001a','#3a1060'],stars:1,d1:'city',d2:'gear',far:'#2a1850',mid:'#1c0f3a',grass:'#c0c8e0',grass2:'#ff3a5a',dirt:'#3a3a58',dirt2:'#2a2a44',plank:'#8aa0c8',plank2:'#566690',spike:'#ff3a5a',node:'#ff3a5a'},
/* часть 4 */
tundra:{sky:['#6aa8e8','#eef8ff'],sun:'#ffffff',cloud:1,snow:1,d1:'peak',d2:'pine',far:'#a9cdf0',mid:'#7aa8d8',grass:'#ffffff',grass2:'#d3e6fa',dirt:'#7b9cc4',dirt2:'#5f80aa',plank:'#bfe4ff',plank2:'#86bfe8',spike:'#9fe4ff',node:'#8ad0ff'},
glacier:{sky:['#2f7fd0','#c4f2ff'],sun:'#ffffff',cloud:1,d1:'peak',d2:'crys',far:'#8fd0f0',mid:'#5aa8d8',grass:'#e0fbff',grass2:'#a8e4f4',dirt:'#5a9ac8',dirt2:'#437fae',plank:'#c8f0ff',plank2:'#7ac0e8',spike:'#d8fbff',node:'#5ac8f0'},
aurora:{sky:['#07123a','#2affb0'],stars:1,d1:'peak',d2:'pine',far:'#1d4a7a',mid:'#143a64',grass:'#cfeeff',grass2:'#8ad0e8',dirt:'#3a5a9a',dirt2:'#2c4680',plank:'#bfe4ff',plank2:'#7aa8d8',spike:'#2affb0',node:'#2affb0'},
blizzard:{sky:['#7f90b0','#e4ecf8'],cloud:1,snow:1,d1:'peak',d2:'pine',far:'#a8b8d8',mid:'#8898b8',grass:'#eef4fc',grass2:'#c0d2ec',dirt:'#8898c0',dirt2:'#6675a0',plank:'#cfe0f4',plank2:'#8ba3c8',spike:'#cfe8ff',node:'#aab8d8'},
icepalace:{sky:['#2a3a8a','#c0dcff'],d1:'tower',d2:'crys',far:'#6a82c8',mid:'#4a62a8',grass:'#eaf8ff',grass2:'#b8dcf4',dirt:'#6a8ac8',dirt2:'#4e6eac',plank:'#d8f0ff',plank2:'#88b0e0',spike:'#ffffff',node:'#9ac0ff'},
yeti:{sky:['#0d1636','#5a8ac8'],sun:null,cloud:0,stars:1,snow:1,d1:'peak',d2:'stal',far:'#27406e',mid:'#1c3058',grass:'#ffffff',grass2:'#cfe4ff',dirt:'#4a6a9a',dirt2:'#385582',plank:'#bfe4ff',plank2:'#7aa8d0',spike:'#d8fbff',node:'#e8402a'},
/* часть 5 */
mush:{sky:['#3a1a5a','#e0a0e8'],cloud:1,d1:'mush',d2:'mush',far:'#7a3a9a',mid:'#5a2a7a',grass:'#b070e8',grass2:'#8a4ac8',dirt:'#5a3a6a',dirt2:'#44285a',plank:'#d8a0f0',plank2:'#9a60c0',spike:'#ff6ab8',node:'#b070e8'},
haunt:{sky:['#150a28','#4a2a60'],stars:1,d1:'tower',d2:'tree',far:'#2a1850',mid:'#1c0f3a',grass:'#7a8a6a',grass2:'#5a6a4c',dirt:'#3a3048',dirt2:'#2a2238',plank:'#8a7a6a',plank2:'#5a4c40',spike:'#c0c0d0',dark:1,node:'#7a5ac8'},
storm:{sky:['#1a2030','#6a7a98'],cloud:1,d1:'peak',d2:'pine',far:'#4a566e',mid:'#38425a',grass:'#6a9a6a',grass2:'#4a7a4c',dirt:'#5a5a6a',dirt2:'#44445a',plank:'#9a9ab0',plank2:'#6a6a88',spike:'#ffe040',node:'#6a7a98'},
clock:{sky:['#3a2412','#e0b068'],sun:'#fff0c0',d1:'gear',d2:'tower',far:'#8a6a44',mid:'#6a4e32',grass:'#c8a060',grass2:'#a07e44',dirt:'#6a4a2c',dirt2:'#503820',plank:'#d0aa70',plank2:'#9a7840',spike:'#c0c0d0',node:'#d0a050'},
dark:{sky:['#000010','#2a0a4a'],stars:1,d1:'crys',d2:'stal',far:'#241040',mid:'#180a30',grass:'#6a4ab0',grass2:'#4a2a90',dirt:'#2a2050',dirt2:'#1c1638',plank:'#6a5aa8',plank2:'#443a80',spike:'#c050ff',node:'#7a3ac0'},
wiz:{sky:['#0a0020','#8a1ab0'],stars:1,ember:1,d1:'tower',d2:'crys',far:'#2a0a50',mid:'#1a0638',grass:'#c050ff',grass2:'#8a2ad0',dirt:'#2a1450',dirt2:'#1c0c38',plank:'#9a70e0',plank2:'#6a40b0',spike:'#ff40a0',node:'#c050ff'},
/* часть 6 */
bridge:{sky:['#5a4a2a','#e8cf9a'],sun:'#fff0c0',d1:'tower',d2:'dune',far:'#7a6240',mid:'#5c4930',grass:'#c8b070',grass2:'#a08a4c',dirt:'#6e5432',dirt2:'#503c24',plank:'#a87e48',plank2:'#785830',spike:'#b0b8c8',node:'#c8a050'},
pass:{sky:['#ff9a50','#ffe8b0'],sun:'#fffbd0',d1:'dune',d2:'cactus',far:'#d8a060',mid:'#b87f44',grass:'#ecd080',grass2:'#c8a858',dirt:'#b87f44',dirt2:'#946432',plank:'#c89458',plank2:'#96703c',spike:'#8a9a50',node:'#f0b040'},
ravine:{sky:['#333f2c','#a8b86a'],d1:'tree',d2:'pine',far:'#46553a',mid:'#33402c',grass:'#78903c',grass2:'#5a702c',dirt:'#54452a',dirt2:'#403622',plank:'#8f7040',plank2:'#645030',spike:'#a4d03a',node:'#7c9a30'},
road6:{sky:['#101a34','#584a7a'],stars:1,d1:'tower',d2:'pine',far:'#2a3050',mid:'#1d2338',grass:'#6a7488',grass2:'#4a5268',dirt:'#3a4054',dirt2:'#2c3144',plank:'#6a7488',plank2:'#4a5268',spike:'#8890a8',node:'#584a8a'},
barong:{sky:['#140a20','#3a2438'],stars:1,d1:'tower',d2:'stal',far:'#241a30',mid:'#181020',grass:'#5a4a5a',grass2:'#403040',dirt:'#241a28',dirt2:'#181020',plank:'#4a3a48',plank2:'#332838',spike:'#9a70c0',dark:1,node:'#7a5080'},
cell:{sky:['#3a2a1a','#8a6a44'],sun:'#ffe8b0',d1:'tower',d2:'round',far:'#554030',mid:'#3e2f22',grass:'#a8905c',grass2:'#887040',dirt:'#554030',dirt2:'#3e2f22',plank:'#8a6a3a',plank2:'#645028',spike:'#c0c0d0',node:'#c8a050'},
/* часть 7 */
descent:{sky:['#0e0722','#2c1a4a'],d1:'stal',d2:'crys',far:'#241543',mid:'#170d33',grass:'#7a68d0',grass2:'#584a9a',dirt:'#3a2c64',dirt2:'#291e4c',plank:'#6a5ab0',plank2:'#4a3e80',spike:'#b050ff',dark:1,node:'#7a68d0'},
maw:{sky:['#1a0a08','#462014'],ember:1,d1:'volc',d2:'stal',far:'#2c1512',mid:'#1f0f0c',grass:'#7a4836',grass2:'#c85620',dirt:'#331f1a',dirt2:'#241512',plank:'#5f4034',plank2:'#463028',spike:'#ff5a20',node:'#c85620'},
deep7:{sky:['#080416','#1e1236'],d1:'stal',d2:'crys',far:'#170e2c',mid:'#0f0820',grass:'#584a9a',grass2:'#403468',dirt:'#241a42',dirt2:'#181026',plank:'#4a3e80',plank2:'#322848',spike:'#8a5aff',dark:1,node:'#5a4ab0'},
corridor:{sky:['#000000','#170a2a'],stars:1,d1:'crys',d2:'stal',far:'#100820',mid:'#080410',grass:'#463262',grass2:'#302144',dirt:'#181026',dirt2:'#0e0818',plank:'#322850',plank2:'#201838',spike:'#c050ff',node:'#463262'},
portal:{sky:['#0a0020','#40105a'],ember:1,stars:1,d1:'tower',d2:'crys',far:'#1a0638',mid:'#10041f',grass:'#7a3ad0',grass2:'#50259a',dirt:'#20103c',dirt2:'#150a26',plank:'#503080',plank2:'#382454',spike:'#ff40a0',node:'#903ad0'},
baronlair:{sky:['#140018','#60102a'],ember:1,stars:1,d1:'tower',d2:'crys',far:'#240a26',mid:'#180418',grass:'#8a2a4a',grass2:'#ff5a3a',dirt:'#30122a',dirt2:'#1f0c1c',plank:'#542838',plank2:'#38202a',spike:'#ff3a70',node:'#c02040'},
/* часть 8: подводные */
reef:{sky:['#0e4a80','#3aa0d8'],uw:1,d1:'coral',d2:'stal',far:'#1e6a9a',mid:'#124a70',grass:'#3ac8b0',grass2:'#24908a',dirt:'#1a4a68',dirt2:'#123349',plank:'#c8a05a',plank2:'#8a6a34',spike:'#ff6a9a',node:'#3ac8b0'},
lagoon:{sky:['#146a9a','#5ac8e0'],uw:1,d1:'coral',d2:'crys',far:'#2a8ab0',mid:'#1c5f80',grass:'#ffd86a',grass2:'#d8a840',dirt:'#2a6a88',dirt2:'#1c4860',plank:'#e0c080',plank2:'#a8844a',spike:'#ff8a6a',node:'#5ad0e0'},
shipwrack:{sky:['#0a2a44','#2a5a80'],uw:1,d1:'stal',d2:'gear',far:'#123048',mid:'#0c2030',grass:'#6a9ac0',grass2:'#46709a',dirt:'#16324a',dirt2:'#0e2233',plank:'#7a5a3a',plank2:'#4e3822',spike:'#9ac0d8',node:'#4a7a9a'},
kelp:{sky:['#0c3a2a','#2a7a4a'],uw:1,d1:'tree',d2:'mush',far:'#1c5f3a',mid:'#12482a',grass:'#3aa06a',grass2:'#24704a',dirt:'#14402a',dirt2:'#0d2a1c',plank:'#8a7a4a',plank2:'#5a5030',spike:'#a0e070',node:'#3aa06a'},
deep8:{sky:['#050a20','#141c40'],uw:1,stars:1,d1:'crys',d2:'stal',far:'#141c40',mid:'#0d1330',grass:'#4a5a9a',grass2:'#303c6a',dirt:'#0e1430',dirt2:'#080d20',plank:'#3a4a78',plank2:'#26305a',spike:'#6a9aff',node:'#3a4a9a'},
trench:{sky:['#020208','#100a24'],uw:1,stars:1,d1:'stal',d2:'crys',far:'#0c0820',mid:'#060412',grass:'#302050',grass2:'#20143a',dirt:'#0a0718',dirt2:'#050310',plank:'#241a44',plank2:'#161030',spike:'#8a5aff',node:'#2a1a50'}
};
const PARTS=[
{n:'Часть 1',t:'Королевство котов',bg:'meadow'},
{n:'Часть 2',t:'Огненные земли',bg:'desert'},
{n:'Часть 3',t:'Космос и конфеты',bg:'candy'},
{n:'Часть 4',t:'Ледяное царство',bg:'tundra'},
{n:'Часть 5',t:'Страна теней',bg:'mush'},
{n:'Часть 6',t:'Провалившийся путь',bg:'bridge'},
{n:'Часть 7',t:'Подземелье Барона',bg:'descent'},
{n:'Часть 8',t:'Солёное море',bg:'reef'}
];
const BOSSES={
king:{hp:6,spd:55,thr:2.8,name:'Кот-Король!',hint:'Прыгай ему на голову!'},
dragon:{hp:7,spd:50,thr:2.5,name:'Дракон Жар!',hint:'Уворачивайся от огня и не наступай на шипы!'},
robot:{hp:8,spd:62,thr:2.2,name:'Мехакот!',hint:'Перепрыгивай лазеры и бей сверху!'},
yeti:{hp:8,spd:48,thr:2.4,name:'Йети Мороз!',hint:'Лёд скользкий! Берегись снежков и ледяных волн!'},
wizard:{hp:10,spd:58,thr:2.0,name:'Тёмный Маг Мурзик!',hint:'Он телепортируется! Уворачивайся от шаров!'},
eater:{hp:14,spd:64,thr:1.8,name:'Пёс-поедатель!',hint:'Он пожирает всё вокруг! Прыгай ему на голову!'}
};
const PART_THEMES={0:[262,0],1:[247,0],2:[330,0],3:[220,1],4:[294,1],5:[233,1],6:[165,1],7:[349,0]};
const SCALE_MAJ=[0,2,4,7,9,12,14,16],SCALE_MIN=[0,2,3,7,9,12,14,16];
/* ---------- собаки-друзья ---------- */
const DOGS=[
{n:'Шарик',S:{body:'#d9822b',belly:'#f7dfb0',ear:'#8a4414'},hat:2,hatCol:'#e8344c',collar:'#4aa8ff',talk:[
['d','Гав-гав! Свобода! Я уже думал, что просижу в этой клетке до самого праздника!'],
['p','Ты цел, Шарик? Не бойся, теперь всё хорошо!'],
['d','Спасибо, {n}! Нас, пятерых друзей, заперли в клетках, а ключи отдали пяти главным злодеям.'],
['d','Кот-Король хвастался, что Золотую косточку унёс дракон в Огненные земли. Будь осторожна!'],
['p','Не переживай. Я освобожу всех и верну косточку!'],
['d','Я побегу домой и расскажу всем, что ты настоящий герой! Удачи!']]},
{n:'Тузик',S:{body:'#f3efe4',belly:'#ffffff',ear:'#3b3b44',spots:'#3b3b44'},hat:5,hatCol:'#ffffff',shirt:2,face:4,collar:'#e8344c',talk:[
['d','Тс-с-с... Он ушёл? Фух! Я хотел его укусить, но он как дыхнёт огнём — гав!'],
['p','Дракон Жар больше никого не напугает, Тузик.'],
['d','Ты так здорово прыгаешь! Слушай: я слышал, как дракон говорил, что отдал косточку Мехакоту.'],
['d','Это огромный железный кот. Он живёт далеко — там, где конфеты растут прямо из земли, а в небе светит Луна.'],
['p','Тогда мне в космос и в конфетную страну! Ждите меня!'],
['d','А я испеку тебе печенье в форме косточки! Гав!']]},
{n:'Дружок',S:{body:'#3a3a48',belly:'#9a9aae',ear:'#22222c'},hat:2,hatCol:'#ffd93d',shirt:3,shirtCol:'#43c767',face:1,collar:'#ff8a3d',talk:[
['d','Наконец-то! Замок на этой клетке сделан очень плохо, я бы починил его за пять минут. Но у меня не было инструментов.'],
['p','Ты очень умный, Дружок!'],
['d','Спасибо! Слушай внимательно: Мехакот был лишь исполнителем. Золотую косточку он передал Йети, который живёт во льдах.'],
['d','А вот и сюрприз самому себе: я собрал для тебя костомагнит! Он притягивает кости, если ты рядом с ними. Носи с собой!'],
['d','И не забывай: Йети обожает скользкий лёд. Тормози заранее!'],
['p','Спасибо, Дружок! Костоманит очень кстати.',1],
['d','Беги, {n}! А я пока придумаю для тебя новые гаджеты. Гав-гав!']]},
{n:'Снежка',S:{body:'#f6f3ec',belly:'#ffffff',ear:'#c4bcae'},hat:3,hatCol:'#4aa8ff',face:5,collar:'#4aa8ff',talk:[
['d','Бр-р-р! Я так замёрзла в этой клетке... Спасибо тебе, {n}!'],
['p','Йети побеждён. Ты знаешь, где Золотая косточка?'],
['d','Йети лишь охранял её по чужому приказу. Косточку забрал Тёмный Маг по имени Мурзик.'],
['d','Он живёт в Стране теней. Там светятся грибы, а в домах прячутся привидения. Маг колдует магическими шарами!'],
['p','Я не боюсь. С вами, друзья, мне ничего не страшно!'],
['d','Оставлю тебе свой тёплый шарфик на удачу. Беги, {n}!']]},
{n:'Барон',S:{body:'#f2c84b',belly:'#fff0b8',ear:'#c28a12'},hat:8,hatCol:'#ffd93d',shirt:6,shirtCol:'#e8344c',face:6,collar:'#e8344c',talk:[
['d','Ах, {n}! Я знал, что ты придёшь. Наконец-то меня выпустили из этой клетки!'],
['p','Барон! Тёмный Маг побеждён. А где же Золотая косточка?'],
['d','Мурзик заколдовал её и спрятал прямо у меня в клетке. Она всё время была рядом. Держи!',1],
['d','Смотри, как она сияет! Золотая косточка снова с нами!',1],
['p','Мы справились! Все пятеро друзей на свободе!'],
['d','Теперь можно устроить настоящий праздник Большой Косточки! Ты — наша героиня, {n}!']]}
];
const dogOutfit=d=>({S:d.S,hat:d.hat||0,hatCol:d.hatCol||null,shirt:d.shirt||0,shirtCol:d.shirtCol||null,face:d.face||0,collar:d.collar||'#e8344c'});
/* ---------- уровни ---------- */
const EN={cat:{w:26,h:22,sp:45,stomp:1},hedgehog:{w:26,h:18,sp:36,stomp:0},crab:{w:28,h:18,sp:62,stomp:1},snowman:{w:26,h:34,sp:30,stomp:1},bee:{w:22,h:18,sp:1.6,stomp:1,fly:1},bird:{w:24,h:18,sp:1.2,stomp:1,fly:1},bat:{w:26,h:16,sp:1.3,stomp:1,fly:1},
scorpion:{w:28,h:18,sp:44,stomp:0},slime:{w:26,h:20,sp:34,stomp:1},robot:{w:26,h:30,sp:50,stomp:1},ufo:{w:30,h:18,sp:1.4,stomp:1,fly:1},ghost:{w:24,h:26,sp:1,stomp:1,fly:1},
shroom:{w:26,h:22,sp:40,stomp:1}};
const POOL_A={flat:1,gap:3,enemies:3,crates:1,hills:2,flyers:2,spikes:2,moverGap:2,crumble:1,highroad:1};
const POOL_B={flat:1,gap:2,enemies:3,crates:1,hills:1,flyers:3,spikes:2,moverGap:2,crumble:2,highroad:1};
const LEVELS=[
/* ЧАСТЬ 1 */
{id:'meadow',name:'Солнечный луг',n:12,seed:7,en:['cat'],fly:['bee'],intro:1,pool:{flat:2,gap:3,enemies:3,crates:2,hills:2,flyers:1},
tips:{gap:'Прыгай через ямы! Нажми прыжок ещё раз в воздухе — получится двойной прыжок.',crates:'Нажми ГАВ — ящик разлетится, а внутри косточки!',enemies:'Прыгни коту на голову или гавкни — и он испугается!'}},
{id:'forest',name:'Шепчущий лес',n:15,seed:21,en:['hedgehog','cat'],fly:['bee'],pool:{flat:1,gap:2,enemies:3,crates:1,hills:2,flyers:2,spikes:2,moverGap:1,highroad:1},
tips:{spikes:'Колючки! Прыгай через них.',moverGap:'Запрыгни на плывущую доску.',enemies:'Ёжика нельзя прыгать сверху. Гавкни — он перевернётся, потом дотронься!'}},
{id:'beach',name:'Пляж Ракушек',n:16,seed:33,en:['crab'],fly:['bird'],pool:{flat:1,gap:3,enemies:3,crates:1,hills:1,flyers:2,spikes:1,moverGap:2,crumble:1,highroad:1},
tips:{crumble:'Эти плиты падают, если стоять долго. Прыгай быстро!',springStar:'Батут подбросит тебя высоко!'}},
{id:'snow',name:'Снежные горы',n:17,seed:45,en:['snowman','hedgehog'],fly:['bird'],ice:1,pool:{flat:1,gap:3,enemies:3,crates:1,hills:2,flyers:1,spikes:2,moverGap:1,crumble:1,highroad:1},
tips:{flat:'Лёд скользкий! Тормози заранее.'}},
{id:'cave',name:'Кристальная пещера',n:18,seed:58,en:['cat','hedgehog'],fly:['bat'],pool:{flat:1,gap:2,enemies:3,crates:1,hills:1,flyers:3,spikes:2,moverGap:2,crumble:2,highroad:1},
tips:{flyers:'Летучие мыши пикируют на тебя. Гавкни, чтобы прогнать!'}},
{id:'castle',name:'Замок Кота-Короля',n:14,seed:77,en:['cat','hedgehog','snowman'],fly:['bat','bird'],boss:'king',cut:'hand_king',pool:{flat:1,gap:2,enemies:3,crates:1,hills:1,flyers:2,spikes:2,moverGap:2,crumble:2,highroad:1}},
/* ЧАСТЬ 2 */
{id:'desert',name:'Жаркая пустыня',n:17,seed:101,en:['scorpion','cat'],fly:['bird'],pool:{flat:1,gap:3,enemies:3,crates:1,hills:2,flyers:1,spikes:2,moverGap:1,crumble:1,highroad:1},
tips:{spikes:'Кактусы колются! Перепрыгивай их.',enemies:'Скорпиона нельзя прыгать сверху. Гавкни — и он перевернётся!'}},
{id:'jungle',name:'Дикие джунгли',n:18,seed:113,en:['slime','scorpion'],fly:['bee'],pool:{flat:1,gap:3,enemies:3,crates:1,hills:2,flyers:2,spikes:2,moverGap:2,crumble:1,highroad:1},
tips:{enemies:'Слизни мягкие — прыгай им на голову!'}},
{id:'swamp',name:'Туманное болото',n:18,seed:127,en:['slime','hedgehog'],fly:['ghost','bee'],pool:{flat:1,gap:2,enemies:3,crates:1,hills:1,flyers:3,spikes:2,moverGap:2,crumble:2,highroad:1},
tips:{flyers:'Привидения плавают в тумане. Гавкни — и они исчезнут!'}},
{id:'volcano',name:'Вулкан Жар-гора',n:19,seed:139,en:['slime','scorpion'],fly:['bat'],pool:{flat:1,gap:2,enemies:3,crates:1,hills:1,flyers:2,spikes:3,moverGap:2,crumble:2,highroad:1},
tips:{crumble:'Горячие камни рассыпаются — не стой на месте!'}},
{id:'ruins',name:'Древние руины',n:19,seed:151,en:['scorpion','cat','slime'],fly:['ghost','bat'],pool:{flat:1,gap:2,enemies:3,crates:1,hills:1,flyers:3,spikes:2,moverGap:2,crumble:2,highroad:1}},
{id:'lair',name:'Логово Дракона',n:14,seed:163,en:['scorpion','slime','cat'],fly:['bat','ghost'],boss:'dragon',cut:'hand_dragon',pool:POOL_A},
/* ЧАСТЬ 3 */
{id:'sky',name:'Облачные острова',n:18,seed:177,en:['cat','hedgehog'],fly:['bird'],pool:{flat:1,gap:3,enemies:3,crates:1,hills:2,flyers:2,spikes:1,moverGap:3,crumble:2,highroad:1},
tips:{moverGap:'Облачка плывут туда-сюда. Прыгай, когда они рядом!'}},
{id:'candy',name:'Конфетная страна',n:18,seed:191,en:['slime','hedgehog'],fly:['bee'],pool:{flat:1,gap:3,enemies:3,crates:2,hills:2,flyers:2,spikes:2,moverGap:1,crumble:1,highroad:1}},
{id:'space',name:'Лунная база',n:19,seed:203,en:['robot','scorpion'],fly:['ufo'],lowg:1,pool:{flat:1,gap:3,enemies:3,crates:1,hills:2,flyers:2,spikes:2,moverGap:2,crumble:1,highroad:1},
tips:{flat:'Здесь слабая гравитация — прыжки получаются выше!'}},
{id:'factory',name:'Завод роботов',n:19,seed:217,en:['robot','hedgehog'],fly:['ufo','bat'],pool:{flat:1,gap:2,enemies:3,crates:1,hills:1,flyers:2,spikes:3,moverGap:2,crumble:2,highroad:1},
tips:{enemies:'Роботов можно прыгать сверху!'}},
{id:'neon',name:'Неоновый город',n:20,seed:229,en:['robot','slime','cat'],fly:['ufo','ghost'],pool:{flat:1,gap:2,enemies:3,crates:1,hills:1,flyers:3,spikes:2,moverGap:2,crumble:2,highroad:1}},
{id:'lab',name:'Лаборатория Мехакота',n:15,seed:241,en:['robot','scorpion','slime'],fly:['ufo','bat'],boss:'robot',cut:'hand_robot',pool:POOL_A},
/* ЧАСТЬ 4 */
{id:'tundra',name:'Ледяная тундра',n:18,seed:257,en:['snowman','hedgehog'],fly:['bird'],pool:{flat:1,gap:3,enemies:3,crates:1,hills:2,flyers:2,spikes:2,moverGap:1,crumble:1,highroad:1}},
{id:'glacier',name:'Скользкий ледник',n:18,seed:269,en:['snowman','cat'],fly:['bat'],ice:1,pool:{flat:2,gap:3,enemies:3,crates:1,hills:2,flyers:1,spikes:2,moverGap:2,crumble:1,highroad:1},
tips:{flat:'Ледник очень скользкий! Тормози заранее и прыгай с запасом.'}},
{id:'aurora',name:'Северное сияние',n:19,seed:281,en:['snowman','hedgehog','robot'],fly:['bird','ufo'],pool:POOL_A},
{id:'blizzard',name:'Ледяная метель',n:19,seed:293,en:['snowman','robot'],fly:['bat','bird'],ice:1,pool:{flat:1,gap:2,enemies:3,crates:1,hills:1,flyers:3,spikes:3,moverGap:2,crumble:2,highroad:1}},
{id:'icepalace',name:'Ледяной дворец',n:20,seed:307,en:['snowman','hedgehog','robot'],fly:['bat','ufo'],ice:1,pool:POOL_B},
{id:'yeti',name:'Пещера Йети',n:14,seed:311,en:['snowman','hedgehog','robot'],fly:['bat','bird'],ice:1,boss:'yeti',cut:'hand_yeti',pool:POOL_A},
/* ЧАСТЬ 5 */
{id:'mush',name:'Грибная роща',n:18,seed:331,en:['shroom','slime'],fly:['bee'],pool:{flat:1,gap:3,enemies:3,crates:2,hills:2,flyers:2,spikes:1,moverGap:2,crumble:1,highroad:1},
tips:{enemies:'Грибочки мягкие — прыгай им на шляпку!'}},
{id:'haunt',name:'Дом с привидениями',n:19,seed:347,en:['cat','shroom'],fly:['ghost','bat'],pool:POOL_B,
tips:{flyers:'В доме темно! Видно только вокруг тебя — ищи косточки поближе.'}},
{id:'storm',name:'Грозовые утёсы',n:19,seed:353,en:['shroom','hedgehog','cat'],fly:['bird','bat'],pool:POOL_A},
{id:'clock',name:'Часовая башня',n:20,seed:367,en:['robot','shroom'],fly:['ufo','ghost'],pool:POOL_B},
{id:'dark',name:'Тёмный лес',n:20,seed:379,en:['shroom','slime','cat'],fly:['ghost','bat'],pool:POOL_B},
{id:'wiz',name:'Башня Тёмного Мага',n:15,seed:383,en:['shroom','robot','scorpion'],fly:['ghost','ufo'],boss:'wizard',cut:'hand_wizard',pool:POOL_A},
/* ЧАСТЬ 6: дорога к Барону */
{id:'bridge',name:'Старый мост',n:16,seed:401,en:['cat','scorpion'],fly:['bird'],pool:{flat:1,gap:3,enemies:3,crates:1,hills:2,flyers:2,spikes:2,moverGap:3,crumble:1,highroad:1}},
{id:'pass',name:'Жаркий перевал',n:17,seed:413,en:['scorpion','cat'],fly:['bird','bat'],pool:{flat:1,gap:3,enemies:3,crates:1,hills:2,flyers:2,spikes:2,moverGap:2,crumble:2,highroad:1}},
{id:'ravine',name:'Овраг тишины',n:17,seed:421,en:['slime','hedgehog'],fly:['ghost','bat'],pool:POOL_A},
{id:'road6',name:'Дорога теней',n:18,seed:433,en:['robot','shroom'],fly:['ufo','ghost'],pool:POOL_B},
{id:'barong',name:'Гора Барона',n:18,seed:445,en:['shroom','cat','robot'],fly:['bat','ghost'],pool:POOL_B,
tips:{flat:'Воздух дрожит... Кажется, где-то рядом прячется плохое.'}},
{id:'cell',name:'Пустая клетка',n:1,seed:451,en:[],fly:[],script:'empty',ending:'collapse',pool:{flat:1}},
/* ЧАСТЬ 7: подземелье */
{id:'descent',name:'Спуск вниз',n:17,seed:461,en:['shroom','robot'],fly:['bat'],pool:POOL_A},
{id:'maw',name:'Каменные глотки',n:18,seed:473,en:['scorpion','shroom'],fly:['bat','ghost'],pool:POOL_B},
{id:'deep7',name:'Где-то глубоко',n:18,seed:481,en:['shroom','cat','robot'],fly:['bat','ghost'],rumble:1,pool:POOL_A,
tips:{flat:'Странно... Трясётся даже воздух. Будто что-то огромное дышит рядом.'}},
{id:'corridor',name:'Коридор теней',n:19,seed:493,en:['shroom','slime'],fly:['ghost','ufo'],rumble:1,pool:POOL_B},
{id:'portal',name:'Преддверие',n:19,seed:505,en:['robot','shroom','scorpion'],fly:['ufo','bat'],pool:POOL_B},
{id:'baronlair',name:'Трон Барона',n:1,seed:511,en:[],fly:[],script:'baron',boss:'eater',ending:'bone',pool:{flat:1}},
/* ЧАСТЬ 8: море */
{id:'reef',name:'Коралловый риф',n:17,seed:521,en:['crab','slime'],fly:['bee'],pool:{flat:1,gap:3,enemies:3,crates:2,hills:2,flyers:1,spikes:2,moverGap:2,crumble:1,highroad:1},
tips:{flat:'Я надел скафандр-шлем! Под водой без него никак.'}},
{id:'lagoon',name:'Золотая лагуна',n:18,seed:537,en:['crab','slime'],fly:['bird'],pool:{flat:1,gap:3,enemies:3,crates:2,hills:2,flyers:2,spikes:2,moverGap:2,crumble:1,highroad:1}},
{id:'shipwrack',name:'Затонувший корабль',n:18,seed:541,en:['crab','robot'],fly:['ghost'],pool:POOL_A,
tips:{enemies:'Старые железные крабы на службе затонувшего корабля. Не бойся!'}},
{id:'kelp',name:'Подводные леса',n:19,seed:553,en:['slime','crab','shroom'],fly:['bee','bat'],pool:POOL_A},
{id:'deep8',name:'Чёрная вода',n:19,seed:567,en:['crab','robot','shroom'],fly:['ghost','ufo'],pool:POOL_B},
{id:'trench',name:'Дорога домой',n:15,seed:573,en:['crab','slime','robot'],fly:['ghost','bird'],ending:'home',pool:{flat:2,gap:2,enemies:2,crates:2,hills:1,flyers:2,spikes:1,moverGap:2,crumble:1,highroad:1}}
];
function buildLevel(idx){
const cfg={...LEVELS[idx]},R=mkRng(cfg.seed*97+idx),MAXC=620,part=Math.floor(idx/6);
cfg.n=Math.max(1,Math.round((cfg.n||14)*1.3));
const t=Array.from({length:ROWS},()=>new Uint8Array(MAXC));
const L={cfg,t,items:[],enemies:[],movers:[],things:[],cols:0,startG:9,arena:null};
let x=0,g=9,d=0;const tips={...(cfg.tips||{})};
const fill=(c0,c1)=>{for(let c=c0;c<c1;c++)for(let r=g;r<ROWS;r++)t[r][c]=1};
const bone=(c,r)=>L.items.push({k:'bone',x:c*TILE+16,y:r*TILE+16});
const bline=(c,r,n)=>{for(let i=0;i<n;i++)bone(c+i,r)};
const barc=(c0,n,r,h)=>{for(let i=0;i<n;i++){const u=(i+.5)/n;bone(c0+i,r-Math.sin(u*Math.PI)*h)}};
const plank=(c,r,n)=>{for(let i=0;i<n;i++)t[r][c+i]=2};
const mk=(kind,px,py)=>({kind,...EN[kind],x:px,y:py,vx:0,vy:0,dir:R()<.5?-1:1,stun:0,t:R()*6,x0:px,y0:py,mode:0,dead:false,onGround:false});
const enemy=(kind,c)=>L.enemies.push(mk(kind,c*TILE+3,g*TILE-EN[kind].h));
const flyer=(kind,c,h)=>L.enemies.push(mk(kind,c*TILE,g*TILE-h));
const tip=(key,c)=>{if(tips[key]){L.things.push({k:'sign',x:c*TILE+16,y:g*TILE,text:tips[key]});delete tips[key]}};
const star=(px,py)=>L.items.push({k:'star',x:px,y:py});
const C={
flat(){tip('flat',x+1);const n=6+(R()*4|0);fill(x,x+n);if(R()<.7)bline(x+1,g-2,n-2);if(R()<.25+d*.2&&n>7)enemy(cfg.en[R()*cfg.en.length|0],x+n-3);x+=n},
hills(){for(let k=0;k<3;k++){const dd=[-2,-1,1,2][R()*4|0];g=clamp(g+dd,6,10);const n=3+(R()*2|0);fill(x,x+n);bline(x,g-2,n);x+=n}},
gap(){tip('gap',x+1);fill(x,x+2);x+=2;const n=3+(R()<d?1:0);barc(x,n,g-1,2);x+=n;fill(x,x+2);x+=2},
spikes(){tip('spikes',x+1);const n=2+(R()<.5?1:0);fill(x,x+3);x+=3;fill(x,x+n);for(let i=0;i<n;i++)t[g-1][x+i]=3;barc(x-1,n+2,g-1,2.6);x+=n;fill(x,x+3);x+=3},
enemies(){const n=10+(R()*3|0);fill(x,x+n);tip('enemies',x+1);const k=2+(R()<d?1:0);for(let i=0;i<k;i++)enemy(cfg.en[R()*cfg.en.length|0],x+3+i*Math.floor((n-4)/k));x+=n},
crates(){fill(x,x+9);tip('crates',x+1);const k=2+(R()*2|0);for(let i=0;i<k;i++){const c=x+3+i*2,h=1+(R()<.4?1:0);for(let q=1;q<=h;q++)t[g-q][c]=4}bline(x+1,g-2,1);x+=9},
springStar(st){if(g<9)g=9;tip('springStar',x+1);fill(x,x+10);t[g-1][x+3]=5;plank(x+5,g-6,4);bline(x+5,g-7,4);if(st)star((x+6.5)*TILE,(g-8)*TILE+16);x+=10},
stairs(st){if(g<9)g=9;fill(x,x+2);x+=2;const hs=[2,3,4,3,2];for(let i=0;i<5;i++){const r=g-hs[i];plank(x+i*3,r,2);bline(x+i*3,r-1,2)}if(st)star((x+7)*TILE,(g-6)*TILE);x+=15;fill(x,x+2);x+=2},
moverGap(){tip('moverGap',x+1);fill(x,x+2);x+=2;const n=9;L.movers.push({k:'mv',x:x*TILE,y:g*TILE+6,w:96,h:12,x0:x*TILE,rng:(n-3)*TILE,dx:0,dy:0});barc(x+1,n-2,g-3,1.2);x+=n;fill(x,x+2);x+=2},
crumble(){tip('crumble',x+1);fill(x,x+2);x+=2;for(let i=0;i<4;i++){const y=(g-(i%2))*TILE+4;L.movers.push({k:'cr',x:(x+i*3)*TILE,y,y0:y,w:64,h:12,st:0,tm:0,vy:0,dx:0,dy:0});bline(x+i*3,g-(i%2)-2,2)}x+=12;fill(x,x+2);x+=2},
flyers(){tip('flyers',x+1);const n=12;fill(x,x+n);const k=2+(R()<d?1:0);for(let i=0;i<k;i++)flyer(cfg.fly[R()*cfg.fly.length|0],x+3+i*3,96+R()*30);bline(x+2,g-2,n-4);x+=n},
highroad(st){if(g<8)g=8;const n=15;fill(x,x+n);for(let i=0;i<4;i++)t[g-1][x+5+i]=3;plank(x+4,g-3,6);bline(x+4,g-4,6);if(st)star((x+7)*TILE,(g-6)*TILE+16);enemy(cfg.en[0],x+12);x+=n},
checkpoint(){fill(x,x+4);L.things.push({k:'cp',x:(x+2)*TILE+16,y:g*TILE,on:false});x+=4}
};
if(cfg.script){ /* рукотворная арена-ловушка */
g=9;fill(0,10);
const a=x+16;fill(10,40);
for(let r=0;r<g;r++)t[r][x+39]=1;
if(cfg.script==='empty'){L.things.push({k:'cage',x:(x+30)*TILE+16,y:g*TILE,dog:-1,open:false,ot:0});bline(21,g-2,8)}
else{plank(x+12,g-3,3);plank(x+25,g-3,3);bline(x+12,g-4,3);bline(x+25,g-4,3)}
L.things.push({k:'cp',x:(x+5)*TILE+16,y:g*TILE,on:false});
L.arena={gate:x+39,trigger:(x+18)*TILE,left:0,right:(x+39)*TILE,g,chestX:(x+21)*TILE,cageX:(x+30)*TILE+16,spawnX:(x+33)*TILE,dog:4,script:cfg.script};
if(cfg.script==='empty'){L.arena.gate=x+39;L.arena.cageX=(x+30)*TILE+16}
L.items.push({k:'heart',x:(x+13.5)*TILE,y:(g-5)*TILE});
L.cols=x+40;
return L;
}
fill(0,10);x=10;
if(cfg.intro)L.things.push({k:'sign',x:4*TILE+16,y:g*TILE,text:'Беги вперёд! Собирай косточки и три больших звезды.'});
bline(5,g-2,4);
const names=Object.keys(cfg.pool).filter(k=>cfg.pool[k]>0);let last='';
const starAt=[.22,.5,.78].map(f=>Math.floor(cfg.n*f));
for(let i=0;i<cfg.n;i++){
d=Math.min(1,i/cfg.n+part*.2);
if(i>0&&i%4===0)C.checkpoint();
const si=starAt.indexOf(i);
if(si>=0){const nm=['springStar','stairs','highroad'][(si+idx)%3];C[nm](true);last=nm;continue}
let nm,tr=0;do{let w=R()*names.reduce((s,k)=>s+cfg.pool[k],0);nm=names.find(k=>(w-=cfg.pool[k])<0)||names[0]}while(nm===last&&tr++<6);
C[nm](false);last=nm;
}
C.checkpoint();
if(cfg.boss){
g=9;const bk=cfg.boss,a=x+6;fill(x,x+28);
for(let r=0;r<g;r++)t[r][x+27]=1;
const mvp=(c,r,rng)=>L.movers.push({k:'mv',x:c*TILE,y:r*TILE+6,w:96,h:12,x0:c*TILE,rng:rng*TILE,dx:0,dy:0});
const crp=(c,r)=>{const y=r*TILE+4;L.movers.push({k:'cr',x:c*TILE,y,y0:y,w:64,h:12,st:0,tm:0,vy:0,dx:0,dy:0});bline(c,r-2,2)};
let hx=x+11.5,hy=g-5;
if(bk==='king'){
plank(x+10,g-3,3);plank(x+19,g-3,3);bline(x+10,g-4,3);bline(x+19,g-4,3)}
else if(bk==='dragon'){
t[g-1][x+16]=3;t[g-1][x+17]=3;plank(x+9,g-3,3);plank(x+22,g-3,3);plank(x+14,g-5,6);
bline(x+9,g-4,3);bline(x+14,g-6,6);hx=x+16.5;hy=g-7}
else if(bk==='robot'){
plank(x+8,g-2,3);plank(x+24,g-3,3);mvp(x+12,g-5,8);bline(x+13,g-7,6);bline(x+8,g-3,3);hx=x+9.5;hy=g-5}
else if(bk==='yeti'){
plank(x+11,g-3,8);plank(x+13,g-5,4);bline(x+11,g-4,2);bline(x+17,g-4,2);bline(x+13,g-6,4);hx=x+14.5;hy=g-7.5}
else if(bk==='wizard'){
crp(x+9,g-3);crp(x+15,g-5);crp(x+21,g-3);t[g-1][x+16]=3;t[g-1][x+17]=3;hx=x+16.5;hy=g-7.5}
else if(bk==='eater'){ /* логово Пса-поедателя */
t[g-1][x+15]=3;t[g-1][x+18]=3;mvp(x+9,g-4,4);mvp(x+21,g-4,4);plank(x+13,g-6,6);
bline(x+13,g-7,6);hx=x+15.5;hy=g-8}
L.items.push({k:'heart',x:hx*TILE,y:hy*TILE});
L.arena={gate:a,trigger:(x+9)*TILE,left:(a+1)*TILE,right:(x+27)*TILE,g,chestX:(x+12)*TILE+16,cageX:(x+23)*TILE+16,spawnX:(x+22)*TILE,dog:part,script:cfg.script||null};
x+=28;
} else {fill(x,x+10);L.things.push({k:'goal',x:(x+6)*TILE,y:g*TILE});bline(x+1,g-2,4);x+=10}
const mid=L.things.filter(q=>q.k==='cp')[1];if(mid)L.items.push({k:'sausage',x:mid.x+TILE*3,y:mid.y-TILE*2});
L.cols=x;
return L;
}
/* ---------- состояние игры ---------- */
let G=null,mode='menu',paused=false,menuT=0,menuBg='meadow',mapPart=0,dlg=null,dlgOpen=false,cut=null,helmetOn=false,musicPart=0;
const TH=()=>THEMES[G.L.cfg.id];
function tile(c,r){if(c<0||c>=G.cols)return 1;if(r<0||r>=ROWS)return 0;return G.t[r][c]}
const solidish=(c,r)=>{const v=tile(c,r);return v===1||v===2||v===4||v===5};
const hit=(a,b)=>a.x<b.x+b.w&&a.x+a.w>b.x&&a.y<b.y+b.h&&a.y+a.h>b.y;
function moveX(e,dx){e.x+=dx;const c0=Math.floor(e.x/TILE),c1=Math.floor((e.x+e.w-.01)/TILE),r0=Math.floor(e.y/TILE),r1=Math.floor((e.y+e.h-.01)/TILE);
for(let r=r0;r<=r1;r++)for(let c=c0;c<=c1;c++){const v=tile(c,r);if(v===1||v===4){if(dx>0)e.x=c*TILE-e.w;else if(dx<0)e.x=(c+1)*TILE;else continue;e.hitX=true;e.vx=0;return}}}
function moveY(e,dy){const prevB=e.y+e.h;e.y+=dy;const c0=Math.floor(e.x/TILE),c1=Math.floor((e.x+e.w-.01)/TILE),r0=Math.floor(e.y/TILE),r1=Math.floor((e.y+e.h-.01)/TILE);
for(let r=r0;r<=r1;r++)for(let c=c0;c<=c1;c++){const v=tile(c,r);
if(v===1||v===4){if(dy>0){e.y=r*TILE-e.h;e.vy=0;e.onGround=true}else if(dy<0){e.y=(r+1)*TILE;e.vy=0}}
else if(v===2&&dy>0&&prevB<=r*TILE+1){e.y=r*TILE-e.h;e.vy=0;e.onGround=true}
else if(v===5&&dy>0){if(e.isP){e.vy=-880;e.onGround=false;e.air=1;SFX.spring();G.spr={c,r,t:.25};e.sq=-.3}else if(prevB<=r*TILE+11){e.y=r*TILE+10-e.h;e.vy=0;e.onGround=true}}}}
/* ---------- эффекты ---------- */
function puff(x,y,n=5,col='rgba(255,255,255,.75)'){for(let i=0;i<n;i++)G.parts.push({t:'c',x,y,vx:(Math.random()-.5)*100,vy:-Math.random()*60,life:.45,max:.45,size:2.5+Math.random()*3,col})}
function burst(x,y,n,cols,sp=220){for(let i=0;i<n;i++){const a=Math.random()*TAU,s=sp*(.3+Math.random()*.7);G.parts.push({t:'c',x,y,vx:Math.cos(a)*s,vy:Math.sin(a)*s-80,g:700,life:.7,max:.7,size:2+Math.random()*3.5,col:cols[i%cols.length]})}}
function confetti(x,y,n){const cols=['#ff5d73','#ffd93d','#4ade80','#4aa8ff','#c084fc','#fb923c'];for(let i=0;i<n;i++){const a=-Math.PI/2+(Math.random()-.5)*2.4,s=200+Math.random()*320;G.parts.push({t:'conf',x,y,vx:Math.cos(a)*s,vy:Math.sin(a)*s,g:500,life:2.2,max:2.2,size:4+Math.random()*4,rot:Math.random()*6,col:cols[i%6]})}}
const ring=(x,y)=>G.parts.push({t:'ring',x,y,life:.35,max:.35,size:6});
function popBones(x,y,n){for(let i=0;i<n;i++)G.items.push({k:'bone',x,y,vx:(Math.random()-.5)*160,vy:-250-Math.random()*120,pop:.35})}
let toastT=0;
function toast(s){const e=$('toast');e.textContent=s;e.classList.add('on');clearTimeout(toastT);toastT=setTimeout(()=>e.classList.remove('on'),2000)}
function banner(a,b){$('banB').textContent=a;$('banI').textContent=b||'';const e=$('banner');e.classList.remove('on');void e.offsetWidth;e.classList.add('on')}
/* ---------- запуск уровня ---------- */
function newPlayer(){return{isP:1,x:2*TILE,y:9*TILE-22,w:24,h:22,vx:0,vy:0,face:1,onGround:true,coyote:0,jbuf:0,air:1,inv:0,hurtT:0,barkCd:0,barkT:0,anim:0,sq:0,power:0,riding:null,combo:0,comboT:0,prevB:0}}
function startLevel(i){
const L=buildLevel(i);const part=Math.floor(i/6);musicPart=part;musicTheme=part%6;helmetOn=part===7;dlgOpen=false;dlg=null;cut=null;
G={i,L,t:L.t,cols:L.cols,items:L.items.map(o=>({...o})),enemies:L.enemies.map(o=>({...o})),movers:L.movers.map(o=>({...o})),things:L.things.map(o=>({...o})),
p:newPlayer(),cam:0,time:0,bones:0,stars:0,hearts:3,parts:[],dying:[],proj:[],waves:[],shake:0,cp:{x:2*TILE,y:9*TILE-22},state:'play',endT:0,shown:false,boss:null,tip:'',spr:null,lastH:-1,lastB:-1,lastS:-1,hasKey:false,ghost:null,pendingCut:0,ending:L.cfg.ending||null,fade:0};
if(L.arena&&L.cfg.boss){const A=L.arena,BD=BOSSES[L.cfg.boss];G.boss={kind:L.cfg.boss,x:A.spawnX,y:A.g*TILE-56,w:52,h:56,vx:0,vy:0,dir:-1,hp:BD.hp,maxhp:BD.hp,inv:0,hurtT:0,mode:'walk',mt:2,thr:2.5,rage:0,active:false,dead:false,onGround:false,t:0,sum:18};if(L.cfg.cut)G.pendingCut=1}
mode='play';paused=false;setScreen(null);showHud(true);$('bossBar').classList.add('hidden');$('tip').classList.remove('on');['l','r','j','b'].forEach(k=>setKey(k,0));jp=bp=false;setHud(true);
banner('Часть '+(part+1)+' · Мир '+(i%6+1),L.cfg.name);
if(L.cfg.rumble)setTimeout(()=>toast('Кажется, где-то рядом что-то есть…'),900);
G.cam=0;
}
/* ---------- урон, смерть, победа ---------- */
function hurt(){const p=G.p;if(p.inv>0||p.power>0||G.state!=='play')return;G.hearts--;p.inv=1.8;p.hurtT=.28;p.vy=-330;p.vx=-p.face*190;p.onGround=false;p.riding=null;G.shake=.3;SFX.hurt();vib(70);burst(p.x+12,p.y+8,8,['#ff5d73','#fff']);setHud();if(G.hearts<=0)lose()}
function fall(){G.hearts--;SFX.hurt();vib(70);setHud();if(G.hearts<=0){lose();return}respawn()}
function respawn(){const p=G.p;p.x=G.cp.x;p.y=G.cp.y;p.vx=p.vy=0;p.inv=2.2;p.riding=null;p.onGround=false;G.shake=.2}
function lose(){if(G.state!=='play')return;G.state='lose';G.endT=0;SFX.lose()}
function win(){if(G.state!=='play')return;G.state='won';G.endT=0;SFX.win();const p=G.p;confetti(p.x,p.y,80);musicOn=false;setTimeout(()=>musicOn=true,2500)}
/* ---------- лай ---------- */
function doBark(){const p=G.p;p.barkCd=.6;p.barkT=.3;SFX.bark();
const box={x:p.face>0?p.x+p.w:p.x-88,y:p.y-18,w:88,h:p.h+30};
G.parts.push({t:'txt',x:p.x+12+p.face*34,y:p.y-12,vy:-34,life:.7,max:.7,text:'ГАВ!'});
for(let r=Math.floor(box.y/TILE);r<=Math.floor((box.y+box.h)/TILE);r++)for(let c=Math.floor(box.x/TILE);c<=Math.floor((box.x+box.w)/TILE);c++){
if(tile(c,r)===4){G.t[r][c]=0;popBones(c*TILE+16,r*TILE+8,3);burst(c*TILE+16,r*TILE+16,10,['#c98a4b','#7a4a1e','#e8b676'],160);SFX.crate()}}
for(const e of G.enemies){if(e.dead||!hit(box,e))continue;if(e.fly)kill(e,p.face);else{e.stun=3.5;e.vy=-220;e.vx=p.face*110;e.onGround=false}}
const b=G.boss;if(b&&b.active&&!b.dead&&hit(box,b)){b.vx=p.face*120}
G.proj=G.proj.filter(q=>{if(hit(box,{x:q.x-8,y:q.y-8,w:16,h:16})){puff(q.x,q.y,6);return false}return true});
}
function kill(e,dir){e.dead=true;G.dying.push({...e,vx:(dir||1)*150,vy:-320,rot:0,rs:(dir||1)*9});popBones(e.x+e.w/2,e.y,2);burst(e.x+e.w/2,e.y+e.h/2,8,['#fff','#ffd93d']);G.p.combo++}
/* ---------- игрок ---------- */
function moverCollide(p){if(p.vy<0)return;for(const m of G.movers){if(m.gone)continue;
if(p.x+p.w>m.x+3&&p.x<m.x+m.w-3&&p.prevB<=m.y+8&&p.y+p.h>=m.y-1&&p.y+p.h<=m.y+m.h+14){p.y=m.y-p.h;p.vy=0;p.onGround=true;p.riding=m;if(m.k==='cr'&&m.st===0){m.st=1;m.tm=.55}}}}
function updPlayer(dt){
const p=G.p,cfg=G.L.cfg,lock=G.state!=='play';
p.inv=Math.max(0,p.inv-dt);p.barkCd-=dt;p.barkT-=dt;p.hurtT=Math.max(0,p.hurtT-dt);p.power=Math.max(0,p.power-dt);p.comboT-=dt;if(p.comboT<=0)p.combo=0;p.sq*=Math.pow(.0005,dt);
const dir=lock||p.hurtT>0?0:(held.r?1:0)-(held.l?1:0),maxV=p.power>0?330:215,ice=cfg.ice&&p.onGround;
if(dir){p.vx=clamp(p.vx+dir*(ice?650:2600)*dt,-maxV,maxV);p.face=dir}
else if(p.hurtT<=0){const f=(p.onGround?(ice?130:2400):500)*dt;p.vx=Math.abs(p.vx)<=f?0:p.vx-Math.sign(p.vx)*f}
if(jp){jp=false;p.jbuf=.13}else p.jbuf-=dt;
if(bp){bp=false;if(!lock&&p.barkCd<=0)doBark()}
if(p.jbuf>0&&!lock){
if(p.coyote>0){p.vy=-610;p.coyote=0;p.jbuf=0;p.onGround=false;p.riding=null;SFX.jump();puff(p.x+12,p.y+22,4);p.sq=-.25}
else if(p.air>0){p.vy=-545;p.air--;p.jbuf=0;SFX.dj();ring(p.x+12,p.y+22);p.sq=-.2}}
const gm=cfg.lowg?.72:1;
p.vy+=((p.vy<0&&!held.j)?3400:1800)*gm*dt;p.vy=Math.min(p.vy,820);
if(p.riding){p.x+=p.riding.dx;p.y+=p.riding.dy}
const wasG=p.onGround,vyB=p.vy;
p.hitX=false;moveX(p,p.vx*dt);
p.prevB=p.y+p.h;p.onGround=false;moveY(p,p.vy*dt);
p.riding=null;moverCollide(p);
if(p.onGround){if(!wasG&&vyB>260){puff(p.x+12,p.y+22,5);p.sq=.35}p.coyote=.1;p.air=1}else p.coyote-=dt;
p.anim+=Math.abs(p.vx)*dt*.075;
if(p.power>0&&Math.random()<.5)G.parts.push({t:'c',x:p.x+12,y:p.y+14,vx:-p.face*60,vy:(Math.random()-.5)*60,life:.5,max:.5,size:3,col:`hsl(${Math.random()*360},90%,65%)`});
if(lock)return;
const c0=Math.floor(p.x/TILE),c1=Math.floor((p.x+p.w)/TILE),r0=Math.floor(p.y/TILE),r1=Math.floor((p.y+p.h)/TILE);
for(let r=r0;r<=r1;r++)for(let c=c0;c<=c1;c++)if(tile(c,r)===3){const sx=c*TILE+4,sy=r*TILE+14;if(p.x+p.w>sx&&p.x<sx+24&&p.y+p.h>sy&&p.y<sy+18)hurt()}
if(p.y>ROWS*TILE+50)fall();
}
/* ---------- враги ---------- */
function updWalk(e,dt){
if(e.stun>0){e.stun-=dt;e.vx*=.92}else e.vx=e.dir*e.sp;
e.vy=Math.min(e.vy+1800*dt,700);
e.hitX=false;moveX(e,e.vx*dt);e.onGround=false;moveY(e,e.vy*dt);
if(e.stun<=0&&e.onGround){const fx=e.dir>0?e.x+e.w+3:e.x-3;if(e.hitX||!solidish(Math.floor(fx/TILE),Math.floor((e.y+e.h+4)/TILE)))e.dir*=-1}
if(e.y>ROWS*TILE+80)e.dead=true;
}
function updFly(e,dt){const p=G.p;
if(e.kind==='bat'){
if(e.mode===0){e.x=e.x0+Math.sin(e.t*1.1)*50;e.y=e.y0+Math.sin(e.t*2.2)*8;e.dir=Math.cos(e.t*1.1)>0?1:-1;if(Math.abs(p.x-e.x)<150&&p.y>e.y&&p.y-e.y<190&&G.state==='play'){e.mode=1;e.tm=0;e.tx=p.x+p.w/2;e.ty=p.y}}
else if(e.mode===1){e.tm+=dt;const dx=e.tx-(e.x+e.w/2),dy=e.ty-(e.y+e.h/2),dd=Math.hypot(dx,dy)||1;e.x+=dx/dd*240*dt;e.y+=dy/dd*240*dt;e.dir=dx>0?1:-1;if(dd<10||e.tm>1.2)e.mode=2}
else{const dx=e.x0-e.x,dy=e.y0-e.y,dd=Math.hypot(dx,dy)||1;e.x+=dx/dd*130*dt;e.y+=dy/dd*130*dt;if(dd<6)e.mode=0}
} else {e.x=e.x0+Math.sin(e.t*e.sp)*70;e.y=e.y0+Math.sin(e.t*e.sp*2.3)*16;e.dir=Math.cos(e.t*e.sp)>0?1:-1}
}
function updEnemies(dt){const p=G.p,lock=G.state!=='play';
for(const e of G.enemies){if(e.dead)continue;if(e.x<G.cam-260||e.x>G.cam+VW+260)continue;e.t+=dt;if(e.fly)updFly(e,dt);else updWalk(e,dt);
if(lock||e.dead)continue;
if(hit(p,{x:e.x+3,y:e.y+3,w:e.w-6,h:e.h-4})){
const above=p.vy>0&&p.prevB<=e.y+9;
if(e.stun>0||p.power>0)kill(e,p.face);
else if(e.stomp&&above){kill(e,p.face);p.vy=held.j?-570:-400;p.air=1;p.onGround=false;p.sq=-.2;SFX.stomp();SFX.bone(2)}
else hurt();
}}
}
/* ---------- боссы ---------- */
function throwAtk(){const b=G.boss,p=G.p,k=b.kind,sx=b.x+b.w/2+b.dir*20,sy=b.y+14,tx=p.x+12,ty=p.y+10;
const pk={dragon:'fire',yeti:'snow',eater:'bone'}[k]||'fish';
const arc=(T,dx)=>G.proj.push({k:pk,x:sx,y:sy,vx:(tx+(dx||0)-sx)/T,vy:(ty-sy-.5*900*T*T)/T,rot:0});
if(k==='robot'){const y=b.y+b.h-17;G.proj.push({k:'bolt',x:sx,y,vx:b.dir*290,vy:0,gr:0,rot:0,dir:b.dir});if(b.rage>=1)G.proj.push({k:'bolt',x:sx-b.dir*80,y,vx:b.dir*290,vy:0,gr:0,rot:0,dir:b.dir})}
else if(k==='dragon'){arc(.85);if(b.rage>=1)arc(1.1,70*b.dir)}
else if(k==='yeti'){arc(.9);if(b.rage>=1)arc(1.15,-80*b.dir)}
else if(k==='wizard'){const n=b.rage>=1?3:1,ang=Math.atan2(ty-sy,tx-sx);for(let i=0;i<n;i++){const a=ang+(i-(n-1)/2)*.32;G.proj.push({k:'orb',x:sx,y:sy,vx:Math.cos(a)*235,vy:Math.sin(a)*235,gr:0,rot:0})}}
else if(k==='eater'){arc(.8);if(b.rage>=1)arc(1.0,80*b.dir)}
else arc(.85);
SFX.crate()}
function summonGhost(){const b=G.boss;if(!b)return;const kinds=['king','dragon','robot','yeti','wizard'];const pk=kinds[Math.random()*kinds.length|0];
G.ghost={kind:pk,t:0,x:G.cam+VW+140};
toast('Он призвал дух '+BOSSES[pk].name.replace('!','')+'!');SFX.power();vib(60);
for(const c of [G.L.arena.left+60,G.L.arena.right-60])G.enemies.push({kind:'robot',...EN.robot,x:c,y:G.L.arena.g*TILE-EN.robot.h,vx:0,vy:0,dir:c<G.p.x?1:-1,stun:0,t:0,x0:c,y0:0,mode:0,dead:false,onGround:false});
}
function activateBoss(){const b=G.boss,A=G.L.arena,BD=BOSSES[b.kind];b.active=true;for(let r=0;r<A.g;r++)G.t[r][A.gate]=1;G.cp={x:(A.gate+2)*TILE,y:A.g*TILE-22};G.shake=.5;banner(BD.name,BD.hint);$('bossBar').classList.remove('hidden');$('bossFill').style.width='100%';musicTheme=4}
function updBoss(dt){const b=G.boss;if(!b||b.dead)return;const p=G.p,A=G.L.arena,BD=BOSSES[b.kind];
if(!b.active){if(G.pendingCut)return;if(p.x>A.trigger&&G.state==='play')activateBoss();return}
b.t+=dt;b.inv=Math.max(0,b.inv-dt);b.hurtT=Math.max(0,b.hurtT-dt);
const dirTo=Math.sign((p.x+12)-(b.x+b.w/2))||1;
if(b.mode==='air'&&b.onGround){b.mode='walk';b.mt=1.6+Math.random()*1.2;b.vx=0;G.shake=.4;puff(b.x+26,b.y+56,10);for(const s of[-1,1])G.waves.push({x:b.x+b.w/2+s*20-8,y:A.g*TILE-14,w:18,h:14,dir:s,d:0})}
if(b.hurtT>0){b.vx*=.9}
else if(b.mode==='walk'){b.dir=dirTo;b.vx=b.dir*(BD.spd+b.rage*28);b.mt-=dt;b.thr-=dt;if(b.thr<=0&&G.state==='play'){throwAtk();b.thr=BD.thr-b.rage*.35}
if(b.kind==='eater'&&G.state==='play'){b.sum-=dt;if(b.sum<=0){b.sum=20-b.rage*4;summonGhost()}}
if(b.mt<=0){
if(b.kind==='wizard'){ /* телепорт */
burst(b.x+26,b.y+28,14,['#b44aff','#f0c8ff'],170);
let nx=A.left+50+Math.random()*(A.right-A.left-170);
if(Math.abs(nx-p.x)<110)nx=clamp(p.x+(p.x>(A.left+A.right)/2?-1:1)*170,A.left+40,A.right-100);
b.x=nx;b.y=A.g*TILE-b.h-110;b.vy=0;b.vx=0;b.mt=2+Math.random()*1.2;
burst(b.x+26,b.y+28,14,['#b44aff','#f0c8ff'],170);SFX.power()}
else{b.mode='crouch';b.mt=.5;b.vx=0}}}
else if(b.mode==='crouch'){b.vx=0;b.mt-=dt;if(b.mt<=0){b.mode='air';b.vy=-640;b.vx=clamp((p.x-b.x)/.8,-240,240);b.onGround=false}}
b.vy=Math.min(b.vy+1800*dt,800);b.hitX=false;moveX(b,b.vx*dt);b.onGround=false;moveY(b,b.vy*dt);
if(G.state!=='play')return;
if(hit(p,{x:b.x+4,y:b.y+4,w:b.w-8,h:b.h-4})){
const above=p.vy>0&&p.prevB<=b.y+16;
if(above){p.vy=-620;p.air=1;p.onGround=false;if(b.inv<=0){b.hp--;b.inv=1.4;b.hurtT=.6;b.vx=-dirTo*80;b.rage=Math.min(2,b.maxhp-b.hp>=3?2:(b.maxhp-b.hp>=1?1:0));SFX.bossHit();G.shake=.5;vib(90);burst(b.x+26,b.y+10,16,['#ffd93d','#fff','#ff5d73']);$('bossFill').style.width=Math.max(0,b.hp/b.maxhp*100)+'%';if(b.hp<=0)beatBoss()}else SFX.stomp()}
else if(b.hurtT<=0&&b.inv<=0)hurt();
}
}
function beatBoss(){const b=G.boss,A=G.L.arena;b.dead=true;G.dying.push({...b,isBoss:1,vx:200,vy:-420,rot:0,rs:6});popBones(b.x+26,b.y,14);confetti(b.x+26,b.y,50);
for(let r=0;r<A.g;r++)G.t[r][A.gate]=0;
$('bossBar').classList.add('hidden');G.proj=[];G.waves=[];
if(A.script==='baron'){ /* косточка возвращается прямо в лапы */
G.state='cut';playCut('bone_back',()=>{save.bone=true;persist();G.state='play';win()});return}
G.things.push({k:'keychest',x:A.chestX,y:A.g*TILE,got:false});
G.things.push({k:'cage',x:A.cageX,y:A.g*TILE,dog:A.dog,open:false,ot:0});
banner('Победа!','Забери ключ из сундука и освободи '+DOGS[A.dog].n+'!');SFX.star()}
function updProj(dt){const p=G.p,A=G.L.arena;
G.proj=G.proj.filter(q=>{const gr=q.gr===undefined?900:q.gr;q.vy+=gr*dt;q.x+=q.vx*dt;q.y+=q.vy*dt;q.rot+=dt*10;
if(solidish(Math.floor(q.x/TILE),Math.floor(q.y/TILE))&&(q.vy>0||gr===0)){puff(q.x,q.y,4);return false}
if(G.state==='play'&&hit(p,{x:q.x-8,y:q.y-8,w:16,h:16})){hurt();return false}return q.y<VH+40&&q.y>-100&&(!A||q.x>A.left-80&&q.x<A.right+80)});
G.waves=G.waves.filter(w=>{w.d+=220*dt;w.x+=w.dir*220*dt;if(Math.random()<.4)puff(w.x+9,w.y+12,1,'rgba(255,230,180,.8)');
if(G.state==='play'&&hit(p,w))hurt();return w.d<300&&(!A||w.x>A.left-20&&w.x<A.right)})}
/* ---------- клетка, ключ и диалоги ---------- */
function openCage(th){th.open=true;th.ot=0;G.state='freeing';G.endT=0;G.hasKey=false;SFX.crate();SFX.star();confetti(th.x,th.y-40,50);burst(th.x,th.y-30,14,['#ffd93d','#fff'],200);banner('Клетка открыта!',DOGS[th.dog].n+' свободен!')}
function startDialog(di){dlg={d:DOGS[di],di,i:0};dlgOpen=true;showHud(false);['l','r','j','b'].forEach(k=>setKey(k,0));setScreen('dlg');showLine()}
function showLine(){const L=dlg.d.talk[dlg.i],me=L[0]==='p';$('dlgName').textContent=me?save.name:dlg.d.n;$('dlgTxt').textContent=L[1].replace(/\{n\}/g,save.name);$('dlgNext').textContent=dlg.i===dlg.d.talk.length-1?'Ура!':'Дальше';SFX.talk();if(L[2])SFX.power()}
function endDialog(){dlgOpen=false;const di=dlg.di;if(!save.dogs.includes(di)){save.dogs.push(di);persist()}
if(di===2&&!save.magnet){save.magnet=true;persist()}
setScreen(null);G.state='play';
if(G.i===29&&!save.bone){playCut('feast_steal',()=>{save.bone=true;persist();win()});return}
win()}
/* ---------- предметы и объекты ---------- */
function collect(it){it.got=true;const p=G.p;
if(it.k==='bone'){G.bones++;save.bank+=BONE_VALUE;p.combo=Math.min(7,p.combo+1);p.comboT=.7;SFX.bone(p.combo);puff(it.x,it.y,3,'rgba(255,255,255,.9)');setBank()}
else if(it.k==='star'){G.stars++;SFX.star();confetti(it.x,it.y,26);toast('Большая звезда! '+G.stars+' из 3');vib(40)}
else if(it.k==='heart'){if(G.hearts<5)G.hearts++;else{G.bones+=1;save.bank+=BONE_VALUE;setBank()}SFX.star();burst(it.x,it.y,10,['#ff5d73','#ffb3c1']);toast('Сердечко!')}
else if(it.k==='sausage'){p.power=8;SFX.power();confetti(it.x,it.y,24);toast('Суперсосиска! Ты неудержима!')}
setHud();
}
function setBank(){const a=$('bankN');if(a)a.textContent=save.bank;const b=$('wardBankN');if(b)b.textContent=save.bank}
function updItems(dt){const p=G.p,px=p.x+p.w/2,py=p.y+p.h/2;
for(const it of G.items){if(it.got)continue;
if(it.pop!==undefined){it.pop-=dt;it.vy+=900*dt;it.x+=it.vx*dt;it.y+=it.vy*dt;
if(it.vy>0&&solidish(Math.floor(it.x/TILE),Math.floor((it.y+8)/TILE))){it.y=Math.floor((it.y+8)/TILE)*TILE-8;it.vy=-it.vy*.35;it.vx*=.6;if(Math.abs(it.vy)<40)it.vy=0}
if(it.pop>0)continue}
/* костомагнит Дружка */
if(save.magnet&&(it.k==='bone')&&Math.abs(it.x-px)<150&&Math.abs(it.y-py)<150){const dd=Math.hypot(px-it.x,py-it.y)||1;it.x+=(px-it.x)/dd*430*dt;it.y+=(py-it.y)/dd*430*dt}
if(Math.abs(it.x-px)>40)continue;
if(Math.hypot(it.x-px,it.y-py)<(it.k==='star'?28:22)&&G.state==='play')collect(it)}
}
function updThings(dt){const p=G.p,px=p.x+p.w/2;let tip='';
for(const th of G.things){
if(th.k==='cage'&&th.open)th.ot+=dt;
if(th.k==='cp'&&!th.on&&px>th.x-10){th.on=true;G.cp={x:th.x-12,y:th.y-22};SFX.check();toast('Контрольная точка!');burst(th.x,th.y-40,12,['#ffd93d','#4ade80','#fff'])}
else if(th.k==='goal'&&G.state==='play'&&Math.abs(px-th.x)<30&&Math.abs(p.y+p.h-th.y)<70){
if(G.ending==='home'){if(!G.homed){G.homed=1;playCut('home',()=>win())}}else win()}
else if(th.k==='keychest'&&!th.got&&G.state==='play'&&Math.abs(px-th.x)<34&&Math.abs(p.y+p.h-th.y)<60){th.got=true;G.hasKey=true;SFX.key();confetti(th.x,th.y-30,30);toast('Ключ у тебя! Беги к клетке!')}
else if(th.k==='cage'&&!th.open&&G.state==='play'&&Math.abs(px-th.x)<46&&Math.abs(p.y+p.h-th.y)<70){
if(G.hasKey)openCage(th);else if(!th.wt||G.time>th.wt){th.wt=G.time+2.5;toast('Клетка заперта! Нужен ключ из сундука')}}
else if(th.k==='sign'&&Math.abs(px-th.x)<84)tip=th.text}
if(tip!==G.tip){G.tip=tip;const e=$('tip');if(tip)e.textContent=tip;e.classList.toggle('on',!!tip)}
}
/* ---------- кинематографичные сцены ---------- */
function obj(bg,chars,who,text){return{bg,chars:chars||[],who:who||'',text}}
const CUTS={
intro:()=>[
obj('meadow',[{k:'bone',x:.5,y:232}],'','Тысячу лет Золотая Косточка лежала в городе собак — главная награда праздника Большой Косточки.'),
obj('meadow',[{k:'cat',x:.28},{k:'cat',x:.46},{k:'cat',x:.64},{k:'bone',x:.5,y:238}],'','Но однажды ночью в город прокралась шайка котов-грабителей.'),
obj('castle',[{k:'boss',kind:'king',x:.5,s:2.2},{k:'bone',x:.5,y:238}],'Кот-Король','Ха-ха! Косточка теперь принадлежит КОТУ-КОРОЛЮ! Спрятать её в моём замке!'),
obj('cave',[{k:'cage',x:.35,di:0},{k:'cage',x:.65,di:1}],'','Котам было мало косточки: они заперли пятерых собак в клетки и разбежались по миру.'),
obj('meadow',[{k:'player',x:.5,face:1,s:2.3}],save.name,'Нет уж, так дело не пойдёт! Я верну косточку и освобожу всех!')],
hand_king:()=>[
obj('castle',[{k:'boss',kind:'king',x:.3,face:1,s:2.3},{k:'bone',x:.62,y:235}],'Кот-Король','Стой, пёс! Ты слишком далеко зашёл ради этой поблёкшей кости.'),
obj('castle',[{k:'player',x:.7,face:-1,s:2.3},{k:'bone',x:.36,y:238}],save.name,'Золотая Косточка — не твоя! Отпусти собак и отдай её!'),
obj('castle',[{k:'boss',kind:'king',x:.3,face:1,s:2.4},{k:'bone',x:.46,y:232}],'Кот-Король','Ха-ха! Они уже давно не выйдут из моих клеток! Берущая — ПРИНИМАЮЩАЯ сторона моя!')],
hand_dragon:()=>[
obj('lair',[{k:'boss',kind:'king',x:.22,face:1,s:2.1},{k:'boss',kind:'dragon',x:.68,face:-1,s:2.3},{k:'bone',x:.45,y:238}],'Кот-Король','Жар! Эта собака шла за мной по пятам! Я не выдержу боя — береги косточку!'),
obj('lair',[{k:'boss',kind:'dragon',x:.68,face:-1,s:2.4},{k:'bone',x:.56,y:238}],'Дракон Жар','Она будет в полной безопасности. В моём … животе. Молодец, что принёс её мне.'),
obj('lair',[{k:'player',x:.75,face:-1,s:2.2},{k:'boss',kind:'dragon',x:.28,face:1,s:2.3}],save.name,'Не радуйся раньше времени, огнедышащий.')],
hand_robot:()=>[
obj('lab',[{k:'boss',kind:'dragon',x:.24,face:1,s:2.1},{k:'boss',kind:'robot',x:.7,face:-1,s:2.3},{k:'bone',x:.46,y:238}],'Дракон Жар','Твой металл спасёт её, Мехакот! Ни один пёс не пройдёт через твои лазеры!'),
obj('lab',[{k:'boss',kind:'robot',x:.7,face:-1,s:2.4},{k:'bone',x:.5,y:238}],'Мехакот','ПРИНЯТО. КОСТЬ БУДЕТ СОХРАНЯТЬСЯ В ЖЕЛЕЗНОМ СЕЙФЕ. РАБОЧИЙ ПРОЦЕСС: НАДОЛГО.'),
obj('lab',[{k:'player',x:.8,face:-1,s:2.2},{k:'boss',kind:'robot',x:.3,face:1,s:2.3}],save.name,'Сейф у тебя отличный. Жаль, что я знаю все его коды.')],
hand_yeti:()=>[
obj('yeti',[{k:'boss',kind:'robot',x:.22,face:1,s:2.1},{k:'boss',kind:'yeti',x:.7,face:-1,s:2.4},{k:'bone',x:.45,y:238}],'Мехакот','ОТКЛОНЕНИЕ: СЕЙФ ПРОБИТ. КОСТЬ ТРЕБУЕТ СОХРАНЕНИЯ В ЛЬДАХ. ПЕРЕДАЮ ВАМ, ЕТИ.'),
obj('yeti',[{k:'boss',kind:'yeti',x:.7,face:-1,s:2.5},{k:'bone',x:.56,y:238}],'Йети Мороз','Мои льды сохранят её лучше всех. Собаке не пройти через мою метель.'),
obj('yeti',[{k:'player',x:.78,face:-1,s:2.2},{k:'boss',kind:'yeti',x:.3,face:1,s:2.3}],save.name,'Посмотрим, кто кого.')],
hand_wizard:()=>[
obj('wiz',[{k:'boss',kind:'yeti',x:.22,face:1,s:2.1},{k:'boss',kind:'wizard',x:.7,face:-1,s:2.3},{k:'bone',x:.46,y:238}],'Йети Мороз','Твоя магия сильнее моих льдов, Мурзик. Забери косточку!'),
obj('wiz',[{k:'boss',kind:'wizard',x:.7,face:-1,s:2.5},{k:'bone',x:.56,y:238}],'Тёмный Маг Мурзик','Она была МНЕ предназначена с самого начала. Я лишь ждал сигнала…'),
obj('wiz',[{k:'player',x:.8,face:-1,s:2.2},{k:'boss',kind:'wizard',x:.3,face:1,s:2.4}],save.name,'И вот он, твой выход, Мурзик.')],
feast_steal:()=>[
obj('meadow',[{k:'player',x:.14,face:1,s:2.1},{k:'dog',d:0,x:.3,face:1,s:1.9},{k:'dog',d:1,x:.45,face:1,s:1.9},{k:'dog',d:2,x:.6,face:1,s:1.9},{k:'bone',x:.76,y:236}],'','УРА! Праздник начался! Все пятеро друзей снова вместе, а Золотая Косточка — на самом видном месте.'),
obj('meadow',[{k:'dog',d:3,x:.5,face:1,s:2.2},{k:'bone',x:.76,y:236}],'Снежка','По правде говоря, я плакала, когда меня освободили!'),
obj('meadow',[{k:'dog',d:4,x:.3,face:1,s:2.2},{k:'bone',x:.76,y:236}],'Барон','Да-да, какой замечательный праздник… Как жаль, что он скоро закончится.'),
obj('meadow',[{k:'dog',d:4,x:.33,face:1,s:2.2},{k:'bone',x:.76,y:236}],save.name,'Барон? Куда ты собираешься?'),
obj('meadow',[{k:'dog',d:4,x:.48,face:1,s:2.2},{k:'bone',x:.48,y:218}],'Барон','НИ ЗА ЧТО я не отдам её людям! Косточка — МОЁ ПРЕДНАЗНАЧЕНИЕ!'),
obj('meadow',[{k:'player',x:.5,face:1,s:2.3}],'Дружок','Он схватил косточку и убежал в сторону Го-ры-Баро-на! Стой! Отдай!'),
obj('meadow',[{k:'player',x:.5,face:1,s:2.3}],'','Золотая Косточка снова исчезла. На этот раз — прямо из-под самого носа.')],
empty_cage:()=>[
obj('cell',[{k:'cage',x:.5,di:-1},{k:'player',x:.18,face:1,s:2.3}],save.name,'Вот она… Клетка, в которой должны были сидеть боссы. Только пусто.'),
obj('cell',[{k:'cage',x:.5,di:-1},{k:'player',x:.22,face:1,s:2.3}],save.name,'Странно… Почему пусто?'),
obj('cell',[{k:'cage',x:.5,di:-1}],'','Вдруг под ногами уходит вниз пол…')],
baron_turn:()=>[
obj('baronlair',[{k:'dog',d:4,x:.3,face:1,s:2.5,mouth:true}],'','Где-то в глубине подземелья горит красное пламя. В зубах у Барона — Золотая Косточка.'),
obj('baronlair',[{k:'player',x:.75,face:-1,s:2.3},{k:'dog',d:4,x:.3,face:1,s:2.3,mouth:true}],save.name,'Барон! Отдай косточку! Немедленно!'),
obj('baronlair',[{k:'dog',d:4,x:.3,face:1,s:2.4,mouth:true}],'Барон','Ты ведь уже догадался, {n}? Я организовал всё: и котов, и клетки, и боссов…'),
obj('baronlair',[{k:'player',x:.75,face:-1,s:2.3},{k:'dog',d:4,x:.3,face:1,s:2.4,mouth:true}],save.name,'Зачем?!'),
obj('baronlair',[{k:'dog',d:4,x:.3,face:1,s:2.5,mouth:true}],'Барон','Золотая Косточка НИКОМУ не нужна! Кроме меня. И НАСТАЛО МОЁ ВРЕМЯ!'),
obj('baronlair',[{k:'boss',kind:'eater',x:.3,face:1,s:2.7}],'','Воздух вспыхивает… Барон исчезает — и на его месте встаёт ЧУДОВИЩЕ.')],
bone_back:()=>[
obj('portal',[{k:'boss',kind:'eater',x:.5,face:1,s:2.6}],'','Красное пламя рассеивается… Пёс-поедатель падает.'),
obj('portal',[{k:'bone',x:.5,y:225}],'','Осталась одна Золотая Косточка. Тёплая. Тяжёлая. На ощупь — настоящая.'),
obj('portal',[{k:'player',x:.5,face:1,s:2.4},{k:'bone',x:.5,y:225}],save.name,'Всё кончено. Косточка снова наша!')],
home:()=>[
obj('meadow',[{k:'player',x:.08,face:1,s:2},{k:'dog',d:0,x:.28,face:1,s:1.7},{k:'dog',d:1,x:.42,face:1,s:1.7},{k:'dog',d:2,x:.55,face:1,s:1.7},{k:'dog',d:3,x:.68,face:1,s:1.7},{k:'bone',x:.88,y:232}],'','Солёный ветер принёс {n} домой. Весь город вышел встречать!'),
obj('meadow',[{k:'dog',d:1,x:.4,face:1,s:2.2},{k:'bone',x:.72,y:230}],'Тузик','СМОТРИТЕ! Косточка! СМОТРИТЕ!!!'),
obj('meadow',[{k:'dog',d:2,x:.4,face:1,s:2.2},{k:'bone',x:.72,y:230}],'Дружок','Она цела. Значит, праздник будет!'),
obj('meadow',[{k:'player',x:.32,face:1,s:2.3},{k:'bone',x:.76,y:228}],save.name,'Всем спасибо. И праздник с косточкой — для всех!'),
obj('meadow',[{k:'player',x:.5,face:1,s:2.5},{k:'bone',x:.62,y:220}],'','Праздник Большой Косточки состоялся. И больше никто её не крал. (Ну, почти…)')]
};
let activeCutDone=null;
function playCut(id,done){
const list=(CUTS[id]?CUTS[id]():[]).map(L=>({...L,text:L.text.replace(/\{n\}/g,save.name)}));
if(!list.length){if(done)done();return}
cut={id,list,i:0,done};activeCutDone=done;
if(mode==='play'&&G){G.state='cut'}
showHud(false);setScreen('cut');['l','r','j','b'].forEach(k=>setKey(k,0));showCutLine();
}
function showCutLine(){const L=cut.list[cut.i];$('cutName').textContent=L.who||'…';$('cutTxt').textContent=L.text;$('cutNext').textContent=cut.i===cut.list.length-1?'Дальше →':'Дальше';SFX.talk()}
function endCut(){const done=cut&&cut.done;cut=null;activeCutDone=null;
if(mode==='play'&&G){setScreen(null);showHud(true);G.state='play'}
if(done)done()}
function drawCut(t){if(!cut)return;const keep=ctx;ctx=$('cutC').getContext('2d');ctx.setTransform(1,0,0,1,0,0);
const L=cut.list[cut.i],T=THEMES[L.bg]||THEMES.meadow;
const g=ctx.createLinearGradient(0,0,0,300);g.addColorStop(0,T.sky[0]);g.addColorStop(1,T.sky[1]);ctx.fillStyle=g;ctx.fillRect(0,0,640,300);
if(T.stars){ctx.fillStyle='#fff';for(let i=0;i<50;i++){const h=hash(i*13);ctx.globalAlpha=.35+.65*Math.abs(Math.sin(t*1.4+i));ctx.fillRect((h%1000)/1000*640,((h>>10)%1000)/1000*150,2,2)}ctx.globalAlpha=1}
if(T.moon||T.sun){circ(540,48,26,T.sun||'#fff6b0')}
ctx.fillStyle=T.mid;ctx.beginPath();ctx.ellipse(120,268,240,66,0,Math.PI,TAU);ctx.ellipse(470,264,260,78,0,Math.PI,TAU);ctx.fill();
ctx.fillStyle=T.grass;ctx.fillRect(0,238,640,62);ctx.fillStyle=T.grass2;ctx.fillRect(0,238,640,5);
for(const ch of L.chars)drawCutChar(ch,t);
if(T.dark){ctx.fillStyle='rgba(0,0,0,.32)';ctx.fillRect(0,0,640,300)}
ctx=keep}
function drawCutChar(ch,t){const gy=268;
if(ch.k==='bone'){drawBone(640*ch.x,ch.y!==undefined?ch.y:gy-12,2.6,0,'#ffd93d','#d98e00');return}
if(ch.k==='cat'){const e={kind:'cat',x:-13,y:-22,w:26,h:22,dir:1,t,stun:0,x0:ch.x*10|0};ctx.save();ctx.translate(640*ch.x,gy);ctx.scale(2.1,2.1);drawEnemy(e,t);ctx.restore();return}
if(ch.k==='cage'){const x=640*ch.x;if(ch.di!==undefined&&ch.di>=0){const O=dogOutfit(DOGS[ch.di]);drawDog(x,gy,{face:1,onGround:true,vx:0,vy:0,anim:0,sq:0,inv:0,power:0,barkT:0},t,O)}ctx.strokeStyle='#aab2c8';ctx.lineWidth=5;for(let i=-42;i<=42;i+=13){ctx.beginPath();ctx.moveTo(x+i,gy-104);ctx.lineTo(x+i,gy-4);ctx.stroke()}ctx.fillStyle='#6a7490';ctx.fillRect(x-52,gy-116,104,12);ctx.fillRect(x-52,gy-6,104,8);return}
if(ch.k==='boss'){const b={kind:ch.kind,x:-26,y:-56,w:52,h:56,dir:ch.face||1,hp:1,maxhp:1,inv:0,hurtT:0,mode:'walk',thr:9,rage:0,t};ctx.save();ctx.translate(640*ch.x,gy);ctx.scale(ch.s||2.2,ch.s||2.2);drawBoss(b,t);ctx.restore();return}
if(ch.k==='dog'){const O=dogOutfit(DOGS[ch.d]);ctx.save();ctx.translate(640*ch.x,gy);ctx.scale(ch.s||2.1,ch.s||2.1);drawDog(0,0,{face:ch.face||1,onGround:true,vx:0,vy:0,anim:0,sq:0,inv:0,power:0,barkT:0},t,O);if(ch.mouth)drawBone((ch.face||1)*24,-22,1.25,0,'#ffd93d','#d98e00');ctx.restore();return}
if(ch.k==='player'){ctx.save();ctx.translate(640*ch.x,gy);ctx.scale(ch.s||2.1,ch.s||2.1);drawDog(0,0,{face:ch.face||1,onGround:true,vx:0,vy:0,anim:0,sq:0,inv:0,power:0,barkT:0},t);ctx.restore()}
}
/* ---------- главный шаг ---------- */
function update(dt){
const p=G.p;G.time+=dt;G.shake=Math.max(0,G.shake-dt);
if(G.fade>0&&G.fade<1.5)G.fade+=dt;
if(G.spr){G.spr.t-=dt;if(G.spr.t<=0)G.spr=null}
if(G.ghost){G.ghost.t+=dt;G.ghost.x-=230*dt;if(G.ghost.t>5)G.ghost=null}
for(const m of G.movers){m.dx=0;m.dy=0;
if(m.k==='mv'){const nx=m.x0+m.rng*(.5-.5*Math.cos(G.time*1.15));m.dx=nx-m.x;m.x=nx}
else if(m.st===1){m.tm-=dt;if(m.tm<=0){m.st=2;m.vy=0}}
else if(m.st===2){m.vy+=1400*dt;m.dy=m.vy*dt;m.y+=m.dy;if(m.y>VH+80){m.st=3;m.tm=2.4;m.gone=true}}
else if(m.st===3){m.tm-=dt;if(m.tm<=0){m.st=0;m.gone=false;m.y=m.y0;m.dy=0}}}
/* кинематографичная сцена перед боссом */
if(G.pendingCut===1&&G.boss){const A=G.L.arena;if(A&&p.x>A.trigger&&G.state==='play'&&G.L.cfg.cut){G.pendingCut=2;G.state='cut';playCut(G.L.cfg.cut,()=>{G.pendingCut=0;G.boss.thr=Math.max(G.boss.thr,1.6);G.boss.mt=1.4})}}
/* скриптовые события уровня */
const sc=G.L.cfg.script;
if(sc){const A=G.L.arena;if(A&&p.x>A.trigger&&G.state==='play'&&!G.scripted){G.scripted=1;if(sc==='baron'){save.bone=false;persist()}G.state='cut';playCut(sc==='empty'?'empty_cage':'baron_turn',()=>{
if(sc==='empty'){G.fade=.001;G.state='won';G.endT=0;G.stars=3;SFX.lose();return}
G.pendingCut=0;G.boss.mt=1.2;G.boss.thr=2;})}}
updPlayer(dt);updEnemies(dt);updBoss(dt);updProj(dt);updItems(dt);updThings(dt);
for(const d of G.dying){d.vy+=1600*dt;d.x+=d.vx*dt;d.y+=d.vy*dt;d.rot+=d.rs*dt}G.dying=G.dying.filter(d=>d.y<VH+120);
for(const q of G.parts){q.life-=dt;q.x+=(q.vx||0)*dt;q.y+=(q.vy||0)*dt;if(q.g)q.vy+=q.g*dt;if(q.rot!==undefined)q.rot+=dt*8}G.parts=G.parts.filter(q=>q.life>0);
const A=G.L.arena,b=G.boss;let tx=p.x+12-VW*.42+p.face*40;
if(b&&b.active&&!b.dead&&VW>=A.right-A.left)tx=(A.left+A.right)/2-VW/2;
tx=clamp(tx,0,Math.max(0,G.cols*TILE-VW));G.cam=lerp(G.cam,tx,1-Math.exp(-6*dt));
if(G.state==='freeing'){G.endT+=dt;if(G.endT>1.5){G.state='dlg';G.endT=0;startDialog(A.dog)}}
if(G.state==='won'){G.endT+=dt;if(G.endT>1.6&&!G.shown){G.shown=true;showWin()}}
if(G.state==='lose'){G.endT+=dt;if(G.endT>.9&&!G.shown){G.shown=true;showLose()}}
}
/* ---------- рисование: помощники ---------- */
function ell(x,y,rx,ry,col,rot=0){if(col)ctx.fillStyle=col;ctx.beginPath();ctx.ellipse(x,y,rx,ry,rot,0,TAU);ctx.fill()}
function circ(x,y,r,col){if(col)ctx.fillStyle=col;ctx.beginPath();ctx.arc(x,y,r,0,TAU);ctx.fill()}
function poly(p,col){if(col)ctx.fillStyle=col;ctx.beginPath();ctx.moveTo(p[0],p[1]);for(let i=2;i<p.length;i+=2)ctx.lineTo(p[i],p[i+1]);ctx.closePath();ctx.fill()}
function rr(x,y,w,h,r){ctx.beginPath();ctx.moveTo(x+r,y);ctx.arcTo(x+w,y,x+w,y+h,r);ctx.arcTo(x+w,y+h,x,y+h,r);ctx.arcTo(x,y+h,x,y,r);ctx.arcTo(x,y,x+w,y,r);ctx.closePath()}
function line(a,b,c,d,col,w){ctx.strokeStyle=col;ctx.lineWidth=w;ctx.lineCap='round';ctx.beginPath();ctx.moveTo(a,b);ctx.lineTo(c,d);ctx.stroke()}
function drawBone(x,y,s=1,rot=0,fill='#fff',edge='#c9a566'){ctx.save();ctx.translate(x,y);ctx.rotate(rot);ctx.scale(s,s);
for(let pass=0;pass<2;pass++){const o=pass?0:1.4;ctx.fillStyle=pass?fill:edge;ctx.fillRect(-8-o,-3-o,16+o*2,6+o*2);for(const q of[[-8,-3.5],[-8,3.5],[8,-3.5],[8,3.5]]){ctx.beginPath();ctx.arc(q[0],q[1],3.5+o,0,TAU);ctx.fill()}}ctx.restore()}
function drawKey(x,y,s,rot){ctx.save();ctx.translate(x,y);ctx.rotate(rot);ctx.scale(s,s);ctx.strokeStyle='#d98e00';ctx.lineWidth=4;ctx.beginPath();ctx.arc(-8,0,6,0,TAU);ctx.stroke();ctx.fillStyle='#ffd93d';ctx.fillRect(-2,-2,18,4);ctx.fillRect(10,2,3,7);ctx.fillRect(15,2,3,5);ctx.restore()}
function drawStar(x,y,r,t){ctx.save();ctx.translate(x,y);
const gl=ctx.createRadialGradient(0,0,2,0,0,r*2.4);gl.addColorStop(0,'rgba(255,230,120,.7)');gl.addColorStop(1,'rgba(255,230,120,0)');ctx.fillStyle=gl;ctx.fillRect(-r*2.4,-r*2.4,r*4.8,r*4.8);
ctx.scale(.8+.2*Math.cos(t*3),1);ctx.beginPath();for(let i=0;i<10;i++){const a=-Math.PI/2+i*Math.PI/5,q=i%2?r*.48:r;ctx[i?'lineTo':'moveTo'](Math.cos(a)*q,Math.sin(a)*q)}ctx.closePath();
ctx.fillStyle='#ffd93d';ctx.fill();ctx.lineWidth=2.5;ctx.strokeStyle='#f29a00';ctx.lineJoin='round';ctx.stroke();
circ(-3.2,1,1.6,'#7a4a00');circ(3.2,1,1.6,'#7a4a00');ctx.strokeStyle='#7a4a00';ctx.lineWidth=1.3;ctx.beginPath();ctx.arc(0,3,3,.2,Math.PI-.2);ctx.stroke();ctx.restore()}
function drawHeart(x,y,s){ctx.save();ctx.translate(x,y);ctx.scale(s,s);ctx.fillStyle='#ff5d73';ctx.strokeStyle='#fff';ctx.lineWidth=2;ctx.beginPath();ctx.moveTo(0,8);ctx.bezierCurveTo(-14,-2,-8,-12,0,-5);ctx.bezierCurveTo(8,-12,14,-2,0,8);ctx.fill();ctx.stroke();ctx.restore()}
function drawSausage(x,y,t){ctx.save();ctx.translate(x,y);ctx.rotate(Math.sin(t*3)*.3-.3);
const gl=ctx.createRadialGradient(0,0,3,0,0,30);gl.addColorStop(0,`hsla(${t*200%360},100%,70%,.6)`);gl.addColorStop(1,'rgba(255,255,255,0)');ctx.fillStyle=gl;ctx.fillRect(-32,-32,64,64);
rr(-13,-6,26,12,6);ctx.fillStyle='#e0714f';ctx.fill();ctx.strokeStyle='#a8442c';ctx.lineWidth=1.5;ctx.stroke();rr(-9,-4,16,3,1.5);ctx.fillStyle='rgba(255,255,255,.4)';ctx.fill();
for(let i=-6;i<=6;i+=6)line(i,-3,i+2,5,'#a8442c',1.5);ctx.restore()}
/* ---------- собака: одежда ---------- */
function drawShirt(O){const k=O.shirt,c=O.shirtCol||SHIRTS[k].c;
ctx.save();ctx.beginPath();ctx.ellipse(0,-19,16,10,0,0,TAU);ctx.clip();
const X=-11,Y=-30,W=20,H=22;
if(k===5){for(let i=0;i<6;i++){ctx.fillStyle=`hsl(${i*60},85%,60%)`;ctx.fillRect(X+i*3.4,Y,3.6,H)}}
else if(k===2){ctx.fillStyle='#fff';ctx.fillRect(X,Y,W,H);ctx.fillStyle=c;for(let y=-30;y<-8;y+=5)ctx.fillRect(X,y,W,2.6)}
else if(k===7){ctx.fillStyle=c;ctx.fillRect(X,Y,W,H);ctx.fillStyle='#fff';ctx.fillRect(3,Y,7,H)}
else{ctx.fillStyle=c;ctx.fillRect(X,Y,W,H);
if(k===1){for(let i=0;i<3;i++)circ(4,-25+i*4.5,1.2,'#fff')}
else if(k===3){ctx.fillStyle='rgba(0,0,0,.2)';rr(-6,-18,11,6,2);ctx.fill();line(5,-28,5,-22,'#fff',1.2);line(8,-28,8,-22,'#fff',1.2)}
else if(k===4){drawHeart(-1,-19,.65)}
else if(k===8){circ(-5,-21,2.6,'#e8344c');circ(-1,-14,1.8,'#4aa8ff');ctx.fillStyle='#4aa8ff';ctx.fillRect(X,-29,W,2)}}
ctx.restore();
if(k===3)ell(7.5,-25.5,4.6,4,c);
}
function drawCape(O,t,run,air){const c=O.shirtCol||SHIRTS[6].c,fl=Math.sin(t*(run?16:4))*3,b=run?-10:air?-4:0;
poly([8,-31,-10,-33,-30+b+fl*.3,-20+fl*.6,-26+b*1.2,-6+fl,4,-12],c);ctx.strokeStyle='rgba(0,0,0,.25)';ctx.lineWidth=1.5;ctx.stroke()}
function drawHat(O,run){const k=O.hat;if(!k)return;const c=O.hatCol||HATS[k].c;
ctx.save();ctx.translate(14.5,-38);ctx.rotate(run?-.1:-.05);
if(k===1){poly([-7,1,7,1,0,-17],c);poly([-4.5,-4,4.5,-4,3,-8,-3,-8],'rgba(255,255,255,.7)');circ(0,-18,3,'#ffd93d')}
else if(k===2){ctx.fillStyle=c;ctx.beginPath();ctx.arc(0,1,9.5,Math.PI,0);ctx.fill();ell(9,1.5,7,2.2,c);ell(9,2,7,1.2,'rgba(0,0,0,.25)');circ(0,-8.5,1.6,'rgba(255,255,255,.85)')}
else if(k===3){ctx.fillStyle=c;ctx.beginPath();ctx.arc(0,1,9.5,Math.PI,0);ctx.fill();ctx.fillStyle='rgba(255,255,255,.45)';rr(-10,-3,20,5,2);ctx.fill();circ(0,-9,3.6,'#fff')}
else if(k===4){ell(0,1,16,3.4,c);ell(0,2.4,16,2,'rgba(0,0,0,.22)');poly([-8,0,-7,-10,-2,-8,2,-8,7,-10,8,0],c);ctx.fillStyle='#6a3a18';ctx.fillRect(-8,-3,16,3)}
else if(k===5){ctx.fillStyle=c;ctx.fillRect(-7,-3,14,5);circ(-5,-7,5);circ(0,-10,6);circ(5,-7,5);ctx.fillStyle='rgba(0,0,0,.1)';ctx.fillRect(-7,-3,14,1.6)}
else if(k===6){poly([-13,1,-6,-9,6,-9,13,1,0,-2],c);line(-12,0,0,-3,'#ffd93d',1.5);line(12,0,0,-3,'#ffd93d',1.5);circ(0,-5,2.2,'#fff');circ(-.8,-5.3,.6,'#222');circ(.8,-5.3,.6,'#222')}
else if(k===7){ell(0,1,13,3,c);ell(0,2.2,13,1.8,'rgba(0,0,0,.22)');poly([-9,1,9,1,3,-28],c);line(-8,-2,8,-2,'#ffd93d',2);circ(-1,-10,1.8,'#ffd93d');circ(2,-18,1.3,'#ffd93d')}
else if(k===8){poly([-8,1,-9,-10,-4,-5,0,-12,4,-5,9,-10,8,1],c);ctx.strokeStyle='#e0a800';ctx.lineWidth=1.3;ctx.stroke();circ(0,-4,1.6,'#e8344c');circ(-5,-3,1.1,'#4aa8ff');circ(5,-3,1.1,'#43c767')}
else if(k===9){ell(0,1,11,2.6,c);rr(-7,-15,14,16,2);ctx.fillStyle=c;ctx.fill();ctx.fillStyle='#e8344c';ctx.fillRect(-7,-5,14,3.5);ctx.fillStyle='rgba(255,255,255,.2)';ctx.fillRect(-5,-14,2,9)}
else if(k===10){ctx.translate(-.5,8.5);ctx.globalAlpha=.3;circ(0,0,14,c);ctx.globalAlpha=1;ctx.strokeStyle='#fff';ctx.lineWidth=2.2;ctx.beginPath();ctx.arc(0,0,14,0,TAU);ctx.stroke();ctx.strokeStyle='rgba(255,255,255,.7)';ctx.lineWidth=2;ctx.beginPath();ctx.arc(0,0,10,3.8,4.6);ctx.stroke();ctx.strokeStyle='#cdd8e8';ctx.lineWidth=3;ctx.beginPath();ctx.ellipse(-3,12,10,3,0,0,TAU);ctx.stroke()}
ctx.restore()}
function drawFace(O,t,run){const f=O.face,c=O.collar;if(!f)return;
if(f===1){ctx.strokeStyle='#33406b';ctx.lineWidth=1.5;ctx.fillStyle='rgba(180,230,255,.35)';ctx.beginPath();ctx.arc(18.2,-31.8,4.6,0,TAU);ctx.fill();ctx.stroke();line(13.6,-32,10,-33.5,'#33406b',1.5)}
else if(f===2){ell(18.6,-31.6,5.4,3.8,'#15151f');line(13.4,-32,10,-33.5,'#15151f',1.8);ell(17,-33,2,1,'rgba(255,255,255,.5)',-.5)}
else if(f===3){}
else if(f===4){poly([9.5,-24.5,3,-29,3,-20],c);poly([9.5,-24.5,16,-29,16,-20],c);circ(9.5,-24.5,2.3,'rgba(0,0,0,.35)')}
else if(f===5){line(7,-22,11,-31,c,6);line(8.3,-24,11.7,-24.5,'#fff',1.5);line(9.4,-27.5,12.2,-27.8,'#fff',1.5);const fl=Math.sin(t*(run?16:5))*2;poly([5,-24,9,-22,-3-(run?6:0),-12+fl,-6-(run?6:0),-15+fl],c)}
else if(f===6){ell(22,-23,3.3,1.7,'#3a2a1a',-.3);ell(27,-23,3.3,1.7,'#3a2a1a',.3)}}
/* ---------- собака ---------- */
function drawDog(bx,by,p,t,O){
O=O||outfitNow(t);const S=O.S;
if(p.inv>0&&!(p.power>0)&&Math.floor(t*16)%2===0)return;
ctx.save();ctx.translate(bx-p.face*6,by);
if(p.power>0){const g=ctx.createRadialGradient(0,-18,4,0,-18,46);g.addColorStop(0,`hsla(${t*300%360},100%,70%,.6)`);g.addColorStop(1,'hsla(0,0%,100%,0)');ctx.fillStyle=g;ctx.fillRect(-52,-72,104,104)}
const sq=p.sq||0;ctx.scale(p.face*(1+sq*.3),1-sq*.3);
const run=p.onGround&&Math.abs(p.vx)>25,ph=p.anim,air=!p.onGround,sw=run?Math.sin(ph)*9:0,cs=Math.cos(ph);
if(run)ctx.translate(0,-Math.abs(Math.sin(ph))*1.5);
const leg=(hx,s,l,col)=>{ctx.strokeStyle=col;ctx.lineWidth=5.5;ctx.lineCap='round';ctx.beginPath();ctx.moveTo(hx,-13);ctx.lineTo(air?hx+(hx>0?7:-7):hx+s,air?-5:-1.5-(run?Math.max(0,l)*4:0));ctx.stroke()};
/* хвост + Золотая Косточка за спиной (тайная награда!) */
ctx.save();ctx.translate(-14,-23);ctx.rotate(-.7+Math.sin(t*(run?20:9))*.45);ctx.strokeStyle=S.body;ctx.lineWidth=5;ctx.lineCap='round';ctx.beginPath();ctx.moveTo(0,0);ctx.quadraticCurveTo(-7,-3,-9,-13);ctx.stroke();ctx.restore();
if(save.bone){ctx.save();ctx.translate(-7,-27);ctx.rotate(-.35);drawBone(0,0,1.1,0,'#ffd93d','#d98e00');ctx.restore()}
if(O.shirt===6)drawCape(O,t,run,air);
leg(-9,-sw,-cs,S.ear);leg(9,sw,cs,S.ear);
ell(0,-19,16,10,S.body);ell(2,-14.5,11,5,S.belly);
if(S.spots){circ(-7,-24,4,S.spots);circ(3,-26,3,S.spots);circ(-1,-17,2.5,S.spots)}
if(O.shirt&&O.shirt!==6)drawShirt(O);
ell(11,-24,8,8,S.body);circ(14,-29.5,9.5,S.body);ell(22,-26,6.5,4.6,S.belly);circ(27.5,-27.3,2.5,'#2a2230');
ctx.strokeStyle='#2a2230';ctx.lineWidth=1.3;ctx.beginPath();ctx.moveTo(22,-23.4);ctx.quadraticCurveTo(25,-22,27,-23.6);ctx.stroke();
if(run||air||p.barkT>0)ell(25,-21,2,3.4,'#ff6b8b');
if(O.face===3){ctx.fillStyle='#2a2a8a';rr(10.5,-36.5,14.5,9,3);ctx.fill()}
circ(17.5,-31.8,2.7,'#fff');circ(18.3,-31.6,1.5,'#2a2230');circ(18.8,-32.2,.55,'#fff');
ctx.save();ctx.translate(10.5,-37);ctx.rotate(run?.55+Math.sin(ph*2)*.25:air?(p.vy<0?-.1:.9):.5);ell(0,4.5,4.4,8.2,S.ear);ctx.restore();
line(7.5,-21.5,10.5,-31,O.collar,3.6);circ(9.7,-20.8,2.2,'#ffd23f');
drawFace(O,t,run);
if(O.shirt===6)circ(8,-27,2.6,'#ffd93d');
drawHat(O,run);
/* скафандр-шлем в подводной части */
if(helmetOn){ctx.globalAlpha=.28;circ(14,-30,15.5,'#9ee8ff');ctx.globalAlpha=1;ctx.strokeStyle='rgba(255,255,255,.95)';ctx.lineWidth=2.4;ctx.beginPath();ctx.arc(14,-30,15.5,0,TAU);ctx.stroke();ctx.strokeStyle='rgba(255,255,255,.75)';ctx.lineWidth=2;ctx.beginPath();ctx.arc(14,-30,11.5,3.9,4.9);ctx.stroke();ctx.fillStyle='#cdd8e8';ctx.fillRect(4,-16,20,3.5)}
leg(-9,sw,cs,S.body);leg(9,-sw,-cs,S.body);
ctx.restore();
}
/* ---------- враги ---------- */
function drawEnemy(e,t){
const cx=e.x+e.w/2,by=e.y+e.h,k=e.kind,ph=e.t*10;
ctx.save();ctx.translate(cx,by);
if((k==='hedgehog'||k==='scorpion')&&e.stun>0){ctx.translate(0,-e.h/2);ctx.scale(1,-1);ctx.translate(0,e.h/2)}
ctx.scale(e.dir||1,1);
const sw=Math.sin(ph)*3,dz=e.stun>0;
if(k==='cat'){const col=['#8e8ea0','#d89a5b','#55556a'][hash(Math.floor(e.x0))%3];
ctx.strokeStyle=col;ctx.lineWidth=4;ctx.lineCap='round';ctx.beginPath();ctx.moveTo(-9,-11);ctx.quadraticCurveTo(-19,-14,-14,-25+Math.sin(ph*.5)*2);ctx.stroke();
ell(-5+sw,-1.5,4,2.5,col);ell(7-sw,-1.5,4,2.5,col);ell(0,-10,11,8,col);circ(9,-15,8,col);
poly([3,-20,5,-29,9,-21],col);poly([10,-21,14,-29,16,-18],col);poly([5,-21,6,-26,8,-21],'#ffb3c1');
if(dz){line(9,-19,12,-15,'#222',1.6);line(12,-19,9,-15,'#222',1.6)}else{circ(12,-16,2.3,'#fff');circ(12.7,-16,1.1,'#222');line(8,-20,14.5,-17.5,'#222',1.6)}
circ(16,-13.5,1.3,'#ff7a9a');line(15,-12,22,-13,'rgba(255,255,255,.8)',.8);line(15,-11,22,-10,'rgba(255,255,255,.8)',.8)}
else if(k==='hedgehog'){ell(0,-8,12,8,'#8a5a3a');ctx.fillStyle='#4e3019';for(let i=0;i<9;i++){const a=Math.PI+(i/8)*Math.PI*.9;poly([Math.cos(a)*10,-8+Math.sin(a)*7,Math.cos(a)*18,-8+Math.sin(a)*15,Math.cos(a+.3)*10,-8+Math.sin(a+.3)*7])}
ell(10,-6,5,4.5,'#f0d2a6');circ(14.5,-6.5,1.7,'#222');circ(11,-9,1.3,'#222');ell(-5+sw,-1,3,2,'#6a4429');ell(5-sw,-1,3,2,'#6a4429')}
else if(k==='crab'){const lg=Math.sin(ph);ctx.strokeStyle='#d9392a';ctx.lineWidth=2;for(let s=-1;s<=1;s+=2)for(let i=0;i<3;i++)line(s*(5+i*3),-6,s*(9+i*3),-1+lg*s*(i-1),'#d9392a',2);
ell(0,-8,12,7,'#ff5d4a');line(-4,-13,-4,-18,'#ff5d4a',2);line(4,-13,4,-18,'#ff5d4a',2);circ(-4,-19,2.6,'#fff');circ(4,-19,2.6,'#fff');circ(-4,-19,1.2,'#222');circ(4,-19,1.2,'#222');
for(let s=-1;s<=1;s+=2){const w=Math.sin(ph*.7)*2;line(s*10,-9,s*15,-14+w,'#ff5d4a',3);circ(s*16,-16+w,4.5,'#ff3d2e');poly([s*16,-16+w,s*21,-20+w,s*19,-14+w],'#ffb09a')}
if(dz)line(-3,-6,3,-6,'#222',1.5)}
else if(k==='snowman'){ctx.rotate(Math.sin(ph*.6)*.06);circ(0,-12,12,'#fff');circ(0,-28,8.5,'#fff');ctx.strokeStyle='#cfe2ff';ctx.lineWidth=1.5;ctx.beginPath();ctx.arc(0,-12,12,0,TAU);ctx.stroke();ctx.beginPath();ctx.arc(0,-28,8.5,0,TAU);ctx.stroke();
ctx.fillStyle='#e8344c';ctx.fillRect(-8,-21,16,4);ctx.fillRect(5,-19,4,8);line(-12,-14,-19,-20,'#6a4429',2);line(12,-14,19,-20,'#6a4429',2);
poly([3,-28,13,-26,3,-25],'#ff9a3d');circ(-2,-30,1.3,'#222');circ(3,-30,1.3,'#222');ctx.fillStyle='#333';ctx.fillRect(-6,-40,12,6);ctx.fillRect(-9,-35,18,2)}
else if(k==='bee'){ell(-1,-17,6,3.5,'rgba(255,255,255,.8)',Math.sin(ph*3)*.6);ell(-6,-16,5,3,'rgba(255,255,255,.7)',-Math.sin(ph*3)*.6);poly([-10,-9,-15,-8,-10,-7],'#333');
ell(0,-9,10,7,'#ffd93d');ctx.save();ctx.beginPath();ctx.ellipse(0,-9,10,7,0,0,TAU);ctx.clip();ctx.fillStyle='#333';ctx.fillRect(-4,-17,3,16);ctx.fillRect(2,-17,3,16);ctx.restore();
circ(6,-10,2.2,'#fff');circ(6.6,-10,1.1,'#222');line(8,-15,10,-19,'#333',1)}
else if(k==='bird'){const col=hash(Math.floor(e.x0))%2?'#4a7dff':'#e85d8a';poly([-9,-9,-17,-13,-17,-6],col);ell(0,-9,11,8,col);ell(2,-6,7,4,'#fff');
ell(-2,-11+Math.sin(ph*2)*3,7,3.5,'rgba(0,0,0,.25)',Math.sin(ph*2)*.5);poly([10,-10,17,-8,10,-6],'#ffa500');circ(6,-12,2,'#fff');circ(6.6,-12,1,'#222')}
else if(k==='bat'){const f=Math.sin(ph*1.8)*7;poly([-2,-8,-21,-13+f,-12,-4],'#5d3b86');poly([2,-8,21,-13+f,12,-4],'#5d3b86');
ell(0,-8,6,6.5,'#3a2457');poly([-5,-12,-4,-19,0,-13],'#3a2457');poly([5,-12,4,-19,0,-13],'#3a2457');circ(-2.2,-9,1.4,'#ff5d73');circ(2.2,-9,1.4,'#ff5d73')}
else if(k==='scorpion'){ctx.strokeStyle='#8a2a1a';ctx.lineWidth=3.5;ctx.lineCap='round';ctx.beginPath();ctx.moveTo(-8,-8);ctx.quadraticCurveTo(-20,-10,-15,-22);ctx.quadraticCurveTo(-13,-28,-7,-26);ctx.stroke();poly([-7,-26,-3,-24,-8,-22],'#ffd93d');
for(let i=0;i<3;i++)line(-4+i*4,-4,-6+i*4+Math.sin(ph+i)*2,0,'#8a2a1a',1.8);
ell(0,-7,11,6,'#c0392b');ell(-1,-9,6,3,'rgba(255,255,255,.18)');
line(9,-8,15,-12,'#c0392b',3);circ(17,-13,3.4,'#e04a3a');poly([17,-13,22,-15,19,-10],'#e04a3a');
circ(8,-10,1.5,'#fff');circ(8.4,-10,.8,'#222')}
else if(k==='slime'){const col=['#6adf5a','#ff7a30','#6ab8ff'][hash(Math.floor(e.x0))%3],sy=1+Math.sin(ph*.8)*.1;ctx.scale(1/sy,sy);ctx.fillStyle=col;ctx.beginPath();ctx.moveTo(-13,0);ctx.bezierCurveTo(-14,-22,14,-22,13,0);ctx.closePath();ctx.fill();
ell(-5,-14,3,2,'rgba(255,255,255,.5)');circ(-3,-9,2.6,'#fff');circ(5,-9,2.6,'#fff');circ(-2.4,-9,1.3,'#222');circ(5.6,-9,1.3,'#222')}
else if(k==='robot'){const s2=Math.sin(ph)*2;ctx.fillStyle='#667189';ctx.fillRect(-7+s2,-7,5,7);ctx.fillRect(2-s2,-7,5,7);rr(-10,-20,20,14,3);ctx.fillStyle='#8896b0';ctx.fill();ctx.fillStyle='#2a3550';ctx.fillRect(-4,-17,8,5);circ(-1,-14.5,1,'#6aff9a');circ(2.5,-14.5,1,'#ff5a5a');
rr(-8,-30,17,11,3);ctx.fillStyle='#aab6cc';ctx.fill();rr(-1,-27,9,4,2);ctx.fillStyle=dz?'#444':'#ff3a3a';ctx.fill();line(0,-30,0,-35,'#667189',1.5);circ(0,-36,2,'#ff5a5a')}
else if(k==='ufo'){ctx.fillStyle='rgba(158,232,255,.9)';ctx.beginPath();ctx.ellipse(0,-11,8,8,0,Math.PI,TAU);ctx.fill();ell(0,-9,15,5.5,'#9aa6bc');ell(0,-11,10,2,'rgba(255,255,255,.35)');for(let i=-1;i<=1;i++)circ(i*8,-8,1.8,Math.floor(e.t*4+i)%2?'#ffd93d':'#ff5a5a');circ(-2.5,-15,1.5,'#33406b');circ(2.5,-15,1.5,'#33406b')}
else if(k==='ghost'){const w=Math.sin(ph*.6)*2;ctx.globalAlpha=.9;ctx.fillStyle='#f2f4ff';ctx.beginPath();ctx.moveTo(-10,-2);ctx.lineTo(-10,-16);ctx.arc(0,-16,10,Math.PI,0);ctx.lineTo(10,-2+w);ctx.lineTo(5,-6);ctx.lineTo(0,-1-w);ctx.lineTo(-5,-6);ctx.closePath();ctx.fill();ctx.globalAlpha=1;ell(-3,-17,2,3,'#33406b');ell(4,-17,2,3,'#33406b');ell(1,-9,2,2.4,'#33406b')}
else if(k==='shroom'){const s2=Math.sin(ph)*2;ell(-5+s2,-2,4,2.6,'#f3e6cf');ell(5-s2,-2,4,2.6,'#f3e6cf');rr(-6,-14,12,12,4);ctx.fillStyle='#f6ead2';ctx.fill();
ctx.beginPath();ctx.ellipse(0,-14,14,10,0,Math.PI,TAU);ctx.fillStyle='#e8344c';ctx.fill();circ(-6,-19,2.6,'#fff');circ(4,-22,2.2,'#fff');circ(8,-16,1.8,'#fff');
circ(-2,-9,1.3,'#222');circ(3,-9,1.3,'#222');line(-2,-6,3,-6,'#a8442c',1)}
ctx.restore();
if(dz){for(let i=0;i<3;i++){const a=t*5+i*2.09;ctx.save();ctx.translate(cx+Math.cos(a)*11,e.y-8+Math.sin(a)*3);ctx.beginPath();for(let q=0;q<10;q++){const aa=-Math.PI/2+q*Math.PI/5,r=q%2?2:4.5;ctx[q?'lineTo':'moveTo'](Math.cos(aa)*r,Math.sin(aa)*r)}ctx.closePath();ctx.fillStyle='#ffd93d';ctx.fill();ctx.restore()}}
}
function bossKing(b,t){
const col=b.rage>=2?'#8a4bd0':'#6b5b95';
poly([-6,-46,-32,-4,-4,-10],'#d63a4f');
ctx.strokeStyle=col;ctx.lineWidth=9;ctx.lineCap='round';ctx.beginPath();ctx.moveTo(-18,-20);ctx.quadraticCurveTo(-40,-24,-34,-50+Math.sin(t*4)*4);ctx.stroke();
ell(-11,-4,9,5,col);ell(13,-4,9,5,col);ell(0,-26,23,22,col);ell(5,-22,14,15,'#e5dcff');
circ(14,-48,16,col);poly([3,-60,5,-77,16,-62],col);poly([18,-62,27,-77,29,-58],col);poly([7,-62,8,-71,13,-63],'#ffb3c1');
poly([4,-62,6,-75,10,-67,15,-78,19,-67,23,-75,25,-62],'#ffd93d');line(4,-62,25,-62,'#e0a800',3);
circ(21,-51,4.5,'#fff');circ(22,-51,2.3,b.rage>=1?'#e12a4a':'#222');line(15,-57,26,-53,'#222',2.4);
ell(25,-43,7,4.6,'#e5dcff');circ(30,-45,2,'#ff7a9a');ctx.strokeStyle='#222';ctx.lineWidth=1.4;ctx.beginPath();ctx.moveTo(24,-40);ctx.quadraticCurveTo(28,-37,31,-41);ctx.stroke();
line(26,-42,38,-45,'rgba(255,255,255,.8)',1);line(26,-40,38,-38,'rgba(255,255,255,.8)',1);
}
function bossDragon(b,t){
const col=b.rage>=2?'#e0482e':'#3fae5a',dk=b.rage>=2?'#a82a18':'#2a8a42',fw=Math.sin(t*6)*5;
poly([-8,-40,-36,-68+fw,-30,-36],dk);poly([-8,-40,-24,-72+fw,-14,-36],'#7ad08a');ctx.strokeStyle=dk;ctx.lineWidth=2;ctx.stroke();
ctx.strokeStyle=col;ctx.lineWidth=10;ctx.lineCap='round';ctx.beginPath();ctx.moveTo(-16,-14);ctx.quadraticCurveTo(-36,-6,-42,-22+Math.sin(t*4)*4);ctx.stroke();
poly([-42,-22+Math.sin(t*4)*4,-52,-26,-44,-12],'#ffb030');
ell(-11,-4,9,5,col);ell(13,-4,9,5,col);
for(let i=0;i<4;i++)poly([-20+i*8,-42+i*2,-16+i*8,-54+i*2,-12+i*8,-44+i*2],'#ffb030');
ell(0,-26,23,22,col);ell(6,-22,14,15,'#ffd98a');for(let i=0;i<4;i++)line(-2,-32+i*6,14,-32+i*6,'rgba(200,140,40,.5)',1.5);
ell(16,-48,15,13,col);ell(29,-45,10,6.5,col);circ(34,-48,1.6,'#222');circ(30,-48,1.4,'#222');
poly([8,-58,4,-74,16,-60],'#f5e6c0');poly([19,-60,21,-76,27,-58],'#f5e6c0');
circ(20,-52,4.8,'#fff');circ(21,-52,2.4,b.rage>=1?'#e12a4a':'#222');line(14,-58,26,-54,'#222',2.4);
line(24,-41,36,-41,'#7a2a1a',1.6);
if(b.thr<.4&&b.mode==='walk'){const r=6+(.4-b.thr)*14;ctx.globalAlpha=.9;circ(40,-42,r,'#ff9a30');circ(40,-42,r*.6,'#ffe27a');ctx.globalAlpha=1}
}
function bossRobot(b,t){
const ang=b.rage>=2,eye=b.rage>=1?'#ff3a3a':'#ffd93d';
ctx.strokeStyle='#667189';ctx.lineWidth=5;ctx.lineCap='round';ctx.beginPath();ctx.moveTo(-20,-22);ctx.quadraticCurveTo(-38,-24,-32,-50+Math.sin(t*5)*4);ctx.stroke();circ(-32,-52+Math.sin(t*5)*4,3.5,'#ff3a5a');
rr(-18,-10,14,10,3);ctx.fillStyle='#667189';ctx.fill();rr(5,-10,14,10,3);ctx.fill();
rr(-23,-48,46,40,8);ctx.fillStyle='#98a6c0';ctx.fill();ctx.strokeStyle='#6a7690';ctx.lineWidth=2;ctx.stroke();
rr(-12,-40,26,20,4);ctx.fillStyle='#2a3550';ctx.fill();
for(let i=0;i<4;i++)circ(-7+i*6,-30,2.2,Math.floor(t*3+i)%2?'#6aff9a':ang?'#ff3a3a':'#4aa8ff');
rr(16,-22,26,10,4);ctx.fillStyle='#556';ctx.fill();rr(36,-24,8,14,3);ctx.fillStyle='#3a4258';ctx.fill();
if(b.thr<.3&&b.mode==='walk'){circ(46,-17,6,'#ffe27a');circ(46,-17,3,'#fff')}
poly([0,-66,2,-82,12,-66],'#aab8d0');poly([22,-66,29,-82,34,-66],'#aab8d0');poly([4,-67,5,-76,9,-67],'#ff3a6a');
rr(-3,-70,40,26,8);ctx.fillStyle='#aab8d0';ctx.fill();ctx.strokeStyle='#6a7690';ctx.lineWidth=2;ctx.stroke();
rr(10,-62,26,10,4);ctx.fillStyle='#111';ctx.fill();circ(28,-57,3.6,eye);circ(28,-57,1.6,'#fff');
for(let i=0;i<3;i++)line(14+i*4,-50,14+i*4,-46,'#556',1.5);
}
function bossYeti(b,t){
const fur=b.rage>=2?'#d0e8ff':'#f4f9ff',sh='#b6cfe8',fw=Math.sin(t*5)*3;
ell(-12,-5,10,6,sh);ell(14,-5,10,6,sh);
ell(0,-30,25,25,fur);ell(4,-24,15,15,'#dcecff');
ctx.strokeStyle=fur;ctx.lineWidth=11;ctx.lineCap='round';
ctx.beginPath();ctx.moveTo(-14,-38);ctx.lineTo(-27,-20+fw);ctx.stroke();
ctx.beginPath();ctx.moveTo(16,-38);ctx.lineTo(31,-24-fw);ctx.stroke();
circ(-27,-18+fw,6.5,'#dcecff');circ(32,-22-fw,6.5,'#dcecff');
for(let i=0;i<3;i++){line(-30+i*3,-14+fw,-31+i*3,-9+fw,'#9ac0e0',1.5);line(29+i*3,-18-fw,30+i*3,-13-fw,'#9ac0e0',1.5)}
poly([-4,-66,-9,-82,3,-70],'#7ad0ff');poly([16,-70,24,-84,23,-64],'#7ad0ff');
circ(8,-54,17,fur);ell(13,-51,11.5,9.5,'#8ad0ff');
circ(8,-58,3.9,'#fff');circ(9,-58,2,b.rage>=1?'#e12a4a':'#222');circ(18,-58,3.9,'#fff');circ(19,-58,2,b.rage>=1?'#e12a4a':'#222');
line(3,-64,13,-60,'#223',2.6);line(23,-63,16,-60,'#223',2.6);
ctx.fillStyle='#223';ctx.beginPath();ctx.ellipse(14,-45,6,3.2,0,0,TAU);ctx.fill();
poly([9,-47,11,-43,13,-47],'#fff');poly([15,-47,17,-43,19,-47],'#fff');
if(b.thr<.4&&b.mode==='walk'){const r=7+(.4-b.thr)*14;ctx.globalAlpha=.9;circ(34,-36,r,'#e8f4ff');circ(32,-38,r*.55,'#fff');ctx.globalAlpha=1}
}
function bossWizard(b,t){
const rb=b.rage>=2?'#b0207a':'#5a3ab8',rd=b.rage>=2?'#701450':'#3a2488',fl=Math.sin(t*4)*2,oc=b.rage>=1?'#ff4a9a':'#b44aff';
ctx.strokeStyle='#2f2f46';ctx.lineWidth=5;ctx.lineCap='round';ctx.beginPath();ctx.moveTo(-14,-14);ctx.quadraticCurveTo(-34,-14,-30,-36+Math.sin(t*5)*4);ctx.stroke();
line(-27,2,-27,-62,'#8a5a30',4);
const gl=ctx.createRadialGradient(-27,-66+fl,2,-27,-66+fl,22);gl.addColorStop(0,oc);gl.addColorStop(1,'rgba(180,74,255,0)');ctx.fillStyle=gl;ctx.fillRect(-52,-92+fl,50,50);
circ(-27,-66+fl,6.5,oc);circ(-29,-68+fl,2,'#fff');
poly([-22,0,-13,-42,19,-42,28,0],rb);poly([-22,0,28,0,26,-5,-20,-5],rd);
circ(-4,-22,2,'#ffd93d');circ(10,-30,1.6,'#ffd93d');circ(14,-14,1.8,'#ffd93d');circ(-10,-10,1.4,'#fff');
ell(18,-30,5,4,'#2f2f46');
circ(6,-52,14,'#2f2f46');poly([-6,-58,-7,-72,2,-62],'#2f2f46');poly([14,-62,20,-72,19,-56],'#2f2f46');
ell(13,-47,8,5.5,'#4a4a66');
ell(12,-54,4.6,3.8,'#ffe040');ell(13,-54,1.5,3.4,'#111');
ell(2,-54,3.8,3.2,'#ffe040');ell(3,-54,1.3,3,'#111');
circ(19,-49,1.6,'#ff7a9a');line(17,-47,27,-48,'rgba(255,255,255,.8)',.9);line(17,-45,27,-44,'rgba(255,255,255,.8)',.9);
ell(8,-61,20,5,rb);poly([-8,-61,26,-61,10,-98+Math.sin(t*3)*2],rb);line(-6,-65,24,-65,'#ffd93d',3);circ(10,-82,2.2,'#ffd93d');circ(8,-73,1.6,'#fff');
if(b.thr<.4&&b.mode==='walk'){circ(-27,-66+fl,9+(.4-b.thr)*18,'rgba(240,200,255,.75)')}
}
function bossEater(b,t){
const br=b.rage>=2?'#c02848':'#6a1428',dk=b.rage>=2?'#7a1020':'#3f0a18',fw=Math.sin(t*4)*3,eye=b.rage>=1?'#ffe040':'#ff8a40';
/* могучее лохматое тело */
ctx.strokeStyle=br;ctx.lineWidth=10;ctx.lineCap='round';
ctx.beginPath();ctx.moveTo(-16,-24);ctx.lineTo(-30,-36+fw);ctx.stroke();
ctx.beginPath();ctx.moveTo(18,-24);ctx.lineTo(32,-34-fw);ctx.stroke();
ell(0,-26,25,23,br);ell(2,-22,16,15,dk);
/* грозная голова */
circ(10,-52,17,br);ell(20,-46,12,8.5,dk);
circ(6,-56,4.6,'#fff');circ(7,-56,2.3,eye);circ(17,-56,4.6,'#fff');circ(18,-56,2.3,eye);
line(2,-63,12,-59,'#000',2.8);line(22,-62,14,-59,'#000',2.8);
/* оскал */
ctx.fillStyle='#1a0008';ctx.beginPath();ctx.ellipse(14,-43,9,4.6,0,0,TAU);ctx.fill();
poly([7,-45,9,-40,11,-45],'#fff');poly([13,-45,15,-40,17,-45],'#fff');poly([19,-45,21,-40,23,-45],'#fff');
/* Золотая Косточка в зубах у предателя */
drawBone(27,-43,1.35,-.25,'#ffd93d','#d98e00');
/* уши-рога */
poly([-2,-66,-6,-84,8,-70],dk);poly([16,-68,22,-82,24,-62],dk);
}
function drawBoss(b,t,dying){
const cx=b.x+b.w/2,by=b.y+b.h;ctx.save();ctx.translate(cx,by);
if(b.inv>0&&!dying&&Math.floor(t*14)%2===0)ctx.globalAlpha=.45;
ctx.scale(b.dir||1,b.mode==='crouch'?.82:1);
const k=b.kind;
if(k==='dragon')bossDragon(b,t);else if(k==='robot')bossRobot(b,t);else if(k==='yeti')bossYeti(b,t);else if(k==='wizard')bossWizard(b,t);else if(k==='eater')bossEater(b,t);else bossKing(b,t);
ctx.restore();
}
/* ---------- мир ---------- */
function scenery(kind,par,col,base,size,sp,cam,T){
ctx.fillStyle=col;if(kind!=='stal')ctx.fillRect(0,base,VW,VH-base+2);
const off=cam*par,i0=Math.floor(off/sp)-1,i1=Math.ceil((off+VW)/sp)+1;
for(let i=i0;i<=i1;i++){const h=hash(i*977+size),x=i*sp-off+(h%30),s=size*(.7+((h>>5)%50)/100);ctx.fillStyle=col;
if(kind==='round'){ctx.beginPath();ctx.ellipse(x,base,s*1.4,s*.9,0,Math.PI,TAU);ctx.fill()}
else if(kind==='dune'){ctx.beginPath();ctx.ellipse(x,base,s*2.2,s*.75,0,Math.PI,TAU);ctx.fill()}
else if(kind==='cactus'){ctx.fillRect(x-4,base-s,8,s);circ(x,base-s,4);ctx.fillRect(x-14,base-s*.55,10,5);ctx.fillRect(x-14,base-s*.8,5,s*.3);ctx.fillRect(x+4,base-s*.45,10,5);ctx.fillRect(x+9,base-s*.7,5,s*.3)}
else if(kind==='tree'){ctx.fillRect(x-3,base-s*.8,6,s*.8);circ(x,base-s*.95,s*.5,col);circ(x-s*.3,base-s*.7,s*.32);circ(x+s*.3,base-s*.7,s*.32)}
else if(kind==='pine'){ctx.fillRect(x-3,base-s*.3,6,s*.3);for(let q=0;q<3;q++){const y0=base-s*(.25+q*.42),w=s*.55*(1-q*.2);poly([x-w,y0,x,y0-s*.7,x+w,y0])}}
else if(kind==='palm'){ctx.strokeStyle=col;ctx.lineWidth=6;ctx.lineCap='round';ctx.beginPath();ctx.moveTo(x,base);ctx.quadraticCurveTo(x+s*.1,base-s*.7,x+s*.25,base-s*1.4);ctx.stroke();for(let q=0;q<6;q++){const a=-Math.PI/2+(q-2.5)*.55;ell(x+s*.25+Math.cos(a)*s*.35,base-s*1.4+Math.sin(a)*s*.25,s*.45,s*.1,col,a)}}
else if(kind==='peak'){poly([x-s*1.2,base,x,base-s*1.7,x+s*1.2,base]);poly([x-s*.36,base-s*1.2,x,base-s*1.7,x+s*.36,base-s*1.2,x+s*.1,base-s*1.05,x-s*.1,base-s*1.2],'rgba(255,255,255,.85)')}
else if(kind==='volc'){poly([x-s*1.3,base,x-s*.3,base-s*1.5,x+s*.3,base-s*1.5,x+s*1.3,base]);poly([x-s*.3,base-s*1.5,x,base-s*1.3,x+s*.3,base-s*1.5],'#ff7a30');ell(x,base-s*1.5,s*.3,s*.07,'#ffc060')}
else if(kind==='lolli'){ctx.fillStyle='#fff';ctx.fillRect(x-2,base-s*1.2,4,s*1.2);circ(x,base-s*1.4,s*.5,col);ctx.strokeStyle='rgba(255,255,255,.75)';ctx.lineWidth=3;ctx.beginPath();ctx.arc(x,base-s*1.4,s*.3,0,4.6);ctx.stroke()}
else if(kind==='planet'){circ(x,base-s*1.6,s*.7,col);ctx.strokeStyle='rgba(255,255,255,.35)';ctx.lineWidth=3;ctx.beginPath();ctx.ellipse(x,base-s*1.6,s*1.1,s*.28,-.3,0,TAU);ctx.stroke()}
else if(kind==='city'){const w=s*.8,hh=s*(1+(h%5)*.35);ctx.fillRect(x-w/2,base-hh,w,hh);ctx.fillStyle='rgba(255,230,120,.7)';for(let q=0;q<Math.floor(hh/14);q++)for(let z=0;z<3;z++)if((hash(i*7+q*3+z)&3)>0)ctx.fillRect(x-w/2+5+z*(w/3.2),base-hh+6+q*13,4,6)}
else if(kind==='gear'){const cy=base-s*.8;circ(x,cy,s*.55,col);for(let q=0;q<8;q++){const a=q*TAU/8;circ(x+Math.cos(a)*s*.62,cy+Math.sin(a)*s*.62,s*.13,col)}circ(x,cy,s*.2,'rgba(0,0,0,.35)')}
else if(kind==='stal'){poly([x-s*.35,0,x,s*1.4,x+s*.35,0])}
else if(kind==='crys'){const c=['#b9a2ff','#7ee0ff','#ff9be0'][h%3];poly([x-s*.25,base,x-s*.1,base-s*1.1,x+s*.15,base],c);poly([x+s*.1,base,x+s*.3,base-s*.7,x+s*.5,base],c);ctx.globalAlpha=.4;poly([x-s*.1,base-s*1.1,x-s*.2,base,x],'#fff');ctx.globalAlpha=1}
else if(kind==='mush'){ctx.fillStyle='rgba(240,225,255,.35)';ctx.fillRect(x-s*.12,base-s*.7,s*.24,s*.7);ctx.fillStyle=col;ctx.beginPath();ctx.ellipse(x,base-s*.7,s*.6,s*.42,0,Math.PI,TAU);ctx.fill();ctx.fillStyle='rgba(255,255,255,.35)';circ(x-s*.2,base-s*.9,s*.07);circ(x+s*.18,base-s*.8,s*.06)}
else if(kind==='coral'){const c=['#ff7a9a','#ffb060','#c080ff'][h%3];ctx.strokeStyle=c;ctx.lineWidth=5;ctx.lineCap='round';ctx.beginPath();ctx.moveTo(x,base);ctx.lineTo(x,base-s*.9);ctx.moveTo(x,base-s*.45);ctx.lineTo(x-s*.4,base-s*.95);ctx.moveTo(x,base-s*.6);ctx.lineTo(x+s*.4,base-s*1.15);ctx.stroke();circ(x,base-s*.97,s*.13,c);circ(x-s*.42,base-s*1.02,s*.12,c);circ(x+s*.42,base-s*1.22,s*.12,c)}
else if(kind==='tower'){ctx.fillRect(x-s*.4,base-s*1.9,s*.8,s*1.9);for(let q=0;q<3;q++)ctx.fillRect(x-s*.4+q*s*.3,base-s*2.05,s*.2,s*.16);poly([x-s*.5,base-s*1.9,x,base-s*2.7,x+s*.5,base-s*1.9]);circ(x,base-s*1.3,3.5,'rgba(255,220,120,.9)')}}
}
function drawBG(cam,t,T){
const g=ctx.createLinearGradient(0,0,0,VH);g.addColorStop(0,T.sky[0]);g.addColorStop(1,T.sky[1]);ctx.fillStyle=g;ctx.fillRect(0,0,VW,VH);
if(T.stars){ctx.fillStyle='#fff';for(let i=0;i<70;i++){const h=hash(i*13);ctx.globalAlpha=.35+.65*Math.abs(Math.sin(t*1.4+i));ctx.fillRect((h%1000)/1000*VW,((h>>10)%1000)/1000*VH*.65,2,2)}ctx.globalAlpha=1}
if(T.sun){const sx=VW*.78,sy=72,gr=ctx.createRadialGradient(sx,sy,10,sx,sy,95);gr.addColorStop(0,'rgba(255,255,255,.55)');gr.addColorStop(1,'rgba(255,255,255,0)');ctx.fillStyle=gr;ctx.fillRect(sx-100,sy-100,200,200);circ(sx,sy,32,T.sun)}
if(T.cloud){ctx.fillStyle='rgba(255,255,255,.88)';const W=VW+400;for(let i=0;i<6;i++){const x=(((i*260-cam*.1+t*8)%W)+W)%W-200,y=34+(i*41%90);ell(x,y,34,13);ell(x+22,y-8,24,14);ell(x-22,y-5,20,11)}}
if(T.sea){ctx.fillStyle='#4bb8ec';ctx.fillRect(0,248,VW,140);ctx.fillStyle='rgba(255,255,255,.4)';for(let i=0;i<VW/30+2;i++)ell(i*30-(cam*.2%30),252+(i%3)*6,10,1.6)}
scenery(T.d1,.2,T.far,285,72,175,cam,T);scenery(T.d2,.45,T.mid,318,52,125,cam,T);
}
function drawSea(cam,t){ctx.fillStyle='#37a9df';ctx.fillRect(0,VH-26,VW,26);ctx.fillStyle='rgba(255,255,255,.6)';for(let i=0;i<VW/26+3;i++){const x=i*26-(cam%26);ctx.beginPath();ctx.arc(x,VH-26+Math.sin(t*2+i+cam*.02)*2,10,Math.PI,TAU);ctx.fill()}}
function drawSnow(t,cam){ctx.fillStyle='rgba(255,255,255,.85)';for(let i=0;i<60;i++){const h=hash(i*7),sp=1+i%3,x=((((h%1000)/1000*VW+Math.sin(t+i)*20-cam*.3*sp)%VW)+VW)%VW,y=(t*35*sp+(hash(i*3)%VH))%VH;ctx.fillRect(x,y,2+i%2,2+i%2)}}
function drawEmbers(t,cam){for(let i=0;i<40;i++){const h=hash(i*11),sp=1+i%3,x=((((h%1000)/1000*VW+Math.sin(t*2+i)*14-cam*.2*sp)%VW)+VW)%VW,y=VH-((t*28*sp+(hash(i*5)%VH))%VH);ctx.fillStyle=i%2?'rgba(255,170,60,.85)':'rgba(255,100,40,.8)';ctx.fillRect(x,y,2+i%2,2+i%2)}}
function drawBubbles(t,cam){ctx.strokeStyle='rgba(255,255,255,.55)';ctx.lineWidth=1.6;for(let i=0;i<34;i++){const h=hash(i*17),sp=.6+(i%3)*.35,x=((((h%1000)/1000*VW+Math.sin(t+i*3)*16)%VW)+VW)%VW,y=VH-((t*55*sp+(hash(i*5)%VH))%VH);ctx.beginPath();ctx.arc(x,y,1.6+(i%3),0,TAU);ctx.stroke()}}
function drawTile(v,c,r,open,T,t){
const x=c*TILE,y=r*TILE,h=hash(c*31+r*17);
if(v===1){ctx.fillStyle=T.dirt;ctx.fillRect(x,y,TILE+1,TILE+1);ctx.fillStyle=T.dirt2;ctx.beginPath();ctx.arc(x+(h%22)+5,y+((h>>5)%18)+10,2+(h%3),0,TAU);ctx.fill();if((h>>9)%3===0)ctx.fillRect(x+(h>>3)%20,y+((h>>7)%18)+8,7,3);
if(open){ctx.fillStyle=T.grass;ctx.fillRect(x,y,TILE+1,9);ctx.fillStyle=T.grass2;ctx.fillRect(x,y+7,TILE+1,3);ctx.fillStyle=T.grass;for(let k=0;k<3;k++){const bx=x+k*11+(h>>12)%6;ctx.beginPath();ctx.moveTo(bx,y+1);ctx.lineTo(bx+3,y-4);ctx.lineTo(bx+6,y+1);ctx.fill()}}}
else if(v===2){ctx.fillStyle=T.plank2;ctx.fillRect(x,y+4,TILE+1,12);ctx.fillStyle=T.plank;ctx.fillRect(x,y+4,TILE+1,8);ctx.fillStyle='rgba(255,255,255,.35)';ctx.fillRect(x,y+4,TILE+1,2);ctx.fillStyle=T.plank2;ctx.fillRect(x+TILE-1,y+4,2,12)}
else if(v===3){ctx.fillStyle=T.spike;poly([x+2,y+32,x+10,y+14,x+18,y+32]);poly([x+14,y+32,x+22,y+14,x+30,y+32]);ctx.fillStyle='rgba(255,255,255,.4)';poly([x+10,y+14,x+12,y+22,x+8,y+22]);poly([x+22,y+14,x+24,y+22,x+20,y+22])}
else if(v===4){rr(x+1,y+1,30,30,4);ctx.fillStyle='#c98a4b';ctx.fill();ctx.strokeStyle='#7a4a1e';ctx.lineWidth=3;ctx.stroke();line(x+5,y+5,x+27,y+27,'#9a622d',3);line(x+27,y+5,x+5,y+27,'#9a622d',3);drawBone(x+16,y+16,.75)}
else if(v===5){const sp=G&&G.spr&&G.spr.c===c&&G.spr.r===r?6:0;ctx.strokeStyle='#8a93ad';ctx.lineWidth=3;ctx.beginPath();ctx.moveTo(x+8,y+32);for(let k=0;k<4;k++)ctx.lineTo(x+(k%2?24:8),y+32-(22-sp)*(k+1)/4*0.9);ctx.stroke();rr(x+3,y+8+sp,26,8,4);ctx.fillStyle='#ff5a5a';ctx.fill();ctx.strokeStyle='#b52a2a';ctx.lineWidth=2;ctx.stroke();ctx.fillStyle='rgba(255,255,255,.5)';ctx.fillRect(x+7,y+10+sp,10,2)}
}
function drawTiles(cam,T,t){const c0=Math.max(0,Math.floor(cam/TILE)),c1=Math.min(G.cols-1,Math.floor((cam+VW)/TILE));
for(let r=0;r<ROWS;r++)for(let c=c0;c<=c1;c++){const v=G.t[r][c];if(v)drawTile(v,c,r,r>0?G.t[r-1][c]!==1:false,T,t)}}
function drawMovers(T,t){for(const m of G.movers){if(m.gone)continue;const sh=m.st===1?Math.sin(t*70)*1.6:0;rr(m.x+sh,m.y,m.w,m.h,5);ctx.fillStyle=T.plank2;ctx.fill();rr(m.x+sh,m.y,m.w,m.h-4,5);ctx.fillStyle=T.plank;ctx.fill();ctx.fillStyle='rgba(255,255,255,.35)';ctx.fillRect(m.x+sh+5,m.y+2,m.w-10,2);
if(m.k==='cr'){line(m.x+18+sh,m.y+1,m.x+26+sh,m.y+10,'rgba(0,0,0,.35)',1.5);line(m.x+44+sh,m.y+1,m.x+38+sh,m.y+10,'rgba(0,0,0,.35)',1.5)}else{circ(m.x+8+sh,m.y+6,2,'#444');circ(m.x+m.w-8+sh,m.y+6,2,'#444')}}}
function drawThings(cam,t,T){for(const th of G.things){if(th.x<cam-90||th.x>cam+VW+90)continue;const x=th.x,y=th.y;
if(th.k==='cp'){ctx.fillStyle='#9aa3b8';ctx.fillRect(x-2,y-50,4,50);circ(x,y-52,4,'#ffd93d');const w=th.on?Math.sin(t*6)*3:0;poly([x+2,y-48,x+28,y-40+w,x+2,y-30],th.on?'#4ade80':'#e8344c');circ(x+11,y-39+w/2,2.6,'#fff')}
else if(th.k==='keychest'){
if(!th.got){const gl=ctx.createRadialGradient(x,y-30,4,x,y-30,70);gl.addColorStop(0,'rgba(255,240,150,.85)');gl.addColorStop(1,'rgba(255,240,150,0)');ctx.fillStyle=gl;ctx.fillRect(x-70,y-100,140,140)}
rr(x-22,y-24,44,24,4);ctx.fillStyle='#d9902a';ctx.fill();ctx.strokeStyle='#8a5410';ctx.lineWidth=2.5;ctx.stroke();ctx.beginPath();ctx.moveTo(x-22,y-24);ctx.quadraticCurveTo(x,y-46,x+22,y-24);ctx.fillStyle='#f0b040';ctx.fill();ctx.stroke();
if(th.got){ell(x,y-25,16,4,'#3a2208')}else{ctx.fillStyle='#8a5410';ctx.fillRect(x-4,y-26,8,10);drawKey(x,y-52+Math.sin(t*3)*4,2,Math.sin(t*2)*.3)}}
else if(th.k==='cage'){
const d=th.dog>=0?DOGS[th.dog]:null,O=d?dogOutfit(d):null,pd={face:-1,onGround:true,vx:0,vy:0,anim:0,sq:0,inv:0,power:0,barkT:0},o=th.open;
const bars=(a,b)=>{for(let i=a;i<=b;i+=10)line(x+i,y-62,x+i,y-5,'#aab2c8',3)};
if(!o){if(d)drawDog(x,y-5,{...pd,sq:Math.sin(t*3)*.04},t,O);bars(-40,40)}
else{const k=Math.min(1,th.ot*1.1),hop=th.ot>.3?Math.abs(Math.sin(th.ot*7))*14:0;if(d)drawDog(x-k*85,y-5-hop,pd,t,O);bars(10,40);line(x-40,y-62,x-62,y-52,'#aab2c8',3);line(x-40,y-5,x-62,y-12,'#aab2c8',3)}
rr(x-44,y-70,88,9,4);ctx.fillStyle='#6a7490';ctx.fill();ctx.fillRect(x-44,y-6,88,6);
if(!o){rr(x-6,y-34,12,10,2);ctx.fillStyle='#ffd93d';ctx.fill();ctx.strokeStyle='#d98e00';ctx.lineWidth=2;ctx.beginPath();ctx.arc(x,y-34,4,Math.PI,0);ctx.stroke();
if(G.hasKey)drawKey(x,y-90+Math.sin(t*5)*3,1.3,0)}}
else if(th.k==='goal'){rr(x-28,y-38,56,38,4);ctx.fillStyle='#e8553f';ctx.fill();poly([x-35,y-35,x,y-68,x+35,y-35],'#a63a2b');ctx.fillStyle='#3a2230';ctx.beginPath();ctx.arc(x,y-17,10,Math.PI,0);ctx.lineTo(x+10,y);ctx.lineTo(x-10,y);ctx.fill();drawBone(x,y-46,.9);line(x+22,y-60,x+22,y-84,'#9aa3b8',3);poly([x+23,y-84,x+42,y-78+Math.sin(t*5)*2,x+23,y-70],'#ffd93d')}
else if(th.k==='sign'){ctx.fillStyle='#8a5a30';ctx.fillRect(x-2,y-24,4,24);rr(x-14,y-42,28,19,4);ctx.fillStyle='#ecc98f';ctx.fill();ctx.strokeStyle='#9a6a3a';ctx.lineWidth=2;ctx.stroke();ctx.font='900 16px Nunito,sans-serif';ctx.textAlign='center';ctx.fillStyle='#c9591a';ctx.fillText('!',x,y-27)}}}
function drawItems(cam,t){for(const it of G.items){if(it.got||it.x<cam-40||it.x>cam+VW+40)continue;
if(it.k==='bone')drawBone(it.x,it.y+(it.pop===undefined?Math.sin(t*3+it.x*.05)*2.5:0),1,Math.sin(t*2+it.x)*.15);
else if(it.k==='star')drawStar(it.x,it.y+Math.sin(t*2.5)*3,14,t);
else if(it.k==='heart')drawHeart(it.x,it.y+Math.sin(t*3)*3,1.2);
else if(it.k==='sausage')drawSausage(it.x,it.y+Math.sin(t*2.5)*3,t)}}
function drawFx(t){const p=G.p;
for(const q of G.proj){ctx.save();ctx.translate(q.x,q.y);
if(q.k==='bolt'){ctx.scale(q.dir,1);ell(-14,0,7,2.2,'rgba(255,58,90,.5)');ell(0,0,14,4,'#ff3a5a');ell(2,0,10,2.2,'#fff')}
else if(q.k==='fire'){ctx.rotate(q.rot);circ(-8,-2,4,'rgba(255,120,30,.6)');circ(0,0,9,'#ff7a20');circ(0,0,6,'#ffc030');circ(0,0,3,'#fff6c0')}
else if(q.k==='snow'){ctx.rotate(q.rot);circ(0,0,9.5,'#e8f4ff');circ(-2,-2,4,'#fff');ctx.strokeStyle='#9ac8f0';ctx.lineWidth=1.5;ctx.beginPath();ctx.arc(0,0,9.5,0,TAU);ctx.stroke()}
else if(q.k==='orb'){circ(0,0,14,'rgba(190,90,255,.35)');circ(0,0,8.5,'#b44aff');circ(0,0,4.8,'#f0c8ff');circ(-2,-2,1.8,'#fff')}
else if(q.k==='bone'){ctx.rotate(q.rot);drawBone(0,0,1.5)}
else{ctx.rotate(q.rot);ell(0,0,9,4.5,'#7fd1ff');poly([8,0,15,-5,15,5],'#7fd1ff');circ(-4,-1,1.4,'#222')}
ctx.restore()}
const bk=G.boss?G.boss.kind:'king',wcs={dragon:['#ff9a30','#ffe27a'],robot:['#7ad0ff','#e0f6ff'],yeti:['#bfeaff','#ffffff'],wizard:['#b44aff','#f0c8ff'],eater:['#ff5a70','#ffc0c8']},wc=wcs[bk]||['#ffd9a0','#fff2d6'];
for(const w of G.waves){poly([w.x,w.y+14,w.x+9,w.y-2,w.x+18,w.y+14],wc[0]);poly([w.x+4,w.y+14,w.x+9,w.y+5,w.x+14,w.y+14],wc[1])}
if(p.barkT>0){const u=1-p.barkT/.3;for(let k=0;k<3;k++){ctx.strokeStyle=`rgba(255,255,255,${.9*(1-u)})`;ctx.lineWidth=3.5;ctx.beginPath();const a=p.face>0?0:Math.PI;ctx.arc(p.x+12+p.face*14,p.y+4,16+k*13+u*26,a-.7,a+.7);ctx.stroke()}}
for(const q of G.parts){const a=clamp(q.life/q.max,0,1);ctx.globalAlpha=a;
if(q.t==='c')circ(q.x,q.y,q.size*(.5+a*.5),q.col);
else if(q.t==='conf'){ctx.save();ctx.translate(q.x,q.y);ctx.rotate(q.rot);ctx.fillStyle=q.col;ctx.fillRect(-q.size/2,-q.size/4,q.size,q.size/2);ctx.restore()}
else if(q.t==='ring'){ctx.strokeStyle='#fff';ctx.lineWidth=2.5;ctx.beginPath();ctx.arc(q.x,q.y,q.size+(1-a)*22,0,TAU);ctx.stroke()}
else if(q.t==='txt'){ctx.font='900 24px Nunito,sans-serif';ctx.textAlign='center';ctx.lineWidth=5;ctx.strokeStyle='#e9742a';ctx.lineJoin='round';ctx.strokeText(q.text,q.x,q.y);ctx.fillStyle='#fff';ctx.fillText(q.text,q.x,q.y)}}
ctx.globalAlpha=1}
function render(){
ctx.setTransform(SC,0,0,SC,0,0);
const T=TH(),cam=Math.round(G.cam),t=G.time,p=G.p;
ctx.save();
if(G.shake>0)ctx.translate((Math.random()-.5)*G.shake*14,(Math.random()-.5)*G.shake*14);
if(G.L.cfg.rumble)ctx.translate(Math.sin(t*23)*2.1+(Math.random()-.5)*1.6,Math.cos(t*29)*2.1);
drawBG(cam,t,T);
if(T.sea)drawSea(cam,t);else if(!T.uw){const g2=ctx.createLinearGradient(0,VH-70,0,VH);g2.addColorStop(0,'rgba(0,0,0,0)');g2.addColorStop(1,'rgba(0,0,0,.4)');ctx.fillStyle=g2;ctx.fillRect(0,VH-70,VW,70)}
ctx.save();ctx.translate(-cam,0);
drawTiles(cam,T,t);drawThings(cam,t,T);drawMovers(T,t);if(!T.dark)drawItems(cam,t);
for(const e of G.enemies)if(!e.dead&&e.x>cam-60&&e.x<cam+VW+60)drawEnemy(e,t);
for(const d of G.dying){const cx=d.x+d.w/2,cy=d.y+d.h/2;ctx.save();ctx.translate(cx,cy);ctx.rotate(d.rot);ctx.translate(-cx,-cy);if(d.isBoss)drawBoss(d,t,true);else drawEnemy(d,t);ctx.restore()}
if(G.boss&&!G.boss.dead)drawBoss(G.boss,t);
if(G.ghost){ctx.save();ctx.globalAlpha=.4;const gh={kind:G.ghost.kind,x:G.ghost.x,y:70,w:52,h:56,dir:-1,hp:1,maxhp:1,inv:0,hurtT:0,mode:'walk',thr:9,rage:1,t:t};drawBoss(gh,t);ctx.restore()}
drawDog(p.x+p.w/2,p.y+p.h,p,t);
if(G.hasKey&&G.state==='play')drawKey(p.x+12,p.y-26+Math.sin(t*4)*3,1.4,-.3);
drawFx(t);
ctx.restore();
if(T.dark){const sx=p.x+12-cam,sy=p.y+10,g=ctx.createRadialGradient(sx,sy,40,sx,sy,270);g.addColorStop(0,'rgba(10,5,30,0)');g.addColorStop(1,'rgba(10,5,30,.8)');ctx.fillStyle=g;ctx.fillRect(0,0,VW,VH);ctx.save();ctx.translate(-cam,0);drawItems(cam,t);ctx.restore()}
if(T.uw){ctx.fillStyle='rgba(12,70,140,.16)';ctx.fillRect(0,0,VW,VH);drawBubbles(t,cam)}
if(T.snow)drawSnow(t,cam);
if(T.ember)drawEmbers(t,cam);
if(G.fade>0){ctx.globalAlpha=clamp(G.fade/1.4,0,1);ctx.fillStyle='#050310';ctx.fillRect(0,0,VW,VH);ctx.globalAlpha=1}
ctx.restore();
}
function renderMenu(){
ctx.setTransform(SC,0,0,SC,0,0);const T=THEMES[menuBg]||THEMES.meadow,t=menuT,cam=t*75;
drawBG(cam,t,T);ctx.save();ctx.translate(-cam,0);
for(let c=Math.floor(cam/TILE)-1;c<=Math.ceil((cam+VW)/TILE);c++){drawTile(1,c,9,true,T,t);drawTile(1,c,10,false,T,t);drawTile(1,c,11,false,T,t)}
for(let i=Math.floor(cam/150);i<cam/150+VW/150+2;i++)drawBone(i*150+60,235-Math.sin(t*3+i)*8,1,Math.sin(t*2+i)*.2);
drawDog(cam+VW*.2,9*TILE,{face:1,onGround:true,vx:210,vy:0,anim:t*14,sq:0,inv:0,power:0,barkT:0},t);
ctx.restore();
if(T.ember)drawEmbers(t,cam);
}
/* ---------- интерфейс ---------- */
const isTouch=matchMedia('(pointer:coarse)').matches||'ontouchstart' in window;
const HEART_P='<path d="M12 21s-8-5.2-8-11a4.5 4.5 0 0 1 8-2.8A4.5 4.5 0 0 1 20 10c0 5.8-8 11-8 11z"/>';
const STAR_PTS='12,2 15,9 22,9.5 16.5,14.5 18.5,22 12,18 5.5,22 7.5,14.5 2,9.5 9,9';
const starSvg=(on,sz)=>`<svg viewBox="0 0 24 24"${sz?` style="width:${sz}px;height:${sz}px"`:''}><polygon points="${STAR_PTS}" fill="${on?'#ffd93d':'#9aa3bd'}" stroke="${on?'#e9a100':'#6b7490'}" stroke-width="1.5" stroke-linejoin="round"/></svg>`;
const BONE_SHAPES='<g fill="#fff" stroke="#d9c3a0" stroke-width="1"><rect x="-8" y="-3" width="16" height="6"/><circle cx="-8" cy="-3.5" r="3.5"/><circle cx="-8" cy="3.5" r="3.5"/><circle cx="8" cy="-3.5" r="3.5"/><circle cx="8" cy="3.5" r="3.5"/></g>';
const GOLD_BONE_SHAPES='<g fill="#ffd93d" stroke="#d98e00" stroke-width="1.2"><rect x="-8" y="-3" width="16" height="6"/><circle cx="-8" cy="-3.5" r="3.5"/><circle cx="-8" cy="3.5" r="3.5"/><circle cx="8" cy="-3.5" r="3.5"/><circle cx="8" cy="3.5" r="3.5"/></g>';
const LOCK_SVG='<svg viewBox="0 0 24 24" width="60%" height="60%" fill="#fff"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3" fill="none" stroke="#fff" stroke-width="2.5"/></svg>';
const totalStars=()=>Object.values(save.stars).reduce((a,b)=>a+b,0);
function setHud(force){if(!G)return;
if(force||G.lastH!==G.hearts){G.lastH=G.hearts;let h='';for(let i=0;i<5;i++)h+=`<svg viewBox="0 0 24 24" fill="${i<G.hearts?'#ff5d73':'rgba(255,255,255,.22)'}" stroke="#fff" stroke-width="1.4">${HEART_P}</svg>`;$('hearts').innerHTML=h}
if(force||G.lastB!==G.bones){G.lastB=G.bones;$('boneN').textContent=G.bones}
if(force||G.lastS!==G.stars){G.lastS=G.stars;let s='';for(let i=0;i<3;i++)s+=starSvg(i<G.stars);$('starsHud').innerHTML=s}}
function setScreen(id){document.querySelectorAll('.screen').forEach(s=>s.classList.toggle('hidden',s.id!==id))}
function showHud(on){$('hud').classList.toggle('hidden',!on);$('touch').classList.toggle('hidden',!(on&&isTouch));if(!on){$('tip').classList.remove('on');$('bossBar').classList.add('hidden')}}
function toMenu(id,part){
if(id==='map')mapPart=part!==undefined?part:(G?Math.floor(G.i/6):mapPart);
mode='menu';G=null;paused=false;dlgOpen=false;dlg=null;cut=null;helmetOn=false;musicPart=0;showHud(false);musicTheme=0;musicOn=true;wardOpen=false;
menuBg='meadow';if(id==='map')buildMap();setScreen(id);setBank()}
function togglePause(){if(mode!=='play'||!G||(G.state!=='play'&&G.state!=='won'&&G.state!=='lose'))return;if(G.state!=='play')return;paused=!paused;setScreen(paused?'pause':null);if(paused)['l','r','j','b'].forEach(k=>setKey(k,0));last=performance.now()}
function showLose(){showHud(false);setScreen('lose')}
const ALL_ITEMS=()=>[...SKINS,...HATS,...SHIRTS,...FACES];
const PART_MSG=[
'Кот-Король побеждён! Ключ из сундука открыл клетку — Шарик на свободе! Он подсказал: Золотую косточку унёс Дракон Жар в Огненные земли. Открыта Часть 2!',
'Дракон Жар повержен! Тузик освобождён и узнал: косточку забрал Мехакот. Открыта Часть 3!',
'Мехакот сломлен! Дружок на свободе: косточка у Йети в Ледяном царстве. Дружок подарил костомагнит! Открыта Часть 4!',
'Йети побеждён! Снежка спасена и сказала: Маг Мурзик забрал косточку в Страну теней. Открыта Часть 5!',
'Тёмный Маг повержен! Барон тоже вышел из клетки… но где-то в городе неспокойно. Открыта Часть 6!',
'',
'Барон повержен! Волшебство рассеялось, а Золотая Косточка снова с тобой! Открыта Часть 8!'];
function showWin(){
const i=G.i;save.stars[i]=Math.max(save.stars[i]||0,G.stars);save.unlocked=Math.max(save.unlocked,Math.min(LEVELS.length-1,i+1));persist();
const final=i===LEVELS.length-1,bossEnd=i%6===5&&!final,collapse=G.ending==='collapse',sec=Math.round(G.time);
$('winH').textContent=collapse?'Провал!':final?'Праздник Большой Косточки!':bossEnd?'Часть '+(Math.floor(i/6)+1)+' пройдена!':'Уровень пройден!';
$('winStars').innerHTML=[0,1,2].map(k=>`<span style="animation-delay:${k*.25}s;display:block">${starSvg(k<G.stars)}</span>`).join('');
$('winStat').innerHTML=`<span><svg viewBox="-12 -8 24 16">${GOLD_BONE_SHAPES}</svg>+${G.bones*BONE_VALUE}</span><span>Время: ${Math.floor(sec/60)}:${String(sec%60).padStart(2,'0')}</span>`;
const boneNote=save.bone?' Золотая Косточка теперь за спиной у твоей собаки — на удачу!':'';
let base;
if(collapse)base='Пол оказался фальшивым! Ты провалился глубоко-глубоко, туда, куда свет не достаёт…';
else if(final)base='Золотая Косточка снова дома! Все пятеро друзей собрались на праздник Большой Косточки!';
else if(bossEnd)base=PART_MSG[Math.floor(i/6)]||'Уровень пройден!';
else base=G.stars===3?'Все три звезды найдены! Великолепно!':'Не все звезды найдены. Они спрятаны высоко — ищи пружинки и плиты!';
$('winMsg').textContent=base+boneNote;
$('wNext').textContent=collapse?'В подземелье!':bossEnd?'Следующая часть':'Дальше';
$('wNext').classList.toggle('hidden',final);showHud(false);setScreen('win');setBank();if(final)confetti(G.p.x,G.p.y-40,120)}
function buildMap(){
const pts=[[7,62],[20,26],[33,62],[46,26],[59,62],[72,26],[85,62],[94,30]],P=PARTS[mapPart];
menuBg=P.bg;
$('mapTitle').textContent=P.n+': '+P.t;
let st=0;for(let k=0;k<6;k++)st+=save.stars[mapPart*6+k]||0;
$('mapSub').textContent='Звёзд в части: '+st+' из 18 · Друзей спасено: '+save.dogs.length+' из '+DOGS.length;
$('mapPath').setAttribute('d','M'+pts.map(p=>p.join(',')).join(' L'));
const box=$('mapNodes');box.innerHTML='';
for(let k=0;k<6;k++){const i=mapPart*6+k,L=LEVELS[i],b=document.createElement('button'),locked=i>save.unlocked,s=save.stars[i]||0,freed=k===5&&mapPart<5&&save.dogs.includes(mapPart);
b.className='node'+(locked?' locked':'')+(k===5&&mapPart<7?' boss':'');b.style.cssText=`left:${pts[k][0]}%;top:${pts[k][1]}%;--c:${THEMES[L.id].node}`;
b.innerHTML=`${locked?LOCK_SVG:k+1}<span class="sts">${[0,1,2].map(q=>starSvg(q<s)).join('')}</span><span class="nmx">${L.name}${freed?' 🐶':''}</span>`;
b.onclick=()=>{initAudio();if(locked){toast('Сначала пройди предыдущий мир!');return}SFX.click();startLevel(i)};box.appendChild(b)}
$('dots').innerHTML=PARTS.map((_,k)=>`<i class="${k===mapPart?'on':''}"></i>`).join('');
$('partPrev').style.visibility=mapPart>0?'visible':'hidden';
$('partNext').style.visibility=mapPart<PARTS.length-1?'visible':'hidden';
$('partNext').classList.toggle('dim',save.unlocked<(mapPart+1)*6);
$('partPrev').classList.remove('dim')}
function changePart(d){const n=mapPart+d;if(n<0||n>=PARTS.length)return;initAudio();SFX.click();mapPart=n;buildMap();if(save.unlocked<n*6)toast('Часть закрыта!')}
/* ---------- гардероб (покупки за кости) ---------- */
let wardOpen=false,wardTab='skin',pvRun=false;
const pvC=$('pvC'),pvX=pvC.getContext('2d');
const PAL=['#e8344c','#ff8a3d','#ffd93d','#43c767','#4aa8ff','#7a5bd6','#ff6ab8','#ffffff','#333344'];
const SKINS=[
{n:'Рыжик',body:'#e39a42',belly:'#f7dfb0',ear:'#a8601f',need:0},
{n:'Шоколад',body:'#80512f',belly:'#dcbb90',ear:'#4d2c16',need:0},
{n:'Снежок',body:'#f6f3ec',belly:'#ffffff',ear:'#c4bcae',need:4},
{n:'Пятнашка',body:'#f3efe4',belly:'#ffffff',ear:'#3b3b44',spots:'#3b3b44',need:9},
{n:'Радуга',rainbow:1,belly:'#ffffff',ear:'#7a5bd6',need:15},
{n:'Чёрныш',body:'#3a3a48',belly:'#9a9aae',ear:'#22222c',need:6},
{n:'Лава',body:'#d9402a',belly:'#ffb070',ear:'#8a2216',need:18},
{n:'Золотой',body:'#f2c84b',belly:'#fff0b8',ear:'#c28a12',need:27},
{n:'Космо',body:'#6a5adf',belly:'#c8c0ff',ear:'#3e32a0',spots:'#ffd93d',need:40},
{n:'Свой цвет',custom:1,need:0},
{n:'Ледяной',body:'#9ad8ff',belly:'#f0fbff',ear:'#4a9ad8',need:50},
{n:'Призрак',body:'#cfd2ff',belly:'#ffffff',ear:'#8a8ad8',spots:'#ffffff',need:65}
];
const CUSTOM=SKINS.findIndex(s=>s.custom);
const HATS=[{n:'Без шапки',need:0},{n:'Праздничный колпак',need:0,c:'#ff5d9a'},{n:'Кепка',need:0,c:'#3a7bd5'},{n:'Шапка с помпоном',need:2,c:'#e8344c'},{n:'Ковбойская шляпа',need:5,c:'#a9703a'},{n:'Поварской колпак',need:8,c:'#ffffff'},{n:'Пиратская треуголка',need:12,c:'#2a2a33'},{n:'Колпак волшебника',need:16,c:'#5a3ab8'},{n:'Корона',need:22,c:'#ffd93d'},{n:'Цилиндр',need:30,c:'#26262e'},{n:'Космошлем',need:36,c:'#9ee8ff'}];
const SHIRTS=[{n:'Без кофты',need:0},{n:'Кофточка',need:0,c:'#e8344c'},{n:'Тельняшка',need:0,c:'#2a4aa8'},{n:'Худи',need:3,c:'#4aa8ff'},{n:'С сердечком',need:6,c:'#ffd93d'},{n:'Радужный свитер',need:14},{n:'Плащ героя',need:20,c:'#e8344c'},{n:'Фрак',need:28,c:'#26262e'},{n:'Космокостюм',need:38,c:'#e8eef8'}];
const FACES=[{n:'Ничего',need:0},{n:'Очки',need:0},{n:'Тёмные очки',need:4},{n:'Маска героя',need:10},{n:'Бабочка',need:2},{n:'Шарфик',need:7},{n:'Усы',need:13}];
const SHIRT_COLORABLE=[1,2,3,4,6,7,8];
const itemPrice=it=>(it.need||0)*10;
const itemOwned=(k,i)=>{const it=LISTS[k][i];return !it||itemPrice(it)===0||save.owned.includes(k+':'+i)};
const totalBonesEarned=()=>0;
function outfitNow(t){const s=SKINS[save.skin]||SKINS[0];let S=s;
if(s.custom)S={body:save.cBody,ear:save.cEar,belly:mixW(save.cBody,.65)};
else if(s.rainbow)S={...s,body:`hsl(${(t*90)%360},80%,62%)`};
const hc=save.hatC,sc=save.shirtC;
return{S,hat:HATS[save.hat]&&itemOwned('hat',save.hat)?save.hat:0,hatCol:hc>=0?PAL[hc]:null,shirt:SHIRTS[save.shirt]&&itemOwned('shirt',save.shirt)?save.shirt:0,shirtCol:sc>=0?PAL[sc]:null,face:FACES[save.face]&&itemOwned('face',save.face)?save.face:0,collar:PAL[save.collar|0]||PAL[0]}}
const mixW=(h,a)=>{const n=parseInt(h.slice(1),16),r=n>>16&255,g=n>>8&255,b=n&255,m=v=>Math.round(v+(255-v)*a);return`rgb(${m(r)},${m(g)},${m(b)})`};
const TABS=[['skin','Окрас'],['hat','Шапка'],['shirt','Кофта'],['face','Аксессуар'],['collar','Ошейник']];
const LISTS={skin:SKINS,hat:HATS,shirt:SHIRTS,face:FACES};
function palRow(label,get,set,auto){const w=document.createElement('div');w.className='palrow';const sp=document.createElement('span');sp.textContent=label;w.appendChild(sp);
if(auto){const a=document.createElement('button');a.className='sw'+(get()<0?' on':'');a.textContent='авто';a.onclick=()=>{SFX.click();set(-1);persist();buildWard()};w.appendChild(a)}
PAL.forEach((c,i)=>{const b=document.createElement('button');b.className='sw'+(get()===i?' on':'');b.style.background=c;b.onclick=()=>{SFX.click();set(i);persist();buildWard()};w.appendChild(b)});
$('cols').appendChild(w)}
function buyItem(k,i){const it=LISTS[k][i],price=itemPrice(it);if(price<=0||save.owned.includes(k+':'+i))return true;
if(save.bank<price){toast('Не хватает костей! Нужно '+price+', у тебя '+save.bank);return false}
save.bank-=price;save.owned.push(k+':'+i);persist();setBank();SFX.star();toast('Куплено: '+it.n+'!');return true}
function buildWard(){
setBank();const tb=$('tabs'),o=$('opts');tb.innerHTML='';o.innerHTML='';$('cols').innerHTML='';
TABS.forEach(([k,n])=>{const b=document.createElement('button');b.className='tab'+(k===wardTab?' on':'');b.textContent=n;b.onclick=()=>{SFX.click();wardTab=k;buildWard()};tb.appendChild(b)});
const list=LISTS[wardTab];
if(list)list.forEach((it,i)=>{const price=itemPrice(it),owned=itemOwned(wardTab,i),b=document.createElement('button');b.className='chip'+(save[wardTab]===i?' on':'')+(owned?'':' lock');
b.innerHTML=it.n+(owned?'':` · ${price} <svg viewBox="-12 -8 24 16" style="width:13px;height:13px">${BONE_SHAPES}</svg>`);
b.onclick=()=>{initAudio();if(!owned){if(!buyItem(wardTab,i))return}SFX.click();save[wardTab]=i;persist();buildWard()};o.appendChild(b)});
const cols=$('cols');
if(wardTab==='skin'&&save.skin===CUSTOM){
for(const [lbl,key] of [['Тело','cBody'],['Уши и лапы','cEar']]){const d=document.createElement('label');d.className='colin';d.innerHTML=`${lbl}<input type="color" value="${save[key]}">`;d.querySelector('input').oninput=e=>{save[key]=e.target.value;persist()};cols.appendChild(d)}}
if(wardTab==='hat'&&save.hat>0)palRow('Цвет шапки',()=>save.hatC,v=>save.hatC=v,true);
if(wardTab==='shirt'&&SHIRT_COLORABLE.includes(save.shirt))palRow('Цвет кофты',()=>save.shirtC,v=>save.shirtC=v,true);
if(wardTab==='face')palRow('Цвет ошейника и аксессуаров',()=>save.collar|0,v=>save.collar=v,false);
if(wardTab==='collar')palRow('Цвет ошейника',()=>save.collar|0,v=>save.collar=v,false);
}
function drawPreview(t){const keep=ctx;ctx=pvX;ctx.setTransform(1,0,0,1,0,0);
const g=ctx.createLinearGradient(0,0,0,190);g.addColorStop(0,'#bfe6ff');g.addColorStop(1,'#eaf8ff');ctx.fillStyle=g;ctx.fillRect(0,0,220,190);
ctx.fillStyle='#7bcf6a';ctx.fillRect(0,158,220,32);ctx.fillStyle='#5db04f';ctx.fillRect(0,158,220,5);
ctx.setTransform(2.3,0,0,2.3,115,156);
drawDog(0,0,{face:1,onGround:true,vx:pvRun?210:0,vy:0,anim:t*14,sq:0,inv:0,power:0,barkT:0},t);
ctx.setTransform(1,0,0,1,0,0);ctx=keep}
/* ---------- диалог: рисунок ---------- */
const dlgC=$('dlgC'),dlgX=dlgC.getContext('2d');
function drawDlg(t){if(!dlg)return;const keep=ctx;ctx=dlgX;ctx.setTransform(1,0,0,1,0,0);
const g=dlgX.createLinearGradient(0,0,0,170);g.addColorStop(0,'#bfe6ff');g.addColorStop(1,'#eaf8ff');dlgX.fillStyle=g;dlgX.fillRect(0,0,360,170);
dlgX.fillStyle='#7bcf6a';dlgX.fillRect(0,136,360,34);dlgX.fillStyle='#5db04f';dlgX.fillRect(0,136,360,5);
ctx=dlgX;
const L=dlg.d.talk[dlg.i],me=L[0]==='p',base={onGround:true,vx:0,vy:0,anim:t*14,sq:0,inv:0,power:0,barkT:0};
const hop=on=>on?-Math.abs(Math.sin(t*9))*5:0;
ctx.globalAlpha=me?1:.6;ctx.setTransform(1.9,0,0,1.9,90,134+hop(me));drawDog(0,0,{...base,face:1},t);
ctx.globalAlpha=me?.6:1;ctx.setTransform(1.9,0,0,1.9,270,134+hop(!me));drawDog(0,0,{...base,face:-1},t,dogOutfit(dlg.d));
ctx.globalAlpha=1;ctx.setTransform(1,0,0,1,0,0);
if(L[2])drawBone(180,96+Math.sin(t*3)*4,2.6,Math.sin(t*2)*.3,'#ffd93d','#d98e00');
ctx.setTransform(1,0,0,1,0,0);ctx=keep}
/* ---------- звук и музыка по частям ---------- */
let AC=null,step16=0,nextNote=0,musicTheme=0,musicOn=true;
function initAudio(){if(AC){if(AC.state==='suspended')AC.resume();return}try{AC=new(window.AudioContext||window.webkitAudioContext)()}catch(e){}}
function tone(f,d=.12,type='sine',vol=.12,slide=0,delay=0){if(!AC||!save.sound)return;const t=AC.currentTime+delay,o=AC.createOscillator(),g=AC.createGain();o.type=type;o.frequency.setValueAtTime(f,t);if(slide)o.frequency.exponentialRampToValueAtTime(Math.max(30,f+slide),t+d);g.gain.setValueAtTime(vol,t);g.gain.exponentialRampToValueAtTime(.0001,t+d);o.connect(g);g.connect(AC.destination);o.start(t);o.stop(t+d+.03)}
const SFX={
jump:()=>tone(330,.16,'square',.06,330),dj:()=>tone(520,.18,'square',.06,420),
bone:n=>{tone(880+n*70,.08,'triangle',.1);tone(1320+n*70,.1,'triangle',.08,0,.06)},
bark:()=>{tone(300,.2,'sawtooth',.13,-190);tone(190,.25,'square',.07,-110,.03)},
stomp:()=>tone(170,.14,'square',.12,-90),hurt:()=>tone(240,.35,'sawtooth',.12,-170),
star:()=>[784,988,1175,1568].forEach((f,i)=>tone(f,.25,'triangle',.1,0,i*.08)),
spring:()=>tone(200,.3,'sine',.18,700),crate:()=>tone(130,.16,'square',.1,-70),
check:()=>[660,880].forEach((f,i)=>tone(f,.15,'triangle',.1,0,i*.1)),
power:()=>[523,659,784,1047].forEach((f,i)=>tone(f,.12,'square',.07,0,i*.06)),
bossHit:()=>{tone(110,.3,'sawtooth',.16,-60);tone(440,.2,'square',.08,-200)},
win:()=>[523,659,784,1047,784,1047,1319].forEach((f,i)=>tone(f,.22,'triangle',.12,0,i*.11)),
lose:()=>[400,330,260,200].forEach((f,i)=>tone(f,.25,'sawtooth',.09,0,i*.14)),
click:()=>tone(700,.07,'triangle',.08),
key:()=>[988,1319,1568].forEach((f,i)=>tone(f,.18,'triangle',.1,0,i*.07)),
talk:()=>tone(420+Math.random()*160,.07,'square',.04)
};
const MEL=[0,2,4,2,5,4,2,1,0,2,4,7,5,4,2,0],BASS=[0,0,5,7];
const partMusic=()=>PART_THEMES[musicPart]||PART_THEMES[0];
function music(){if(!AC||!save.sound||!save.music||!musicOn)return;const now=AC.currentTime;if(nextNote<now-.5)nextNote=now+.05;
while(nextNote<now+.25){const i=step16%16,[root,minor]=partMusic(),tr=[0,0,5,3][(step16>>4)&3],sc=minor?SCALE_MIN:SCALE_MAJ,r=root*Math.pow(2,tr/12);
tone(r*Math.pow(2,sc[MEL[i]%sc.length]/12),.22,'triangle',.045,0,nextNote-now);
if(i%4===0)tone(r/2*Math.pow(2,BASS[(i>>2)]/12),.5,'sine',.07,0,nextNote-now);
nextNote+=.19;step16++}}
/* ---------- управление ---------- */
const held={l:0,r:0,j:0,b:0};let jp=false,bp=false;
function setKey(k,v){if(v&&!held[k]){if(k==='j')jp=true;if(k==='b')bp=true}held[k]=v?1:0}
const KM={ArrowLeft:'l',KeyA:'l',ArrowRight:'r',KeyD:'r',ArrowUp:'j',KeyW:'j',Space:'j',KeyX:'b',KeyZ:'b',KeyJ:'b',KeyK:'b',ShiftLeft:'b'};
addEventListener('keydown',e=>{initAudio();const k=KM[e.code];if(k&&!(e.target&&e.target.tagName==='INPUT')){setKey(k,1);e.preventDefault()}if((e.code==='Escape'||e.code==='KeyP')&&!e.repeat)togglePause()});
addEventListener('keyup',e=>{const k=KM[e.code];if(k){setKey(k,0)}});
/* ---------- запуск ---------- */
function resize(){const dpr=Math.min(devicePixelRatio||1,2),w=Math.round(innerWidth*dpr),h=Math.round(innerHeight*dpr);cvs.width=w;cvs.height=h;SC=h/VH;VW=w/SC}
addEventListener('resize',resize);addEventListener('orientationchange',()=>setTimeout(resize,200));resize();
document.addEventListener('touchmove',e=>{if(!e.target.closest('.panel'))e.preventDefault()},{passive:false});
document.addEventListener('contextmenu',e=>e.preventDefault());
document.addEventListener('visibilitychange',()=>{if(document.hidden&&!paused)togglePause()});
$('hudBone').innerHTML=BONE_SHAPES;$('menuBone').innerHTML=BONE_SHAPES;$('wardBone').innerHTML=BONE_SHAPES;
[['bJump','j'],['bBark','b']].forEach(([id,k])=>{const el=$(id);
el.addEventListener('pointerdown',e=>{e.preventDefault();initAudio();setKey(k,1);el.classList.add('on');try{el.setPointerCapture(e.pointerId)}catch(_){}});
['pointerup','pointercancel','lostpointercapture'].forEach(n=>el.addEventListener(n,()=>{setKey(k,0);el.classList.remove('on')}))});
const dp=$('dpad');
const dpSet=e=>{const r=dp.getBoundingClientRect(),x=(e.clientX-r.left)/r.width;setKey('l',x<.5);setKey('r',x>=.5);dp.dataset.d=x<.5?'l':'r'};
dp.addEventListener('pointerdown',e=>{e.preventDefault();initAudio();try{dp.setPointerCapture(e.pointerId)}catch(_){}dpSet(e)});
dp.addEventListener('pointermove',e=>{if(dp.hasPointerCapture&&dp.hasPointerCapture(e.pointerId))dpSet(e)});
['pointerup','pointercancel','lostpointercapture'].forEach(n=>dp.addEventListener(n,()=>{setKey('l',0);setKey('r',0);dp.dataset.d=''}));
$('pauseBtn').addEventListener('pointerdown',e=>{e.preventDefault();togglePause()});
const sndLabel=()=>{$('pSnd').textContent='Звук: '+(save.sound?'вкл':'выкл');$('setSnd').textContent='Звук: '+(save.sound?'вкл':'выкл')};
const musLabel=()=>{$('setMus').textContent='Музыка: '+(save.music?'вкл':'выкл')};
const vibLabel=()=>{$('setVib').textContent='Вибрация: '+(save.vibe?'вкл':'выкл')};
const sndToggle=()=>{initAudio();save.sound=!save.sound;persist();sndLabel();SFX.click()};
const musToggle=()=>{initAudio();save.music=!save.music;persist();musLabel();SFX.click()};
const vibToggle=()=>{save.vibe=!save.vibe;persist();vibLabel();SFX.click()};
$('pSnd').onclick=sndToggle;$('setSnd').onclick=sndToggle;sndLabel();
$('setMus').onclick=musToggle;musLabel();
$('setVib').onclick=vibToggle;vibLabel();
const de=document.documentElement;if(!(de.requestFullscreen||de.webkitRequestFullscreen)){$('fsBtn').classList.add('hidden');$('setFs').classList.add('hidden')}
$('fsBtn').onclick=()=>{try{(de.requestFullscreen||de.webkitRequestFullscreen).call(de)}catch(e){}};
$('setFs').onclick=()=>{try{(de.requestFullscreen||de.webkitRequestFullscreen).call(de)}catch(e){}};
$('setReset').onclick=()=>{initAudio();SFX.click();const b=$('setReset');if(b.dataset.arm){try{localStorage.removeItem('bublik-v2');localStorage.removeItem('bublik-v1')}catch(e){}location.reload()}else{b.dataset.arm='1';b.textContent='Точно стереть прогресс?'}};
$('nameIn').value=save.name;$('nameIn').oninput=e=>{save.name=e.target.value.trim()||'Бублик';persist()};
$('playBtn').onclick=()=>{initAudio();SFX.click();if(!save.story){playCut('intro',()=>{save.story=true;persist();mapPart=0;buildMap();setScreen('map')})}else{mapPart=Math.min(PARTS.length-1,Math.floor(save.unlocked/6));buildMap();setScreen('map')}};
$('updBtn').onclick=()=>{initAudio();SFX.click();setScreen('upd')};
$('updBack').onclick=()=>{SFX.click();setScreen('title')};
$('setBtn').onclick=()=>{initAudio();SFX.click();setScreen('set')};
$('setBack').onclick=()=>{SFX.click();setScreen('title')};
$('cutNext').onclick=()=>{initAudio();SFX.click();if(cut.i<cut.list.length-1){cut.i++;showCutLine()}else endCut()};
$('dlgNext').onclick=()=>{initAudio();SFX.click();if(dlg.i<dlg.d.talk.length-1){dlg.i++;showLine()}else endDialog()};
$('mapBack').onclick=()=>{SFX.click();toMenu('title')};
$('partPrev').onclick=()=>changePart(-1);$('partNext').onclick=()=>changePart(1);
$('wardBtn').onclick=()=>{initAudio();SFX.click();wardOpen=true;buildWard();setScreen('ward')};
$('wardOk').onclick=()=>{SFX.click();wardOpen=false;setScreen('title')};
pvC.onclick=()=>{initAudio();pvRun=!pvRun;if(!pvRun)SFX.click();else SFX.jump()};
$('pResume').onclick=togglePause;$('pRestart').onclick=()=>startLevel(G.i);$('pMap').onclick=()=>toMenu('map');
$('wNext').onclick=()=>{if(G.ending==='collapse'){toMenu('map',6);return}if(G.i%6===5)toMenu('map',Math.floor(G.i/6)+1);else startLevel(G.i+1)};
$('wAgain').onclick=()=>startLevel(G.i);$('wMap').onclick=()=>toMenu('map');
$('lRetry').onclick=()=>{G.state='play';G.hearts=3;G.shown=false;respawn();setHud(true);setScreen(null);showHud(true)};
$('lMap').onclick=()=>toMenu('map');
let last=performance.now(),acc=0;
function frame(now){
const dt=Math.min(.05,(now-last)/1000);last=now;
if(mode==='play'&&G){if(!paused&&innerHeight<=innerWidth){acc+=dt;let n=0;while(acc>=STEP&&n++<6){update(STEP);acc-=STEP}if(n>=6)acc=0}render();if(dlgOpen)drawDlg(G.time)}
else{menuT+=dt;renderMenu();if(wardOpen)drawPreview(menuT)}
if(cut)drawCut((G&&mode==='play')?G.time:menuT);
music();requestAnimationFrame(frame)}
setBank();setScreen('title');requestAnimationFrame(frame);
</script>
</body>
</html>