| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672 |
- <!DOCTYPE html>
- <html lang="ru">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
- <title>ЩИТ ДАННЫХ — Гибрид v11</title>
- <style>
- *{box-sizing:border-box;margin:0;padding:0}
- html,body{height:100%;background:#050810;overflow:hidden;font-family:'Segoe UI',system-ui,sans-serif;color:#e8eef8;user-select:none;-webkit-tap-highlight-color:transparent}
- #wrap{position:fixed;inset:0;display:flex;align-items:center;justify-content:center}
- #stage{position:relative;outline:none}
- canvas.main{display:block;width:100%;height:100%;background:#050810;border-radius:6px;outline:none}
- #hud{position:absolute;top:0;left:0;right:0;display:flex;gap:.5em;justify-content:center;padding:.5em .8em;z-index:10;pointer-events:none;flex-wrap:wrap;align-items:center}
- .hud-item{background:rgba(10,15,26,.92);border:1px solid rgba(78,161,255,.22);border-radius:.5em;padding:.24em .7em;text-align:center;min-width:4.6em}
- .hud-item span{display:block;font-size:.56em;letter-spacing:.1em;color:#7d92b0}
- .hud-item b{font-size:1em;color:#e8eef8}
- .hud-item.danger b{color:#ff7a7a}
- .hud-item.good b{color:#7ddca8}
- #progWrap{background:rgba(10,15,26,.92);border:1px solid rgba(78,161,255,.22);border-radius:.5em;padding:.24em .5em;min-width:11em}
- #progWrap .lbl{font-size:.56em;letter-spacing:.1em;color:#7d92b0;text-align:center;margin-bottom:.15em}
- #progBar{height:8px;background:#0a1220;border-radius:4px;overflow:hidden}
- #progBar i{display:block;height:100%;background:linear-gradient(90deg,#1f7ae0,#4ade80);width:0%;transition:width .3s}
- #topRight{position:absolute;top:.5em;right:.8em;display:flex;gap:.4em;z-index:12}
- #topRight button{padding:.35em .65em;font-size:.9em;min-width:2.4em}
- #taskPanel{position:absolute;top:5.2em;left:.9em;z-index:11;background:rgba(10,15,26,.92);border:1px solid rgba(78,161,255,.22);border-radius:.55em;padding:.6em .9em;min-width:12em;opacity:0;transition:opacity .25s}
- #taskPanel.show{opacity:1}
- .task-title{color:#8ba3c7;font-size:.68em;letter-spacing:.14em;margin-bottom:.35em;text-transform:uppercase;font-weight:600}
- #taskList{list-style:none;display:flex;flex-direction:column;gap:.3em;font-size:.86em}
- #taskList li{display:flex;justify-content:space-between;gap:.9em;color:#cfe2ff}
- #taskList li.done{color:#4ade80;opacity:.65}
- #taskList li.done .name{text-decoration:line-through}
- #taskList li b{color:#8ee7ff;font-variant-numeric:tabular-nums}
- #logPanel{position:absolute;bottom:1em;left:.9em;z-index:11;background:rgba(10,15,26,.94);border:1px solid rgba(78,161,255,.22);border-radius:.55em;padding:.55em .8em;width:20em;opacity:0;transition:opacity .25s;pointer-events:none;overflow:hidden}
- #logPanel.show{opacity:1}
- #logList{list-style:none;display:flex;flex-direction:column;gap:.12em;font-size:.7em;font-family:'Consolas',monospace;color:#a8c4e0}
- #logList li{display:flex;gap:.4em;line-height:1.35;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
- #logList li .t{color:#5a7090;flex-shrink:0}
- #logList li.ok{color:#7ddca8}
- #logList li.bad{color:#ff9a9a}
- #logList li.warn{color:#fbbf24}
- #logList li.sys{color:#58a6ff;font-weight:700}
- #minimap{position:absolute;bottom:1em;right:1em;width:180px;height:130px;background:rgba(10,15,26,.92);border:1px solid rgba(78,161,255,.22);border-radius:.55em;z-index:11;pointer-events:none;opacity:0;transition:opacity .25s}
- #minimap.show{opacity:1}
- #hintBar{position:absolute;left:50%;bottom:1em;transform:translateX(-50%);background:rgba(10,15,26,.94);border:1px solid rgba(78,161,255,.3);border-radius:.55em;padding:.55em 1.2em;font-size:.9em;color:#bcd4f5;white-space:nowrap;z-index:30;pointer-events:none;max-width:94%;overflow:hidden;text-overflow:ellipsis;opacity:0;transition:opacity .25s}
- #hintBar.show{opacity:1}
- #hintBar.radio{border-color:rgba(88,166,255,.6);box-shadow:0 0 12px rgba(88,166,255,.15);color:#cfe6ff}
- .screen{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:radial-gradient(circle at 50% 40%,rgba(14,22,40,.94),rgba(4,7,14,.98));z-index:20;padding:1em}
- .screen.hide{display:none}
- .panel{width:min(52em,94%);max-height:92%;overflow:auto;background:linear-gradient(160deg,rgba(22,32,52,.98),rgba(11,18,32,.99));border:1px solid rgba(78,161,255,.2);border-radius:1em;padding:1.6em 1.9em;text-align:center}
- h1{font-size:2.4em;line-height:1.05;background:linear-gradient(135deg,#66d9ff,#4ade80 60%,#a3e635);-webkit-background-clip:text;background-clip:text;color:transparent;font-weight:800}
- .sub{color:#7d92b0;font-size:.88em;letter-spacing:.18em;text-transform:uppercase;margin-bottom:1em}
- h2{font-size:1.2em;color:#dbe9ff;margin-bottom:.85em;line-height:1.35;font-weight:600}
- .desc{color:#a8bfdd;font-size:.92em;line-height:1.55;margin-bottom:1.1em;text-align:left;background:rgba(255,255,255,.03);border-left:3px solid #2f7fd6;border-radius:.4em;padding:.85em 1.05em}
- .btns{display:flex;flex-wrap:wrap;gap:.5em;justify-content:center;margin-bottom:.8em}
- .btns.col{flex-direction:column;align-items:stretch;max-width:22em;margin-left:auto;margin-right:auto}
- button{font:inherit;cursor:pointer;border-radius:.5em;border:1px solid rgba(78,161,255,.28);background:rgba(38,60,105,.4);color:#dce9ff;padding:.6em 1.2em;transition:.15s;font-size:.92em;outline:none}
- button:hover:not(:disabled){background:rgba(58,90,150,.6);border-color:rgba(120,180,255,.6)}
- button.primary{background:linear-gradient(135deg,#1f7ae0,#22c1a5);border-color:transparent;color:#fff;font-weight:600}
- button.danger{background:linear-gradient(135deg,#a02020,#c73a3a);border-color:transparent;color:#fff;font-weight:600}
- button.big{padding:1em 1.5em;font-size:1.15em;font-weight:700}
- button.ghost{background:transparent;border-color:rgba(120,180,255,.25)}
- .hintline{color:#7d92b0;font-size:.78em;margin-top:.6em}
- .rules{text-align:left;display:grid;gap:.5em;margin-bottom:1em}
- .rule{display:flex;gap:.6em;align-items:flex-start;background:rgba(255,255,255,.03);border:1px solid rgba(78,161,255,.12);border-radius:.5em;padding:.6em .8em;font-size:.88em;color:#bdd3ee}
- .rule kbd{background:#152a4a;border:1px solid #2a4a7a;border-radius:.3em;padding:.1em .4em;font-family:'Consolas',monospace;font-size:.95em;color:#dce9ff}
- .stats{display:flex;gap:.6em;justify-content:center;flex-wrap:wrap;margin-bottom:1.1em}
- .stat{background:rgba(255,255,255,.04);border:1px solid rgba(78,161,255,.15);border-radius:.55em;padding:.65em 1.15em;min-width:6.5em}
- .stat span{display:block;font-size:.6em;letter-spacing:.1em;color:#7d92b0}
- .stat b{font-size:1.4em;color:#8ee7ff}
- .setting{display:flex;justify-content:space-between;align-items:center;gap:.8em;background:rgba(255,255,255,.035);border:1px solid rgba(78,161,255,.14);border-radius:.5em;padding:.7em .9em;text-align:left;font-size:.92em}
- .setting .lbl{color:#cfe2ff;font-weight:600}
- .seg{display:flex;gap:.3em}
- .seg button{padding:.35em .7em;font-size:.82em}
- .seg button.active{background:linear-gradient(135deg,#1f7ae0,#22c1a5);border-color:transparent;color:#fff}
- #endTitle.win{background:linear-gradient(135deg,#4ade80,#22d3ee);-webkit-background-clip:text;background-clip:text;color:transparent}
- #endTitle.lose{background:linear-gradient(135deg,#ff4444,#ff8a3a);-webkit-background-clip:text;background-clip:text;color:transparent}
- #puzzleScreen .panel{padding:0;width:min(38em,96%);background:#0d1117;border:1px solid #30363d;overflow:hidden}
- .pzHeader{display:flex;align-items:center;gap:.6em;padding:.6em 1em;background:#161b22;border-bottom:1px solid #30363d;font-size:.85em;color:#c9d1d9;font-weight:600;letter-spacing:.06em;text-transform:uppercase}
- .pzHeader .dot{width:8px;height:8px;border-radius:50%;background:#58a6ff}
- .pzCanvasWrap{background:#0d1117;position:relative}
- .pzCanvas{display:block;width:100%;height:auto;background:#0d1117;touch-action:none;outline:none;cursor:pointer}
- .pzFoot{display:flex;justify-content:space-between;align-items:center;padding:.6em .9em;background:#161b22;border-top:1px solid #30363d;gap:.6em;flex-wrap:wrap}
- .pzKeys{background:#21262d;padding:.3em .6em;border-radius:.35em;border:1px solid #30363d;font-size:.78em;color:#8b949e;font-family:'Consolas',monospace}
- #pzHint{font-size:.82em;color:#8b949e;flex:1;text-align:right}
- #pzHint.ok{color:#3fb950}
- #pzHint.bad{color:#f85149}
- #pzCancel{background:#21262d;border-color:#30363d;color:#8b949e;font-size:.82em;padding:.35em .8em}
- .auditList{text-align:left;display:grid;gap:.4em;margin-bottom:1em}
- .tutGrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:.6em;margin-bottom:1em}
- .tutCard{background:rgba(255,255,255,.04);border:1px solid rgba(78,161,255,.15);border-radius:.6em;padding:.8em .5em;cursor:pointer;transition:.15s;text-align:center}
- .tutCard:hover{background:rgba(58,90,150,.5);border-color:rgba(120,180,255,.5);transform:translateY(-2px)}
- .tutCard .ic{font-size:2em;display:block;margin-bottom:.2em}
- .tutCard .ti{font-size:.82em;color:#cfe2ff;font-weight:600}
- .tutBody{text-align:left;color:#bdd3ee;font-size:.9em;line-height:1.55;margin-bottom:1em}
- #cameraScreen .panel{padding:0;width:min(70em,96%);background:#0d1117;border:1px solid #30363d;overflow:hidden;text-align:left}
- .camHeader{display:flex;align-items:center;gap:.6em;padding:.7em 1em;background:#161b22;border-bottom:1px solid #30363d;font-size:.9em;color:#c9d1d9;font-weight:700;letter-spacing:.05em;text-transform:uppercase}
- .camHeader .rec{width:10px;height:10px;border-radius:50%;background:#f85149;animation:recPulse 1.2s infinite}
- @keyframes recPulse{0%,100%{opacity:1}50%{opacity:.3}}
- .camHeader .title{flex:1}
- .camGrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:6px;padding:8px;background:#0d1117;max-height:62vh;overflow-y:auto}
- .camCell{position:relative;background:#050810;border:2px solid #30363d;border-radius:6px;overflow:hidden;cursor:pointer;transition:.15s;aspect-ratio:16/10}
- .camCell:hover{border-color:#58a6ff}
- .camCell.active{border-color:#4ade80;box-shadow:0 0 15px rgba(74,222,128,.35)}
- .camCell .camLabel{position:absolute;top:4px;left:6px;font-size:.62em;color:#8b949e;letter-spacing:.1em;text-transform:uppercase;font-weight:700;background:rgba(0,0,0,.6);padding:.15em .4em;border-radius:.25em;z-index:2}
- .camCell .camRoom{position:absolute;top:4px;right:6px;font-size:.62em;color:#c9d1d9;background:rgba(0,0,0,.6);padding:.15em .4em;border-radius:.25em;z-index:2;max-width:55%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
- .camCell .camAlert{position:absolute;bottom:6px;left:6px;right:6px;background:rgba(200,20,20,.9);color:#fff;font-size:.68em;font-weight:700;padding:.25em .5em;border-radius:.3em;text-align:center;letter-spacing:.05em;animation:alertBlink 1s infinite;z-index:3}
- @keyframes alertBlink{0%,100%{opacity:1}50%{opacity:.55}}
- .camCell canvas{display:block;width:100%;height:100%}
- .camFoot{display:flex;justify-content:space-between;align-items:center;padding:.6em 1em;background:#161b22;border-top:1px solid #30363d;font-size:.82em;color:#8b949e;gap:.6em;flex-wrap:wrap}
- .camFoot .info{flex:1}
- .camFoot button{font-size:.82em;padding:.4em 1em}
- #camReport{background:linear-gradient(135deg,#a02020,#c73a3a);border-color:transparent;color:#fff;font-weight:700}
- #camReport:disabled{opacity:.4;cursor:default;background:#30363d;color:#8b949e}
- .camStats{display:flex;gap:.9em;padding:.5em 1em;background:#0d1117;border-bottom:1px solid #21262d;font-size:.75em;color:#8b949e;flex-wrap:wrap}
- .camStats span b{color:#c9d1d9;margin-left:.3em}
- #modalBack{position:absolute;inset:0;background:rgba(4,7,14,.75);z-index:40;display:flex;align-items:center;justify-content:center}
- #modalBack.hide{display:none}
- .modalPanel{background:linear-gradient(160deg,rgba(22,32,52,.98),rgba(11,18,32,.99));border:1px solid rgba(78,161,255,.3);border-radius:.9em;padding:1.4em 1.7em;min-width:20em;max-width:90%;text-align:center}
- .modalPanel h3{color:#dbe9ff;font-size:1.1em;margin-bottom:1em}
- #mobileCtl{position:absolute;inset:0;z-index:15;pointer-events:none;display:none}
- #mobileCtl.show{display:block}
- #joyPad{position:absolute;bottom:1.5em;left:1.5em;width:150px;height:150px;pointer-events:auto}
- #joyPad .b{position:absolute;width:50px;height:50px;background:rgba(30,50,80,.65);border:1px solid rgba(120,180,255,.4);border-radius:8px;display:flex;align-items:center;justify-content:center;color:#cfe2ff;font-size:1.5em;user-select:none;touch-action:none}
- #joyPad .b.up{top:0;left:50px}
- #joyPad .b.down{bottom:0;left:50px}
- #joyPad .b.left{top:50px;left:0}
- #joyPad .b.right{top:50px;right:0}
- #btnAction{position:absolute;bottom:2em;right:1.5em;width:90px;height:90px;background:linear-gradient(135deg,#1f7ae0,#22c1a5);border:2px solid rgba(120,220,255,.5);border-radius:50%;color:#fff;font-size:1.1em;font-weight:700;display:flex;align-items:center;justify-content:center;pointer-events:auto;touch-action:none}
- #btnAction:active{transform:scale(.94)}
- #achPanel{position:absolute;top:5.2em;right:.9em;z-index:11;background:rgba(10,15,26,.92);border:1px solid rgba(78,161,255,.22);border-radius:.55em;padding:.6em .9em;min-width:13em;opacity:0;transition:opacity .25s;pointer-events:none;max-width:15em}
- #achPanel.show{opacity:1}
- #achList{list-style:none;display:flex;flex-direction:column;gap:.25em;font-size:.78em}
- #achList li{color:#6e7681;display:flex;gap:.4em;align-items:center;opacity:.4}
- #achList li.unlocked{color:#fbbf24;opacity:1}
- </style>
- </head>
- <body>
- <div id="wrap">
- <div id="stage" tabindex="0">
- <canvas id="cv" class="main" tabindex="-1"></canvas>
- <div id="hud" class="hide">
- <div class="hud-item"><span>ОЧКИ</span><b id="hudScore">0</b></div>
- <div class="hud-item"><span>СМЕНА</span><b id="hudWave">1 / 4</b></div>
- <div class="hud-item"><span>ЗАКРЫТО</span><b id="hudFixed">0</b></div>
- <div class="hud-item danger"><span>УТЕЧКИ</span><b id="hudLeaks">0 / 6</b></div>
- <div class="hud-item good"><span>ПОЙМАНО</span><b id="hudCaught">0</b></div>
- <div class="hud-item"><span>РЕКОРД</span><b id="hudHigh">0</b></div>
- <div id="progWrap"><div class="lbl">ПРОГРЕСС СМЕНЫ</div><div id="progBar"><i id="progFill"></i></div></div>
- </div>
- <div id="taskPanel"><div class="task-title">📋 Задачи смены</div><ul id="taskList"></ul></div>
- <div id="achPanel"><div class="task-title">🏆 Достижения</div><ul id="achList"></ul></div>
- <div id="logPanel"><div class="task-title">📻 Журнал смены</div><ul id="logList"></ul></div>
- <canvas id="minimap" width="180" height="130"></canvas>
- <div id="topRight">
- <button id="btnHomeTop" tabindex="-1">⌂</button>
- <button id="btnPauseTop" tabindex="-1">⏸</button>
- <button id="btnHelpTop" tabindex="-1">💡</button>
- <button id="btnFsTop" tabindex="-1">⛶</button>
- </div>
- <div id="hintBar"><span id="hintText"></span></div>
- <div id="mobileCtl">
- <div id="joyPad">
- <div class="b up" data-k="up">▲</div>
- <div class="b down" data-k="down">▼</div>
- <div class="b left" data-k="left">◀</div>
- <div class="b right" data-k="right">▶</div>
- </div>
- <div id="btnAction">E</div>
- </div>
- <div id="mainMenuScreen" class="screen">
- <div class="panel">
- <h1>ЩИТ ДАННЫХ</h1>
- <div class="sub">Оператор информационной безопасности · Гибрид v11</div>
- <div class="btns col">
- <button class="primary big" id="btnContinue" style="display:none">▶ Продолжить смену</button>
- <button class="primary big" id="btnPlayGame">▶ Новая смена</button>
- <button class="big" id="btnTutorial">🎓 Обучение</button>
- <button class="big" id="btnPuzzleHelp">📖 Головоломки</button>
- <button class="big" id="btnSettings">⚙ Настройки</button>
- <button class="big" id="btnAchievements">🏆 Достижения</button>
- <button class="ghost" id="btnRules">❔ Правила</button>
- </div>
- <div class="hintline"><kbd>W</kbd><kbd>A</kbd><kbd>S</kbd><kbd>D</kbd> движение · <kbd>E</kbd> действие · <kbd>C</kbd> камеры · <kbd>Esc</kbd> пауза</div>
- <div class="hintline" id="highScoreLine">🏆 Рекорд: 0</div>
- </div>
- </div>
- <div id="achScreen" class="screen hide">
- <div class="panel">
- <h2>🏆 Достижения</h2>
- <div id="achScreenList" style="text-align:left;display:grid;gap:.5em;margin-bottom:1em"></div>
- <div class="btns"><button class="primary" id="btnAchBack">← Назад</button></div>
- </div>
- </div>
- <div id="settingsScreen" class="screen hide">
- <div class="panel">
- <h2>⚙ Настройки</h2>
- <div style="display:grid;gap:.5em;margin-bottom:1em">
- <div class="setting"><div><span class="lbl">Сложность</span></div><div class="seg" id="segDiff"><button data-v="easy">Легко</button><button data-v="normal">Норм.</button><button data-v="hard">Сложно</button></div></div>
- <div class="setting"><div><span class="lbl">Звук</span></div><div class="seg" id="segSound"><button data-v="1">Вкл</button><button data-v="0">Выкл</button></div></div>
- <div class="setting"><div><span class="lbl">Мобильное управление</span></div><div class="seg" id="segMobile"><button data-v="auto">Авто</button><button data-v="1">Вкл</button><button data-v="0">Выкл</button></div></div>
- <div class="setting"><div><span class="lbl">Полный экран</span></div><button id="btnFs" class="primary" style="padding:.4em .9em;font-size:.85em">⛶ Переключить</button></div>
- <div class="setting"><div><span class="lbl">Сброс прогресса</span></div><button id="btnResetProgress" class="danger" style="padding:.4em .9em;font-size:.85em">🗑 Сбросить</button></div>
- </div>
- <div class="btns"><button class="primary" id="btnSettingsBack">← Назад в меню</button></div>
- </div>
- </div>
- <div id="rulesScreen" class="screen hide">
- <div class="panel">
- <h2>Как играть</h2>
- <div class="rules">
- <div class="rule"><div><b>SOC (центр)</b> — ваша комната, от неё растут коридоры.</div></div>
- <div class="rule"><div><kbd>C</kbd> — камеры (только в SOC).</div></div>
- <div class="rule"><div>Клик по камере → фокус, <kbd>E</kbd> — доложить.</div></div>
- <div class="rule"><div>Движение — <kbd>WASD</kbd> / <kbd>стрелки</kbd> / джойстик.</div></div>
- <div class="rule"><div><kbd>E</kbd> — открыть инцидент рядом.</div></div>
- <div class="rule"><div>Инциденты: таймер. Просрочка → утечка. 6 → провал.</div></div>
- <div class="rule"><div>После всех смен — <b>аудит</b>.</div></div>
- </div>
- <div class="btns"><button id="btnRulesBack" class="primary">Понятно</button></div>
- </div>
- </div>
- <div id="pauseScreen" class="screen hide">
- <div class="panel" style="width:min(24em,90%)">
- <h2>⏸ Пауза</h2>
- <div class="btns col">
- <button id="btnResume" class="primary big">▶ Продолжить</button>
- <button id="btnPauseRules">❔ Правила</button>
- <button id="btnExitMenu" class="danger">⌂ Выйти в меню</button>
- </div>
- </div>
- </div>
- <div id="shiftScreen" class="screen hide">
- <div class="panel">
- <h2 id="shiftTitle">Рапорт</h2>
- <div class="desc" id="shiftMsg"></div>
- <div class="stats">
- <div class="stat"><span>ЗАКРЫТО</span><b id="shiftFixed">0</b></div>
- <div class="stat"><span>УТЕЧКИ</span><b id="shiftLeaks">0</b></div>
- <div class="stat"><span>ПОЙМАНО</span><b id="shiftCaught">0</b></div>
- <div class="stat"><span>ОЧКИ</span><b id="shiftScore">0</b></div>
- </div>
- <div class="btns"><button id="shiftNext" class="primary big">Следующая смена ▶</button></div>
- </div>
- </div>
- <div id="auditScreen" class="screen hide">
- <div class="panel">
- <h1 style="font-size:2em">🔍 АУДИТ</h1>
- <div class="sub">Проверка службы ИБ</div>
- <div class="desc">📻 <b>Диспетчер:</b> Едет проверяющий. Закройте все инциденты без утечек.</div>
- <div class="auditList" id="auditList"></div>
- <div class="btns"><button id="btnAuditStart" class="primary big">Начать аудит ▶</button></div>
- </div>
- </div>
- <div id="puzzleScreen" class="screen hide">
- <div class="panel">
- <div class="pzHeader"><div class="dot" id="pzDot"></div><span id="pzTitle">Инцидент</span></div>
- <div class="pzCanvasWrap"><canvas id="pzCanvas" width="480" height="360" class="pzCanvas" tabindex="0"></canvas></div>
- <div class="pzFoot">
- <span class="pzKeys" id="pzKeys">—</span>
- <span id="pzHint">—</span>
- <button id="pzCancel">✕</button>
- </div>
- </div>
- </div>
- <div id="cameraScreen" class="screen hide">
- <div class="panel">
- <div class="camHeader"><span class="rec"></span><span class="title">📹 СИСТЕМА ВИДЕОНАБЛЮДЕНИЯ</span><span style="color:#8b949e;font-weight:400;font-size:.85em">LIVE</span></div>
- <div class="camStats">
- <span>Комнат: <b id="camBotsCount">0</b></span>
- <span>Подозрительных: <b id="camSusCount" style="color:#f85149">0</b></span>
- <span>Поймано (за смену / всего): <b id="camCaughtCount" style="color:#4ade80">0 / 0</b></span>
- </div>
- <div class="camGrid" id="camGrid"></div>
- <div class="camFoot">
- <span class="info" id="camInfo">Клик по камере · E — доложить · C — закрыть</span>
- <button id="camReport" disabled>🚨 Доложить</button>
- <button id="camClose">✕</button>
- </div>
- </div>
- </div>
- <div id="endScreen" class="screen hide">
- <div class="panel">
- <h1 id="endTitle">Смена закрыта</h1>
- <div id="endSub" class="sub">Результат</div>
- <div class="stats">
- <div class="stat"><span>ОЧКИ</span><b id="stScore">0</b></div>
- <div class="stat"><span>ЗАКРЫТО</span><b id="stFixed">0</b></div>
- <div class="stat"><span>УТЕЧКИ</span><b id="stLeaks">0</b></div>
- <div class="stat"><span>ПОЙМАНО</span><b id="stCaught">0</b></div>
- </div>
- <div id="endMsg" class="desc"></div>
- <div class="btns">
- <button id="btnRestart" class="primary">↻ Снова на смену</button>
- <button id="btnMenu">⌂ В главное меню</button>
- </div>
- </div>
- </div>
- <div id="tutorialScreen" class="screen hide">
- <div class="panel">
- <h1>📖 Обучение</h1>
- <div class="sub">Как проходить головоломки</div>
- <div class="tutGrid" id="tutGrid"></div>
- <div class="btns"><button id="btnTutBack" class="primary">← Назад в меню</button></div>
- </div>
- </div>
- <div id="tutDetailScreen" class="screen hide">
- <div class="panel">
- <h1 id="tutDetailTitle" style="font-size:1.7em">—</h1>
- <div class="sub" id="tutDetailSub">—</div>
- <div class="tutBody" id="tutDetailBody"></div>
- <div class="btns">
- <button id="btnTutTry" class="primary">▶ Попробовать</button>
- <button id="btnTutDetailBack">← К списку</button>
- </div>
- </div>
- </div>
- <div id="modalBack" class="hide">
- <div class="modalPanel">
- <h3 id="modalText">Выйти в главное меню?</h3>
- <div class="btns">
- <button id="modalYes" class="danger">Да</button>
- <button id="modalNo" class="primary">Отмена</button>
- </div>
- </div>
- </div>
- </div>
- </div>
- <script>
- (function(){
- 'use strict';
- /* ============================================================
- SAFE BOOT — глобальный обработчик ошибок
- ============================================================ */
- window.addEventListener('error', function(e){
- try {
- console.error('[FATAL]', e.message, e.filename + ':' + e.lineno);
- const h = document.getElementById('hintBar');
- const t = document.getElementById('hintText');
- if (h && t){ t.textContent = 'ОШИБКА: ' + e.message + ' · стр. ' + e.lineno; h.classList.add('show'); }
- } catch(_){}
- });
- /* ============================================================
- ЭЛЕМЕНТЫ
- ============================================================ */
- const $ = id => document.getElementById(id);
- const el = {};
- [
- 'cv','stage','hud','hudScore','hudWave','hudFixed','hudLeaks','hudCaught','hudHigh','progFill',
- 'taskPanel','taskList','achPanel','achList','logPanel','logList','minimap','hintBar','hintText',
- 'pzCanvas','pzTitle','pzHint','pzKeys','pzDot','pzCancel',
- 'mainMenuScreen','achScreen','achScreenList','settingsScreen','rulesScreen','pauseScreen',
- 'shiftScreen','shiftTitle','shiftMsg','shiftFixed','shiftLeaks','shiftCaught','shiftScore','shiftNext',
- 'puzzleScreen','auditScreen','auditList','btnAuditStart','endScreen',
- 'tutorialScreen','tutDetailScreen','tutGrid','tutDetailTitle','tutDetailSub','tutDetailBody',
- 'btnTutBack','btnTutTry','btnTutDetailBack','btnPuzzleHelp','btnAchievements','btnAchBack',
- 'btnResetProgress','cameraScreen','camGrid','camReport','camClose','camInfo','camBotsCount',
- 'camSusCount','camCaughtCount','modalBack','modalText','modalYes','modalNo','highScoreLine',
- 'mobileCtl','joyPad','btnAction','btnContinue','btnPlayGame','btnTutorial','btnSettings',
- 'btnRules','btnResume','btnPauseRules','btnExitMenu','btnRestart','btnMenu','btnHomeTop',
- 'btnPauseTop','btnHelpTop','btnFsTop','btnFs','btnSettingsBack','btnRulesBack',
- 'endTitle','endSub','stScore','stFixed','stLeaks','stCaught','endMsg'
- ].forEach(id => { el[id] = $(id); });
- for (const k in el){ if (!el[k]) console.warn('[MISSING EL]', k); }
- /* ============================================================
- БАЗА
- ============================================================ */
- const W = 1280, H = 720, DEPTH = 0.82, T = 22;
- const ROOM_SIZE = 700, DOOR_SIZE = 180;
- let WORLD_W = 1400, WORLD_D = 1100;
- let camX = 0, camY = 0;
- const cv = el.cv;
- const ctx = cv.getContext('2d', {alpha:false});
- cv.width = W; cv.height = H;
- function resize(){
- const s = Math.min(window.innerWidth / W, window.innerHeight / H);
- el.stage.style.width = Math.floor(W * s) + 'px';
- el.stage.style.height = Math.floor(H * s) + 'px';
- el.stage.style.fontSize = Math.max(9, 16 * s) + 'px';
- }
- window.addEventListener('resize', resize); resize();
- const clamp = (v,a,b) => v < a ? a : (v > b ? b : v);
- const rand = (a,b) => a + Math.random() * (b - a);
- function shuffle(a){ for (let i = a.length - 1; i > 0; i--){ const j = Math.floor(Math.random() * (i + 1)); const t = a[i]; a[i] = a[j]; a[j] = t; } return a; }
- function roundRect(c, x, y, w, h, r){ c.beginPath(); c.moveTo(x+r, y); c.arcTo(x+w, y, x+w, y+h, r); c.arcTo(x+w, y+h, x, y+h, r); c.arcTo(x, y+h, x, y, r); c.arcTo(x, y, x+w, y, r); c.closePath(); }
- function dist2(ax, ay, bx, by){ const dx=ax-bx, dy=ay-by; return dx*dx+dy*dy; }
- let _lastFont = '';
- function setFont(f){ if (_lastFont !== f){ ctx.font = f; _lastFont = f; } }
- /* ============================================================
- НАСТРОЙКИ
- ============================================================ */
- const settings = { diff:'normal', sound:1, mobile:'auto' };
- let highScore = 0;
- try {
- const s = JSON.parse(localStorage.getItem('shield9_settings') || 'null'); if (s) Object.assign(settings, s);
- highScore = parseInt(localStorage.getItem('shield9_highscore') || '0', 10) || 0;
- } catch(e){}
- function saveSettings(){ try { localStorage.setItem('shield9_settings', JSON.stringify(settings)); } catch(e){} }
- function saveHigh(){ try { localStorage.setItem('shield9_highscore', String(highScore)); } catch(e){} }
- function applySettingsToUI(){
- document.querySelectorAll('#segDiff button').forEach(b => b.classList.toggle('active', b.dataset.v === settings.diff));
- document.querySelectorAll('#segSound button').forEach(b => b.classList.toggle('active', +b.dataset.v === settings.sound));
- document.querySelectorAll('#segMobile button').forEach(b => b.classList.toggle('active', b.dataset.v === settings.mobile));
- if (el.highScoreLine) el.highScoreLine.textContent = '🏆 Рекорд: ' + highScore;
- }
- const isTouchDevice = ('ontouchstart' in window) || navigator.maxTouchPoints > 0;
- function updateMobileVisibility(){
- const show = settings.mobile === '1' || (settings.mobile === 'auto' && isTouchDevice);
- if (el.mobileCtl) el.mobileCtl.classList.toggle('show', show && state === 'playing');
- }
- /* ============================================================
- ДОСТИЖЕНИЯ
- ============================================================ */
- const ACHIEVEMENTS = [
- {id:'first_shift', ic:'🎬', name:'Первая смена', desc:'Завершить первую смену', check: s => s.shifts >= 1},
- {id:'perfect', ic:'💎', name:'Безупречно', desc:'Смена без утечек', check: s => s.perfectShift},
- {id:'catcher', ic:'🕸️', name:'Ловец', desc:'Поймать 5 нарушителей', check: s => s.totalCaught >= 5},
- {id:'veteran', ic:'🎖️', name:'Ветеран', desc:'Пройти все 4 смены', check: s => s.shifts >= 4},
- {id:'audit_pass', ic:'✅', name:'Проверку прошёл', desc:'Успешно пройти аудит', check: s => s.auditPassed},
- {id:'no_errors', ic:'🎯', name:'Снайпер', desc:'10 закрытий без ошибок', check: s => s.fixedNoErrors >= 10},
- {id:'record', ic:'🏅', name:'Рекордсмен', desc:'500 очков', check: s => s.score >= 500}
- ];
- let unlockedAchievements = new Set();
- try { const a = JSON.parse(localStorage.getItem('shield9_ach') || '[]'); unlockedAchievements = new Set(a); } catch(e){}
- function saveAch(){ try { localStorage.setItem('shield9_ach', JSON.stringify([...unlockedAchievements])); } catch(e){} }
- function checkAchievements(stats){
- for (const a of ACHIEVEMENTS){
- if (!unlockedAchievements.has(a.id) && a.check(stats)){
- unlockedAchievements.add(a.id); saveAch();
- toast('🏆 ' + a.name + ' — ' + a.desc, 'ok');
- addLog('🏆 Достижение: ' + a.name, 'sys');
- soundAch();
- renderAchievementsUI(); refreshAchievementHUD();
- }
- }
- }
- function renderAchievementsUI(){
- if (el.achList){ el.achList.innerHTML = ''; }
- if (el.achScreenList){ el.achScreenList.innerHTML = ''; }
- for (const a of ACHIEVEMENTS){
- const unlocked = unlockedAchievements.has(a.id);
- if (el.achList){
- const li = document.createElement('li'); li.className = unlocked ? 'unlocked' : '';
- const ic = document.createElement('span'); ic.className = 'ic'; ic.textContent = a.ic;
- const nm = document.createElement('span'); nm.textContent = a.name;
- li.appendChild(ic); li.appendChild(nm); el.achList.appendChild(li);
- }
- if (el.achScreenList){
- const row = document.createElement('div');
- row.style.cssText = 'background:rgba(255,255,255,.03);border:1px solid ' + (unlocked?'rgba(251,191,36,.4)':'rgba(78,161,255,.12)') + ';border-radius:.5em;padding:.6em .8em;display:flex;gap:.7em;align-items:center;opacity:' + (unlocked?'1':'.5');
- const icB = document.createElement('span'); icB.style.fontSize = '1.6em'; icB.textContent = a.ic;
- const txt = document.createElement('div');
- const nmB = document.createElement('b'); nmB.style.color = unlocked ? '#fbbf24' : '#cfe2ff'; nmB.textContent = a.name;
- const ds = document.createElement('div'); ds.style.color = '#8ba3c7'; ds.style.fontSize = '.82em'; ds.textContent = a.desc;
- txt.appendChild(nmB); txt.appendChild(ds);
- row.appendChild(icB); row.appendChild(txt); el.achScreenList.appendChild(row);
- }
- }
- }
- function refreshAchievementHUD(){ if (el.achPanel) el.achPanel.classList.toggle('show', state === 'playing' && unlockedAchievements.size > 0); }
- /* ============================================================
- SAVE STATE
- ============================================================ */
- function saveGameState(){
- try {
- localStorage.setItem('shield9_savestate', JSON.stringify({
- diff: currentDiff.key, shift: currentShift,
- score, leaks, fixedCount, totalCaught, ts: Date.now()
- }));
- } catch(e){}
- }
- function loadGameState(){
- try {
- const s = JSON.parse(localStorage.getItem('shield9_savestate') || 'null');
- if (!s) return null;
- if (Date.now() - s.ts > 24*60*60*1000) return null;
- return s;
- } catch(e){ return null; }
- }
- function clearGameState(){ try { localStorage.removeItem('shield9_savestate'); } catch(e){} }
- function updateContinueButton(){ if (el.btnContinue) el.btnContinue.style.display = loadGameState() ? '' : 'none'; }
- /* ============================================================
- ЗВУК
- ============================================================ */
- let AC = null;
- function beep(f, d, type, v){
- if (!settings.sound) return;
- try {
- AC = AC || new (window.AudioContext || window.webkitAudioContext)();
- const o = AC.createOscillator(), g = AC.createGain();
- o.type = type || 'sine'; o.frequency.value = f; g.gain.value = v || 0.05;
- o.connect(g); g.connect(AC.destination);
- const t = AC.currentTime;
- g.gain.setValueAtTime(v || 0.05, t);
- g.gain.exponentialRampToValueAtTime(0.0001, t + d);
- o.start(t); o.stop(t + d + 0.02);
- } catch(e){}
- }
- function radioBeep(){ beep(1000, .04); setTimeout(() => beep(1400, .05), 50); }
- function soundAlert(){ beep(180, .25, 'sawtooth', .06); }
- function soundOk(){ beep(760, .1); }
- function soundCaught(){ beep(880, .15); setTimeout(() => beep(1320, .15), 150); }
- function soundAch(){ beep(1320, .12); setTimeout(() => beep(1760, .12), 100); setTimeout(() => beep(2200, .15), 200); }
- /* ============================================================
- ЖУРНАЛ
- ============================================================ */
- const shiftLog = [];
- function addLog(text, type){
- const now = new Date();
- const t = String(now.getHours()).padStart(2,'0') + ':' + String(now.getMinutes()).padStart(2,'0') + ':' + String(now.getSeconds()).padStart(2,'0');
- shiftLog.unshift({t, text, type: type || 'info'});
- if (shiftLog.length > 8) shiftLog.pop();
- if (!el.logList) return;
- const frag = document.createDocumentFragment();
- for (const e of shiftLog){
- const li = document.createElement('li'); li.className = e.type;
- const st = document.createElement('span'); st.className = 't'; st.textContent = '[' + e.t + ']';
- const stx = document.createElement('span'); stx.textContent = e.text;
- li.appendChild(st); li.appendChild(stx); frag.appendChild(li);
- }
- el.logList.innerHTML = ''; el.logList.appendChild(frag);
- }
- function clearLog(){ shiftLog.length = 0; if (el.logList) el.logList.innerHTML = ''; }
- let hintTimer = null;
- function showHint(t, ms, radio){
- ms = ms || 3000;
- if (!el.hintText || !el.hintBar) return;
- el.hintText.textContent = t;
- el.hintBar.classList.add('show');
- el.hintBar.classList.toggle('radio', !!radio);
- clearTimeout(hintTimer);
- hintTimer = setTimeout(() => { el.hintBar.classList.remove('show'); el.hintBar.classList.remove('radio'); }, ms);
- }
- function dispatch(text){ radioBeep(); showHint('📻 Диспетчер: ' + text, 4200, true); addLog('📻 ' + text, 'sys'); }
- /* ============================================================
- MODAL
- ============================================================ */
- let modalResolve = null;
- function showModal(text){
- return new Promise(resolve => {
- if (!el.modalBack){ resolve(false); return; }
- if (el.modalText) el.modalText.textContent = text;
- el.modalBack.classList.remove('hide');
- modalResolve = resolve;
- });
- }
- /* ============================================================
- THEMES
- ============================================================ */
- const ROOM_THEMES = {
- soc: { name:'SOC · Операторская', floor:['#1a2540','#0a1228'], accent:'#4ade80', pattern:'carpet',
- furniture: [
- {kind:'camwall', w:280, d:60, h:80, tags:[]},
- {kind:'desk', w:170, d:80, h:42, tags:['logs','access']},
- {kind:'desk', w:170, d:80, h:42, tags:['ports','phishing']}
- ]},
- server: { name:'Серверная', floor:['#0e2238','#08172a'], accent:'#2f7fd6', pattern:'grid',
- furniture: [
- {kind:'rack', w:120, d:100, h:130, tags:['access','ports']},
- {kind:'rack', w:120, d:100, h:130, tags:['access','ports','logs']},
- {kind:'desk', w:170, d:80, h:42, tags:['logs']},
- {kind:'rack', w:120, d:100, h:130, tags:['ports']}
- ]},
- open: { name:'Опенспейс', floor:['#142840','#0a1928'], accent:'#3a9ac8', pattern:'tiles',
- furniture: [
- {kind:'desk', w:170, d:80, h:42, tags:['phishing','password']},
- {kind:'desk', w:170, d:80, h:42, tags:['phishing','password']},
- {kind:'desk', w:170, d:80, h:42, tags:['phishing']},
- {kind:'desk', w:170, d:80, h:42, tags:['password']}
- ]},
- archive: { name:'Архив', floor:['#2a1f3a','#150e24'], accent:'#8a5ac8', pattern:'wood',
- furniture: [
- {kind:'shelf', w:100, d:170, h:120, tags:['backup']},
- {kind:'shelf', w:100, d:170, h:120, tags:['backup']},
- {kind:'safe', w:130, d:110, h:100, tags:['cipher']},
- {kind:'desk', w:170, d:80, h:42, tags:['cipher']}
- ]},
- meeting: { name:'Переговорка', floor:['#1c2a1c','#0e1a0e'], accent:'#4ade80', pattern:'carpet',
- furniture: [
- {kind:'bigtable', w:340, d:170, h:50, tags:['response']},
- {kind:'desk', w:130, d:90, h:70, tags:['response']}
- ]}
- };
- const ESSENTIAL_THEMES = ['server','open','archive','meeting'];
- const FURN_SIZES = {
- desk:{w:170,d:80,h:42}, bigtable:{w:340,d:170,h:50}, rack:{w:120,d:100,h:130},
- shelf:{w:100,d:170,h:120}, safe:{w:130,d:110,h:100}, camwall:{w:280,d:60,h:80}
- };
- const FURN_COLOR = {
- desk: {tL:'#a08a60', t:'#7a6440', f:'#504028', fD:'#302010', a:'#5a9aff'},
- bigtable:{tL:'#b09868', t:'#8a7048', f:'#5a4830', fD:'#3a2818', a:'#5a9aff'},
- rack: {tL:'#4a5868', t:'#384858', f:'#202c3c', fD:'#0e1828', a:'#4ade80'},
- shelf: {tL:'#6a4a30', t:'#4a3020', f:'#2a1a08', fD:'#1a0e00', a:'#d4a868'},
- safe: {tL:'#7a8288', t:'#5a6268', f:'#2a3038', fD:'#1a2028', a:'#4ade80'},
- camwall:{tL:'#2a3038', t:'#1a2030', f:'#0a1018', fD:'#050508', a:'#58a6ff'}
- };
- /* ============================================================
- МИР
- ============================================================ */
- let ROOMS = [], WALLS = [], DOORS = [], FURN = [];
- let socRoom = null, exitTile = null;
- function generateLayoutFromCenter(roomCount){
- const GRID = 15;
- const center = Math.floor(GRID / 2);
- const cells = new Map();
- cells.set(center + ',' + center, {r:center, c:center, depth:0});
- const dirs = [[0,-1],[0,1],[-1,0],[1,0]];
- const firstDirs = shuffle(dirs.slice());
- for (const [dr, dc] of firstDirs){
- const nr = center + dr, nc = center + dc;
- if (nr < 1 || nr >= GRID-1 || nc < 1 || nc >= GRID-1) continue;
- cells.set(nr + ',' + nc, {r:nr, c:nc, depth:1});
- if (cells.size >= roomCount) break;
- }
- let attempts = 0;
- while (cells.size < roomCount && attempts < 800){
- attempts++;
- const list = Array.from(cells.values());
- const base = list[Math.floor(Math.random() * list.length)];
- const shuffled = shuffle(dirs.slice());
- for (const [dr, dc] of shuffled){
- const nr = base.r + dr, nc = base.c + dc;
- if (nr < 1 || nr >= GRID-1 || nc < 1 || nc >= GRID-1) continue;
- if (cells.has(nr + ',' + nc)) continue;
- cells.set(nr + ',' + nc, {r:nr, c:nc, depth: base.depth + 1});
- break;
- }
- }
- return {cells, center, GRID};
- }
- function generateWorld(){
- const roomCount = 7 + Math.floor(Math.random() * 4);
- const layout = generateLayoutFromCenter(roomCount);
- const cellArr = Array.from(layout.cells.values());
- let minR = 999, minC = 999, maxR = -1, maxC = -1;
- for (const c of cellArr){
- if (c.r < minR) minR = c.r; if (c.r > maxR) maxR = c.r;
- if (c.c < minC) minC = c.c; if (c.c > maxC) maxC = c.c;
- }
- WORLD_W = (maxC - minC + 1) * ROOM_SIZE;
- WORLD_D = (maxR - minR + 1) * ROOM_SIZE;
- ROOMS.length = 0; WALLS.length = 0; DOORS.length = 0; FURN.length = 0;
- socRoom = null; minimapBg = null;
- const nonSocArr = cellArr.filter(c => !(c.r === layout.center && c.c === layout.center));
- const themePool = [];
- for (let i = 0; i < nonSocArr.length; i++){
- if (i < ESSENTIAL_THEMES.length) themePool.push(ESSENTIAL_THEMES[i]);
- else themePool.push(ESSENTIAL_THEMES[Math.floor(Math.random() * ESSENTIAL_THEMES.length)]);
- }
- shuffle(themePool);
- const roomMap = new Map();
- let themeIdx = 0;
- for (const c of cellArr){
- const isStart = (c.r === layout.center && c.c === layout.center);
- const themeId = isStart ? 'soc' : themePool[themeIdx++];
- const theme = ROOM_THEMES[themeId];
- const room = {
- x: (c.c - minC) * ROOM_SIZE, y: (c.r - minR) * ROOM_SIZE,
- w: ROOM_SIZE, h: ROOM_SIZE,
- theme: themeId, name: theme.name, floor: theme.floor, accent: theme.accent, pattern: theme.pattern,
- isStart, isSoc: isStart, r: c.r, c: c.c, depth: c.depth
- };
- ROOMS.push(room); roomMap.set(c.r + ',' + c.c, room);
- if (isStart) socRoom = room;
- }
- for (const c of cellArr){
- const room = roomMap.get(c.r + ',' + c.c);
- if (roomMap.has(c.r + ',' + (c.c + 1)))
- DOORS.push({x: room.x + room.w - T/2, y: room.y + (ROOM_SIZE - DOOR_SIZE)/2, w: T, h: DOOR_SIZE, dir:'v'});
- if (roomMap.has((c.r + 1) + ',' + c.c))
- DOORS.push({x: room.x + (ROOM_SIZE - DOOR_SIZE)/2, y: room.y + room.h - T/2, w: DOOR_SIZE, h: T, dir:'h'});
- }
- const dv = (ROOM_SIZE - DOOR_SIZE) / 2;
- for (const c of cellArr){
- const room = roomMap.get(c.r + ',' + c.c);
- const hasN = roomMap.has((c.r - 1) + ',' + c.c);
- const hasS = roomMap.has((c.r + 1) + ',' + c.c);
- const hasW = roomMap.has(c.r + ',' + (c.c - 1));
- const hasE = roomMap.has(c.r + ',' + (c.c + 1));
- if (!hasN) WALLS.push({x: room.x, y: room.y - T/2, w: ROOM_SIZE, h: T});
- else { WALLS.push({x: room.x, y: room.y - T/2, w: dv, h: T}); WALLS.push({x: room.x + dv + DOOR_SIZE, y: room.y - T/2, w: ROOM_SIZE - dv - DOOR_SIZE, h: T}); }
- if (!hasS) WALLS.push({x: room.x, y: room.y + ROOM_SIZE - T/2, w: ROOM_SIZE, h: T});
- if (!hasW) WALLS.push({x: room.x - T/2, y: room.y, w: T, h: ROOM_SIZE});
- else { WALLS.push({x: room.x - T/2, y: room.y, w: T, h: dv}); WALLS.push({x: room.x - T/2, y: room.y + dv + DOOR_SIZE, w: T, h: ROOM_SIZE - dv - DOOR_SIZE}); }
- if (!hasE) WALLS.push({x: room.x + ROOM_SIZE - T/2, y: room.y, w: T, h: ROOM_SIZE});
- else { WALLS.push({x: room.x + ROOM_SIZE - T/2, y: room.y, w: T, h: dv}); WALLS.push({x: room.x + ROOM_SIZE - T/2, y: room.y + dv + DOOR_SIZE, w: T, h: ROOM_SIZE - dv - DOOR_SIZE}); }
- }
- for (const room of ROOMS){
- const theme = ROOM_THEMES[room.theme];
- if (room.isSoc){
- const padX = 120;
- const camF = theme.furniture.find(f => f.kind === 'camwall');
- if (camF) FURN.push({kind:'camwall', x: Math.round(room.x + (room.w - camF.w)/2), y: Math.round(room.y + 60), w: camF.w, d: camF.d, h: camF.h, tags:[]});
- const others = theme.furniture.filter(f => f.kind !== 'camwall');
- const positions = [{cx: room.x + padX + 150, cy: room.y + room.h - 180}, {cx: room.x + room.w - padX - 150, cy: room.y + room.h - 180}];
- for (let i = 0; i < others.length && i < positions.length; i++){
- const f = others[i], pos = positions[i];
- FURN.push({kind: f.kind, x: Math.round(clamp(pos.cx - f.w/2, room.x + 40, room.x + room.w - f.w - 40)), y: Math.round(clamp(pos.cy - f.d/2, room.y + 40, room.y + room.h - f.d - 40)), w: f.w, d: f.d, h: f.h, tags: f.tags});
- }
- } else {
- const padX = 140, padY = 140;
- const cellW = (room.w - padX*2) / 2;
- const cellH = (room.h - padY*2) / 2;
- const positions = [
- {cx: room.x + padX + cellW*0.5, cy: room.y + padY + cellH*0.5},
- {cx: room.x + padX + cellW*1.5, cy: room.y + padY + cellH*0.5},
- {cx: room.x + padX + cellW*0.5, cy: room.y + padY + cellH*1.5},
- {cx: room.x + padX + cellW*1.5, cy: room.y + padY + cellH*1.5}
- ];
- shuffle(positions);
- const furniture = shuffle(theme.furniture.slice());
- for (let i = 0; i < positions.length && i < furniture.length; i++){
- const f = furniture[i], pos = positions[i];
- const fx = clamp(pos.cx - f.w/2 + (Math.random() - 0.5) * 30, room.x + 40, room.x + room.w - f.w - 40);
- const fy = clamp(pos.cy - f.d/2 + (Math.random() - 0.5) * 30, room.y + 40, room.y + room.h - f.d - 40);
- FURN.push({kind: f.kind, x: Math.round(fx), y: Math.round(fy), w: f.w, d: f.d, h: f.h, tags: f.tags});
- }
- }
- }
- let farthestRoom = socRoom, maxDist = -1;
- for (const r of ROOMS){
- const d = dist2(r.x + r.w/2, r.y + r.h/2, socRoom.x + socRoom.w/2, socRoom.y + socRoom.h/2);
- if (d > maxDist){ maxDist = d; farthestRoom = r; }
- }
- exitTile = {x: farthestRoom.x + farthestRoom.w - 80, y: farthestRoom.y + farthestRoom.h - 80, room: farthestRoom};
- player.x = socRoom.x + socRoom.w/2;
- player.y = socRoom.y + socRoom.h/2 + 60;
- let tries = 0;
- while (isBlocked(player.x, player.y, player.r + 4) && tries < 80){
- player.x = socRoom.x + 150 + Math.random() * (socRoom.w - 300);
- player.y = socRoom.y + 250 + Math.random() * (socRoom.h - 350);
- tries++;
- }
- collide(player, player.r);
- staticReady = false;
- if (staticCanvas.width !== WORLD_W) staticCanvas.width = WORLD_W;
- const newH = Math.ceil(WORLD_D * DEPTH);
- if (staticCanvas.height !== newH) staticCanvas.height = newH;
- updateCamera();
- buildFurnitureSprites();
- buildStaticLayer();
- }
- /* ============================================================
- ИНЦИДЕНТЫ
- ============================================================ */
- const INCIDENTS = {
- phishing: {icon:'📧', label:'Фишинговое письмо', color:'#ffd166', tag:'phishing'},
- password: {icon:'🔑', label:'Слабый пароль', color:'#4ea1ff', tag:'password'},
- logs: {icon:'📋', label:'Подозрительные логи', color:'#c084fc', tag:'logs'},
- access: {icon:'🚪', label:'Права доступа', color:'#4ade80', tag:'access'},
- ports: {icon:'🌐', label:'Открытые порты', color:'#38bdf8', tag:'ports'},
- cipher: {icon:'🔐', label:'Шифрование', color:'#f472b6', tag:'cipher'},
- backup: {icon:'💾', label:'Резервные копии', color:'#fbbf24', tag:'backup'},
- response: {icon:'🚨', label:'Реагирование', color:'#ff7b6b', tag:'response'}
- };
- const ALL_INCIDENT_TYPES = Object.keys(INCIDENTS);
- const DIFF = {
- easy: { key:'easy', label:'Легко', leaksMax:6, botCount:3, botSabotage:0.15, botLeak:0.10,
- shifts: [{count:2,time:55},{count:3,time:50},{count:4,time:45},{count:5,time:40}] },
- normal: { key:'normal', label:'Нормально', leaksMax:6, botCount:4, botSabotage:0.30, botLeak:0.20,
- shifts: [{count:3,time:45},{count:4,time:40},{count:4,time:38},{count:6,time:32}] },
- hard: { key:'hard', label:'Сложно', leaksMax:5, botCount:5, botSabotage:0.45, botLeak:0.30,
- shifts: [{count:4,time:38},{count:5,time:32},{count:5,time:30},{count:7,time:26}] }
- };
- let currentDiff = DIFF.normal;
- /* ============================================================
- СОСТОЯНИЕ
- ============================================================ */
- let state = 'menu';
- let currentShift = 0;
- let score = 0, leaks = 0, fixedCount = 0, caughtCount = 0;
- let caughtThisShift = 0, totalCaught = 0;
- let statsAch = { shifts: 0, perfectShift: false, totalCaught: 0, fixedNoErrors: 0, auditPassed: false, score: 0, shiftErrors: 0 };
- let incidents = [], particles = [], toasts = [];
- let time = 0;
- let pausedFrom = null, stateBeforePuzzle = null;
- let activeIncident = null, puzzle = null, puzzleRAF = null;
- let puzzleMouse = {x:-1, y:-1, down:false};
- let waveTasks = [];
- let spawnedInShift = 0, shiftSpawnTimer = 0;
- let demoMode = false, puzzleFailedActive = false;
- const BOT_NAMES = ['Иванов','Петрова','Сидоров','Кузнецов','Смирнова','Волков','Морозов','Новиков'];
- const BOT_COLORS = ['#ff6b6b','#4ea1ff','#4ade80','#fbbf24','#c084fc','#f472b6','#38bdf8','#a3e635'];
- let bots = [];
- let cameraOpen = false, activeCameraIdx = 0;
- let camBufs = [], camRooms = [];
- const player = {x:0, y:0, r:18, dir:1, moving:false};
- const keys = {up:false, down:false, left:false, right:false};
- let actionPressed = false;
- /* ============================================================
- КОЛЛИЗИИ
- ============================================================ */
- function resolveRect(p, rx, ry, rw, rh, r){
- const cx = p.x < rx ? rx : (p.x > rx+rw ? rx+rw : p.x);
- const cy = p.y < ry ? ry : (p.y > ry+rh ? ry+rh : p.y);
- const dx = p.x - cx, dy = p.y - cy, d2 = dx*dx + dy*dy;
- if (d2 >= r*r) return;
- if (d2 > 0.0001){ const d = Math.sqrt(d2); p.x = cx + (dx/d)*r; p.y = cy + (dy/d)*r; }
- else {
- const L = p.x - rx, R = (rx+rw) - p.x, Tp = p.y - ry, B = (ry+rh) - p.y;
- const m = Math.min(L, R, Tp, B);
- if (m === L) p.x = rx - r; else if (m === R) p.x = rx + rw + r;
- else if (m === Tp) p.y = ry - r; else p.y = ry + rh + r;
- }
- }
- function collide(p, r){
- for (const f of FURN) resolveRect(p, f.x, f.y, f.w, f.d, r);
- for (const w of WALLS) resolveRect(p, w.x, w.y, w.w, w.h, r);
- p.x = clamp(p.x, r, WORLD_W - r);
- p.y = clamp(p.y, r, WORLD_D - r);
- }
- function isBlocked(x, y, r){
- for (const f of FURN) if (x > f.x - r && x < f.x + f.w + r && y > f.y - r && y < f.y + f.d + r) return true;
- for (const w of WALLS) if (x > w.x - r && x < w.x + w.w + r && y > w.y - r && y < w.y + w.h + r) return true;
- if (x < r || x > WORLD_W - r || y < r || y > WORLD_D - r) return true;
- return false;
- }
- function roomAt(x, y){
- for (const r of ROOMS) if (x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h) return r;
- return null;
- }
- /* ============================================================
- PATHFINDING
- ============================================================ */
- function findRoomPath(fromRoom, toRoom){
- if (!fromRoom || !toRoom) return null;
- if (fromRoom === toRoom) return [fromRoom];
- const grid = new Map();
- for (const r of ROOMS) grid.set(r.r + ',' + r.c, r);
- const startKey = fromRoom.r + ',' + fromRoom.c;
- const goalKey = toRoom.r + ',' + toRoom.c;
- if (!grid.has(startKey) || !grid.has(goalKey)) return null;
- const queue = [startKey];
- const came = new Map(); came.set(startKey, null);
- const dirs = [[0,1],[0,-1],[1,0],[-1,0]];
- while (queue.length){
- const cur = queue.shift();
- if (cur === goalKey) break;
- const parts = cur.split(','); const cr = +parts[0], cc = +parts[1];
- for (const [dr, dc] of dirs){
- const nk = (cr + dr) + ',' + (cc + dc);
- if (!grid.has(nk) || came.has(nk)) continue;
- came.set(nk, cur); queue.push(nk);
- }
- }
- if (!came.has(goalKey)) return null;
- const path = [];
- let cur = goalKey;
- while (cur !== null){ path.unshift(grid.get(cur)); cur = came.get(cur); }
- return path;
- }
- function doorBetween(a, b){
- if (a.c === b.c - 1) return {x: a.x + a.w + T/2, y: a.y + a.h/2};
- if (a.c === b.c + 1) return {x: a.x - T/2, y: a.y + a.h/2};
- if (a.r === b.r - 1) return {x: a.x + a.w/2, y: a.y + a.h + T/2};
- if (a.r === b.r + 1) return {x: a.x + a.w/2, y: a.y - T/2};
- return null;
- }
- function buildBotPath(bot, tx, ty){
- const fromRoom = roomAt(bot.x, bot.y);
- const toRoom = roomAt(tx, ty);
- if (!fromRoom || !toRoom){ bot.waypoints = null; bot.wpIdx = 0; bot.targetX = tx; bot.targetY = ty; return; }
- const path = findRoomPath(fromRoom, toRoom);
- if (!path || path.length === 0){ bot.waypoints = null; bot.wpIdx = 0; bot.targetX = tx; bot.targetY = ty; return; }
- const wps = [];
- for (let i = 0; i < path.length - 1; i++){
- const d = doorBetween(path[i], path[i+1]);
- if (d) wps.push(d);
- }
- wps.push({x: tx, y: ty});
- bot.waypoints = wps;
- bot.wpIdx = 0;
- bot.targetX = wps[0].x; bot.targetY = wps[0].y;
- }
- /* ============================================================
- СПРАЙТЫ
- ============================================================ */
- const FURN_SPRITES = {};
- function buildFurnitureSprites(){
- for (const kind in FURN_SIZES) if (FURN_COLOR[kind]) buildFurnitureSprite(kind);
- }
- function buildFurnitureSprite(kind){
- const sz = FURN_SIZES[kind], col = FURN_COLOR[kind];
- if (!sz || !col) return;
- const d = sz.d * DEPTH;
- const hPx = sz.h * DEPTH;
- const pad = 20;
- const cw = sz.w + pad*2, ch = d + hPx + pad*2;
- const canvas = document.createElement('canvas');
- canvas.width = cw; canvas.height = ch;
- const c = canvas.getContext('2d');
- c.translate(pad, pad);
- const shGrad = c.createRadialGradient(sz.w/2, d + hPx, 2, sz.w/2, d + hPx, Math.max(sz.w, hPx)*0.7);
- shGrad.addColorStop(0, 'rgba(0,0,0,.55)');
- shGrad.addColorStop(1, 'rgba(0,0,0,0)');
- c.fillStyle = shGrad;
- c.beginPath(); c.ellipse(sz.w/2, d + hPx - 2, sz.w*0.65, Math.min(14, hPx*0.5), 0, 0, 7); c.fill();
- const frontGrad = c.createLinearGradient(0, d, 0, d + hPx);
- frontGrad.addColorStop(0, col.f); frontGrad.addColorStop(1, col.fD);
- c.fillStyle = frontGrad; c.fillRect(0, d, sz.w, hPx);
- const topGrad = c.createLinearGradient(0, 0, 0, d);
- topGrad.addColorStop(0, col.t); topGrad.addColorStop(1, col.tL);
- c.fillStyle = topGrad; c.fillRect(0, 0, sz.w, d);
- c.fillStyle = 'rgba(255,255,255,.35)'; c.fillRect(0, 0, sz.w, 1);
- c.fillStyle = 'rgba(0,0,0,.4)'; c.fillRect(0, d + hPx - 2, sz.w, 2);
- c.fillStyle = 'rgba(0,0,0,.25)'; c.fillRect(sz.w - 1, 0, 1, d + hPx);
- decorateFurniture(c, kind, sz.w, d, hPx, col);
- FURN_SPRITES[kind] = {canvas, pad, w:cw, h:ch};
- }
- function decorateFurniture(c, kind, w, d, hPx, col){
- const cx = w/2;
- if (kind === 'desk' || kind === 'bigtable'){
- const mw = Math.min(56, w*0.3), mh = 20;
- c.fillStyle = '#0a0a14'; c.fillRect(cx-mw/2-1, d*0.15-1, mw+2, mh+2);
- c.fillStyle = '#58a6ff'; c.fillRect(cx-mw/2, d*0.15, mw, mh);
- c.fillStyle = 'rgba(255,255,255,.3)'; c.fillRect(cx-mw/2+2, d*0.15+2, (mw-4)*0.7, 1);
- c.fillStyle = '#1a1a2a'; c.fillRect(cx-20, d*0.65, 40, 5);
- } else if (kind === 'rack'){
- for (let i = 0; i < 8; i++){
- const uy = d*0.3 + i*(hPx*0.65/8);
- c.fillStyle = '#0a0a14'; c.fillRect(4, uy, w - 8, hPx*0.65/8 - 2);
- c.fillStyle = i % 2 === 0 ? '#4ade80' : '#1e4a28'; c.fillRect(w - 10, uy + 2, 3, 3);
- c.fillStyle = i % 3 === 0 ? '#58a6ff' : '#1e3a5a'; c.fillRect(w - 15, uy + 2, 3, 3);
- }
- } else if (kind === 'shelf'){
- for (let s = 0; s < 4; s++){
- const sy = d*0.15 + (hPx*0.65/4)*s;
- const sh = hPx*0.65/4 - 3;
- c.fillStyle = 'rgba(0,0,0,.5)'; c.fillRect(3, sy, w - 6, sh);
- const bookColors = ['#c73a3a','#3a6ac7','#c7a83a','#4ade80','#c73a8a','#6ac7b8','#d89a48'];
- let bx = 5;
- while (bx < w - 8){
- const bw = 3 + Math.random()*2.5, bh = sh * (0.55 + Math.random()*0.4);
- c.fillStyle = bookColors[Math.floor(Math.random()*bookColors.length)];
- c.fillRect(bx, sy + sh - bh + 1, bw, bh - 1);
- bx += bw + 1;
- }
- }
- } else if (kind === 'safe'){
- c.fillStyle = '#1a2028'; c.fillRect(4, d*0.3, w - 8, hPx*0.5);
- c.fillStyle = '#c0a080'; c.beginPath(); c.arc(cx, d*0.35 + hPx*0.2, 6, 0, 7); c.fill();
- c.strokeStyle = '#0a0a10'; c.lineWidth = 2; c.beginPath(); c.arc(cx, d*0.35 + hPx*0.2, 6, 0, 7); c.stroke();
- c.fillStyle = '#8a8a92'; c.fillRect(w - 16, d*0.35 + hPx*0.35, 10, 3);
- } else if (kind === 'camwall'){
- const cols = 3, rows = 2, gp = 4;
- const mw2 = (w - gp*(cols+1)) / cols;
- const mh2 = (d - gp*(rows+1)) / rows;
- const screenCols = ['#2a4a3a','#3a2a2a','#2a3a4a','#3a3a2a','#2a3a3a','#3a2a3a'];
- for (let r2 = 0; r2 < rows; r2++) for (let c2 = 0; c2 < cols; c2++){
- const mx2 = gp + c2*(mw2+gp), my2 = gp + r2*(mh2+gp);
- c.fillStyle = '#0a1018'; c.fillRect(mx2-1, my2-1, mw2+2, mh2+2);
- c.fillStyle = screenCols[r2*cols+c2]; c.fillRect(mx2, my2, mw2, mh2);
- c.fillStyle = 'rgba(255,255,255,.5)';
- c.fillRect(mx2+3, my2+4, (mw2-6)*0.6, 1); c.fillRect(mx2+3, my2+7, (mw2-6)*0.35, 1);
- c.fillStyle = '#f85149'; c.beginPath(); c.arc(mx2+mw2-5, my2+5, 2, 0, 7); c.fill();
- }
- }
- }
- /* ============================================================
- СТАТИЧНЫЙ СЛОЙ
- ============================================================ */
- const staticCanvas = document.createElement('canvas');
- const staticCtx = staticCanvas.getContext('2d', {alpha:false});
- let staticReady = false;
- let minimapBg = null;
- function drawRoomFloor(c, r){
- const x1 = r.x, y1 = r.y * DEPTH, w = r.w, h = r.h * DEPTH;
- c.fillStyle = r.floor[0]; c.fillRect(x1, y1, w, h);
- if (r.pattern === 'grid'){
- c.strokeStyle = 'rgba(120,180,255,.10)'; c.lineWidth = 1;
- for (let gx = 0; gx < r.w; gx += 60){ c.beginPath(); c.moveTo(x1+gx, y1); c.lineTo(x1+gx, y1+h); c.stroke(); }
- for (let gy = 0; gy < r.h; gy += 60){ const py = (r.y+gy)*DEPTH; c.beginPath(); c.moveTo(x1, py); c.lineTo(x1+w, py); c.stroke(); }
- } else if (r.pattern === 'wood'){
- c.strokeStyle = 'rgba(180,140,90,.10)';
- for (let gy = 0; gy < r.h; gy += 40){ const py = (r.y+gy)*DEPTH; c.beginPath(); c.moveTo(x1, py); c.lineTo(x1+w, py); c.stroke(); }
- } else if (r.pattern === 'carpet'){
- c.fillStyle = 'rgba(180,60,60,.10)'; c.fillRect(x1+40, y1+40, w-80, h-80);
- c.strokeStyle = 'rgba(255,180,180,.20)'; c.lineWidth = 2; c.strokeRect(x1+40, y1+40, w-80, h-80);
- } else if (r.pattern === 'tiles'){
- for (let gx = 0; gx < r.w; gx += 90) for (let gy = 0; gy < r.h; gy += 90){
- const px = r.x+gx, py = (r.y+gy)*DEPTH;
- const odd = ((gx/90+gy/90)|0)%2;
- c.fillStyle = odd ? 'rgba(120,180,255,.06)' : 'rgba(255,255,255,.02)';
- c.fillRect(px, py, 90, 90*DEPTH);
- }
- }
- const g = c.createLinearGradient(0, y1, 0, y1+h);
- g.addColorStop(0, 'rgba(255,255,255,.04)'); g.addColorStop(1, 'rgba(0,0,0,.20)');
- c.fillStyle = g; c.fillRect(x1, y1, w, h);
- c.font = 'bold 15px "Segoe UI",sans-serif'; c.textAlign = 'center'; c.textBaseline = 'top';
- c.fillStyle = r.accent + 'cc';
- c.fillText((r.isSoc ? '★ ' : '◄ ') + r.name.toUpperCase() + ' ►', x1 + w/2, y1 + 12);
- }
- function drawWallStatic(c, w){
- const x1 = w.x, yF = w.y * DEPTH, ww = w.w, wh = w.h * DEPTH;
- c.fillStyle = 'rgba(0,0,0,.55)'; c.fillRect(x1+3, yF+wh, ww, 5);
- c.fillStyle = '#3a4d70'; c.fillRect(x1, yF-26, ww, wh);
- c.fillStyle = '#8ea9d4'; c.fillRect(x1, yF-26, ww, 3);
- c.fillStyle = '#b8ccec'; c.fillRect(x1, yF-26, ww, 1);
- c.fillStyle = '#080d14'; c.fillRect(x1, yF+wh-26, ww, 26);
- c.strokeStyle = 'rgba(0,0,0,.75)'; c.lineWidth = 1;
- c.strokeRect(x1+0.5, yF-25.5, ww-1, wh-1);
- c.strokeRect(x1+0.5, yF+wh-25.5, ww-1, 25);
- }
- function drawDoorStatic(c, d){
- const x1 = d.x, y1 = d.y * DEPTH, ww = d.w, wh = d.h * DEPTH;
- c.fillStyle = 'rgba(255,209,102,.35)'; c.fillRect(x1, y1, ww, wh);
- c.strokeStyle = '#ffd166'; c.lineWidth = 2; c.strokeRect(x1+1, y1+1, ww-2, wh-2);
- c.strokeStyle = '#ffd166'; c.lineWidth = 3; c.lineCap = 'round';
- const cx = x1+ww/2, cy = y1+wh/2;
- if (d.dir === 'h'){
- c.beginPath(); c.moveTo(cx-12, cy-8); c.lineTo(cx-4, cy); c.lineTo(cx-12, cy+8); c.stroke();
- c.beginPath(); c.moveTo(cx+12, cy-8); c.lineTo(cx+4, cy); c.lineTo(cx+12, cy+8); c.stroke();
- } else {
- c.beginPath(); c.moveTo(cx-8, cy-12); c.lineTo(cx, cy-4); c.lineTo(cx+8, cy-12); c.stroke();
- c.beginPath(); c.moveTo(cx-8, cy+12); c.lineTo(cx, cy+4); c.lineTo(cx+8, cy+12); c.stroke();
- }
- }
- function buildStaticLayer(){
- try {
- staticCtx.fillStyle = '#03050b';
- staticCtx.fillRect(0, 0, staticCanvas.width, staticCanvas.height);
- for (const r of ROOMS) drawRoomFloor(staticCtx, r);
- for (const w of WALLS) drawWallStatic(staticCtx, w);
- for (const d of DOORS) drawDoorStatic(staticCtx, d);
- staticReady = true;
- } catch(e){ staticReady = false; }
- }
- function updateCamera(){
- camX = clamp(player.x - W/2, 0, Math.max(0, WORLD_W - W));
- camY = clamp(player.y * DEPTH - H/2, 0, Math.max(0, WORLD_D * DEPTH - H));
- }
- /* ============================================================
- БОТЫ
- ============================================================ */
- function trySpawnBotInRoom(bot, room){
- const pad = 100;
- for (let t = 0; t < 150; t++){
- const x = room.x + pad + Math.random() * (room.w - pad*2);
- const y = room.y + pad + Math.random() * (room.h - pad*2);
- if (!isBlocked(x, y, bot.r + 4)){
- bot.x = x; bot.y = y;
- collide(bot, bot.r);
- if (Math.abs(bot.x - x) < 40 && Math.abs(bot.y - y) < 40) return true;
- }
- }
- return false;
- }
- function spawnBots(){
- bots.length = 0;
- const count = currentDiff.botCount || 4;
- const names = shuffle(BOT_NAMES.slice()).slice(0, count);
- const colors = shuffle(BOT_COLORS.slice()).slice(0, count);
- const spawnRooms = ROOMS.filter(r => !r.isSoc);
- shuffle(spawnRooms);
- for (let i = 0; i < count; i++){
- const bot = {
- x:0, y:0, r:15, name: names[i], color: colors[i],
- dir:1, speed: rand(55, 80),
- targetX:0, targetY:0, waypoints: null, wpIdx: 0,
- waitTimer: rand(0.5, 2),
- state: 'wander', suspectTimer: 0, isSuspect: false, isCaught: false,
- sabotageTarget: null, lastX: 0, lastY: 0, stuckTimer: 0
- };
- const room = spawnRooms.length > 0 ? spawnRooms[i % spawnRooms.length] : socRoom;
- let ok = trySpawnBotInRoom(bot, room);
- if (!ok){ for (const r of spawnRooms){ if (trySpawnBotInRoom(bot, r)){ ok = true; break; } } }
- if (!ok) trySpawnBotInRoom(bot, socRoom);
- bot.lastX = bot.x; bot.lastY = bot.y;
- pickBotTarget(bot);
- bots.push(bot);
- }
- }
- function pickBotTarget(bot){
- const rooms = ROOMS.filter(r => !r.isSoc);
- const room = rooms.length > 0 ? rooms[Math.floor(Math.random() * rooms.length)] : socRoom;
- for (let t = 0; t < 25; t++){
- const tx = room.x + 80 + Math.random() * (room.w - 160);
- const ty = room.y + 80 + Math.random() * (room.h - 160);
- if (!isBlocked(tx, ty, bot.r + 6)){ buildBotPath(bot, tx, ty); return; }
- }
- buildBotPath(bot, room.x + room.w/2, room.y + room.h/2);
- }
- function botPickNextAction(bot){
- const roll = Math.random();
- let sabChance = currentDiff.botSabotage || 0.3;
- let leakChance = currentDiff.botLeak || 0.2;
- if (bot.isSuspect){ sabChance *= 0.3; leakChance *= 0.3; }
- if (roll < sabChance){
- const taskTypes = waveTasks.filter(w => w.done < w.need).map(w => w.type);
- const pool = taskTypes.length > 0 ? taskTypes : waveTasks.map(w => w.type);
- if (pool.length > 0){
- const type = pool[Math.floor(Math.random() * pool.length)];
- const def = INCIDENTS[type];
- const available = FURN.filter(f => f.tags && f.tags.includes(def.tag) && !incidents.some(i => i.f === f));
- if (available.length){
- const f = available[Math.floor(Math.random() * available.length)];
- bot.state = 'sabotage';
- bot.sabotageTarget = f;
- buildBotPath(bot, f.x + f.w/2, f.y + f.d + 30);
- bot.isSuspect = true;
- bot.suspectTimer = 0;
- return true;
- }
- }
- } else if (roll < sabChance + leakChance){
- if (exitTile){
- bot.state = 'leak';
- buildBotPath(bot, exitTile.x, exitTile.y);
- bot.isSuspect = true;
- bot.suspectTimer = 0;
- return true;
- }
- }
- bot.state = 'wander';
- bot.isSuspect = false;
- pickBotTarget(bot);
- return false;
- }
- function updateBots(dt){
- for (const bot of bots){
- if (bot.isCaught) continue;
- if (bot.waitTimer > 0){ bot.waitTimer -= dt; continue; }
- const dx = bot.targetX - bot.x, dy = bot.targetY - bot.y;
- const d = Math.hypot(dx, dy);
- if (d < 12){
- if (bot.waypoints && bot.wpIdx !== undefined && bot.wpIdx < bot.waypoints.length - 1){
- bot.wpIdx++;
- const wp = bot.waypoints[bot.wpIdx];
- bot.targetX = wp.x; bot.targetY = wp.y;
- continue;
- }
- bot.waypoints = null; bot.wpIdx = 0;
- if (bot.state === 'sabotage' && bot.sabotageTarget){
- const f = bot.sabotageTarget;
- const typePool = f.tags.filter(t => INCIDENTS[t] && waveTasks.some(w => w.type === t) && !incidents.some(i => i.type === t && i.f === f));
- if (typePool.length && !incidents.some(i => i.f === f)){
- const type = typePool[Math.floor(Math.random() * typePool.length)];
- const life = currentDiff.shifts[currentShift].time;
- incidents.push({ type, f, x: f.x + f.w/2, y: f.y + f.d/2, maxTime: life, timeLeft: life, pop: 0, fromBot: bot.name });
- spawnedInShift++;
- shiftSpawnTimer = rand(3, 5);
- addLog('⚠ Саботаж: ' + bot.name + ' · ' + INCIDENTS[type].label, 'warn');
- toast('🕵️ ' + bot.name + ' саботирует: ' + INCIDENTS[type].label, 'bad');
- soundAlert();
- }
- bot.state = 'wander'; bot.sabotageTarget = null;
- bot.isSuspect = false;
- bot.waitTimer = rand(2, 5);
- botPickNextAction(bot);
- } else if (bot.state === 'leak'){
- leaks++; statsAch.shiftErrors++;
- updateHUD();
- addLog('✗ ' + bot.name + ' слил данные!', 'bad');
- toast('💀 ' + bot.name + ' сливает данные!', 'bad');
- dispatch('Утечка данных сотрудником ' + bot.name + '!');
- bot.state = 'wander'; bot.isSuspect = false;
- bot.waitTimer = rand(3, 7);
- botPickNextAction(bot);
- if (leaks >= currentDiff.leaksMax) endGame(false);
- } else {
- bot.waitTimer = rand(0.5, 2);
- botPickNextAction(bot);
- }
- continue;
- }
- const step = bot.speed * dt;
- bot.x += (dx/d) * step;
- bot.y += (dy/d) * step;
- collide(bot, bot.r);
- bot.dir = dx > 0 ? 1 : -1;
- const moved = Math.hypot(bot.x - bot.lastX, bot.y - bot.lastY);
- if (moved < 0.5){
- bot.stuckTimer += dt;
- if (bot.stuckTimer > 1.5){
- bot.stuckTimer = 0;
- if (bot.state === 'sabotage' && bot.sabotageTarget){
- buildBotPath(bot, bot.sabotageTarget.x + bot.sabotageTarget.w/2, bot.sabotageTarget.y + bot.sabotageTarget.d + 30);
- } else if (bot.state === 'leak' && exitTile){
- buildBotPath(bot, exitTile.x, exitTile.y);
- } else pickBotTarget(bot);
- }
- } else bot.stuckTimer = 0;
- bot.lastX = bot.x; bot.lastY = bot.y;
- if (bot.isSuspect) bot.suspectTimer += dt;
- }
- }
- /* ============================================================
- КАМЕРЫ
- ============================================================ */
- let camFrame = 0;
- function initCameras(){
- camBufs = []; camRooms = ROOMS.slice();
- for (let i = 0; i < camRooms.length; i++){
- const buf = document.createElement('canvas');
- buf.width = 240; buf.height = 150;
- camBufs.push(buf);
- }
- if (activeCameraIdx >= camRooms.length) activeCameraIdx = 0;
- buildCamGrid();
- }
- function buildCamGrid(){
- if (!el.camGrid) return;
- el.camGrid.innerHTML = '';
- for (let i = 0; i < camRooms.length; i++){
- const cell = document.createElement('div');
- cell.className = 'camCell' + (i === activeCameraIdx ? ' active' : '');
- const cam = camRooms[i];
- const shortName = cam.name.length > 18 ? cam.name.slice(0, 16) + '…' : cam.name;
- const lbl = document.createElement('div'); lbl.className = 'camLabel'; lbl.textContent = 'CAM ' + String(i+1).padStart(2, '0');
- const rm = document.createElement('div'); rm.className = 'camRoom'; rm.textContent = (cam.isSoc ? '★ ' : '') + shortName;
- const cnv = document.createElement('canvas'); cnv.width = 240; cnv.height = 150;
- const al = document.createElement('div'); al.className = 'camAlert'; al.style.display = 'none'; al.textContent = '⚠ НАРУШЕНИЕ';
- cell.appendChild(lbl); cell.appendChild(rm); cell.appendChild(cnv); cell.appendChild(al);
- cell.onclick = () => { activeCameraIdx = i; buildCamGrid(); updateCamInfo(); };
- el.camGrid.appendChild(cell);
- }
- updateCamInfo();
- }
- function updateCamInfo(){
- const cam = camRooms[activeCameraIdx];
- const suspects = bots.filter(b => !b.isCaught && b.isSuspect).length;
- if (el.camBotsCount) el.camBotsCount.textContent = camRooms.length;
- if (el.camSusCount) el.camSusCount.textContent = suspects;
- if (el.camCaughtCount) el.camCaughtCount.textContent = caughtThisShift + ' / ' + totalCaught;
- if (!cam){ if (el.camInfo) el.camInfo.textContent = 'Нет камер'; if (el.camReport) el.camReport.disabled = true; return; }
- const susInCam = bots.find(b => !b.isCaught && b.isSuspect && roomAt(b.x, b.y) === cam);
- if (susInCam){
- if (el.camInfo) el.camInfo.textContent = '⚠ ' + cam.name + ' · ' + susInCam.name + ' (' + (susInCam.state === 'sabotage' ? 'саботаж' : susInCam.state === 'leak' ? 'слив' : 'подозрение') + ')';
- if (el.camReport) el.camReport.disabled = false;
- } else {
- const hereBots = bots.filter(b => !b.isCaught && roomAt(b.x, b.y) === cam).length;
- if (el.camInfo) el.camInfo.textContent = cam.name + ' · сотрудников: ' + hereBots;
- if (el.camReport) el.camReport.disabled = true;
- }
- }
- function drawCameras(){
- if (!cameraOpen) return;
- camFrame++;
- for (let i = 0; i < camRooms.length; i++){
- const isActive = i === activeCameraIdx;
- if (!isActive && camFrame % 3 !== 0) continue;
- const room = camRooms[i], buf = camBufs[i];
- if (!buf) continue;
- const bctx = buf.getContext('2d');
- bctx.fillStyle = room.floor[0]; bctx.fillRect(0, 0, buf.width, buf.height);
- bctx.strokeStyle = 'rgba(120,180,255,.08)'; bctx.lineWidth = 1;
- for (let gx = 0; gx < buf.width; gx += 24){ bctx.beginPath(); bctx.moveTo(gx, 0); bctx.lineTo(gx, buf.height); bctx.stroke(); }
- for (let gy = 0; gy < buf.height; gy += 24){ bctx.beginPath(); bctx.moveTo(0, gy); bctx.lineTo(buf.width, gy); bctx.stroke(); }
- const scX = buf.width / room.w, scY = buf.height / room.h;
- for (const f of FURN){
- if (f.x + f.w < room.x || f.x > room.x + room.w) continue;
- if (f.y + f.d < room.y || f.y > room.y + room.h) continue;
- const rx = (f.x - room.x) * scX, ry = (f.y - room.y) * scY;
- const rw = Math.max(3, f.w * scX), rh = Math.max(3, f.d * scY);
- bctx.fillStyle = f.kind === 'camwall' ? '#1a3a1a' : '#3a4d70';
- bctx.fillRect(rx, ry, rw, rh);
- bctx.strokeStyle = f.kind === 'camwall' ? '#4ade80' : '#8ea9d4'; bctx.lineWidth = 1;
- bctx.strokeRect(rx + 0.5, ry + 0.5, rw - 1, rh - 1);
- }
- for (const inc of incidents){
- if (inc.x < room.x || inc.x > room.x + room.w) continue;
- if (inc.y < room.y || inc.y > room.y + room.h) continue;
- const rx = (inc.x - room.x) * scX, ry = (inc.y - room.y) * scY;
- bctx.globalAlpha = 0.6 + Math.sin(time * 5) * 0.4;
- bctx.fillStyle = INCIDENTS[inc.type].color;
- bctx.beginPath(); bctx.arc(rx, ry, 7, 0, 7); bctx.fill();
- bctx.globalAlpha = 1;
- }
- for (const bot of bots){
- if (bot.isCaught) continue;
- if (bot.x < room.x || bot.x > room.x + room.w) continue;
- if (bot.y < room.y || bot.y > room.y + room.h) continue;
- const rx = (bot.x - room.x) * scX, ry = (bot.y - room.y) * scY;
- if (bot.isSuspect){
- bctx.globalAlpha = 0.4 + Math.sin(time * 8) * 0.35;
- bctx.fillStyle = '#ff3030'; bctx.beginPath(); bctx.arc(rx, ry, 13, 0, 7); bctx.fill();
- bctx.globalAlpha = 1;
- }
- bctx.fillStyle = bot.color; bctx.beginPath(); bctx.arc(rx, ry, 6, 0, 7); bctx.fill();
- bctx.strokeStyle = bot.isSuspect ? '#ff3030' : '#000'; bctx.lineWidth = 2; bctx.stroke();
- bctx.fillStyle = bot.isSuspect ? '#ff8080' : '#fff';
- bctx.font = 'bold 9px "Segoe UI",sans-serif'; bctx.textAlign = 'center'; bctx.textBaseline = 'bottom';
- bctx.fillText(bot.name, rx, ry - 9);
- if (bot.state === 'sabotage') bctx.fillText('🔧', rx + 12, ry + 4);
- else if (bot.state === 'leak') bctx.fillText('📤', rx + 12, ry + 4);
- }
- if (player.x >= room.x && player.x <= room.x + room.w && player.y >= room.y && player.y <= room.y + room.h){
- const rx = (player.x - room.x) * scX, ry = (player.y - room.y) * scY;
- bctx.fillStyle = '#fff'; bctx.beginPath(); bctx.arc(rx, ry, 7, 0, 7); bctx.fill();
- bctx.strokeStyle = '#4ea1ff'; bctx.lineWidth = 2; bctx.stroke();
- bctx.fillStyle = '#8ee7ff'; bctx.font = 'bold 9px "Segoe UI",sans-serif'; bctx.textAlign = 'center'; bctx.textBaseline = 'bottom';
- bctx.fillText('ВЫ', rx, ry - 9);
- }
- bctx.fillStyle = 'rgba(0,0,0,.06)';
- for (let y = 0; y < buf.height; y += 3) bctx.fillRect(0, y, buf.width, 1);
- const cell = el.camGrid.children[i];
- if (cell){
- const cc = cell.querySelector('canvas');
- if (cc){ const c2 = cc.getContext('2d'); c2.clearRect(0, 0, cc.width, cc.height); c2.drawImage(buf, 0, 0, cc.width, cc.height); }
- const alert = cell.querySelector('.camAlert');
- if (alert) alert.style.display = bots.some(b => !b.isCaught && b.isSuspect && roomAt(b.x, b.y) === room) ? 'block' : 'none';
- }
- }
- }
- function openCameraView(){
- if (!socRoom) return;
- const here = roomAt(player.x, player.y);
- if (!here || !here.isSoc){ showHint('Камеры доступны только в SOC', 3000); return; }
- cameraOpen = true; state = 'camera';
- hideAll(); showScreen('camera');
- buildCamGrid(); updateCamInfo(); updateMobileVisibility();
- }
- function closeCameraView(){
- cameraOpen = false; state = 'playing'; hideAll();
- el.hud.classList.remove('hide');
- el.taskPanel.classList.add('show'); el.logPanel.classList.add('show'); el.minimap.classList.add('show');
- refreshAchievementHUD(); updateMobileVisibility(); focusStage();
- }
- function reportSuspect(){
- const cam = camRooms[activeCameraIdx];
- if (!cam){ showHint('Нет камеры', 2000); return; }
- const sus = bots.find(b => !b.isCaught && b.isSuspect && roomAt(b.x, b.y) === cam);
- if (!sus){ showHint('На этой камере никого не подозревают', 2500); return; }
- const wasLeak = sus.state === 'leak', wasSab = sus.state === 'sabotage';
- sus.isCaught = true; sus.isSuspect = false; sus.state = 'caught';
- caughtCount++; caughtThisShift++; totalCaught++;
- statsAch.totalCaught = totalCaught;
- score += 60;
- addLog('✓ Поймали: ' + sus.name + ' (+60)', 'ok');
- toast('✓ Поймали: ' + sus.name, 'ok');
- if (wasLeak){ addLog('🛡 Предотвращена утечка', 'ok'); toast('🛡 Утечка предотвращена!', 'ok'); }
- if (wasSab){ addLog('🛡 Предотвращён саботаж', 'ok'); }
- updateHUD(); updateCamInfo(); soundCaught(); checkAchievements(statsAch);
- }
- /* ============================================================
- ЧАСТИЦЫ
- ============================================================ */
- const particlePool = [];
- function getParticle(){ return particlePool.length > 0 ? particlePool.pop() : {}; }
- function releaseParticle(p){ if (particlePool.length < 100) particlePool.push(p); }
- function burst(wx, wy, color, n, spd){
- spd = spd || 1; n = Math.min(n, 10);
- for (let i = 0; i < n; i++){
- const a = Math.random() * Math.PI * 2, s = rand(40, 180) * spd;
- const p = getParticle();
- p.x = wx; p.y = wy; p.z = rand(20, 70);
- p.vx = Math.cos(a)*s; p.vy = Math.sin(a)*s; p.vz = rand(50, 180);
- p.life = 0.75; p.color = color; p.size = rand(2, 4);
- particles.push(p);
- }
- }
- function toast(text, type){
- const w = Math.min(600, text.length * 8 + 34);
- toasts.push({text, type: type || 'ok', life: 4, w});
- if (toasts.length > 3) toasts.shift();
- }
- /* ============================================================
- ИНЦИДЕНТЫ
- ============================================================ */
- function nearestIncident(){
- let best = null, bd = Infinity;
- for (const inc of incidents){
- const dx = Math.max(inc.f.x - player.x, 0, player.x - (inc.f.x + inc.f.w));
- const dy = Math.max(inc.f.y - player.y, 0, player.y - (inc.f.y + inc.f.d));
- const d = Math.hypot(dx, dy);
- if (d < bd){ bd = d; best = inc; }
- }
- return {inc: best, d: bd};
- }
- function fixIncident(inc){
- const def = INCIDENTS[inc.type];
- const bonus = Math.round(inc.timeLeft);
- score += 20 + bonus; fixedCount++;
- if (statsAch.shiftErrors === 0) statsAch.fixedNoErrors++;
- const i = incidents.indexOf(inc);
- if (i >= 0) incidents.splice(i, 1);
- const wt = waveTasks.find(w => w.type === inc.type);
- if (wt && wt.done < wt.need) wt.done++;
- burst(inc.x, inc.y, def.color, 10);
- addLog('✓ Закрыто: ' + def.label + ' (+' + (20 + bonus) + ')', 'ok');
- toast(def.icon + ' ' + def.label + ' — закрыт', 'ok');
- updateHUD(); updateTaskUI(); soundOk();
- }
- function leakIncident(inc){
- const def = INCIDENTS[inc.type];
- leaks++; statsAch.shiftErrors++;
- score = Math.max(0, score - 15);
- const i = incidents.indexOf(inc);
- if (i >= 0) incidents.splice(i, 1);
- burst(inc.x, inc.y, '#ff3030', 14, 1.3);
- addLog('✗ УТЕЧКА: ' + def.label, 'bad');
- toast('💀 Утечка: ' + def.label, 'bad');
- updateHUD(); soundAlert();
- dispatch('Внимание! Утечка: ' + def.label);
- if (leaks >= currentDiff.leaksMax) endGame(false);
- }
- /* ============================================================
- HUD
- ============================================================ */
- let _lastHud = {score:-1, wave:'', fixed:-1, leaks:'', caught:-1, high:-1};
- function updateHUD(){
- if (!el.hudScore) return;
- if (_lastHud.score !== score){ el.hudScore.textContent = score; _lastHud.score = score; }
- const wv = (currentShift + 1) + ' / ' + currentDiff.shifts.length;
- if (_lastHud.wave !== wv){ el.hudWave.textContent = wv; _lastHud.wave = wv; }
- if (_lastHud.fixed !== fixedCount){ el.hudFixed.textContent = fixedCount; _lastHud.fixed = fixedCount; }
- const lk = leaks + ' / ' + currentDiff.leaksMax;
- if (_lastHud.leaks !== lk){
- el.hudLeaks.textContent = lk;
- el.hudLeaks.style.color = leaks >= currentDiff.leaksMax - 1 ? '#ff6b6b' : '#ff8a8a';
- _lastHud.leaks = lk;
- }
- if (_lastHud.caught !== caughtThisShift){ el.hudCaught.textContent = caughtThisShift; _lastHud.caught = caughtThisShift; }
- if (_lastHud.high !== highScore){ el.hudHigh.textContent = highScore; _lastHud.high = highScore; }
- }
- let _lastProgPct = -1;
- function updateProgressBar(){
- if (!el.progFill) return;
- let total = 0, done = 0;
- for (const w of waveTasks){ total += w.need; done += Math.min(w.done, w.need); }
- const pct = total > 0 ? Math.round((done / total) * 100) : 0;
- if (pct !== _lastProgPct){ el.progFill.style.width = pct + '%'; _lastProgPct = pct; }
- }
- function updateTaskUI(){
- if (!el.taskList) return;
- el.taskList.innerHTML = '';
- for (const wt of waveTasks){
- const def = INCIDENTS[wt.type], done = wt.done >= wt.need;
- const li = document.createElement('li');
- if (done) li.className = 'done';
- const s1 = document.createElement('span');
- const ic = document.createElement('span'); ic.style.marginRight = '.4em'; ic.textContent = def.icon;
- const nm = document.createElement('span'); nm.className = 'name'; nm.textContent = def.label;
- s1.appendChild(ic); s1.appendChild(nm);
- const b = document.createElement('b'); b.textContent = wt.done + '/' + wt.need;
- li.appendChild(s1); li.appendChild(b);
- el.taskList.appendChild(li);
- }
- updateProgressBar();
- }
- /* ============================================================
- ЭКРАНЫ
- ============================================================ */
- const screens = {
- menu: el.mainMenuScreen, settings: el.settingsScreen, rules: el.rulesScreen,
- pause: el.pauseScreen, shift: el.shiftScreen, puzzle: el.puzzleScreen,
- audit: el.auditScreen, end: el.endScreen,
- tutorial: el.tutorialScreen, tutdetail: el.tutDetailScreen,
- camera: el.cameraScreen, ach: el.achScreen
- };
- function hideAll(){ for (const k in screens) { if (screens[k]) screens[k].classList.add('hide'); } }
- function showScreen(k){ if (screens[k]) screens[k].classList.remove('hide'); }
- /* ============================================================
- КЛАВИАТУРА
- ============================================================ */
- const CODE_ACTION = {
- KeyW:'up', ArrowUp:'up', KeyS:'down', ArrowDown:'down',
- KeyA:'left', ArrowLeft:'left', KeyD:'right', ArrowRight:'right',
- KeyE:'action', Space:'action', Escape:'escape', KeyP:'pause', KeyH:'hint',
- KeyF:'fullscreen', KeyM:'home', KeyC:'camera',
- Enter:'enter', Backspace:'backspace', Delete:'backspace'
- };
- function actionFromKey(k){
- if (!k) return null;
- if (k === ' ' || k === 'Spacebar') return 'action';
- if (k === 'ArrowUp') return 'up';
- if (k === 'ArrowDown') return 'down';
- if (k === 'ArrowLeft') return 'left';
- if (k === 'ArrowRight') return 'right';
- if (k === 'Enter') return 'enter';
- if (k === 'Escape' || k === 'Esc') return 'escape';
- if (k === 'Backspace' || k === 'Delete') return 'backspace';
- if (/^[0-9]$/.test(k)) return k;
- const low = k.toLowerCase();
- if (low === 'w' || low === 'ц') return 'up';
- if (low === 's' || low === 'ы') return 'down';
- if (low === 'a' || low === 'ф') return 'left';
- if (low === 'd' || low === 'в') return 'right';
- if (low === 'e' || low === 'у') return 'action';
- if (low === 'h' || low === 'р') return 'hint';
- if (low === 'f' || low === 'а') return 'fullscreen';
- if (low === 'p' || low === 'з') return 'pause';
- if (low === 'm' || low === 'ь') return 'home';
- if (low === 'c' || low === 'с') return 'camera';
- return null;
- }
- function resolveAction(e){
- if (e.code && CODE_ACTION[e.code]) return CODE_ACTION[e.code];
- return actionFromKey(e.key);
- }
- function handleKeyDown(e){
- if (state === 'puzzle' && puzzle){
- if (e.key === 'Escape'){ e.preventDefault(); closePuzzle(); return; }
- if (puzzleFailedActive && !demoMode){ e.preventDefault(); return; }
- if (e.ctrlKey || e.metaKey || e.altKey) return;
- if (e.key === 'Tab'){ e.preventDefault(); return; }
- if (e.code === 'KeyC' || e.code === 'KeyM' || e.code === 'KeyP' || e.code === 'KeyH' || e.code === 'KeyF'){ e.preventDefault(); return; }
- if (e.key === 'Enter' || e.key === 'Backspace'){
- e.preventDefault();
- if (puzzle.handleKey) puzzle.handleKey(e.key === 'Enter' ? 'enter' : 'backspace');
- return;
- }
- if (puzzle.handleText && e.key && e.key.length === 1){ e.preventDefault(); puzzle.handleText(e.key); return; }
- const action = resolveAction(e);
- if (action && puzzle.handleKey){ if (puzzle.handleKey(action)) e.preventDefault(); }
- return;
- }
- if (state === 'camera'){
- if (e.key === 'Escape'){ e.preventDefault(); closeCameraView(); return; }
- const action = resolveAction(e);
- if (action === 'action' || action === 'enter'){ e.preventDefault(); reportSuspect(); return; }
- if (action === 'camera'){ e.preventDefault(); closeCameraView(); return; }
- if (/^[1-9]$/.test(action || '')){
- const idx = parseInt(action, 10) - 1;
- if (idx >= 0 && idx < camRooms.length){ activeCameraIdx = idx; buildCamGrid(); updateCamInfo(); }
- }
- return;
- }
- const action = resolveAction(e);
- if (!action) return;
- if (['up','down','left','right','action'].includes(action)) e.preventDefault();
- if (action === 'camera' && !e.repeat){ openCameraView(); return; }
- if (action === 'home' && !e.repeat){ exitToMenu(); return; }
- if (action === 'escape'){
- e.preventDefault();
- if (state === 'paused'){ resumeGame(); return; }
- if (state === 'playing'){ pauseGame(); return; }
- if (state === 'settings' || state === 'rules' || state === 'ach'){ state = 'menu'; hideAll(); showScreen('menu'); return; }
- return;
- }
- if (action === 'pause' && !e.repeat){
- if (state === 'playing') pauseGame(); else if (state === 'paused') resumeGame();
- return;
- }
- if (action === 'fullscreen' && !e.repeat){ toggleFullscreen(); return; }
- if (action === 'hint' && !e.repeat && state !== 'paused'){ showContextHint(); return; }
- if (state === 'paused') return;
- if (state === 'playing'){
- if (action === 'up') keys.up = true;
- else if (action === 'down') keys.down = true;
- else if (action === 'left') keys.left = true;
- else if (action === 'right') keys.right = true;
- else if (action === 'action' && !e.repeat) actionPressed = true;
- }
- }
- function handleKeyUp(e){
- const action = resolveAction(e);
- if (!action) return;
- if (action === 'up') keys.up = false;
- else if (action === 'down') keys.down = false;
- else if (action === 'left') keys.left = false;
- else if (action === 'right') keys.right = false;
- }
- window.addEventListener('keydown', handleKeyDown, true);
- window.addEventListener('keyup', handleKeyUp, true);
- function focusStage(){ if (document.activeElement && document.activeElement.blur) document.activeElement.blur(); try { el.stage.focus({preventScroll:true}); } catch(e){ el.stage.focus(); } }
- function toggleFullscreen(){
- const e = document.getElementById('wrap') || document.documentElement;
- const isFs = document.fullscreenElement || document.webkitFullscreenElement;
- if (!isFs){
- const req = e.requestFullscreen || e.webkitRequestFullscreen;
- if (req){ try { const p = req.call(e); if (p && p.catch) p.catch(()=>{}); } catch(err){} }
- } else {
- const ex = document.exitFullscreen || document.webkitExitFullscreen;
- if (ex){ try { const p = ex.call(document); if (p && p.catch) p.catch(()=>{}); } catch(err){} }
- }
- }
- /* ============================================================
- ПЕРЕХОДЫ
- ============================================================ */
- async function exitToMenu(){
- if (state === 'menu') return;
- if (state === 'tutorial' || state === 'tutdetail'){ demoMode = false; state = 'menu'; hideAll(); showScreen('menu'); return; }
- if (state === 'camera'){ closeCameraView(); return; }
- if (state === 'settings' || state === 'rules' || state === 'ach'){ state = 'menu'; hideAll(); showScreen('menu'); return; }
- const needsConfirm = (state === 'playing' || state === 'puzzle' || state === 'shift' || state === 'paused' || state === 'audit');
- if (needsConfirm){
- const ok = await showModal('Выйти в главное меню?');
- if (!ok) return;
- saveGameState();
- }
- stopPuzzleLoop(); puzzle = null;
- state = 'menu'; pausedFrom = null; stateBeforePuzzle = null; demoMode = false;
- puzzleFailedActive = false; cameraOpen = false;
- keys.up = keys.down = keys.left = keys.right = false;
- hideAll();
- if (el.hud) el.hud.classList.add('hide');
- if (el.taskPanel) el.taskPanel.classList.remove('show');
- if (el.logPanel) el.logPanel.classList.remove('show');
- if (el.achPanel) el.achPanel.classList.remove('show');
- if (el.minimap) el.minimap.classList.remove('show');
- if (el.hintBar) el.hintBar.classList.remove('show');
- updateMobileVisibility(); updateContinueButton();
- showScreen('menu'); focusStage();
- }
- function pauseGame(){ if (state === 'paused' || state === 'camera') return; pausedFrom = state; state = 'paused'; showScreen('pause'); }
- function resumeGame(){ if (state !== 'paused') return; state = pausedFrom || 'playing'; hideAll(); if (state === 'playing') focusStage(); }
- function showContextHint(){
- if (state === 'playing'){
- const here = roomAt(player.x, player.y);
- if (here && here.isSoc){ showHint('★ SOC · C — камеры · E — инцидент', 3000); return; }
- const {inc, d} = nearestIncident();
- if (!inc){ showHint('Инцидентов рядом нет', 3000); return; }
- const def = INCIDENTS[inc.type];
- showHint(d < 60 ? 'E — открыть: ' + def.label : 'Ближайший: ' + def.icon + ' ' + def.label, 3000);
- } else if (state === 'puzzle'){
- if (puzzle && puzzle.keys){ if (el.pzHint){ el.pzHint.textContent = puzzle.keys; el.pzHint.className = ''; } }
- } else if (state === 'camera'){ showHint('Клик по камере · 1-9 · E — доложить · C — закрыть', 3500); }
- }
- /* ============================================================
- ЗАДАЧИ СМЕНЫ
- ============================================================ */
- function setupShiftTasks(shift){
- const allTypes = ALL_INCIDENT_TYPES.slice();
- const n = Math.min(shift.count, allTypes.length);
- const chosen = shuffle(allTypes).slice(0, n);
- waveTasks = chosen.map(t => ({type: t, need: 1, done: 0}));
- let rem = shift.count - n;
- while (rem > 0){ waveTasks[Math.floor(Math.random() * waveTasks.length)].need++; rem--; }
- shuffle(waveTasks);
- updateTaskUI();
- }
- /* ============================================================
- СТАРТ / СМЕНЫ
- ============================================================ */
- function startGame(){
- currentDiff = DIFF[settings.diff] || DIFF.normal;
- score = 0; leaks = 0; fixedCount = 0; caughtCount = 0;
- caughtThisShift = 0; totalCaught = 0;
- statsAch = { shifts: 0, perfectShift: false, totalCaught: 0, fixedNoErrors: 0, auditPassed: false, score: 0, shiftErrors: 0 };
- currentShift = 0; demoMode = false; puzzleFailedActive = false; cameraOpen = false;
- generateWorld(); initCameras(); spawnBots(); resetAfterWorld();
- hideAll();
- el.hud.classList.remove('hide');
- el.taskPanel.classList.add('show'); el.logPanel.classList.add('show'); el.minimap.classList.add('show');
- startShift(0); updateMobileVisibility(); focusStage();
- }
- function resetAfterWorld(){
- incidents.length = 0; particles.length = 0; toasts.length = 0;
- clearLog(); updateHUD();
- }
- function startShift(idx){
- currentShift = idx;
- const shift = currentDiff.shifts[idx];
- spawnedInShift = 0; shiftSpawnTimer = 1.0;
- incidents.length = 0; caughtThisShift = 0; statsAch.shiftErrors = 0;
- setupShiftTasks(shift);
- spawnBots();
- updateHUD(); state = 'playing'; hideAll();
- el.hud.classList.remove('hide');
- el.taskPanel.classList.add('show'); el.logPanel.classList.add('show'); el.minimap.classList.add('show');
- refreshAchievementHUD();
- addLog('─── СМЕНА ' + (idx + 1) + ' / ' + currentDiff.shifts.length + ' ───', 'sys');
- const msgs = ['Смена принята. Вы в SOC. C — камеры.','Сотрудники в офисе. Следите за камерами.','Служба ИБ на связи.','Проверяющий выехал. Не подведите.'];
- setTimeout(() => dispatch(msgs[idx % msgs.length]), 300);
- updateMobileVisibility(); focusStage(); saveGameState();
- }
- function showShiftDebrief(){
- state = 'shift'; hideAll();
- el.hud.classList.add('hide');
- el.taskPanel.classList.remove('show'); el.logPanel.classList.remove('show');
- el.achPanel.classList.remove('show'); el.minimap.classList.remove('show');
- updateMobileVisibility();
- statsAch.shifts = currentShift + 1;
- statsAch.perfectShift = (statsAch.shiftErrors === 0 && leaks === 0);
- statsAch.score = score;
- checkAchievements(statsAch);
- el.shiftFixed.textContent = fixedCount;
- el.shiftLeaks.textContent = leaks;
- el.shiftCaught.textContent = caughtThisShift;
- el.shiftScore.textContent = score;
- el.shiftTitle.textContent = 'Рапорт · смена ' + (currentShift + 1);
- el.shiftMsg.textContent = leaks === 0 ? 'Смена закрыта без утечек. Отличная работа!' : 'Смена закрыта. Утечек: ' + leaks;
- if (currentShift >= currentDiff.shifts.length - 1){
- el.shiftNext.textContent = 'Перейти к аудиту ▶';
- } else {
- el.shiftNext.textContent = 'Следующая смена ▶';
- }
- showScreen('shift');
- }
- /* ============================================================
- END / AUDIT
- ============================================================ */
- function endGame(win){
- state = 'end'; hideAll();
- el.hud.classList.add('hide');
- el.taskPanel.classList.remove('show'); el.logPanel.classList.remove('show');
- el.achPanel.classList.remove('show'); el.minimap.classList.remove('show');
- updateMobileVisibility();
- if (score > highScore){ highScore = score; saveHigh(); }
- statsAch.score = score;
- statsAch.shifts = win ? currentDiff.shifts.length : currentShift;
- checkAchievements(statsAch);
- el.endTitle.textContent = win ? 'Данные защищены' : 'Утечка данных';
- el.endTitle.className = win ? 'win' : 'lose';
- el.endSub.textContent = win ? 'Смена закрыта' : 'Провал';
- el.stScore.textContent = score; el.stFixed.textContent = fixedCount;
- el.stLeaks.textContent = leaks; el.stCaught.textContent = caughtThisShift;
- el.endMsg.textContent = win ? 'Все инциденты закрыты. Сервис работает.' : 'Слишком много утечек.';
- showScreen('end');
- clearGameState();
- }
- function startAudit(){
- state = 'audit'; hideAll(); showScreen('audit');
- const list = el.auditList; list.innerHTML = '';
- const checks = [
- {ok: leaks === 0, txt: '0 утечек данных'},
- {ok: fixedCount >= currentDiff.shifts.length, txt: 'Все инциденты закрыты'},
- {ok: true, txt: 'SOC работает штатно'},
- {ok: caughtThisShift >= 1, txt: 'Пойман хотя бы 1 нарушитель'}
- ];
- for (const c of checks){
- const d = document.createElement('div'); d.className = 'rule';
- d.innerHTML = (c.ok ? '✅ ' : '⚠️ ') + c.txt;
- list.appendChild(d);
- }
- }
- /* ============================================================
- ОБУЧЕНИЕ
- ============================================================ */
- const TUT_ITEMS = [
- {id:'keypad', ic:'🔢', name:'Кодовый замок', sub:'Введите 4-значный код'},
- {id:'wires', ic:'🔌', name:'Провода', sub:'Соедините одинаковые'},
- {id:'dials', ic:'🎛️', name:'Диски', sub:'Совместите стрелки'},
- {id:'sliders', ic:'📊', name:'Ползунки', sub:'В зелёную зону'},
- {id:'card', ic:'💳', name:'Карта', sub:'Проведи карту'},
- {id:'sequence',ic:'🎵', name:'Последовательность',sub:'Повтори 4 шага'},
- {id:'power', ic:'⚡', name:'Мощность', sub:'Поймай 3 раза'},
- {id:'flicker', ic:'📺', name:'Помехи', sub:'Клик по точке'}
- ];
- function buildTutGrid(){
- if (!el.tutGrid) return;
- el.tutGrid.innerHTML = '';
- for (const t of TUT_ITEMS){
- const card = document.createElement('div');
- card.className = 'tutCard';
- const ic = document.createElement('span'); ic.className = 'ic'; ic.textContent = t.ic;
- const ti = document.createElement('div'); ti.className = 'ti'; ti.textContent = t.name;
- card.appendChild(ic); card.appendChild(ti);
- card.onclick = () => showTutDetail(t);
- el.tutGrid.appendChild(card);
- }
- }
- let curTut = null;
- function showTutDetail(t){
- curTut = t;
- el.tutDetailTitle.textContent = t.ic + ' ' + t.name;
- el.tutDetailSub.textContent = t.sub;
- el.tutDetailBody.innerHTML = '<div class="lead">Попробуйте пройти мини-игру. Это демо без штрафов.</div>' +
- '<h3>Управление</h3><div>Мышь — клики/перетаскивание. Клавиатура: <kbd>Enter</kbd> подтвердить, <kbd>Backspace</kbd> стереть, <kbd>1-9</kbd> — прямые действия.</div>';
- hideAll(); showScreen('tutdetail');
- }
- /* ============================================================
- PUZZLES
- ============================================================ */
- const pzCanvas = el.pzCanvas;
- const pzCtx = pzCanvas.getContext('2d');
- const PZ_W = 480, PZ_H = 360;
- let puzzleDirty = true;
- const PC = {bg:'#0d1117',card:'#161b22',panel:'#21262d',panelHover:'#30363d',border:'#30363d',borderLight:'#484f58',text:'#c9d1d9',textBright:'#f0f6fc',textDim:'#8b949e',textMute:'#6e7681',blue:'#58a6ff',blueDeep:'#1f6feb',green:'#3fb950',greenDeep:'#238636',yellow:'#d29922',red:'#f85149',purple:'#a371f7'};
- function pzRR(x,y,w,h,r){ pzCtx.beginPath(); pzCtx.moveTo(x+r,y); pzCtx.arcTo(x+w,y,x+w,y+h,r); pzCtx.arcTo(x+w,y+h,x,y+h,r); pzCtx.arcTo(x,y+h,x,y,r); pzCtx.arcTo(x,y,x+w,y,r); pzCtx.closePath(); }
- function pzHover(x,y,w,h){ return puzzleMouse.x>=x && puzzleMouse.x<=x+w && puzzleMouse.y>=y && puzzleMouse.y<=y+h; }
- function pzHeader(text, tone){
- pzCtx.fillStyle = PC.card; pzCtx.fillRect(0, 0, PZ_W, 34);
- pzCtx.fillStyle = PC.border; pzCtx.fillRect(0, 33, PZ_W, 1);
- pzCtx.fillStyle = tone === 'ok' ? PC.green : tone === 'warn' ? PC.yellow : tone === 'bad' ? PC.red : PC.blue;
- pzCtx.beginPath(); pzCtx.arc(16, 17, 4, 0, 7); pzCtx.fill();
- pzCtx.font = '600 12px "Segoe UI",sans-serif'; pzCtx.textAlign = 'left'; pzCtx.textBaseline = 'middle';
- pzCtx.fillStyle = PC.textBright; pzCtx.fillText(text, 28, 17);
- }
- function pzFooter(left, right, tone){
- const y = PZ_H - 28;
- pzCtx.fillStyle = PC.card; pzCtx.fillRect(0, y, PZ_W, 28);
- pzCtx.fillStyle = PC.border; pzCtx.fillRect(0, y, PZ_W, 1);
- pzCtx.font = '500 11px "Segoe UI",sans-serif'; pzCtx.textBaseline = 'middle';
- if (left){ pzCtx.textAlign = 'left'; pzCtx.fillStyle = PC.textMute; pzCtx.fillText(left, 14, y+14); }
- if (right){ pzCtx.textAlign = 'right'; pzCtx.fillStyle = tone === 'ok' ? PC.green : tone === 'bad' ? PC.red : PC.textDim; pzCtx.font = '600 11px "Segoe UI",sans-serif'; pzCtx.fillText(right, PZ_W - 14, y+14); }
- }
- function pzButton(x, y, w, h, label, hover, variant){
- let bg, border, fg;
- if (variant === 'primary'){ bg = hover ? '#388bfd' : PC.blueDeep; border = hover ? PC.blue : '#388bfd'; fg = '#fff'; }
- else if (variant === 'ok'){ bg = hover ? '#2ea043' : PC.greenDeep; border = hover ? PC.green : '#2ea043'; fg = '#fff'; }
- else if (variant === 'danger'){ bg = hover ? '#da3633' : '#8e1519'; border = hover ? PC.red : '#da3633'; fg = '#fff'; }
- else { bg = hover ? PC.panelHover : PC.panel; border = hover ? PC.borderLight : PC.border; fg = PC.text; }
- pzCtx.fillStyle = bg; pzRR(x, y, w, h, 6); pzCtx.fill();
- pzCtx.strokeStyle = border; pzCtx.lineWidth = 1; pzRR(x+0.5, y+0.5, w-1, h-1, 6); pzCtx.stroke();
- pzCtx.font = label.length > 2 ? '600 13px "Segoe UI",sans-serif' : '600 18px "Segoe UI",sans-serif';
- pzCtx.fillStyle = fg; pzCtx.textAlign = 'center'; pzCtx.textBaseline = 'middle';
- pzCtx.fillText(label, x + w/2, y + h/2 + 1);
- }
- function makePuzzle(kind){
- switch(kind){
- case 'keypad': return makeKeypad();
- case 'wires': return makeWires();
- case 'dials': return makeDials();
- case 'sliders': return makeSliders();
- case 'card': return makeCard();
- case 'sequence': return makeSequence();
- case 'power': return makePower();
- case 'flicker': return makeFlicker();
- default: return makeKeypad();
- }
- }
- function makeKeypad(){
- const code = String(Math.floor(1000 + Math.random()*9000));
- let entered = '';
- const kW = 72, kH = 42, kG = 8;
- const kx0 = (PZ_W - (kW*3 + kG*2))/2;
- const ky0 = 165;
- const keysArr = [['1','2','3'],['4','5','6'],['7','8','9'],['C','0','OK']];
- function keyRect(r,c){ return {x:kx0+c*(kW+kG), y:ky0+r*(kH+kG), w:kW, h:kH}; }
- function submit(){ if (entered === code) puzzleSolved(); else { entered = ''; puzzleFailed(); } }
- function press(k){
- if (k === 'C'){ entered = ''; beep(300,.08,'square'); }
- else if (k === 'OK'){ submit(); }
- else if (entered.length < 4){ entered += k; beep(600,.05); if (entered === code) setTimeout(puzzleSolved, 250); }
- puzzleDirty = true;
- }
- return {
- keys:'0-9 · Enter · Backspace',
- draw:function(){
- pzCtx.fillStyle = PC.bg; pzCtx.fillRect(0,0,PZ_W,PZ_H);
- pzHeader('ВВЕДИТЕ PIN-КОД', entered.length === 4 ? 'ok' : 'info');
- const cardY = 48;
- pzCtx.fillStyle = PC.card; pzRR(120, cardY, 240, 58, 8); pzCtx.fill();
- pzCtx.font = '600 10px "Segoe UI",sans-serif'; pzCtx.textAlign = 'center'; pzCtx.textBaseline = 'middle'; pzCtx.fillStyle = PC.textMute;
- pzCtx.fillText('КОД', PZ_W/2, cardY + 15);
- pzCtx.font = '700 28px "Consolas",monospace'; pzCtx.fillStyle = PC.yellow; pzCtx.fillText(code, PZ_W/2, cardY + 39);
- const inX = 120, inY = 118, inW = 240, inH = 38;
- pzCtx.fillStyle = '#010409'; pzRR(inX, inY, inW, inH, 6); pzCtx.fill();
- pzCtx.strokeStyle = entered.length === 4 ? PC.green : PC.border; pzCtx.lineWidth = 1.5; pzRR(inX+0.5, inY+0.5, inW-1, inH-1, 6); pzCtx.stroke();
- const cellW = (inW - 18) / 4;
- for (let i = 0; i < 4; i++){
- const cx2 = inX + 9 + i*(cellW+6) + cellW/2, cy2 = inY + inH/2;
- if (entered[i]){ pzCtx.font = '700 20px "Consolas",monospace'; pzCtx.fillStyle = entered.length === 4 ? PC.green : PC.blue; pzCtx.fillText(entered[i], cx2, cy2+1); }
- else { pzCtx.fillStyle = PC.border; pzCtx.beginPath(); pzCtx.arc(cx2, cy2, 3, 0, 7); pzCtx.fill(); }
- }
- for (let r = 0; r < 4; r++) for (let c = 0; c < 3; c++){
- const rr = keyRect(r,c);
- const v = keysArr[r][c] === 'OK' ? 'ok' : keysArr[r][c] === 'C' ? 'danger' : 'default';
- pzButton(rr.x, rr.y, rr.w, rr.h, keysArr[r][c], pzHover(rr.x, rr.y, rr.w, rr.h), v);
- }
- pzFooter('Введите 4-значный код', entered.length + ' / 4', entered.length === 4 ? 'ok' : null);
- },
- down:function(x,y){
- for (let r = 0; r < 4; r++) for (let c = 0; c < 3; c++){
- const rr = keyRect(r,c);
- if (x >= rr.x && x <= rr.x+rr.w && y >= rr.y && y <= rr.y+rr.h){ press(keysArr[r][c]); return true; }
- }
- return false;
- },
- move:function(){}, up:function(){},
- handleKey:function(a){
- if (a === 'enter'){ submit(); return true; }
- if (a === 'backspace'){ entered = entered.slice(0,-1); return true; }
- if (/^[0-9]$/.test(a)){ if (entered.length < 4){ entered += a; beep(600,.05); if (entered === code) setTimeout(puzzleSolved, 250); } return true; }
- return false;
- }
- };
- }
- function makeWires(){
- const colors = [PC.red, PC.blue, PC.yellow, PC.purple];
- const leftX = 90, rightX = PZ_W - 90;
- const yStart = 95, yStep = 62;
- const left = colors.map((c,i) => ({x:leftX, y:yStart+i*yStep, color:c, done:false}));
- const right = colors.slice().sort(() => Math.random()-0.5).map((c,i) => ({x:rightX, y:yStart+i*yStep, color:c, done:false}));
- let picked = -1;
- function drawNode(n, isLeft, idx){
- const h = pzHover(n.x-22, n.y-22, 44, 44);
- const isPicked = isLeft && picked === idx;
- const r = (isPicked || h) ? 13 : 11;
- if (isPicked){ pzCtx.fillStyle = n.color; pzCtx.globalAlpha = 0.3; pzCtx.beginPath(); pzCtx.arc(n.x, n.y, r+9, 0, 7); pzCtx.fill(); pzCtx.globalAlpha = 1; }
- pzCtx.fillStyle = n.color; pzCtx.beginPath(); pzCtx.arc(n.x, n.y, r, 0, 7); pzCtx.fill();
- pzCtx.fillStyle = PC.bg; pzCtx.beginPath(); pzCtx.arc(n.x, n.y, r*0.45, 0, 7); pzCtx.fill();
- if (n.done){ pzCtx.strokeStyle = PC.green; pzCtx.lineWidth = 2; pzCtx.beginPath(); pzCtx.moveTo(n.x-4, n.y); pzCtx.lineTo(n.x-1, n.y+3); pzCtx.lineTo(n.x+4, n.y-3); pzCtx.stroke(); }
- pzCtx.font = '700 10px "Segoe UI",sans-serif'; pzCtx.textAlign = 'center'; pzCtx.textBaseline = 'middle'; pzCtx.fillStyle = PC.textMute;
- if (!n.done) pzCtx.fillText(String(idx+1), n.x, n.y - r - 10);
- }
- function tryConnect(idx){
- if (picked < 0){ if (!left[idx].done){ picked = idx; beep(500,.05); } }
- else if (!right[idx].done){
- if (left[picked].color === right[idx].color){
- left[picked].done = true; right[idx].done = true; picked = -1; beep(800,.1);
- if (left.every(l => l.done)) setTimeout(puzzleSolved, 300);
- } else { puzzleFailed(); picked = -1; }
- }
- }
- return {
- keys:'Клик левый-правый · 1-4',
- draw:function(){
- pzCtx.fillStyle = PC.bg; pzCtx.fillRect(0,0,PZ_W,PZ_H);
- pzHeader(picked >= 0 ? 'ТЕПЕРЬ ПРАВЫЙ' : 'СОЕДИНИ ПРОВОДА', picked >= 0 ? 'warn' : 'info');
- pzCtx.fillStyle = PC.card; pzRR(50, 60, 80, 260, 8); pzCtx.fill(); pzRR(PZ_W-130, 60, 80, 260, 8); pzCtx.fill();
- for (let i = 0; i < left.length; i++){
- if (left[i].done){
- const R = right.find(r => r.color === left[i].color && r.done);
- if (R){
- pzCtx.strokeStyle = left[i].color; pzCtx.lineWidth = 3; pzCtx.lineCap = 'round';
- pzCtx.beginPath(); pzCtx.moveTo(left[i].x, left[i].y);
- pzCtx.bezierCurveTo(left[i].x + 130, left[i].y, R.x - 130, R.y, R.x, R.y); pzCtx.stroke();
- }
- }
- }
- for (let i = 0; i < left.length; i++) drawNode(left[i], true, i);
- for (let i = 0; i < right.length; i++) drawNode(right[i], false, i);
- pzFooter('Соедини одинаковые цвета', left.filter(l => l.done).length + ' / 4', left.every(l => l.done) ? 'ok' : null);
- },
- down:function(x,y){
- for (let i = 0; i < left.length; i++){
- const ddx = x-left[i].x, ddy = y-left[i].y;
- if (Math.sqrt(ddx*ddx+ddy*ddy) < 22){ if (left[i].done) return false; picked = i; beep(500,.05); return true; }
- }
- if (picked >= 0){
- for (let i = 0; i < right.length; i++){
- const ddx = x-right[i].x, ddy = y-right[i].y;
- if (Math.sqrt(ddx*ddx+ddy*ddy) < 22){ tryConnect(i); return true; }
- }
- }
- return false;
- },
- move:function(){}, up:function(){},
- handleKey:function(a){ const n = /^[1-9]$/.test(a) ? parseInt(a,10) : -1; if (n >= 1 && n <= 4){ tryConnect(n-1); return true; } return false; }
- };
- }
- function makeDials(){
- const targets = [Math.floor(Math.random()*8)*45, Math.floor(Math.random()*8)*45];
- const angles = [Math.floor(Math.random()*8)*45, Math.floor(Math.random()*8)*45];
- const dials = [{x:140, y:170, r:70}, {x:340, y:170, r:70}];
- function angDiff(a,b){ const d = Math.abs(a-b)%360; return Math.min(d, 360-d); }
- function dialOK(i){ return angDiff(angles[i], targets[i]) < 15; }
- function drawDial(i){
- const dd = dials[i], cx = dd.x, cy = dd.y, r = dd.r, ok = dialOK(i);
- pzCtx.fillStyle = '#010409'; pzCtx.beginPath(); pzCtx.arc(cx, cy, r, 0, 7); pzCtx.fill();
- pzCtx.strokeStyle = ok ? PC.green : PC.border; pzCtx.lineWidth = 2; pzCtx.beginPath(); pzCtx.arc(cx, cy, r, 0, 7); pzCtx.stroke();
- const tRad = (targets[i] - 90) * Math.PI/180;
- pzCtx.fillStyle = PC.green; pzCtx.beginPath(); pzCtx.arc(cx + Math.cos(tRad)*(r-22), cy + Math.sin(tRad)*(r-22), 6, 0, 7); pzCtx.fill();
- const rRad = (angles[i] - 90) * Math.PI/180;
- pzCtx.strokeStyle = ok ? PC.green : PC.blue; pzCtx.lineWidth = 3; pzCtx.lineCap = 'round';
- pzCtx.beginPath(); pzCtx.moveTo(cx, cy); pzCtx.lineTo(cx + Math.cos(rRad)*(r-28), cy + Math.sin(rRad)*(r-28)); pzCtx.stroke();
- pzCtx.font = '600 10px "Segoe UI",sans-serif'; pzCtx.textAlign = 'center'; pzCtx.textBaseline = 'middle'; pzCtx.fillStyle = ok ? PC.green : PC.textMute;
- pzCtx.fillText('ДИСК ' + (i+1) + (ok ? ' OK' : ''), cx, cy - r - 14);
- const btnW = 44, btnH = 30, gap = 12;
- const bx1 = cx - gap/2 - btnW, bx2 = cx + gap/2, by = cy + r + 12;
- pzButton(bx1, by, btnW, btnH, '<', pzHover(bx1, by, btnW, btnH), 'default');
- pzButton(bx2, by, btnW, btnH, '>', pzHover(bx2, by, btnW, btnH), 'default');
- }
- return {
- keys:'Кнопки < >',
- draw:function(){
- pzCtx.fillStyle = PC.bg; pzCtx.fillRect(0,0,PZ_W,PZ_H);
- const bothOK = dialOK(0) && dialOK(1);
- pzHeader(bothOK ? 'ВСЁ СОВПАЛО' : 'СОВМЕСТИ СТРЕЛКИ', bothOK ? 'ok' : 'info');
- drawDial(0); drawDial(1);
- pzFooter('Метка — зелёный кружок', bothOK ? 'Готово' : null, bothOK ? 'ok' : null);
- },
- down:function(x,y){
- for (let i = 0; i < 2; i++){
- const dd = dials[i], cx = dd.x, cy = dd.y, r = dd.r;
- const btnW = 44, btnH = 30, gap = 12;
- const bx1 = cx - gap/2 - btnW, bx2 = cx + gap/2, by = cy + r + 12;
- if (x >= bx1 && x <= bx1+btnW && y >= by && y <= by+btnH){ angles[i] = (angles[i] - 45 + 360) % 360; beep(500,.06); }
- else if (x >= bx2 && x <= bx2+btnW && y >= by && y <= by+btnH){ angles[i] = (angles[i] + 45) % 360; beep(700,.06); }
- }
- if (dialOK(0) && dialOK(1)) setTimeout(puzzleSolved, 300);
- return true;
- },
- move:function(){}, up:function(){},
- handleKey:function(a){ if (a === 'left'){ angles[0] = (angles[0] - 45 + 360) % 360; return true; } if (a === 'right'){ angles[0] = (angles[0] + 45) % 360; return true; } return false; }
- };
- }
- function makeSliders(){
- const targets = [25, 50, 75];
- const values = [15, 85, 35];
- const trackX = 90, trackW = 300, trackH = 6;
- function sliderY(i){ return 105 + i*68; }
- function isOK(i){ return Math.abs(values[i] - targets[i]) < 6; }
- function allOK(){ return isOK(0) && isOK(1) && isOK(2); }
- return {
- keys:'Клик по дорожке',
- draw:function(){
- pzCtx.fillStyle = PC.bg; pzCtx.fillRect(0,0,PZ_W,PZ_H);
- const ok = allOK();
- pzHeader(ok ? 'ВСЁ НА МЕСТЕ' : 'ПОЛЗУНКИ В ЗЕЛЁНУЮ ЗОНУ', ok ? 'ok' : 'info');
- for (let i = 0; i < 3; i++){
- const y = sliderY(i);
- pzCtx.fillStyle = '#010409'; pzRR(trackX, y - trackH/2, trackW, trackH, 3); pzCtx.fill();
- const zx = trackX + (targets[i] - 8)/100*trackW, zw = 16/100*trackW;
- pzCtx.fillStyle = 'rgba(63,185,80,.3)'; pzRR(zx, y - 10, zw, 20, 4); pzCtx.fill();
- const hx = trackX + values[i]/100*trackW;
- pzCtx.fillStyle = isOK(i) ? PC.green : PC.card; pzRR(hx - 8, y - 14, 16, 28, 5); pzCtx.fill();
- pzCtx.font = '600 11px "Consolas",monospace'; pzCtx.textAlign = 'left'; pzCtx.textBaseline = 'middle'; pzCtx.fillStyle = isOK(i) ? PC.green : PC.textDim;
- pzCtx.fillText(Math.round(values[i]) + '%', trackX + trackW + 12, y);
- }
- pzFooter('Клик по дорожке', ok ? 'Готово' : null, ok ? 'ok' : null);
- },
- down:function(x, y){
- for (let i = 0; i < 3; i++){
- const ly = sliderY(i);
- if (y >= ly - 24 && y <= ly + 24 && x >= trackX - 20 && x <= trackX + trackW + 20){
- values[i] = clamp((x - trackX)/trackW * 100, 0, 100); beep(600,.06);
- if (allOK()) setTimeout(puzzleSolved, 300);
- return true;
- }
- }
- return false;
- },
- move:function(){}, up:function(){},
- handleKey:function(a){ if (a === 'left'){ values[0] = clamp(values[0]-3, 0, 100); return true; } if (a === 'right'){ values[0] = clamp(values[0]+3, 0, 100); return true; } return false; }
- };
- }
- function makeCard(){
- const card = {x:40, y:190, w:110, h:66, dragging:false};
- const zone = {x:200, y:70, w:230, h:220};
- let lastT = 0, lastX = 0, speed = 0;
- return {
- keys:'Тяни карту · Enter — авто',
- draw:function(){
- pzCtx.fillStyle = PC.bg; pzCtx.fillRect(0,0,PZ_W,PZ_H);
- pzHeader(card.dragging ? 'ПРОВЕДИ КАРТУ' : 'ЗАЖМИ КАРТУ', card.dragging ? 'ok' : 'info');
- pzCtx.fillStyle = 'rgba(88,166,255,.05)'; pzRR(zone.x, zone.y, zone.w, zone.h, 12); pzCtx.fill();
- pzCtx.setLineDash([6,4]); pzCtx.strokeStyle = PC.blue; pzCtx.lineWidth = 1.5; pzRR(zone.x, zone.y, zone.w, zone.h, 12); pzCtx.stroke(); pzCtx.setLineDash([]);
- const h = pzHover(card.x, card.y, card.w, card.h);
- pzCtx.fillStyle = h || card.dragging ? '#4a86d4' : PC.blueDeep; pzRR(card.x, card.y, card.w, card.h, 8); pzCtx.fill();
- pzCtx.font = '700 11px "Consolas",monospace'; pzCtx.textAlign = 'center'; pzCtx.textBaseline = 'middle'; pzCtx.fillStyle = '#fff';
- pzCtx.fillText('CARD', card.x + card.w/2, card.y + card.h/2);
- pzFooter('Проведи с нормальной скоростью', null, null);
- },
- down:function(x, y){
- if (x >= card.x && x <= card.x + card.w && y >= card.y && y <= card.y + card.h){ card.dragging = true; lastX = x; lastT = performance.now(); speed = 0; return true; }
- return false;
- },
- move:function(x, y){
- if (card.dragging){
- const now = performance.now(), dt = (now - lastT)/1000;
- if (dt > 0.02){ speed = Math.abs((x - lastX)/dt); lastX = x; lastT = now; }
- card.x = clamp(x - card.w/2, 10, PZ_W - card.w - 10);
- card.y = clamp(y - card.h/2, 60, PZ_H - card.h - 60);
- return true;
- }
- return false;
- },
- up:function(){
- if (card.dragging){
- card.dragging = false;
- const cx2 = card.x + card.w/2, cy2 = card.y + card.h/2;
- const inZone = cx2 > zone.x && cx2 < zone.x + zone.w && cy2 > zone.y && cy2 < zone.y + zone.h;
- if (inZone && speed > 250 && speed < 900) setTimeout(puzzleSolved, 250);
- else if (inZone) puzzleFailed();
- return true;
- }
- return false;
- },
- handleKey:function(a){
- if (a === 'action' || a === 'enter'){ card.x = zone.x + (zone.w - card.w)/2; card.y = zone.y + (zone.h - card.h)/2; speed = 600; setTimeout(puzzleSolved, 300); return true; }
- return false;
- }
- };
- }
- function makeSequence(){
- const colors = [PC.red, PC.blue, PC.green, PC.yellow];
- const seq = [];
- for (let i = 0; i < 4; i++) seq.push(Math.floor(Math.random()*4));
- let inputIdx = 0, showIdx = 0, showTimer = 0, showPhase = true;
- const btnR = 36, gap = 12;
- const cxs = [PZ_W/2 - btnR - gap, PZ_W/2 + btnR + gap];
- const cys = [130, 130 + btnR*2 + gap*2];
- function btnRect(i){ return {cx: cxs[i%2], cy: cys[(i/2)|0], r:btnR}; }
- return {
- keys:'Повтори последовательность',
- draw:function(){
- pzCtx.fillStyle = PC.bg; pzCtx.fillRect(0,0,PZ_W,PZ_H);
- pzHeader(showPhase ? 'СМОТРИ' : 'ПОВТОРИ', showPhase ? 'warn' : 'info');
- for (let i = 0; i < 4; i++){
- const b = btnRect(i);
- const active = showPhase && showIdx < 4 && seq[showIdx] === i && showTimer < 0.5;
- pzCtx.fillStyle = active ? colors[i] : PC.panel; pzCtx.beginPath(); pzCtx.arc(b.cx, b.cy, b.r, 0, 7); pzCtx.fill();
- pzCtx.strokeStyle = active ? colors[i] : PC.border; pzCtx.lineWidth = 2; pzCtx.beginPath(); pzCtx.arc(b.cx, b.cy, b.r, 0, 7); pzCtx.stroke();
- }
- pzFooter('Повтори 4 шага', showPhase ? 'PLAY' : (inputIdx + ' / 4'), null);
- },
- update:function(dt){
- if (showPhase){ showTimer += dt; if (showTimer > 0.7){ showTimer = 0; showIdx++; if (showIdx >= 4){ showPhase = false; showIdx = 0; } } }
- },
- down:function(x,y){
- if (showPhase) return false;
- for (let i = 0; i < 4; i++){
- const b = btnRect(i);
- const ddx = x-b.cx, ddy = y-b.cy;
- if (Math.sqrt(ddx*ddx+ddy*ddy) < b.r){
- beep(400 + i*100, 0.08);
- if (seq[inputIdx] === i){ inputIdx++; if (inputIdx >= 4) setTimeout(puzzleSolved, 200); }
- else { puzzleFailed(); inputIdx = 0; }
- return true;
- }
- }
- return false;
- },
- move:function(){}, up:function(){},
- handleKey:function(a){
- const n = /^[1-4]$/.test(a) ? parseInt(a,10)-1 : -1;
- if (n >= 0 && n < 4){
- beep(400 + n*100, 0.08);
- if (seq[inputIdx] === n){ inputIdx++; if (inputIdx >= 4) setTimeout(puzzleSolved, 200); }
- else { puzzleFailed(); inputIdx = 0; }
- return true;
- }
- return false;
- }
- };
- }
- function makePower(){
- const target = 0.35; let pos = 0, dir = 1, spd = 0.6, hits = 0, misses = 0, need = 3;
- return {
- keys:'Пробел — стоп',
- draw:function(){
- pzCtx.fillStyle = PC.bg; pzCtx.fillRect(0,0,PZ_W,PZ_H);
- pzHeader('ПОЙМАЙ ЗОНУ ×'+need, 'info');
- const barX = 60, barY = 170, barW = PZ_W-120, barH = 30;
- pzCtx.fillStyle = '#010409'; pzRR(barX, barY, barW, barH, 8); pzCtx.fill();
- pzCtx.fillStyle = 'rgba(63,185,80,.35)'; const zoneX = barX + target*barW - barW*0.08;
- pzRR(zoneX, barY, barW*0.16, barH, 8); pzCtx.fill();
- pzCtx.fillStyle = PC.blue; pzRR(barX + pos*barW - 4, barY - 6, 8, barH + 12, 4); pzCtx.fill();
- pzCtx.font = '600 14px "Segoe UI",sans-serif'; pzCtx.textAlign = 'center'; pzCtx.textBaseline = 'middle'; pzCtx.fillStyle = PC.textBright;
- pzCtx.fillText('ПОПАДАНИЯ: ' + hits + ' / ' + need, PZ_W/2, 100);
- pzFooter('Пробел — стоп', misses > 0 ? 'мимо: ' + misses : null, misses > 0 ? 'bad' : null);
- },
- update:function(dt){ pos += dir * spd * dt; if (pos >= 1){ pos = 1; dir = -1; } if (pos <= 0){ pos = 0; dir = 1; } puzzleDirty = true; },
- down:function(){ return this.tryStop(); },
- move:function(){}, up:function(){},
- tryStop:function(){
- if (Math.abs(pos - target) < 0.08){ hits++; beep(900,.08); if (hits >= need) setTimeout(puzzleSolved, 200); }
- else { misses++; beep(200,.1,'square'); if (misses >= 3) puzzleFailed(); }
- return true;
- },
- handleKey:function(a){ if (a === 'action' || a === 'enter') return this.tryStop(); return false; }
- };
- }
- function makeFlicker(){
- let fx = rand(60, PZ_W-60), fy = rand(90, PZ_H-90), ft = 1.5, clicks = 0;
- const need = 3;
- return {
- keys:'Клик по помехе',
- draw:function(){
- pzCtx.fillStyle = PC.bg; pzCtx.fillRect(0,0,PZ_W,PZ_H);
- pzHeader('СТАБИЛИЗИРУЙ КАМЕРУ ×'+need, 'info');
- pzCtx.fillStyle = PC.card; pzRR(80, 70, PZ_W-160, PZ_H-150, 10); pzCtx.fill();
- if (ft > 0){ pzCtx.fillStyle = 'rgba(248,81,73,.6)'; pzCtx.beginPath(); pzCtx.arc(fx, fy, 18, 0, 7); pzCtx.fill(); }
- pzCtx.font = '600 14px "Segoe UI",sans-serif'; pzCtx.textAlign = 'center'; pzCtx.textBaseline = 'middle'; pzCtx.fillStyle = PC.textBright;
- pzCtx.fillText('ПОМЕХИ: ' + clicks + ' / ' + need, PZ_W/2, 100);
- pzFooter('Клик по красной точке', null, null);
- },
- update:function(dt){ ft -= dt; if (ft <= 0){ fx = rand(60, PZ_W-60); fy = rand(90, PZ_H-120); ft = 1.2; } puzzleDirty = true; },
- down:function(x,y){
- const dx = x-fx, dy = y-fy;
- if (ft > 0 && Math.sqrt(dx*dx+dy*dy) < 22){ clicks++; beep(700,.06); ft = 0.5; if (clicks >= need) setTimeout(puzzleSolved, 200); return true; }
- return false;
- },
- move:function(){}, up:function(){},
- handleKey:function(){ return false; }
- };
- }
- function openPuzzle(inc){
- activeIncident = inc;
- const def = INCIDENTS[inc.type];
- const kindMap = {phishing:'keypad', password:'wires', logs:'dials', access:'sliders', ports:'card', cipher:'sequence', backup:'power', response:'flicker'};
- puzzle = makePuzzle(kindMap[def.tag] || 'keypad');
- puzzleDirty = true;
- stateBeforePuzzle = state; state = 'puzzle';
- el.pzTitle.textContent = def.label;
- el.pzDot.style.background = def.color;
- el.pzKeys.textContent = puzzle.keys || '—';
- el.pzHint.textContent = '—'; el.pzHint.className = '';
- hideAll(); showScreen('puzzle'); updateMobileVisibility();
- focusStage(); startPuzzleLoop();
- }
- function closePuzzle(){
- stopPuzzleLoop(); puzzle = null; activeIncident = null;
- state = stateBeforePuzzle || 'playing'; stateBeforePuzzle = null;
- hideAll();
- if (state === 'playing'){ focusStage(); }
- updateMobileVisibility();
- }
- function puzzleSolved(){
- if (!activeIncident) return;
- const inc = activeIncident;
- activeIncident = null;
- el.pzHint.textContent = 'OK'; el.pzHint.className = 'ok';
- beep(880,.1); setTimeout(() => beep(1200,.12), 100);
- setTimeout(() => {
- stopPuzzleLoop(); puzzle = null;
- if (!demoMode) fixIncident(inc);
- state = demoMode ? 'menu' : 'playing'; stateBeforePuzzle = null;
- hideAll();
- if (demoMode){ showScreen('menu'); demoMode = false; } else focusStage();
- updateMobileVisibility();
- }, 300);
- }
- function puzzleFailed(){
- if (demoMode) return;
- if (!activeIncident) return;
- el.pzHint.textContent = 'ОШИБКА'; el.pzHint.className = 'bad';
- beep(200,.15,'square');
- puzzleFailedActive = true;
- setTimeout(() => { puzzleFailedActive = false; }, 800);
- }
- function startPuzzleLoop(){
- if (puzzleRAF) return;
- let lastT = performance.now();
- function tick(now){
- puzzleRAF = requestAnimationFrame(tick);
- const dt = Math.min(0.05, (now - lastT)/1000); lastT = now;
- if (!puzzle) return;
- if (puzzle.update) puzzle.update(dt);
- if (puzzleDirty){ puzzle.draw(); puzzleDirty = false; }
- }
- puzzleRAF = requestAnimationFrame(tick);
- }
- function stopPuzzleLoop(){ if (puzzleRAF){ cancelAnimationFrame(puzzleRAF); puzzleRAF = null; } }
- function pzCoordsFromEvent(e){
- const r = pzCanvas.getBoundingClientRect();
- return {x: (e.clientX - r.left) * (PZ_W / r.width), y: (e.clientY - r.top) * (PZ_H / r.height)};
- }
- pzCanvas.addEventListener('mousedown', e => {
- const p = pzCoordsFromEvent(e); puzzleMouse.x = p.x; puzzleMouse.y = p.y; puzzleMouse.down = true;
- if (puzzle && puzzle.down) puzzle.down(p.x, p.y); puzzleDirty = true;
- });
- pzCanvas.addEventListener('mousemove', e => {
- const p = pzCoordsFromEvent(e); puzzleMouse.x = p.x; puzzleMouse.y = p.y;
- if (puzzle && puzzle.move) puzzle.move(p.x, p.y); puzzleDirty = true;
- });
- window.addEventListener('mouseup', () => {
- puzzleMouse.down = false;
- if (puzzle && puzzle.up) puzzle.up(); puzzleDirty = true;
- });
- function startDemo(kind){
- demoMode = true; state = 'puzzle';
- puzzle = makePuzzle(kind); puzzleDirty = true;
- el.pzTitle.textContent = 'Демо: ' + kind;
- el.pzKeys.textContent = puzzle.keys || '—';
- el.pzHint.textContent = 'Демо — без штрафов'; el.pzHint.className = '';
- hideAll(); showScreen('puzzle');
- focusStage(); startPuzzleLoop();
- }
- /* ============================================================
- ИГРОВОЙ ЦИКЛ
- ============================================================ */
- let minimapBgDirty = true;
- function updateMinimapBg(){
- if (!minimapBg) minimapBg = document.createElement('canvas');
- minimapBg.width = el.minimap.width; minimapBg.height = el.minimap.height;
- const c = minimapBg.getContext('2d');
- c.fillStyle = '#05080f'; c.fillRect(0, 0, c.canvas.width, c.canvas.height);
- const s = Math.min(c.canvas.width / WORLD_W, c.canvas.height / WORLD_D);
- const ox = (c.canvas.width - WORLD_W*s)/2, oy = (c.canvas.height - WORLD_D*s)/2;
- for (const r of ROOMS){
- c.fillStyle = r.isSoc ? 'rgba(74,222,128,.5)' : 'rgba(60,120,220,.3)';
- c.fillRect(ox + r.x*s, oy + r.y*s, r.w*s, r.h*s);
- c.strokeStyle = r.accent; c.lineWidth = 1;
- c.strokeRect(ox + r.x*s + 0.5, oy + r.y*s + 0.5, r.w*s - 1, r.h*s - 1);
- }
- minimapBgDirty = false;
- }
- function drawMinimap(){
- if (minimapBgDirty) updateMinimapBg();
- const c = el.minimap.getContext('2d');
- c.clearRect(0, 0, el.minimap.width, el.minimap.height);
- if (minimapBg) c.drawImage(minimapBg, 0, 0);
- const s = Math.min(el.minimap.width / WORLD_W, el.minimap.height / WORLD_D);
- const ox = (el.minimap.width - WORLD_W*s)/2, oy = (el.minimap.height - WORLD_D*s)/2;
- for (const inc of incidents){
- c.fillStyle = INCIDENTS[inc.type].color;
- c.beginPath(); c.arc(ox + inc.x*s, oy + inc.y*s, 2, 0, 7); c.fill();
- }
- for (const b of bots){
- if (b.isCaught) continue;
- c.fillStyle = b.isSuspect ? '#ff3030' : b.color;
- c.beginPath(); c.arc(ox + b.x*s, oy + b.y*s, b.isSuspect ? 3 : 2, 0, 7); c.fill();
- }
- c.fillStyle = '#58a6ff';
- c.beginPath(); c.arc(ox + player.x*s, oy + player.y*s, 3.5, 0, 7); c.fill();
- }
- function drawFurniture(f){
- const spr = FURN_SPRITES[f.kind];
- if (!spr) return;
- const dx = f.x - camX - spr.pad;
- const dy = f.y * DEPTH - camY - spr.pad;
- if (dx + spr.w < 0 || dx > W || dy + spr.h < 0 || dy > H) return;
- ctx.drawImage(spr.canvas, dx, dy);
- }
- function drawIncident(inc){
- const f = inc.f;
- const sx = f.x + f.w/2 - camX;
- const sy = f.y * DEPTH - camY + f.d * DEPTH/2;
- const pulse = 0.5 + Math.sin(time * 6 + inc.x * 0.01) * 0.5;
- const def = INCIDENTS[inc.type];
- ctx.strokeStyle = def.color;
- ctx.globalAlpha = 0.4 + pulse * 0.5;
- ctx.lineWidth = 2;
- ctx.strokeRect(f.x - camX - 2, f.y * DEPTH - camY - 2, f.w + 4, f.d * DEPTH + 4);
- ctx.globalAlpha = 1;
- setFont('700 11px "Consolas",monospace');
- const txt = def.tag.toUpperCase().slice(0, 4);
- const tw = ctx.measureText(txt).width + 10;
- const bx = sx - tw/2, by = sy - 42;
- ctx.fillStyle = def.color;
- roundRect(ctx, bx, by, tw, 14, 3); ctx.fill();
- ctx.fillStyle = '#0a0a0a';
- ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
- ctx.fillText(txt, sx, by + 7);
- const ratio = clamp(inc.timeLeft / inc.maxTime, 0, 1);
- ctx.fillStyle = 'rgba(0,0,0,.7)';
- ctx.fillRect(sx - 18, sy - 24, 36, 3);
- ctx.fillStyle = ratio < 0.3 ? '#f85149' : ratio < 0.6 ? '#fbbf24' : '#4ade80';
- ctx.fillRect(sx - 18, sy - 24, 36 * ratio, 3);
- }
- function drawBot(b){
- const sx = b.x - camX, sy = b.y * DEPTH - camY;
- ctx.fillStyle = 'rgba(0,0,0,.4)';
- ctx.beginPath(); ctx.ellipse(sx, sy + 4, 11, 4, 0, 0, 7); ctx.fill();
- ctx.fillStyle = b.color;
- roundRect(ctx, sx - 8, sy - 18, 16, 20, 4); ctx.fill();
- ctx.strokeStyle = 'rgba(0,0,0,.4)'; ctx.lineWidth = 1;
- roundRect(ctx, sx - 8, sy - 18, 16, 20, 4); ctx.stroke();
- ctx.fillStyle = '#f5d5b5';
- ctx.beginPath(); ctx.arc(sx, sy - 22, 6, 0, 7); ctx.fill();
- ctx.fillStyle = b.color;
- ctx.beginPath(); ctx.arc(sx, sy - 25, 6, Math.PI, 0); ctx.fill();
- if (b.isSuspect){
- ctx.strokeStyle = 'rgba(255,48,48,' + (0.5 + Math.sin(time * 8) * 0.5) + ')';
- ctx.lineWidth = 2;
- ctx.beginPath(); ctx.arc(sx, sy - 10, 18, 0, 7); ctx.stroke();
- }
- }
- function drawPlayer(){
- const bob = player.moving ? Math.sin(time * 15) * 1.5 : 0;
- const sx = player.x - camX, sy = player.y * DEPTH - camY + bob;
- ctx.fillStyle = 'rgba(0,0,0,.5)';
- ctx.beginPath(); ctx.ellipse(sx, sy + 5, 12, 4, 0, 0, 7); ctx.fill();
- ctx.fillStyle = '#2a7aef';
- roundRect(ctx, sx - 10, sy - 20, 20, 22, 5); ctx.fill();
- ctx.fillStyle = 'rgba(255,255,255,.3)';
- ctx.beginPath();
- ctx.moveTo(sx - 5, sy - 20); ctx.lineTo(sx, sy - 16); ctx.lineTo(sx + 5, sy - 20);
- ctx.closePath(); ctx.fill();
- ctx.fillStyle = '#ffd5b5';
- ctx.beginPath(); ctx.arc(sx, sy - 26, 7, 0, 7); ctx.fill();
- ctx.fillStyle = '#3a2010';
- ctx.beginPath(); ctx.arc(sx, sy - 29, 7, Math.PI, 0); ctx.fill();
- ctx.fillStyle = '#1a1a2a';
- ctx.beginPath(); ctx.arc(sx + player.dir * 2, sy - 26, 1.5, 0, 7); ctx.fill();
- }
- const _drawQueue = [];
- function drawAllEntities(){
- _drawQueue.length = 0;
- for (const f of FURN){
- const sx = f.x - camX, sy = f.y * DEPTH - camY;
- if (sx + f.w < -50 || sx > W+50 || sy + f.d * DEPTH < -100 || sy > H+100) continue;
- _drawQueue.push({t:0, o:f, y:f.y + f.d*0.5});
- }
- for (const inc of incidents) _drawQueue.push({t:1, o:inc, y:inc.f.y + inc.f.d*0.5});
- for (const b of bots) if (!b.isCaught) _drawQueue.push({t:2, o:b, y:b.y});
- if (state === 'playing') _drawQueue.push({t:3, o:player, y:player.y});
- _drawQueue.sort((a,b) => a.y - b.y);
- for (const e of _drawQueue){
- if (e.t === 0) drawFurniture(e.o);
- else if (e.t === 1) drawIncident(e.o);
- else if (e.t === 2) drawBot(e.o);
- else if (e.t === 3) drawPlayer();
- }
- }
- function drawParticles(){
- for (let i = particles.length - 1; i >= 0; i--){
- const p = particles[i];
- p.life -= 1/60;
- if (p.life <= 0){ releaseParticle(p); particles.splice(i, 1); continue; }
- p.x += p.vx * 0.016; p.y += p.vy * 0.016; p.z += p.vz * 0.016;
- p.vz -= 400 * 0.016;
- if (p.z < 0){ p.z = 0; p.vz *= -0.4; }
- p.vx *= 0.96; p.vy *= 0.96;
- ctx.globalAlpha = clamp(p.life / 0.75, 0, 1);
- ctx.fillStyle = p.color;
- ctx.beginPath(); ctx.arc(p.x - camX, p.y * DEPTH - camY - p.z, p.size, 0, 7); ctx.fill();
- }
- ctx.globalAlpha = 1;
- }
- function drawToasts(){
- let y = 80;
- for (const t of toasts){
- const x = W/2 - t.w/2;
- ctx.globalAlpha = clamp(t.life, 0, 1);
- ctx.fillStyle = 'rgba(10,15,26,.95)';
- ctx.fillRect(x, y, t.w, 26);
- ctx.strokeStyle = t.type === 'bad' ? '#f85149' : t.type === 'warn' ? '#fbbf24' : '#4ade80';
- ctx.lineWidth = 1;
- ctx.strokeRect(x + 0.5, y + 0.5, t.w - 1, 25);
- setFont('600 12px "Segoe UI",sans-serif');
- ctx.fillStyle = '#fff';
- ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
- ctx.fillText(t.text, W/2, y + 13);
- y += 30;
- }
- ctx.globalAlpha = 1;
- for (let i = toasts.length - 1; i >= 0; i--){
- toasts[i].life -= 1/60;
- if (toasts[i].life <= 0) toasts.splice(i, 1);
- }
- }
- function updatePlayer(dt, speed){
- let dx = 0, dy = 0;
- if (keys.up) dy -= 1; if (keys.down) dy += 1;
- if (keys.left) dx -= 1; if (keys.right) dx += 1;
- player.moving = (dx !== 0 || dy !== 0);
- if (player.moving){
- const l = Math.sqrt(dx*dx + dy*dy); dx /= l; dy /= l;
- const total = speed * dt, steps = Math.max(1, Math.ceil(total / 5));
- const stepLen = total / steps;
- for (let s = 0; s < steps; s++){ player.x += dx * stepLen; player.y += dy * stepLen; collide(player, player.r); }
- if (dx !== 0) player.dir = dx > 0 ? 1 : -1;
- }
- }
- function updateIncidents(dt){
- for (let i = incidents.length - 1; i >= 0; i--){
- incidents[i].timeLeft -= dt;
- if (incidents[i].timeLeft <= 0){ leakIncident(incidents[i]); }
- }
- }
- function updateSpawning(dt){
- shiftSpawnTimer -= dt;
- if (shiftSpawnTimer > 0) return;
- const shift = currentDiff.shifts[currentShift];
- if (spawnedInShift >= shift.count) return;
- shiftSpawnTimer = 3 + Math.random() * 3;
- const pending = waveTasks.filter(w => w.done < w.need);
- if (!pending.length) return;
- const wt = pending[Math.floor(Math.random() * pending.length)];
- const def = INCIDENTS[wt.type];
- const cands = FURN.filter(f => f.tags && f.tags.includes(def.tag) && !incidents.some(i => i.f === f));
- if (!cands.length) return;
- const f = cands[Math.floor(Math.random() * cands.length)];
- const life = shift.time;
- incidents.push({type: wt.type, f, x: f.x + f.w/2, y: f.y + f.d/2, maxTime: life, timeLeft: life});
- spawnedInShift++;
- addLog('Обнаружено: ' + def.label, 'warn');
- }
- function checkShiftComplete(){
- if (state !== 'playing') return;
- if (spawnedInShift < currentDiff.shifts[currentShift].count) return;
- if (incidents.length > 0) return;
- for (const w of waveTasks) if (w.done < w.need) return;
- setTimeout(showShiftDebrief, 800);
- }
- let lastT = performance.now();
- function loop(now){
- const dt = Math.min(0.05, (now - lastT) / 1000); lastT = now;
- time += dt;
- if (state === 'playing'){
- updatePlayer(dt, 280);
- updateBots(dt);
- updateIncidents(dt);
- updateSpawning(dt);
- updateCamera();
- if (actionPressed){
- actionPressed = false;
- const {inc, d} = nearestIncident();
- if (inc && d < 60) openPuzzle(inc);
- else {
- const here = roomAt(player.x, player.y);
- if (here && here.isSoc) openCameraView();
- }
- }
- checkShiftComplete();
- ctx.fillStyle = '#050810'; ctx.fillRect(0, 0, W, H);
- if (staticReady){
- const sx = camX | 0, sy = camY | 0;
- const sw = Math.min(W, staticCanvas.width - sx);
- const sh = Math.min(H, staticCanvas.height - sy);
- if (sw > 0 && sh > 0) ctx.drawImage(staticCanvas, sx, sy, sw, sh, 0, 0, sw, sh);
- }
- drawAllEntities();
- drawParticles();
- drawToasts();
- drawMinimap();
- } else if (state === 'camera'){
- drawCameras();
- }
- requestAnimationFrame(loop);
- }
- /* ============================================================
- СТАРТ ИГРЫ
- ============================================================ */
- function tryLoadGame(){
- const s = loadGameState();
- if (!s){ showHint('Нет сохранения', 2500); return; }
- settings.diff = s.diff || 'normal';
- applySettingsToUI();
- startGame();
- score = s.score || 0; leaks = s.leaks || 0; fixedCount = s.fixedCount || 0; totalCaught = s.totalCaught || 0;
- currentShift = s.shift || 0;
- updateHUD();
- }
- /* ============================================================
- SAFE BIND — все обработчики
- ============================================================ */
- function bind(id, evt, fn){
- const e = document.getElementById(id);
- if (!e){ console.warn('[BIND FAIL] #' + id + ' not found'); return; }
- e.addEventListener(evt, fn);
- }
- bind('modalYes', 'click', () => { el.modalBack.classList.add('hide'); if (modalResolve){ modalResolve(true); modalResolve = null; } });
- bind('modalNo', 'click', () => { el.modalBack.classList.add('hide'); if (modalResolve){ modalResolve(false); modalResolve = null; } });
- bind('btnPlayGame', 'click', () => { clearGameState(); startGame(); });
- bind('btnContinue', 'click', () => tryLoadGame());
- bind('btnTutorial', 'click', () => { buildTutGrid(); state = 'tutorial'; hideAll(); showScreen('tutorial'); });
- bind('btnPuzzleHelp', 'click', () => { buildTutGrid(); state = 'tutorial'; hideAll(); showScreen('tutorial'); });
- bind('btnSettings', 'click', () => { state = 'settings'; hideAll(); showScreen('settings'); });
- bind('btnAchievements', 'click', () => { renderAchievementsUI(); state = 'ach'; hideAll(); showScreen('ach'); });
- bind('btnAchBack', 'click', () => { state = 'menu'; hideAll(); showScreen('menu'); });
- bind('btnRules', 'click', () => { state = 'rules'; hideAll(); showScreen('rules'); });
- bind('btnRulesBack', 'click', () => { state = 'menu'; hideAll(); showScreen('menu'); });
- bind('btnSettingsBack', 'click', () => { state = 'menu'; hideAll(); showScreen('menu'); });
- bind('btnTutBack', 'click', () => { state = 'menu'; hideAll(); showScreen('menu'); });
- bind('btnTutTry', 'click', () => { if (curTut) startDemo(curTut.id); });
- bind('btnTutDetailBack', 'click', () => { hideAll(); showScreen('tutorial'); });
- bind('btnResume', 'click', () => resumeGame());
- bind('btnPauseRules', 'click', () => { state = 'rules'; hideAll(); showScreen('rules'); });
- bind('btnExitMenu', 'click', () => exitToMenu());
- bind('btnRestart', 'click', () => { clearGameState(); startGame(); });
- bind('btnMenu', 'click', () => { state = 'end'; exitToMenu(); });
- bind('btnHomeTop', 'click', () => exitToMenu());
- bind('btnPauseTop', 'click', () => { if (state === 'playing') pauseGame(); else if (state === 'paused') resumeGame(); });
- bind('btnHelpTop', 'click', () => showContextHint());
- bind('btnFsTop', 'click', () => toggleFullscreen());
- bind('btnFs', 'click', () => toggleFullscreen());
- bind('camClose', 'click', () => closeCameraView());
- bind('camReport', 'click', () => reportSuspect());
- bind('shiftNext', 'click', () => {
- if (currentShift >= currentDiff.shifts.length - 1) startAudit();
- else startShift(currentShift + 1);
- });
- bind('btnAuditStart', 'click', () => {
- const passed = leaks === 0;
- statsAch.auditPassed = passed;
- checkAchievements(statsAch);
- endGame(passed);
- });
- bind('pzCancel', 'click', closePuzzle);
- bind('btnResetProgress', 'click', async () => {
- const ok = await showModal('Удалить весь прогресс?');
- if (!ok) return;
- try { localStorage.removeItem('shield9_highscore'); localStorage.removeItem('shield9_ach'); localStorage.removeItem('shield9_savestate'); } catch(e){}
- highScore = 0; unlockedAchievements = new Set();
- applySettingsToUI(); renderAchievementsUI(); refreshAchievementHUD(); updateContinueButton();
- toast('Прогресс сброшен', 'info');
- });
- document.querySelectorAll('#segDiff button').forEach(b => {
- b.addEventListener('click', () => { settings.diff = b.dataset.v; saveSettings(); applySettingsToUI(); });
- });
- document.querySelectorAll('#segSound button').forEach(b => {
- b.addEventListener('click', () => { settings.sound = +b.dataset.v; saveSettings(); applySettingsToUI(); });
- });
- document.querySelectorAll('#segMobile button').forEach(b => {
- b.addEventListener('click', () => { settings.mobile = b.dataset.v; saveSettings(); applySettingsToUI(); updateMobileVisibility(); });
- });
- /* Mobile controls */
- if (el.joyPad){
- const joyPadBtns = el.joyPad.querySelectorAll('.b');
- joyPadBtns.forEach(b => {
- const k = b.dataset.k;
- b.addEventListener('pointerdown', e => { e.preventDefault(); keys[k] = true; });
- b.addEventListener('pointerup', e => { e.preventDefault(); keys[k] = false; });
- b.addEventListener('pointercancel', () => { keys[k] = false; });
- b.addEventListener('pointerleave', () => { keys[k] = false; });
- });
- }
- if (el.btnAction){
- el.btnAction.addEventListener('pointerdown', e => { e.preventDefault(); actionPressed = true; });
- }
- /* ============================================================
- INIT
- ============================================================ */
- try {
- applySettingsToUI();
- renderAchievementsUI();
- updateContinueButton();
- focusStage();
- requestAnimationFrame(loop);
- console.log('[BOOT] OK');
- } catch(e){
- console.error('[BOOT FAIL]', e);
- const h = document.getElementById('hintBar');
- const t = document.getElementById('hintText');
- if (h && t){ t.textContent = 'ОШИБКА ЗАПУСКА: ' + e.message; h.classList.add('show'); }
- }
- })();
- </script>
- </body>
- </html>
|