shield data.html 148 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849
  1. <!DOCTYPE html>
  2. <html lang="ru">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
  6. <title>ЩИТ ДАННЫХ — Гибрид v12</title>
  7. <style>
  8. *{box-sizing:border-box;margin:0;padding:0}
  9. 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}
  10. #wrap{position:fixed;inset:0;display:flex;align-items:center;justify-content:center}
  11. #stage{position:relative;outline:none}
  12. canvas.main{display:block;width:100%;height:100%;background:#050810;border-radius:6px;outline:none}
  13. #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}
  14. .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}
  15. .hud-item span{display:block;font-size:.56em;letter-spacing:.1em;color:#7d92b0}
  16. .hud-item b{font-size:1em;color:#e8eef8}
  17. .hud-item.danger b{color:#ff7a7a}
  18. .hud-item.good b{color:#7ddca8}
  19. #progWrap{background:rgba(10,15,26,.92);border:1px solid rgba(78,161,255,.22);border-radius:.5em;padding:.24em .5em;min-width:11em}
  20. #progWrap .lbl{font-size:.56em;letter-spacing:.1em;color:#7d92b0;text-align:center;margin-bottom:.15em}
  21. #progBar{height:8px;background:#0a1220;border-radius:4px;overflow:hidden}
  22. #progBar i{display:block;height:100%;background:linear-gradient(90deg,#1f7ae0,#4ade80);width:0%;transition:width .3s}
  23. #topRight{position:absolute;top:.5em;right:.8em;display:flex;gap:.4em;z-index:12}
  24. #topRight button{padding:.35em .65em;font-size:.9em;min-width:2.4em}
  25. #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}
  26. #taskPanel.show{opacity:1}
  27. .task-title{color:#8ba3c7;font-size:.68em;letter-spacing:.14em;margin-bottom:.35em;text-transform:uppercase;font-weight:600}
  28. #taskList{list-style:none;display:flex;flex-direction:column;gap:.3em;font-size:.86em}
  29. #taskList li{display:flex;justify-content:space-between;gap:.9em;color:#cfe2ff}
  30. #taskList li.done{color:#4ade80;opacity:.65}
  31. #taskList li.done .name{text-decoration:line-through}
  32. #taskList li b{color:#8ee7ff;font-variant-numeric:tabular-nums}
  33. #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}
  34. #logPanel.show{opacity:1}
  35. #logList{list-style:none;display:flex;flex-direction:column;gap:.12em;font-size:.7em;font-family:'Consolas',monospace;color:#a8c4e0}
  36. #logList li{display:flex;gap:.4em;line-height:1.35;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
  37. #logList li .t{color:#5a7090;flex-shrink:0}
  38. #logList li.ok{color:#7ddca8}
  39. #logList li.bad{color:#ff9a9a}
  40. #logList li.warn{color:#fbbf24}
  41. #logList li.sys{color:#58a6ff;font-weight:700}
  42. #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}
  43. #minimap.show{opacity:1}
  44. #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}
  45. #hintBar.show{opacity:1}
  46. #hintBar.radio{border-color:rgba(88,166,255,.6);box-shadow:0 0 12px rgba(88,166,255,.15);color:#cfe6ff}
  47. .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}
  48. .screen.hide{display:none}
  49. .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}
  50. 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}
  51. .sub{color:#7d92b0;font-size:.88em;letter-spacing:.18em;text-transform:uppercase;margin-bottom:1em}
  52. h2{font-size:1.2em;color:#dbe9ff;margin-bottom:.85em;line-height:1.35;font-weight:600}
  53. .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}
  54. .btns{display:flex;flex-wrap:wrap;gap:.5em;justify-content:center;margin-bottom:.8em}
  55. .btns.col{flex-direction:column;align-items:stretch;max-width:22em;margin-left:auto;margin-right:auto}
  56. 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}
  57. button:hover:not(:disabled){background:rgba(58,90,150,.6);border-color:rgba(120,180,255,.6)}
  58. button.primary{background:linear-gradient(135deg,#1f7ae0,#22c1a5);border-color:transparent;color:#fff;font-weight:600}
  59. button.danger{background:linear-gradient(135deg,#a02020,#c73a3a);border-color:transparent;color:#fff;font-weight:600}
  60. button.big{padding:1em 1.5em;font-size:1.15em;font-weight:700}
  61. button.ghost{background:transparent;border-color:rgba(120,180,255,.25)}
  62. .hintline{color:#7d92b0;font-size:.78em;margin-top:.6em}
  63. .rules{text-align:left;display:grid;gap:.5em;margin-bottom:1em}
  64. .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}
  65. .rule kbd{background:#152a4a;border:1px solid #2a4a7a;border-radius:.3em;padding:.1em .4em;font-family:'Consolas',monospace;font-size:.95em;color:#dce9ff}
  66. .stats{display:flex;gap:.6em;justify-content:center;flex-wrap:wrap;margin-bottom:1.1em}
  67. .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}
  68. .stat span{display:block;font-size:.6em;letter-spacing:.1em;color:#7d92b0}
  69. .stat b{font-size:1.4em;color:#8ee7ff}
  70. .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}
  71. .setting .lbl{color:#cfe2ff;font-weight:600}
  72. .seg{display:flex;gap:.3em}
  73. .seg button{padding:.35em .7em;font-size:.82em}
  74. .seg button.active{background:linear-gradient(135deg,#1f7ae0,#22c1a5);border-color:transparent;color:#fff}
  75. #endTitle.win{background:linear-gradient(135deg,#4ade80,#22d3ee);-webkit-background-clip:text;background-clip:text;color:transparent}
  76. #endTitle.lose{background:linear-gradient(135deg,#ff4444,#ff8a3a);-webkit-background-clip:text;background-clip:text;color:transparent}
  77. #puzzleScreen .panel{padding:0;width:min(38em,96%);background:#0d1117;border:1px solid #30363d;overflow:hidden}
  78. .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}
  79. .pzHeader .dot{width:8px;height:8px;border-radius:50%;background:#58a6ff}
  80. .pzCanvasWrap{background:#0d1117;position:relative}
  81. .pzCanvas{display:block;width:100%;height:auto;background:#0d1117;touch-action:none;outline:none;cursor:pointer}
  82. .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}
  83. .pzKeys{background:#21262d;padding:.3em .6em;border-radius:.35em;border:1px solid #30363d;font-size:.78em;color:#8b949e;font-family:'Consolas',monospace}
  84. #pzHint{font-size:.82em;color:#8b949e;flex:1;text-align:right}
  85. #pzHint.ok{color:#3fb950}
  86. #pzHint.bad{color:#f85149}
  87. #pzCancel{background:#21262d;border-color:#30363d;color:#8b949e;font-size:.82em;padding:.35em .8em}
  88. .auditList{text-align:left;display:grid;gap:.4em;margin-bottom:1em}
  89. .tutGrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:.6em;margin-bottom:1em}
  90. .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}
  91. .tutCard:hover{background:rgba(58,90,150,.5);border-color:rgba(120,180,255,.5);transform:translateY(-2px)}
  92. .tutCard .ic{font-size:2em;display:block;margin-bottom:.2em}
  93. .tutCard .ti{font-size:.82em;color:#cfe2ff;font-weight:600}
  94. .tutBody{text-align:left;color:#bdd3ee;font-size:.9em;line-height:1.55;margin-bottom:1em}
  95. .tutBody .lead{background:rgba(88,166,255,.08);border-left:3px solid #58a6ff;border-radius:.4em;padding:.7em .9em;margin-bottom:.8em}
  96. .tutBody h3{color:#8ee7ff;font-size:.9em;margin:.9em 0 .35em 0;letter-spacing:.04em;text-transform:uppercase;font-weight:700}
  97. .tutBody kbd{background:#152a4a;border:1px solid #2a4a7a;border-radius:.25em;padding:.05em .35em;font-family:'Consolas',monospace;font-size:.9em;color:#8ee7ff}
  98. #cameraScreen .panel{padding:0;width:min(70em,96%);background:#0d1117;border:1px solid #30363d;overflow:hidden;text-align:left}
  99. .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}
  100. .camHeader .rec{width:10px;height:10px;border-radius:50%;background:#f85149;animation:recPulse 1.2s infinite}
  101. @keyframes recPulse{0%,100%{opacity:1}50%{opacity:.3}}
  102. .camHeader .title{flex:1}
  103. .camGrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:6px;padding:8px;background:#0d1117;max-height:62vh;overflow-y:auto}
  104. .camCell{position:relative;background:#050810;border:2px solid #30363d;border-radius:6px;overflow:hidden;cursor:pointer;transition:.15s;aspect-ratio:16/10}
  105. .camCell:hover{border-color:#58a6ff}
  106. .camCell.active{border-color:#4ade80;box-shadow:0 0 15px rgba(74,222,128,.35)}
  107. .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}
  108. .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}
  109. .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}
  110. @keyframes alertBlink{0%,100%{opacity:1}50%{opacity:.55}}
  111. .camCell canvas{display:block;width:100%;height:100%}
  112. .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}
  113. .camFoot .info{flex:1}
  114. .camFoot button{font-size:.82em;padding:.4em 1em}
  115. #camReport{background:linear-gradient(135deg,#a02020,#c73a3a);border-color:transparent;color:#fff;font-weight:700}
  116. #camReport:disabled{opacity:.4;cursor:default;background:#30363d;color:#8b949e}
  117. .camStats{display:flex;gap:.9em;padding:.5em 1em;background:#0d1117;border-bottom:1px solid #21262d;font-size:.75em;color:#8b949e;flex-wrap:wrap}
  118. .camStats span b{color:#c9d1d9;margin-left:.3em}
  119. #modalBack{position:absolute;inset:0;background:rgba(4,7,14,.75);z-index:40;display:flex;align-items:center;justify-content:center}
  120. #modalBack.hide{display:none}
  121. .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}
  122. .modalPanel h3{color:#dbe9ff;font-size:1.1em;margin-bottom:1em}
  123. #mobileCtl{position:absolute;inset:0;z-index:15;pointer-events:none;display:none}
  124. #mobileCtl.show{display:block}
  125. #joyPad{position:absolute;bottom:1.5em;left:1.5em;width:150px;height:150px;pointer-events:auto}
  126. #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}
  127. #joyPad .b.up{top:0;left:50px}
  128. #joyPad .b.down{bottom:0;left:50px}
  129. #joyPad .b.left{top:50px;left:0}
  130. #joyPad .b.right{top:50px;right:0}
  131. #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}
  132. #btnAction:active{transform:scale(.94)}
  133. #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}
  134. #achPanel.show{opacity:1}
  135. #achList{list-style:none;display:flex;flex-direction:column;gap:.25em;font-size:.78em}
  136. #achList li{color:#6e7681;display:flex;gap:.4em;align-items:center;opacity:.4}
  137. #achList li.unlocked{color:#fbbf24;opacity:1}
  138. #hintPanel{position:absolute;top:5.2em;left:.9em;z-index:12;background:rgba(10,20,40,.95);border:1px solid rgba(74,222,128,.5);border-radius:.55em;padding:.6em .9em;min-width:16em;max-width:20em;opacity:0;transition:opacity .25s;pointer-events:none;box-shadow:0 0 20px rgba(74,222,128,.2)}
  139. #hintPanel.show{opacity:1}
  140. #hintPanel .htitle{color:#4ade80;font-size:.68em;letter-spacing:.14em;margin-bottom:.35em;text-transform:uppercase;font-weight:700;display:flex;gap:.4em;align-items:center}
  141. #hintPanel .htitle::before{content:'💡';font-size:1.2em}
  142. #hintPanel .hbody{color:#cfe2ff;font-size:.82em;line-height:1.5}
  143. #hintPanel .hbody kbd{background:#152a4a;border:1px solid #2a4a7a;border-radius:.25em;padding:.05em .35em;font-family:'Consolas',monospace;font-size:.9em;color:#8ee7ff}
  144. #hintPanel .haction{color:#fbbf24;font-weight:600;margin-top:.35em;font-size:.78em}
  145. #diffDesc{color:#8ba3c7;font-size:.82em;line-height:1.4;margin-top:.4em;padding:.5em .7em;background:rgba(88,166,255,.08);border-left:2px solid #58a6ff;border-radius:.3em;min-height:3em;text-align:left}
  146. </style>
  147. </head>
  148. <body>
  149. <div id="wrap">
  150. <div id="stage" tabindex="0">
  151. <canvas id="cv" class="main" tabindex="-1"></canvas>
  152. <div id="hud" class="hide">
  153. <div class="hud-item"><span>ОЧКИ</span><b id="hudScore">0</b></div>
  154. <div class="hud-item"><span>СМЕНА</span><b id="hudWave">1 / 4</b></div>
  155. <div class="hud-item"><span>ЗАКРЫТО</span><b id="hudFixed">0</b></div>
  156. <div class="hud-item danger"><span>УТЕЧКИ</span><b id="hudLeaks">0 / 6</b></div>
  157. <div class="hud-item good"><span>ПОЙМАНО</span><b id="hudCaught">0</b></div>
  158. <div class="hud-item"><span>РЕКОРД</span><b id="hudHigh">0</b></div>
  159. <div id="progWrap"><div class="lbl">ПРОГРЕСС СМЕНЫ</div><div id="progBar"><i id="progFill"></i></div></div>
  160. </div>
  161. <div id="taskPanel"><div class="task-title">📋 Задачи смены</div><ul id="taskList"></ul></div>
  162. <div id="achPanel"><div class="task-title">🏆 Достижения</div><ul id="achList"></ul></div>
  163. <div id="hintPanel">
  164. <div class="htitle">Подсказка</div>
  165. <div class="hbody" id="hintPanelBody">Осмотритесь вокруг</div>
  166. <div class="haction" id="hintPanelAction"></div>
  167. </div>
  168. <div id="logPanel"><div class="task-title">📻 Журнал смены</div><ul id="logList"></ul></div>
  169. <canvas id="minimap" width="180" height="130"></canvas>
  170. <div id="topRight">
  171. <button id="btnHomeTop" tabindex="-1">⌂</button>
  172. <button id="btnPauseTop" tabindex="-1">⏸</button>
  173. <button id="btnHelpTop" tabindex="-1">💡</button>
  174. <button id="btnFsTop" tabindex="-1">⛶</button>
  175. </div>
  176. <div id="hintBar"><span id="hintText"></span></div>
  177. <div id="mobileCtl">
  178. <div id="joyPad">
  179. <div class="b up" data-k="up">▲</div>
  180. <div class="b down" data-k="down">▼</div>
  181. <div class="b left" data-k="left">◀</div>
  182. <div class="b right" data-k="right">▶</div>
  183. </div>
  184. <div id="btnAction">E</div>
  185. </div>
  186. <div id="mainMenuScreen" class="screen">
  187. <div class="panel">
  188. <h1>ЩИТ ДАННЫХ</h1>
  189. <div class="sub">Оператор информационной безопасности · Гибрид v12</div>
  190. <div class="btns col">
  191. <button class="primary big" id="btnContinue" style="display:none">▶ Продолжить смену</button>
  192. <button class="primary big" id="btnPlayGame">▶ Новая смена</button>
  193. <button class="big" id="btnTutorial">🎓 Обучение</button>
  194. <button class="big" id="btnPuzzleHelp">📖 Головоломки</button>
  195. <button class="big" id="btnSettings">⚙ Настройки</button>
  196. <button class="big" id="btnAchievements">🏆 Достижения</button>
  197. <button class="ghost" id="btnRules">❔ Правила</button>
  198. </div>
  199. <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>
  200. <div class="hintline" id="highScoreLine">🏆 Рекорд: 0</div>
  201. </div>
  202. </div>
  203. <div id="achScreen" class="screen hide">
  204. <div class="panel">
  205. <h2>🏆 Достижения</h2>
  206. <div id="achScreenList" style="text-align:left;display:grid;gap:.5em;margin-bottom:1em"></div>
  207. <div class="btns"><button class="primary" id="btnAchBack">← Назад</button></div>
  208. </div>
  209. </div>
  210. <div id="settingsScreen" class="screen hide">
  211. <div class="panel">
  212. <h2>⚙ Настройки</h2>
  213. <div style="display:grid;gap:.5em;margin-bottom:1em">
  214. <div class="setting" style="flex-direction:column;align-items:stretch">
  215. <div><span class="lbl">Сложность</span></div>
  216. <div class="seg" id="segDiff" style="margin-top:.4em">
  217. <button data-v="easy" style="flex:1">🌱 Легко</button>
  218. <button data-v="normal" style="flex:1">⚡ Средне</button>
  219. <button data-v="hard" style="flex:1">💀 Сложно</button>
  220. </div>
  221. <div id="diffDesc">Выберите уровень сложности</div>
  222. </div>
  223. <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>
  224. <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>
  225. <div class="setting"><div><span class="lbl">Полный экран</span></div><button id="btnFs" class="primary" style="padding:.4em .9em;font-size:.85em">⛶ Переключить</button></div>
  226. <div class="setting"><div><span class="lbl">Сброс прогресса</span></div><button id="btnResetProgress" class="danger" style="padding:.4em .9em;font-size:.85em">🗑 Сбросить</button></div>
  227. </div>
  228. <div class="btns"><button class="primary" id="btnSettingsBack">← Назад в меню</button></div>
  229. </div>
  230. </div>
  231. <div id="rulesScreen" class="screen hide">
  232. <div class="panel">
  233. <h2>Как играть</h2>
  234. <div class="rules">
  235. <div class="rule"><div><b>SOC (центр)</b> — ваша комната, от неё растут коридоры.</div></div>
  236. <div class="rule"><div><kbd>C</kbd> — камеры (только в SOC).</div></div>
  237. <div class="rule"><div>Клик по камере → фокус, <kbd>E</kbd> — доложить.</div></div>
  238. <div class="rule"><div>Движение — <kbd>WASD</kbd> / <kbd>стрелки</kbd> / джойстик.</div></div>
  239. <div class="rule"><div><kbd>E</kbd> — открыть инцидент рядом.</div></div>
  240. <div class="rule"><div>Инциденты: таймер. Просрочка → утечка. 6 → провал.</div></div>
  241. <div class="rule"><div>После всех смен — <b>аудит</b>.</div></div>
  242. </div>
  243. <div class="btns"><button id="btnRulesBack" class="primary">Понятно</button></div>
  244. </div>
  245. </div>
  246. <div id="pauseScreen" class="screen hide">
  247. <div class="panel" style="width:min(24em,90%)">
  248. <h2>⏸ Пауза</h2>
  249. <div class="btns col">
  250. <button id="btnResume" class="primary big">▶ Продолжить</button>
  251. <button id="btnPauseRules">❔ Правила</button>
  252. <button id="btnExitMenu" class="danger">⌂ Выйти в меню</button>
  253. </div>
  254. </div>
  255. </div>
  256. <div id="shiftScreen" class="screen hide">
  257. <div class="panel">
  258. <h2 id="shiftTitle">Рапорт</h2>
  259. <div class="desc" id="shiftMsg"></div>
  260. <div class="stats">
  261. <div class="stat"><span>ЗАКРЫТО</span><b id="shiftFixed">0</b></div>
  262. <div class="stat"><span>УТЕЧКИ</span><b id="shiftLeaks">0</b></div>
  263. <div class="stat"><span>ПОЙМАНО</span><b id="shiftCaught">0</b></div>
  264. <div class="stat"><span>ОЧКИ</span><b id="shiftScore">0</b></div>
  265. </div>
  266. <div class="btns"><button id="shiftNext" class="primary big">Следующая смена ▶</button></div>
  267. </div>
  268. </div>
  269. <div id="auditScreen" class="screen hide">
  270. <div class="panel">
  271. <h1 style="font-size:2em">🔍 АУДИТ</h1>
  272. <div class="sub">Проверка службы ИБ</div>
  273. <div class="desc">📻 <b>Диспетчер:</b> Едет проверяющий. Закройте все инциденты без утечек.</div>
  274. <div class="auditList" id="auditList"></div>
  275. <div class="btns"><button id="btnAuditStart" class="primary big">Начать аудит ▶</button></div>
  276. </div>
  277. </div>
  278. <div id="puzzleScreen" class="screen hide">
  279. <div class="panel">
  280. <div class="pzHeader"><div class="dot" id="pzDot"></div><span id="pzTitle">Инцидент</span></div>
  281. <div class="pzCanvasWrap"><canvas id="pzCanvas" width="480" height="360" class="pzCanvas" tabindex="0"></canvas></div>
  282. <div class="pzFoot">
  283. <span class="pzKeys" id="pzKeys">—</span>
  284. <span id="pzHint">—</span>
  285. <button id="pzCancel">✕</button>
  286. </div>
  287. </div>
  288. </div>
  289. <div id="cameraScreen" class="screen hide">
  290. <div class="panel">
  291. <div class="camHeader"><span class="rec"></span><span class="title">📹 СИСТЕМА ВИДЕОНАБЛЮДЕНИЯ</span><span style="color:#8b949e;font-weight:400;font-size:.85em">LIVE</span></div>
  292. <div class="camStats">
  293. <span>Комнат: <b id="camBotsCount">0</b></span>
  294. <span>Подозрительных: <b id="camSusCount" style="color:#f85149">0</b></span>
  295. <span>Поймано (за смену / всего): <b id="camCaughtCount" style="color:#4ade80">0 / 0</b></span>
  296. </div>
  297. <div class="camGrid" id="camGrid"></div>
  298. <div class="camFoot">
  299. <span class="info" id="camInfo">Клик по камере · E — доложить · C — закрыть</span>
  300. <button id="camReport" disabled>🚨 Доложить</button>
  301. <button id="camClose">✕</button>
  302. </div>
  303. </div>
  304. </div>
  305. <div id="endScreen" class="screen hide">
  306. <div class="panel">
  307. <h1 id="endTitle">Смена закрыта</h1>
  308. <div id="endSub" class="sub">Результат</div>
  309. <div class="stats">
  310. <div class="stat"><span>ОЧКИ</span><b id="stScore">0</b></div>
  311. <div class="stat"><span>ЗАКРЫТО</span><b id="stFixed">0</b></div>
  312. <div class="stat"><span>УТЕЧКИ</span><b id="stLeaks">0</b></div>
  313. <div class="stat"><span>ПОЙМАНО</span><b id="stCaught">0</b></div>
  314. </div>
  315. <div id="endMsg" class="desc"></div>
  316. <div class="btns">
  317. <button id="btnRestart" class="primary">↻ Снова на смену</button>
  318. <button id="btnMenu">⌂ В главное меню</button>
  319. </div>
  320. </div>
  321. </div>
  322. <div id="tutorialScreen" class="screen hide">
  323. <div class="panel">
  324. <h1>📖 Обучение</h1>
  325. <div class="sub">Всё, что нужно знать оператору</div>
  326. <div class="tutGrid" id="tutGrid"></div>
  327. <div class="btns"><button id="btnTutBack" class="primary">← Назад в меню</button></div>
  328. </div>
  329. </div>
  330. <div id="tutSectionScreen" class="screen hide">
  331. <div class="panel" style="width:min(46em,94%)">
  332. <h1 id="tutSectionTitle" style="font-size:1.8em">—</h1>
  333. <div class="sub" id="tutSectionSub">—</div>
  334. <div class="tutBody" id="tutSectionBody" style="max-height:55vh;overflow-y:auto"></div>
  335. <div class="btns">
  336. <button id="btnTutSectionBack">← К разделам</button>
  337. </div>
  338. </div>
  339. </div>
  340. <div id="tutDetailScreen" class="screen hide">
  341. <div class="panel">
  342. <h1 id="tutDetailTitle" style="font-size:1.7em">—</h1>
  343. <div class="sub" id="tutDetailSub">—</div>
  344. <div class="tutBody" id="tutDetailBody"></div>
  345. <div class="btns">
  346. <button id="btnTutTry" class="primary">▶ Попробовать</button>
  347. <button id="btnTutDetailBack">← К списку</button>
  348. </div>
  349. </div>
  350. </div>
  351. <div id="modalBack" class="hide">
  352. <div class="modalPanel">
  353. <h3 id="modalText">Выйти в главное меню?</h3>
  354. <div class="btns">
  355. <button id="modalYes" class="danger">Да</button>
  356. <button id="modalNo" class="primary">Отмена</button>
  357. </div>
  358. </div>
  359. </div>
  360. </div>
  361. </div>
  362. <script>
  363. (function(){
  364. 'use strict';
  365. window.addEventListener('error', function(e){
  366. try {
  367. console.error('[FATAL]', e.message, e.filename + ':' + e.lineno);
  368. const h = document.getElementById('hintBar');
  369. const t = document.getElementById('hintText');
  370. if (h && t){ t.textContent = 'ОШИБКА: ' + e.message + ' · стр. ' + e.lineno; h.classList.add('show'); }
  371. } catch(_){}
  372. });
  373. const $ = id => document.getElementById(id);
  374. const el = {};
  375. [
  376. 'cv','stage','hud','hudScore','hudWave','hudFixed','hudLeaks','hudCaught','hudHigh','progFill',
  377. 'taskPanel','taskList','achPanel','achList','logPanel','logList','minimap','hintBar','hintText',
  378. 'pzCanvas','pzTitle','pzHint','pzKeys','pzDot','pzCancel',
  379. 'mainMenuScreen','achScreen','achScreenList','settingsScreen','rulesScreen','pauseScreen',
  380. 'shiftScreen','shiftTitle','shiftMsg','shiftFixed','shiftLeaks','shiftCaught','shiftScore','shiftNext',
  381. 'puzzleScreen','auditScreen','auditList','btnAuditStart','endScreen',
  382. 'tutorialScreen','tutDetailScreen','tutGrid','tutDetailTitle','tutDetailSub','tutDetailBody',
  383. 'tutSectionScreen','tutSectionTitle','tutSectionSub','tutSectionBody','btnTutSectionBack',
  384. 'btnTutBack','btnTutTry','btnTutDetailBack','btnPuzzleHelp','btnAchievements','btnAchBack',
  385. 'btnResetProgress','cameraScreen','camGrid','camReport','camClose','camInfo','camBotsCount',
  386. 'camSusCount','camCaughtCount','modalBack','modalText','modalYes','modalNo','highScoreLine',
  387. 'mobileCtl','joyPad','btnAction','btnContinue','btnPlayGame','btnTutorial','btnSettings',
  388. 'btnRules','btnResume','btnPauseRules','btnExitMenu','btnRestart','btnMenu','btnHomeTop',
  389. 'btnPauseTop','btnHelpTop','btnFsTop','btnFs','btnSettingsBack','btnRulesBack',
  390. 'endTitle','endSub','stScore','stFixed','stLeaks','stCaught','endMsg',
  391. 'hintPanel','hintPanelBody','hintPanelAction','diffDesc'
  392. ].forEach(id => { el[id] = $(id); });
  393. for (const k in el){ if (!el[k]) console.warn('[MISSING EL]', k); }
  394. const W = 1280, H = 720, DEPTH = 0.82, T = 22;
  395. const ROOM_SIZE = 700, DOOR_SIZE = 180;
  396. let WORLD_W = 1400, WORLD_D = 1100;
  397. let camX = 0, camY = 0;
  398. const cv = el.cv;
  399. const ctx = cv.getContext('2d', {alpha:false});
  400. cv.width = W; cv.height = H;
  401. function resize(){
  402. const s = Math.min(window.innerWidth / W, window.innerHeight / H);
  403. el.stage.style.width = Math.floor(W * s) + 'px';
  404. el.stage.style.height = Math.floor(H * s) + 'px';
  405. el.stage.style.fontSize = Math.max(9, 16 * s) + 'px';
  406. }
  407. window.addEventListener('resize', resize); resize();
  408. const clamp = (v,a,b) => v < a ? a : (v > b ? b : v);
  409. const rand = (a,b) => a + Math.random() * (b - a);
  410. 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; }
  411. 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(); }
  412. function dist2(ax, ay, bx, by){ const dx=ax-bx, dy=ay-by; return dx*dx+dy*dy; }
  413. let _lastFont = '';
  414. function setFont(f){ if (_lastFont !== f){ ctx.font = f; _lastFont = f; } }
  415. const settings = { diff:'normal', sound:1, mobile:'auto' };
  416. let highScore = 0;
  417. try {
  418. const s = JSON.parse(localStorage.getItem('shield9_settings') || 'null'); if (s) Object.assign(settings, s);
  419. highScore = parseInt(localStorage.getItem('shield9_highscore') || '0', 10) || 0;
  420. } catch(e){}
  421. function saveSettings(){ try { localStorage.setItem('shield9_settings', JSON.stringify(settings)); } catch(e){} }
  422. function saveHigh(){ try { localStorage.setItem('shield9_highscore', String(highScore)); } catch(e){} }
  423. function applySettingsToUI(){
  424. document.querySelectorAll('#segDiff button').forEach(b => b.classList.toggle('active', b.dataset.v === settings.diff));
  425. document.querySelectorAll('#segSound button').forEach(b => b.classList.toggle('active', +b.dataset.v === settings.sound));
  426. document.querySelectorAll('#segMobile button').forEach(b => b.classList.toggle('active', b.dataset.v === settings.mobile));
  427. if (el.highScoreLine) el.highScoreLine.textContent = '🏆 Рекорд: ' + highScore;
  428. if (el.diffDesc){
  429. const d = DIFF[settings.diff] || DIFF.normal;
  430. el.diffDesc.innerHTML = '<b style="color:#cfe2ff">' + d.icon + ' ' + d.label + '</b> · ' + d.description;
  431. }
  432. }
  433. const isTouchDevice = ('ontouchstart' in window) || navigator.maxTouchPoints > 0;
  434. function updateMobileVisibility(){
  435. const show = settings.mobile === '1' || (settings.mobile === 'auto' && isTouchDevice);
  436. if (el.mobileCtl) el.mobileCtl.classList.toggle('show', show && state === 'playing');
  437. }
  438. const ACHIEVEMENTS = [
  439. {id:'first_shift', ic:'🎬', name:'Первая смена', desc:'Завершить первую смену', check: s => s.shifts >= 1},
  440. {id:'perfect', ic:'💎', name:'Безупречно', desc:'Смена без утечек', check: s => s.perfectShift},
  441. {id:'catcher', ic:'🕸️', name:'Ловец', desc:'Поймать 5 нарушителей', check: s => s.totalCaught >= 5},
  442. {id:'veteran', ic:'🎖️', name:'Ветеран', desc:'Пройти все 4 смены', check: s => s.shifts >= 4},
  443. {id:'audit_pass', ic:'✅', name:'Проверку прошёл', desc:'Успешно пройти аудит', check: s => s.auditPassed},
  444. {id:'no_errors', ic:'🎯', name:'Снайпер', desc:'10 закрытий без ошибок', check: s => s.fixedNoErrors >= 10},
  445. {id:'record', ic:'🏅', name:'Рекордсмен', desc:'500 очков', check: s => s.score >= 500}
  446. ];
  447. let unlockedAchievements = new Set();
  448. try { const a = JSON.parse(localStorage.getItem('shield9_ach') || '[]'); unlockedAchievements = new Set(a); } catch(e){}
  449. function saveAch(){ try { localStorage.setItem('shield9_ach', JSON.stringify([...unlockedAchievements])); } catch(e){} }
  450. function checkAchievements(stats){
  451. for (const a of ACHIEVEMENTS){
  452. if (!unlockedAchievements.has(a.id) && a.check(stats)){
  453. unlockedAchievements.add(a.id); saveAch();
  454. toast('🏆 ' + a.name + ' — ' + a.desc, 'ok');
  455. addLog('🏆 Достижение: ' + a.name, 'sys');
  456. soundAch();
  457. renderAchievementsUI(); refreshAchievementHUD();
  458. }
  459. }
  460. }
  461. function renderAchievementsUI(){
  462. if (el.achList){ el.achList.innerHTML = ''; }
  463. if (el.achScreenList){ el.achScreenList.innerHTML = ''; }
  464. for (const a of ACHIEVEMENTS){
  465. const unlocked = unlockedAchievements.has(a.id);
  466. if (el.achList){
  467. const li = document.createElement('li'); li.className = unlocked ? 'unlocked' : '';
  468. const ic = document.createElement('span'); ic.className = 'ic'; ic.textContent = a.ic;
  469. const nm = document.createElement('span'); nm.textContent = a.name;
  470. li.appendChild(ic); li.appendChild(nm); el.achList.appendChild(li);
  471. }
  472. if (el.achScreenList){
  473. const row = document.createElement('div');
  474. 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');
  475. const icB = document.createElement('span'); icB.style.fontSize = '1.6em'; icB.textContent = a.ic;
  476. const txt = document.createElement('div');
  477. const nmB = document.createElement('b'); nmB.style.color = unlocked ? '#fbbf24' : '#cfe2ff'; nmB.textContent = a.name;
  478. const ds = document.createElement('div'); ds.style.color = '#8ba3c7'; ds.style.fontSize = '.82em'; ds.textContent = a.desc;
  479. txt.appendChild(nmB); txt.appendChild(ds);
  480. row.appendChild(icB); row.appendChild(txt); el.achScreenList.appendChild(row);
  481. }
  482. }
  483. }
  484. function refreshAchievementHUD(){ if (el.achPanel) el.achPanel.classList.toggle('show', state === 'playing' && unlockedAchievements.size > 0); }
  485. function saveGameState(){
  486. try {
  487. localStorage.setItem('shield9_savestate', JSON.stringify({
  488. diff: currentDiff.key, shift: currentShift,
  489. score, leaks, fixedCount, totalCaught, ts: Date.now()
  490. }));
  491. } catch(e){}
  492. }
  493. function loadGameState(){
  494. try {
  495. const s = JSON.parse(localStorage.getItem('shield9_savestate') || 'null');
  496. if (!s) return null;
  497. if (Date.now() - s.ts > 24*60*60*1000) return null;
  498. return s;
  499. } catch(e){ return null; }
  500. }
  501. function clearGameState(){ try { localStorage.removeItem('shield9_savestate'); } catch(e){} }
  502. function updateContinueButton(){ if (el.btnContinue) el.btnContinue.style.display = loadGameState() ? '' : 'none'; }
  503. let AC = null;
  504. function beep(f, d, type, v){
  505. if (!settings.sound) return;
  506. try {
  507. AC = AC || new (window.AudioContext || window.webkitAudioContext)();
  508. const o = AC.createOscillator(), g = AC.createGain();
  509. o.type = type || 'sine'; o.frequency.value = f; g.gain.value = v || 0.05;
  510. o.connect(g); g.connect(AC.destination);
  511. const t = AC.currentTime;
  512. g.gain.setValueAtTime(v || 0.05, t);
  513. g.gain.exponentialRampToValueAtTime(0.0001, t + d);
  514. o.start(t); o.stop(t + d + 0.02);
  515. } catch(e){}
  516. }
  517. function radioBeep(){ beep(1000, .04); setTimeout(() => beep(1400, .05), 50); }
  518. function soundAlert(){ beep(180, .25, 'sawtooth', .06); }
  519. function soundOk(){ beep(760, .1); }
  520. function soundCaught(){ beep(880, .15); setTimeout(() => beep(1320, .15), 150); }
  521. function soundAch(){ beep(1320, .12); setTimeout(() => beep(1760, .12), 100); setTimeout(() => beep(2200, .15), 200); }
  522. const shiftLog = [];
  523. function addLog(text, type){
  524. const now = new Date();
  525. const t = String(now.getHours()).padStart(2,'0') + ':' + String(now.getMinutes()).padStart(2,'0') + ':' + String(now.getSeconds()).padStart(2,'0');
  526. shiftLog.unshift({t, text, type: type || 'info'});
  527. if (shiftLog.length > 8) shiftLog.pop();
  528. if (!el.logList) return;
  529. const frag = document.createDocumentFragment();
  530. for (const e of shiftLog){
  531. const li = document.createElement('li'); li.className = e.type;
  532. const st = document.createElement('span'); st.className = 't'; st.textContent = '[' + e.t + ']';
  533. const stx = document.createElement('span'); stx.textContent = e.text;
  534. li.appendChild(st); li.appendChild(stx); frag.appendChild(li);
  535. }
  536. el.logList.innerHTML = ''; el.logList.appendChild(frag);
  537. }
  538. function clearLog(){ shiftLog.length = 0; if (el.logList) el.logList.innerHTML = ''; }
  539. let hintTimer = null;
  540. function showHint(t, ms, radio){
  541. ms = ms || 3000;
  542. if (!el.hintText || !el.hintBar) return;
  543. el.hintText.textContent = t;
  544. el.hintBar.classList.add('show');
  545. el.hintBar.classList.toggle('radio', !!radio);
  546. clearTimeout(hintTimer);
  547. hintTimer = setTimeout(() => { el.hintBar.classList.remove('show'); el.hintBar.classList.remove('radio'); }, ms);
  548. }
  549. function dispatch(text){ radioBeep(); showHint('📻 Диспетчер: ' + text, 4200, true); addLog('📻 ' + text, 'sys'); }
  550. function showHintPanel(text, action){
  551. if (!el.hintPanel) return;
  552. if (el.hintPanelBody) el.hintPanelBody.innerHTML = text;
  553. if (el.hintPanelAction) el.hintPanelAction.innerHTML = action || '';
  554. el.hintPanel.classList.add('show');
  555. }
  556. function hideHintPanel(){
  557. if (el.hintPanel) el.hintPanel.classList.remove('show');
  558. }
  559. function updateHintPanel(){
  560. if (!el.hintPanel) return;
  561. const shouldShow = (state === 'playing') && currentDiff.showHints;
  562. if (!shouldShow){ hideHintPanel(); return; }
  563. const here = roomAt(player.x, player.y);
  564. const {inc, d} = nearestIncident();
  565. if (inc && d < 120){
  566. const def = INCIDENTS[inc.type];
  567. const hintForType = {
  568. phishing: 'Нажмите <kbd>E</kbd> — введите PIN-код с экрана',
  569. password: 'Нажмите <kbd>E</kbd> — соедините провода по цветам',
  570. logs: 'Нажмите <kbd>E</kbd> — совместите стрелки с метками',
  571. access: 'Нажмите <kbd>E</kbd> — поставьте ползунки в зелёные зоны',
  572. ports: 'Нажмите <kbd>E</kbd> — проведите карту в зону',
  573. cipher: 'Нажмите <kbd>E</kbd> — повторите последовательность',
  574. backup: 'Нажмите <kbd>E</kbd> — нажмите в зелёную зону',
  575. response: 'Нажмите <kbd>E</kbd> — кликайте по красным точкам'
  576. };
  577. showHintPanel(
  578. 'Рядом инцидент: <b style="color:' + def.color + '">' + def.icon + ' ' + def.label + '</b>',
  579. hintForType[inc.type] || 'Нажмите E чтобы открыть'
  580. );
  581. return;
  582. }
  583. if (here && here.isSoc){
  584. showHintPanel(
  585. 'Вы в <b style="color:#4ade80">SOC</b> — центре безопасности',
  586. 'Нажмите <kbd>C</kbd> — камеры · <kbd>WASD</kbd> — идти к инциденту'
  587. );
  588. return;
  589. }
  590. const suspects = bots.filter(b => !b.isCaught && b.isSuspect);
  591. if (suspects.length > 0){
  592. showHintPanel(
  593. '⚠ Подозрительных сотрудников: <b style="color:#ff6b6b">' + suspects.length + '</b>',
  594. 'Нажмите <kbd>C</kbd> (в SOC) чтобы поймать через камеру'
  595. );
  596. return;
  597. }
  598. if (inc){
  599. const def = INCIDENTS[inc.type];
  600. showHintPanel(
  601. 'Ближайший инцидент: <b style="color:' + def.color + '">' + def.icon + ' ' + def.label + '</b>',
  602. 'Идите по миникарте (точки внизу справа)'
  603. );
  604. return;
  605. }
  606. showHintPanel('Все инциденты закрыты. Ждите следующего...', 'Следите за камерами');
  607. }
  608. let modalResolve = null;
  609. function showModal(text){
  610. return new Promise(resolve => {
  611. if (!el.modalBack){ resolve(false); return; }
  612. if (el.modalText) el.modalText.textContent = text;
  613. el.modalBack.classList.remove('hide');
  614. modalResolve = resolve;
  615. });
  616. }
  617. const ROOM_THEMES = {
  618. soc: { name:'SOC · Операторская', floor:['#1a2540','#0a1228'], accent:'#4ade80', pattern:'carpet',
  619. furniture: [
  620. {kind:'camwall', w:280, d:60, h:80, tags:[]},
  621. {kind:'desk', w:170, d:80, h:42, tags:['logs','access']},
  622. {kind:'desk', w:170, d:80, h:42, tags:['ports','phishing']}
  623. ]},
  624. server: { name:'Серверная', floor:['#0e2238','#08172a'], accent:'#2f7fd6', pattern:'grid',
  625. furniture: [
  626. {kind:'rack', w:120, d:100, h:130, tags:['access','ports']},
  627. {kind:'rack', w:120, d:100, h:130, tags:['access','ports','logs']},
  628. {kind:'desk', w:170, d:80, h:42, tags:['logs']},
  629. {kind:'rack', w:120, d:100, h:130, tags:['ports']}
  630. ]},
  631. open: { name:'Опенспейс', floor:['#142840','#0a1928'], accent:'#3a9ac8', pattern:'tiles',
  632. furniture: [
  633. {kind:'desk', w:170, d:80, h:42, tags:['phishing','password']},
  634. {kind:'desk', w:170, d:80, h:42, tags:['phishing','password']},
  635. {kind:'desk', w:170, d:80, h:42, tags:['phishing']},
  636. {kind:'desk', w:170, d:80, h:42, tags:['password']}
  637. ]},
  638. archive: { name:'Архив', floor:['#2a1f3a','#150e24'], accent:'#8a5ac8', pattern:'wood',
  639. furniture: [
  640. {kind:'shelf', w:100, d:170, h:120, tags:['backup']},
  641. {kind:'shelf', w:100, d:170, h:120, tags:['backup']},
  642. {kind:'safe', w:130, d:110, h:100, tags:['cipher']},
  643. {kind:'desk', w:170, d:80, h:42, tags:['cipher']}
  644. ]},
  645. meeting: { name:'Переговорка', floor:['#1c2a1c','#0e1a0e'], accent:'#4ade80', pattern:'carpet',
  646. furniture: [
  647. {kind:'bigtable', w:340, d:170, h:50, tags:['response']},
  648. {kind:'desk', w:130, d:90, h:70, tags:['response']}
  649. ]}
  650. };
  651. const ESSENTIAL_THEMES = ['server','open','archive','meeting'];
  652. const FURN_SIZES = {
  653. desk:{w:170,d:80,h:42}, bigtable:{w:340,d:170,h:50}, rack:{w:120,d:100,h:130},
  654. shelf:{w:100,d:170,h:120}, safe:{w:130,d:110,h:100}, camwall:{w:280,d:60,h:80}
  655. };
  656. const FURN_COLOR = {
  657. desk: {tL:'#a08a60', t:'#7a6440', f:'#504028', fD:'#302010', a:'#5a9aff'},
  658. bigtable:{tL:'#b09868', t:'#8a7048', f:'#5a4830', fD:'#3a2818', a:'#5a9aff'},
  659. rack: {tL:'#4a5868', t:'#384858', f:'#202c3c', fD:'#0e1828', a:'#4ade80'},
  660. shelf: {tL:'#6a4a30', t:'#4a3020', f:'#2a1a08', fD:'#1a0e00', a:'#d4a868'},
  661. safe: {tL:'#7a8288', t:'#5a6268', f:'#2a3038', fD:'#1a2028', a:'#4ade80'},
  662. camwall:{tL:'#2a3038', t:'#1a2030', f:'#0a1018', fD:'#050508', a:'#58a6ff'}
  663. };
  664. let ROOMS = [], WALLS = [], DOORS = [], FURN = [];
  665. let socRoom = null, exitTile = null;
  666. function generateLayoutFromCenter(roomCount){
  667. const GRID = 15;
  668. const center = Math.floor(GRID / 2);
  669. const cells = new Map();
  670. cells.set(center + ',' + center, {r:center, c:center, depth:0});
  671. const dirs = [[0,-1],[0,1],[-1,0],[1,0]];
  672. const firstDirs = shuffle(dirs.slice());
  673. for (const [dr, dc] of firstDirs){
  674. const nr = center + dr, nc = center + dc;
  675. if (nr < 1 || nr >= GRID-1 || nc < 1 || nc >= GRID-1) continue;
  676. cells.set(nr + ',' + nc, {r:nr, c:nc, depth:1});
  677. if (cells.size >= roomCount) break;
  678. }
  679. let attempts = 0;
  680. while (cells.size < roomCount && attempts < 800){
  681. attempts++;
  682. const list = Array.from(cells.values());
  683. const base = list[Math.floor(Math.random() * list.length)];
  684. const shuffled = shuffle(dirs.slice());
  685. for (const [dr, dc] of shuffled){
  686. const nr = base.r + dr, nc = base.c + dc;
  687. if (nr < 1 || nr >= GRID-1 || nc < 1 || nc >= GRID-1) continue;
  688. if (cells.has(nr + ',' + nc)) continue;
  689. cells.set(nr + ',' + nc, {r:nr, c:nc, depth: base.depth + 1});
  690. break;
  691. }
  692. }
  693. return {cells, center, GRID};
  694. }
  695. function generateWorld(){
  696. const roomCount = 7 + Math.floor(Math.random() * 4);
  697. const layout = generateLayoutFromCenter(roomCount);
  698. const cellArr = Array.from(layout.cells.values());
  699. let minR = 999, minC = 999, maxR = -1, maxC = -1;
  700. for (const c of cellArr){
  701. if (c.r < minR) minR = c.r; if (c.r > maxR) maxR = c.r;
  702. if (c.c < minC) minC = c.c; if (c.c > maxC) maxC = c.c;
  703. }
  704. WORLD_W = (maxC - minC + 1) * ROOM_SIZE;
  705. WORLD_D = (maxR - minR + 1) * ROOM_SIZE;
  706. ROOMS.length = 0; WALLS.length = 0; DOORS.length = 0; FURN.length = 0;
  707. socRoom = null; minimapBg = null;
  708. const nonSocArr = cellArr.filter(c => !(c.r === layout.center && c.c === layout.center));
  709. const themePool = [];
  710. for (let i = 0; i < nonSocArr.length; i++){
  711. if (i < ESSENTIAL_THEMES.length) themePool.push(ESSENTIAL_THEMES[i]);
  712. else themePool.push(ESSENTIAL_THEMES[Math.floor(Math.random() * ESSENTIAL_THEMES.length)]);
  713. }
  714. shuffle(themePool);
  715. const roomMap = new Map();
  716. let themeIdx = 0;
  717. for (const c of cellArr){
  718. const isStart = (c.r === layout.center && c.c === layout.center);
  719. const themeId = isStart ? 'soc' : themePool[themeIdx++];
  720. const theme = ROOM_THEMES[themeId];
  721. const room = {
  722. x: (c.c - minC) * ROOM_SIZE, y: (c.r - minR) * ROOM_SIZE,
  723. w: ROOM_SIZE, h: ROOM_SIZE,
  724. theme: themeId, name: theme.name, floor: theme.floor, accent: theme.accent, pattern: theme.pattern,
  725. isStart, isSoc: isStart, r: c.r, c: c.c, depth: c.depth
  726. };
  727. ROOMS.push(room); roomMap.set(c.r + ',' + c.c, room);
  728. if (isStart) socRoom = room;
  729. }
  730. for (const c of cellArr){
  731. const room = roomMap.get(c.r + ',' + c.c);
  732. if (roomMap.has(c.r + ',' + (c.c + 1)))
  733. DOORS.push({x: room.x + room.w - T/2, y: room.y + (ROOM_SIZE - DOOR_SIZE)/2, w: T, h: DOOR_SIZE, dir:'v'});
  734. if (roomMap.has((c.r + 1) + ',' + c.c))
  735. DOORS.push({x: room.x + (ROOM_SIZE - DOOR_SIZE)/2, y: room.y + room.h - T/2, w: DOOR_SIZE, h: T, dir:'h'});
  736. }
  737. const dv = (ROOM_SIZE - DOOR_SIZE) / 2;
  738. for (const c of cellArr){
  739. const room = roomMap.get(c.r + ',' + c.c);
  740. const hasN = roomMap.has((c.r - 1) + ',' + c.c);
  741. const hasS = roomMap.has((c.r + 1) + ',' + c.c);
  742. const hasW = roomMap.has(c.r + ',' + (c.c - 1));
  743. const hasE = roomMap.has(c.r + ',' + (c.c + 1));
  744. if (!hasN) WALLS.push({x: room.x, y: room.y - T/2, w: ROOM_SIZE, h: T});
  745. 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}); }
  746. if (!hasS) WALLS.push({x: room.x, y: room.y + ROOM_SIZE - T/2, w: ROOM_SIZE, h: T});
  747. if (!hasW) WALLS.push({x: room.x - T/2, y: room.y, w: T, h: ROOM_SIZE});
  748. 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}); }
  749. if (!hasE) WALLS.push({x: room.x + ROOM_SIZE - T/2, y: room.y, w: T, h: ROOM_SIZE});
  750. 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}); }
  751. }
  752. for (const room of ROOMS){
  753. const theme = ROOM_THEMES[room.theme];
  754. if (room.isSoc){
  755. const padX = 120;
  756. const camF = theme.furniture.find(f => f.kind === 'camwall');
  757. 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:[]});
  758. const others = theme.furniture.filter(f => f.kind !== 'camwall');
  759. 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}];
  760. for (let i = 0; i < others.length && i < positions.length; i++){
  761. const f = others[i], pos = positions[i];
  762. 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});
  763. }
  764. } else {
  765. const padX = 140, padY = 140;
  766. const cellW = (room.w - padX*2) / 2;
  767. const cellH = (room.h - padY*2) / 2;
  768. const positions = [
  769. {cx: room.x + padX + cellW*0.5, cy: room.y + padY + cellH*0.5},
  770. {cx: room.x + padX + cellW*1.5, cy: room.y + padY + cellH*0.5},
  771. {cx: room.x + padX + cellW*0.5, cy: room.y + padY + cellH*1.5},
  772. {cx: room.x + padX + cellW*1.5, cy: room.y + padY + cellH*1.5}
  773. ];
  774. shuffle(positions);
  775. const furniture = shuffle(theme.furniture.slice());
  776. for (let i = 0; i < positions.length && i < furniture.length; i++){
  777. const f = furniture[i], pos = positions[i];
  778. const fx = clamp(pos.cx - f.w/2 + (Math.random() - 0.5) * 30, room.x + 40, room.x + room.w - f.w - 40);
  779. const fy = clamp(pos.cy - f.d/2 + (Math.random() - 0.5) * 30, room.y + 40, room.y + room.h - f.d - 40);
  780. 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});
  781. }
  782. }
  783. }
  784. let farthestRoom = socRoom, maxDist = -1;
  785. for (const r of ROOMS){
  786. const d = dist2(r.x + r.w/2, r.y + r.h/2, socRoom.x + socRoom.w/2, socRoom.y + socRoom.h/2);
  787. if (d > maxDist){ maxDist = d; farthestRoom = r; }
  788. }
  789. exitTile = {x: farthestRoom.x + farthestRoom.w - 80, y: farthestRoom.y + farthestRoom.h - 80, room: farthestRoom};
  790. player.x = socRoom.x + socRoom.w/2;
  791. player.y = socRoom.y + socRoom.h/2 + 60;
  792. let tries = 0;
  793. while (isBlocked(player.x, player.y, player.r + 4) && tries < 80){
  794. player.x = socRoom.x + 150 + Math.random() * (socRoom.w - 300);
  795. player.y = socRoom.y + 250 + Math.random() * (socRoom.h - 350);
  796. tries++;
  797. }
  798. collide(player, player.r);
  799. staticReady = false;
  800. if (staticCanvas.width !== WORLD_W) staticCanvas.width = WORLD_W;
  801. const newH = Math.ceil(WORLD_D * DEPTH);
  802. if (staticCanvas.height !== newH) staticCanvas.height = newH;
  803. updateCamera();
  804. buildFurnitureSprites();
  805. buildStaticLayer();
  806. }
  807. const INCIDENTS = {
  808. phishing: {icon:'📧', label:'Фишинговое письмо', color:'#ffd166', tag:'phishing'},
  809. password: {icon:'🔑', label:'Слабый пароль', color:'#4ea1ff', tag:'password'},
  810. logs: {icon:'📋', label:'Подозрительные логи', color:'#c084fc', tag:'logs'},
  811. access: {icon:'🚪', label:'Права доступа', color:'#4ade80', tag:'access'},
  812. ports: {icon:'🌐', label:'Открытые порты', color:'#38bdf8', tag:'ports'},
  813. cipher: {icon:'🔐', label:'Шифрование', color:'#f472b6', tag:'cipher'},
  814. backup: {icon:'💾', label:'Резервные копии', color:'#fbbf24', tag:'backup'},
  815. response: {icon:'🚨', label:'Реагирование', color:'#ff7b6b', tag:'response'}
  816. };
  817. const ALL_INCIDENT_TYPES = Object.keys(INCIDENTS);
  818. const DIFF = {
  819. easy: {
  820. key:'easy', label:'Легко', icon:'🌱',
  821. leaksMax:8, botCount:2, botSabotage:0.08, botLeak:0.05,
  822. showHints: true,
  823. hintsAlwaysVisible: true,
  824. shifts: [
  825. {count:2,time:90},{count:3,time:80},{count:4,time:70},{count:5,time:60}
  826. ],
  827. description: 'Подсказки всегда на экране. Боты почти не мешают. Время на реакцию большое. Идеально для обучения.'
  828. },
  829. normal: {
  830. key:'normal', label:'Средне', icon:'⚡',
  831. leaksMax:6, botCount:4, botSabotage:0.30, botLeak:0.20,
  832. showHints: true,
  833. hintsAlwaysVisible: false,
  834. shifts: [
  835. {count:3,time:50},{count:4,time:45},{count:4,time:42},{count:6,time:36}
  836. ],
  837. description: 'Подсказки в начале смены. Боты активны. Стандартный баланс. Рекомендуется для знакомства.'
  838. },
  839. hard: {
  840. key:'hard', label:'Сложно', icon:'💀',
  841. leaksMax:5, botCount:5, botSabotage:0.50, botLeak:0.35,
  842. showHints: false,
  843. hintsAlwaysVisible: false,
  844. shifts: [
  845. {count:4,time:40},{count:5,time:34},{count:6,time:30},{count:7,time:26}
  846. ],
  847. description: 'Без подсказок. Боты агрессивны. Короткие таймеры. Для опытных операторов.'
  848. }
  849. };
  850. let currentDiff = DIFF.normal;
  851. let state = 'menu';
  852. let currentShift = 0;
  853. let score = 0, leaks = 0, fixedCount = 0, caughtCount = 0;
  854. let caughtThisShift = 0, totalCaught = 0;
  855. let statsAch = { shifts: 0, perfectShift: false, totalCaught: 0, fixedNoErrors: 0, auditPassed: false, score: 0, shiftErrors: 0 };
  856. let incidents = [], particles = [], toasts = [];
  857. let time = 0;
  858. let pausedFrom = null, stateBeforePuzzle = null;
  859. let activeIncident = null, puzzle = null, puzzleRAF = null;
  860. let puzzleMouse = {x:-1, y:-1, down:false};
  861. let waveTasks = [];
  862. let spawnedInShift = 0, shiftSpawnTimer = 0;
  863. let demoMode = false, puzzleFailedActive = false;
  864. const BOT_NAMES = ['Иванов','Петрова','Сидоров','Кузнецов','Смирнова','Волков','Морозов','Новиков'];
  865. const BOT_COLORS = ['#ff6b6b','#4ea1ff','#4ade80','#fbbf24','#c084fc','#f472b6','#38bdf8','#a3e635'];
  866. let bots = [];
  867. let cameraOpen = false, activeCameraIdx = 0;
  868. let camBufs = [], camRooms = [];
  869. const player = {x:0, y:0, r:18, dir:1, moving:false};
  870. const keys = {up:false, down:false, left:false, right:false};
  871. let actionPressed = false;
  872. function resolveRect(p, rx, ry, rw, rh, r){
  873. const cx = p.x < rx ? rx : (p.x > rx+rw ? rx+rw : p.x);
  874. const cy = p.y < ry ? ry : (p.y > ry+rh ? ry+rh : p.y);
  875. const dx = p.x - cx, dy = p.y - cy, d2 = dx*dx + dy*dy;
  876. if (d2 >= r*r) return;
  877. if (d2 > 0.0001){ const d = Math.sqrt(d2); p.x = cx + (dx/d)*r; p.y = cy + (dy/d)*r; }
  878. else {
  879. const L = p.x - rx, R = (rx+rw) - p.x, Tp = p.y - ry, B = (ry+rh) - p.y;
  880. const m = Math.min(L, R, Tp, B);
  881. if (m === L) p.x = rx - r; else if (m === R) p.x = rx + rw + r;
  882. else if (m === Tp) p.y = ry - r; else p.y = ry + rh + r;
  883. }
  884. }
  885. function collide(p, r){
  886. for (const f of FURN) resolveRect(p, f.x, f.y, f.w, f.d, r);
  887. for (const w of WALLS) resolveRect(p, w.x, w.y, w.w, w.h, r);
  888. p.x = clamp(p.x, r, WORLD_W - r);
  889. p.y = clamp(p.y, r, WORLD_D - r);
  890. }
  891. function isBlocked(x, y, r){
  892. 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;
  893. 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;
  894. if (x < r || x > WORLD_W - r || y < r || y > WORLD_D - r) return true;
  895. return false;
  896. }
  897. function roomAt(x, y){
  898. for (const r of ROOMS) if (x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h) return r;
  899. return null;
  900. }
  901. function findRoomPath(fromRoom, toRoom){
  902. if (!fromRoom || !toRoom) return null;
  903. if (fromRoom === toRoom) return [fromRoom];
  904. const grid = new Map();
  905. for (const r of ROOMS) grid.set(r.r + ',' + r.c, r);
  906. const startKey = fromRoom.r + ',' + fromRoom.c;
  907. const goalKey = toRoom.r + ',' + toRoom.c;
  908. if (!grid.has(startKey) || !grid.has(goalKey)) return null;
  909. const queue = [startKey];
  910. const came = new Map(); came.set(startKey, null);
  911. const dirs = [[0,1],[0,-1],[1,0],[-1,0]];
  912. while (queue.length){
  913. const cur = queue.shift();
  914. if (cur === goalKey) break;
  915. const parts = cur.split(','); const cr = +parts[0], cc = +parts[1];
  916. for (const [dr, dc] of dirs){
  917. const nk = (cr + dr) + ',' + (cc + dc);
  918. if (!grid.has(nk) || came.has(nk)) continue;
  919. came.set(nk, cur); queue.push(nk);
  920. }
  921. }
  922. if (!came.has(goalKey)) return null;
  923. const path = [];
  924. let cur = goalKey;
  925. while (cur !== null){ path.unshift(grid.get(cur)); cur = came.get(cur); }
  926. return path;
  927. }
  928. function doorBetween(a, b){
  929. if (a.c === b.c - 1) return {x: a.x + a.w + T/2, y: a.y + a.h/2};
  930. if (a.c === b.c + 1) return {x: a.x - T/2, y: a.y + a.h/2};
  931. if (a.r === b.r - 1) return {x: a.x + a.w/2, y: a.y + a.h + T/2};
  932. if (a.r === b.r + 1) return {x: a.x + a.w/2, y: a.y - T/2};
  933. return null;
  934. }
  935. function buildBotPath(bot, tx, ty){
  936. const fromRoom = roomAt(bot.x, bot.y);
  937. const toRoom = roomAt(tx, ty);
  938. if (!fromRoom || !toRoom){ bot.waypoints = null; bot.wpIdx = 0; bot.targetX = tx; bot.targetY = ty; return; }
  939. const path = findRoomPath(fromRoom, toRoom);
  940. if (!path || path.length === 0){ bot.waypoints = null; bot.wpIdx = 0; bot.targetX = tx; bot.targetY = ty; return; }
  941. const wps = [];
  942. for (let i = 0; i < path.length - 1; i++){
  943. const d = doorBetween(path[i], path[i+1]);
  944. if (d) wps.push(d);
  945. }
  946. wps.push({x: tx, y: ty});
  947. bot.waypoints = wps;
  948. bot.wpIdx = 0;
  949. bot.targetX = wps[0].x; bot.targetY = wps[0].y;
  950. }
  951. const FURN_SPRITES = {};
  952. function buildFurnitureSprites(){
  953. for (const kind in FURN_SIZES) if (FURN_COLOR[kind]) buildFurnitureSprite(kind);
  954. }
  955. function buildFurnitureSprite(kind){
  956. const sz = FURN_SIZES[kind], col = FURN_COLOR[kind];
  957. if (!sz || !col) return;
  958. const d = sz.d * DEPTH;
  959. const hPx = sz.h * DEPTH;
  960. const pad = 20;
  961. const cw = sz.w + pad*2, ch = d + hPx + pad*2;
  962. const canvas = document.createElement('canvas');
  963. canvas.width = cw; canvas.height = ch;
  964. const c = canvas.getContext('2d');
  965. c.translate(pad, pad);
  966. const shGrad = c.createRadialGradient(sz.w/2, d + hPx, 2, sz.w/2, d + hPx, Math.max(sz.w, hPx)*0.7);
  967. shGrad.addColorStop(0, 'rgba(0,0,0,.55)');
  968. shGrad.addColorStop(1, 'rgba(0,0,0,0)');
  969. c.fillStyle = shGrad;
  970. 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();
  971. const frontGrad = c.createLinearGradient(0, d, 0, d + hPx);
  972. frontGrad.addColorStop(0, col.f); frontGrad.addColorStop(1, col.fD);
  973. c.fillStyle = frontGrad; c.fillRect(0, d, sz.w, hPx);
  974. const topGrad = c.createLinearGradient(0, 0, 0, d);
  975. topGrad.addColorStop(0, col.t); topGrad.addColorStop(1, col.tL);
  976. c.fillStyle = topGrad; c.fillRect(0, 0, sz.w, d);
  977. c.fillStyle = 'rgba(255,255,255,.35)'; c.fillRect(0, 0, sz.w, 1);
  978. c.fillStyle = 'rgba(0,0,0,.4)'; c.fillRect(0, d + hPx - 2, sz.w, 2);
  979. c.fillStyle = 'rgba(0,0,0,.25)'; c.fillRect(sz.w - 1, 0, 1, d + hPx);
  980. decorateFurniture(c, kind, sz.w, d, hPx, col);
  981. FURN_SPRITES[kind] = {canvas, pad, w:cw, h:ch};
  982. }
  983. function decorateFurniture(c, kind, w, d, hPx, col){
  984. const cx = w/2;
  985. if (kind === 'desk' || kind === 'bigtable'){
  986. const mw = Math.min(56, w*0.3), mh = 20;
  987. c.fillStyle = '#0a0a14'; c.fillRect(cx-mw/2-1, d*0.15-1, mw+2, mh+2);
  988. c.fillStyle = '#58a6ff'; c.fillRect(cx-mw/2, d*0.15, mw, mh);
  989. c.fillStyle = 'rgba(255,255,255,.3)'; c.fillRect(cx-mw/2+2, d*0.15+2, (mw-4)*0.7, 1);
  990. c.fillStyle = '#1a1a2a'; c.fillRect(cx-20, d*0.65, 40, 5);
  991. } else if (kind === 'rack'){
  992. for (let i = 0; i < 8; i++){
  993. const uy = d*0.3 + i*(hPx*0.65/8);
  994. c.fillStyle = '#0a0a14'; c.fillRect(4, uy, w - 8, hPx*0.65/8 - 2);
  995. c.fillStyle = i % 2 === 0 ? '#4ade80' : '#1e4a28'; c.fillRect(w - 10, uy + 2, 3, 3);
  996. c.fillStyle = i % 3 === 0 ? '#58a6ff' : '#1e3a5a'; c.fillRect(w - 15, uy + 2, 3, 3);
  997. }
  998. } else if (kind === 'shelf'){
  999. for (let s = 0; s < 4; s++){
  1000. const sy = d*0.15 + (hPx*0.65/4)*s;
  1001. const sh = hPx*0.65/4 - 3;
  1002. c.fillStyle = 'rgba(0,0,0,.5)'; c.fillRect(3, sy, w - 6, sh);
  1003. const bookColors = ['#c73a3a','#3a6ac7','#c7a83a','#4ade80','#c73a8a','#6ac7b8','#d89a48'];
  1004. let bx = 5;
  1005. while (bx < w - 8){
  1006. const bw = 3 + Math.random()*2.5, bh = sh * (0.55 + Math.random()*0.4);
  1007. c.fillStyle = bookColors[Math.floor(Math.random()*bookColors.length)];
  1008. c.fillRect(bx, sy + sh - bh + 1, bw, bh - 1);
  1009. bx += bw + 1;
  1010. }
  1011. }
  1012. } else if (kind === 'safe'){
  1013. c.fillStyle = '#1a2028'; c.fillRect(4, d*0.3, w - 8, hPx*0.5);
  1014. c.fillStyle = '#c0a080'; c.beginPath(); c.arc(cx, d*0.35 + hPx*0.2, 6, 0, 7); c.fill();
  1015. c.strokeStyle = '#0a0a10'; c.lineWidth = 2; c.beginPath(); c.arc(cx, d*0.35 + hPx*0.2, 6, 0, 7); c.stroke();
  1016. c.fillStyle = '#8a8a92'; c.fillRect(w - 16, d*0.35 + hPx*0.35, 10, 3);
  1017. } else if (kind === 'camwall'){
  1018. const cols = 3, rows = 2, gp = 4;
  1019. const mw2 = (w - gp*(cols+1)) / cols;
  1020. const mh2 = (d - gp*(rows+1)) / rows;
  1021. const screenCols = ['#2a4a3a','#3a2a2a','#2a3a4a','#3a3a2a','#2a3a3a','#3a2a3a'];
  1022. for (let r2 = 0; r2 < rows; r2++) for (let c2 = 0; c2 < cols; c2++){
  1023. const mx2 = gp + c2*(mw2+gp), my2 = gp + r2*(mh2+gp);
  1024. c.fillStyle = '#0a1018'; c.fillRect(mx2-1, my2-1, mw2+2, mh2+2);
  1025. c.fillStyle = screenCols[r2*cols+c2]; c.fillRect(mx2, my2, mw2, mh2);
  1026. c.fillStyle = 'rgba(255,255,255,.5)';
  1027. c.fillRect(mx2+3, my2+4, (mw2-6)*0.6, 1); c.fillRect(mx2+3, my2+7, (mw2-6)*0.35, 1);
  1028. c.fillStyle = '#f85149'; c.beginPath(); c.arc(mx2+mw2-5, my2+5, 2, 0, 7); c.fill();
  1029. }
  1030. }
  1031. }
  1032. const staticCanvas = document.createElement('canvas');
  1033. const staticCtx = staticCanvas.getContext('2d', {alpha:false});
  1034. let staticReady = false;
  1035. let minimapBg = null;
  1036. function drawRoomFloor(c, r){
  1037. const x1 = r.x, y1 = r.y * DEPTH, w = r.w, h = r.h * DEPTH;
  1038. c.fillStyle = r.floor[0]; c.fillRect(x1, y1, w, h);
  1039. if (r.pattern === 'grid'){
  1040. c.strokeStyle = 'rgba(120,180,255,.10)'; c.lineWidth = 1;
  1041. for (let gx = 0; gx < r.w; gx += 60){ c.beginPath(); c.moveTo(x1+gx, y1); c.lineTo(x1+gx, y1+h); c.stroke(); }
  1042. 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(); }
  1043. } else if (r.pattern === 'wood'){
  1044. c.strokeStyle = 'rgba(180,140,90,.10)';
  1045. 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(); }
  1046. } else if (r.pattern === 'carpet'){
  1047. c.fillStyle = 'rgba(180,60,60,.10)'; c.fillRect(x1+40, y1+40, w-80, h-80);
  1048. c.strokeStyle = 'rgba(255,180,180,.20)'; c.lineWidth = 2; c.strokeRect(x1+40, y1+40, w-80, h-80);
  1049. } else if (r.pattern === 'tiles'){
  1050. for (let gx = 0; gx < r.w; gx += 90) for (let gy = 0; gy < r.h; gy += 90){
  1051. const px = r.x+gx, py = (r.y+gy)*DEPTH;
  1052. const odd = ((gx/90+gy/90)|0)%2;
  1053. c.fillStyle = odd ? 'rgba(120,180,255,.06)' : 'rgba(255,255,255,.02)';
  1054. c.fillRect(px, py, 90, 90*DEPTH);
  1055. }
  1056. }
  1057. const g = c.createLinearGradient(0, y1, 0, y1+h);
  1058. g.addColorStop(0, 'rgba(255,255,255,.04)'); g.addColorStop(1, 'rgba(0,0,0,.20)');
  1059. c.fillStyle = g; c.fillRect(x1, y1, w, h);
  1060. c.font = 'bold 15px "Segoe UI",sans-serif'; c.textAlign = 'center'; c.textBaseline = 'top';
  1061. c.fillStyle = r.accent + 'cc';
  1062. c.fillText((r.isSoc ? '★ ' : '◄ ') + r.name.toUpperCase() + ' ►', x1 + w/2, y1 + 12);
  1063. }
  1064. function drawWallStatic(c, w){
  1065. const x1 = w.x, yF = w.y * DEPTH, ww = w.w, wh = w.h * DEPTH;
  1066. c.fillStyle = 'rgba(0,0,0,.55)'; c.fillRect(x1+3, yF+wh, ww, 5);
  1067. c.fillStyle = '#3a4d70'; c.fillRect(x1, yF-26, ww, wh);
  1068. c.fillStyle = '#8ea9d4'; c.fillRect(x1, yF-26, ww, 3);
  1069. c.fillStyle = '#b8ccec'; c.fillRect(x1, yF-26, ww, 1);
  1070. c.fillStyle = '#080d14'; c.fillRect(x1, yF+wh-26, ww, 26);
  1071. c.strokeStyle = 'rgba(0,0,0,.75)'; c.lineWidth = 1;
  1072. c.strokeRect(x1+0.5, yF-25.5, ww-1, wh-1);
  1073. c.strokeRect(x1+0.5, yF+wh-25.5, ww-1, 25);
  1074. }
  1075. function drawDoorStatic(c, d){
  1076. const x1 = d.x, y1 = d.y * DEPTH, ww = d.w, wh = d.h * DEPTH;
  1077. c.fillStyle = 'rgba(255,209,102,.35)'; c.fillRect(x1, y1, ww, wh);
  1078. c.strokeStyle = '#ffd166'; c.lineWidth = 2; c.strokeRect(x1+1, y1+1, ww-2, wh-2);
  1079. c.strokeStyle = '#ffd166'; c.lineWidth = 3; c.lineCap = 'round';
  1080. const cx = x1+ww/2, cy = y1+wh/2;
  1081. if (d.dir === 'h'){
  1082. c.beginPath(); c.moveTo(cx-12, cy-8); c.lineTo(cx-4, cy); c.lineTo(cx-12, cy+8); c.stroke();
  1083. c.beginPath(); c.moveTo(cx+12, cy-8); c.lineTo(cx+4, cy); c.lineTo(cx+12, cy+8); c.stroke();
  1084. } else {
  1085. c.beginPath(); c.moveTo(cx-8, cy-12); c.lineTo(cx, cy-4); c.lineTo(cx+8, cy-12); c.stroke();
  1086. c.beginPath(); c.moveTo(cx-8, cy+12); c.lineTo(cx, cy+4); c.lineTo(cx+8, cy+12); c.stroke();
  1087. }
  1088. }
  1089. function buildStaticLayer(){
  1090. try {
  1091. staticCtx.fillStyle = '#03050b';
  1092. staticCtx.fillRect(0, 0, staticCanvas.width, staticCanvas.height);
  1093. for (const r of ROOMS) drawRoomFloor(staticCtx, r);
  1094. for (const w of WALLS) drawWallStatic(staticCtx, w);
  1095. for (const d of DOORS) drawDoorStatic(staticCtx, d);
  1096. staticReady = true;
  1097. } catch(e){ staticReady = false; }
  1098. }
  1099. function updateCamera(){
  1100. camX = clamp(player.x - W/2, 0, Math.max(0, WORLD_W - W));
  1101. camY = clamp(player.y * DEPTH - H/2, 0, Math.max(0, WORLD_D * DEPTH - H));
  1102. }
  1103. function trySpawnBotInRoom(bot, room){
  1104. const pad = 100;
  1105. for (let t = 0; t < 150; t++){
  1106. const x = room.x + pad + Math.random() * (room.w - pad*2);
  1107. const y = room.y + pad + Math.random() * (room.h - pad*2);
  1108. if (!isBlocked(x, y, bot.r + 4)){
  1109. bot.x = x; bot.y = y;
  1110. collide(bot, bot.r);
  1111. if (Math.abs(bot.x - x) < 40 && Math.abs(bot.y - y) < 40) return true;
  1112. }
  1113. }
  1114. return false;
  1115. }
  1116. function spawnBots(){
  1117. bots.length = 0;
  1118. const count = currentDiff.botCount || 4;
  1119. const names = shuffle(BOT_NAMES.slice()).slice(0, count);
  1120. const colors = shuffle(BOT_COLORS.slice()).slice(0, count);
  1121. const spawnRooms = ROOMS.filter(r => !r.isSoc);
  1122. shuffle(spawnRooms);
  1123. for (let i = 0; i < count; i++){
  1124. const bot = {
  1125. x:0, y:0, r:15, name: names[i], color: colors[i],
  1126. dir:1, speed: rand(55, 80),
  1127. targetX:0, targetY:0, waypoints: null, wpIdx: 0,
  1128. waitTimer: rand(0.5, 2),
  1129. state: 'wander', suspectTimer: 0, isSuspect: false, isCaught: false,
  1130. sabotageTarget: null, lastX: 0, lastY: 0, stuckTimer: 0
  1131. };
  1132. const room = spawnRooms.length > 0 ? spawnRooms[i % spawnRooms.length] : socRoom;
  1133. let ok = trySpawnBotInRoom(bot, room);
  1134. if (!ok){ for (const r of spawnRooms){ if (trySpawnBotInRoom(bot, r)){ ok = true; break; } } }
  1135. if (!ok) trySpawnBotInRoom(bot, socRoom);
  1136. bot.lastX = bot.x; bot.lastY = bot.y;
  1137. pickBotTarget(bot);
  1138. bots.push(bot);
  1139. }
  1140. }
  1141. function pickBotTarget(bot){
  1142. const rooms = ROOMS.filter(r => !r.isSoc);
  1143. const room = rooms.length > 0 ? rooms[Math.floor(Math.random() * rooms.length)] : socRoom;
  1144. for (let t = 0; t < 25; t++){
  1145. const tx = room.x + 80 + Math.random() * (room.w - 160);
  1146. const ty = room.y + 80 + Math.random() * (room.h - 160);
  1147. if (!isBlocked(tx, ty, bot.r + 6)){ buildBotPath(bot, tx, ty); return; }
  1148. }
  1149. buildBotPath(bot, room.x + room.w/2, room.y + room.h/2);
  1150. }
  1151. function botPickNextAction(bot){
  1152. const roll = Math.random();
  1153. let sabChance = currentDiff.botSabotage || 0.3;
  1154. let leakChance = currentDiff.botLeak || 0.2;
  1155. if (bot.isSuspect){ sabChance *= 0.3; leakChance *= 0.3; }
  1156. if (roll < sabChance){
  1157. const taskTypes = waveTasks.filter(w => w.done < w.need).map(w => w.type);
  1158. const pool = taskTypes.length > 0 ? taskTypes : waveTasks.map(w => w.type);
  1159. if (pool.length > 0){
  1160. const type = pool[Math.floor(Math.random() * pool.length)];
  1161. const def = INCIDENTS[type];
  1162. const available = FURN.filter(f => f.tags && f.tags.includes(def.tag) && !incidents.some(i => i.f === f));
  1163. if (available.length){
  1164. const f = available[Math.floor(Math.random() * available.length)];
  1165. bot.state = 'sabotage';
  1166. bot.sabotageTarget = f;
  1167. buildBotPath(bot, f.x + f.w/2, f.y + f.d + 30);
  1168. bot.isSuspect = true;
  1169. bot.suspectTimer = 0;
  1170. return true;
  1171. }
  1172. }
  1173. } else if (roll < sabChance + leakChance){
  1174. if (exitTile){
  1175. bot.state = 'leak';
  1176. buildBotPath(bot, exitTile.x, exitTile.y);
  1177. bot.isSuspect = true;
  1178. bot.suspectTimer = 0;
  1179. return true;
  1180. }
  1181. }
  1182. bot.state = 'wander';
  1183. bot.isSuspect = false;
  1184. pickBotTarget(bot);
  1185. return false;
  1186. }
  1187. function updateBots(dt){
  1188. for (const bot of bots){
  1189. if (bot.isCaught) continue;
  1190. if (bot.waitTimer > 0){ bot.waitTimer -= dt; continue; }
  1191. const dx = bot.targetX - bot.x, dy = bot.targetY - bot.y;
  1192. const d = Math.hypot(dx, dy);
  1193. if (d < 12){
  1194. if (bot.waypoints && bot.wpIdx !== undefined && bot.wpIdx < bot.waypoints.length - 1){
  1195. bot.wpIdx++;
  1196. const wp = bot.waypoints[bot.wpIdx];
  1197. bot.targetX = wp.x; bot.targetY = wp.y;
  1198. continue;
  1199. }
  1200. bot.waypoints = null; bot.wpIdx = 0;
  1201. if (bot.state === 'sabotage' && bot.sabotageTarget){
  1202. const f = bot.sabotageTarget;
  1203. const typePool = f.tags.filter(t => INCIDENTS[t] && waveTasks.some(w => w.type === t) && !incidents.some(i => i.type === t && i.f === f));
  1204. if (typePool.length && !incidents.some(i => i.f === f)){
  1205. const type = typePool[Math.floor(Math.random() * typePool.length)];
  1206. const life = currentDiff.shifts[currentShift].time;
  1207. 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 });
  1208. spawnedInShift++;
  1209. shiftSpawnTimer = rand(3, 5);
  1210. addLog('⚠ Саботаж: ' + bot.name + ' · ' + INCIDENTS[type].label, 'warn');
  1211. toast('🕵️ ' + bot.name + ' саботирует: ' + INCIDENTS[type].label, 'bad');
  1212. soundAlert();
  1213. }
  1214. bot.state = 'wander'; bot.sabotageTarget = null;
  1215. bot.isSuspect = false;
  1216. bot.waitTimer = rand(2, 5);
  1217. botPickNextAction(bot);
  1218. } else if (bot.state === 'leak'){
  1219. leaks++; statsAch.shiftErrors++;
  1220. updateHUD();
  1221. addLog('✗ ' + bot.name + ' слил данные!', 'bad');
  1222. toast('💀 ' + bot.name + ' сливает данные!', 'bad');
  1223. dispatch('Утечка данных сотрудником ' + bot.name + '!');
  1224. bot.state = 'wander'; bot.isSuspect = false;
  1225. bot.waitTimer = rand(3, 7);
  1226. botPickNextAction(bot);
  1227. if (leaks >= currentDiff.leaksMax) endGame(false);
  1228. } else {
  1229. bot.waitTimer = rand(0.5, 2);
  1230. botPickNextAction(bot);
  1231. }
  1232. continue;
  1233. }
  1234. const step = bot.speed * dt;
  1235. bot.x += (dx/d) * step;
  1236. bot.y += (dy/d) * step;
  1237. collide(bot, bot.r);
  1238. bot.dir = dx > 0 ? 1 : -1;
  1239. const moved = Math.hypot(bot.x - bot.lastX, bot.y - bot.lastY);
  1240. if (moved < 0.5){
  1241. bot.stuckTimer += dt;
  1242. if (bot.stuckTimer > 1.5){
  1243. bot.stuckTimer = 0;
  1244. if (bot.state === 'sabotage' && bot.sabotageTarget){
  1245. buildBotPath(bot, bot.sabotageTarget.x + bot.sabotageTarget.w/2, bot.sabotageTarget.y + bot.sabotageTarget.d + 30);
  1246. } else if (bot.state === 'leak' && exitTile){
  1247. buildBotPath(bot, exitTile.x, exitTile.y);
  1248. } else pickBotTarget(bot);
  1249. }
  1250. } else bot.stuckTimer = 0;
  1251. bot.lastX = bot.x; bot.lastY = bot.y;
  1252. if (bot.isSuspect) bot.suspectTimer += dt;
  1253. }
  1254. }
  1255. let camFrame = 0;
  1256. function initCameras(){
  1257. camBufs = []; camRooms = ROOMS.slice();
  1258. for (let i = 0; i < camRooms.length; i++){
  1259. const buf = document.createElement('canvas');
  1260. buf.width = 240; buf.height = 150;
  1261. camBufs.push(buf);
  1262. }
  1263. if (activeCameraIdx >= camRooms.length) activeCameraIdx = 0;
  1264. buildCamGrid();
  1265. }
  1266. function buildCamGrid(){
  1267. if (!el.camGrid) return;
  1268. el.camGrid.innerHTML = '';
  1269. for (let i = 0; i < camRooms.length; i++){
  1270. const cell = document.createElement('div');
  1271. cell.className = 'camCell' + (i === activeCameraIdx ? ' active' : '');
  1272. const cam = camRooms[i];
  1273. const shortName = cam.name.length > 18 ? cam.name.slice(0, 16) + '…' : cam.name;
  1274. const lbl = document.createElement('div'); lbl.className = 'camLabel'; lbl.textContent = 'CAM ' + String(i+1).padStart(2, '0');
  1275. const rm = document.createElement('div'); rm.className = 'camRoom'; rm.textContent = (cam.isSoc ? '★ ' : '') + shortName;
  1276. const cnv = document.createElement('canvas'); cnv.width = 240; cnv.height = 150;
  1277. const al = document.createElement('div'); al.className = 'camAlert'; al.style.display = 'none'; al.textContent = '⚠ НАРУШЕНИЕ';
  1278. cell.appendChild(lbl); cell.appendChild(rm); cell.appendChild(cnv); cell.appendChild(al);
  1279. cell.onclick = () => { activeCameraIdx = i; buildCamGrid(); updateCamInfo(); };
  1280. el.camGrid.appendChild(cell);
  1281. }
  1282. updateCamInfo();
  1283. }
  1284. function updateCamInfo(){
  1285. const cam = camRooms[activeCameraIdx];
  1286. const suspects = bots.filter(b => !b.isCaught && b.isSuspect).length;
  1287. if (el.camBotsCount) el.camBotsCount.textContent = camRooms.length;
  1288. if (el.camSusCount) el.camSusCount.textContent = suspects;
  1289. if (el.camCaughtCount) el.camCaughtCount.textContent = caughtThisShift + ' / ' + totalCaught;
  1290. if (!cam){ if (el.camInfo) el.camInfo.textContent = 'Нет камер'; if (el.camReport) el.camReport.disabled = true; return; }
  1291. const susInCam = bots.find(b => !b.isCaught && b.isSuspect && roomAt(b.x, b.y) === cam);
  1292. if (susInCam){
  1293. if (el.camInfo) el.camInfo.textContent = '⚠ ' + cam.name + ' · ' + susInCam.name + ' (' + (susInCam.state === 'sabotage' ? 'саботаж' : susInCam.state === 'leak' ? 'слив' : 'подозрение') + ')';
  1294. if (el.camReport) el.camReport.disabled = false;
  1295. } else {
  1296. const hereBots = bots.filter(b => !b.isCaught && roomAt(b.x, b.y) === cam).length;
  1297. if (el.camInfo) el.camInfo.textContent = cam.name + ' · сотрудников: ' + hereBots;
  1298. if (el.camReport) el.camReport.disabled = true;
  1299. }
  1300. }
  1301. function drawCameras(){
  1302. if (!cameraOpen) return;
  1303. camFrame++;
  1304. for (let i = 0; i < camRooms.length; i++){
  1305. const isActive = i === activeCameraIdx;
  1306. if (!isActive && camFrame % 3 !== 0) continue;
  1307. const room = camRooms[i], buf = camBufs[i];
  1308. if (!buf) continue;
  1309. const bctx = buf.getContext('2d');
  1310. bctx.fillStyle = room.floor[0]; bctx.fillRect(0, 0, buf.width, buf.height);
  1311. bctx.strokeStyle = 'rgba(120,180,255,.08)'; bctx.lineWidth = 1;
  1312. for (let gx = 0; gx < buf.width; gx += 24){ bctx.beginPath(); bctx.moveTo(gx, 0); bctx.lineTo(gx, buf.height); bctx.stroke(); }
  1313. for (let gy = 0; gy < buf.height; gy += 24){ bctx.beginPath(); bctx.moveTo(0, gy); bctx.lineTo(buf.width, gy); bctx.stroke(); }
  1314. const scX = buf.width / room.w, scY = buf.height / room.h;
  1315. for (const f of FURN){
  1316. if (f.x + f.w < room.x || f.x > room.x + room.w) continue;
  1317. if (f.y + f.d < room.y || f.y > room.y + room.h) continue;
  1318. const rx = (f.x - room.x) * scX, ry = (f.y - room.y) * scY;
  1319. const rw = Math.max(3, f.w * scX), rh = Math.max(3, f.d * scY);
  1320. bctx.fillStyle = f.kind === 'camwall' ? '#1a3a1a' : '#3a4d70';
  1321. bctx.fillRect(rx, ry, rw, rh);
  1322. bctx.strokeStyle = f.kind === 'camwall' ? '#4ade80' : '#8ea9d4'; bctx.lineWidth = 1;
  1323. bctx.strokeRect(rx + 0.5, ry + 0.5, rw - 1, rh - 1);
  1324. }
  1325. for (const inc of incidents){
  1326. if (inc.x < room.x || inc.x > room.x + room.w) continue;
  1327. if (inc.y < room.y || inc.y > room.y + room.h) continue;
  1328. const rx = (inc.x - room.x) * scX, ry = (inc.y - room.y) * scY;
  1329. bctx.globalAlpha = 0.6 + Math.sin(time * 5) * 0.4;
  1330. bctx.fillStyle = INCIDENTS[inc.type].color;
  1331. bctx.beginPath(); bctx.arc(rx, ry, 7, 0, 7); bctx.fill();
  1332. bctx.globalAlpha = 1;
  1333. }
  1334. for (const bot of bots){
  1335. if (bot.isCaught) continue;
  1336. if (bot.x < room.x || bot.x > room.x + room.w) continue;
  1337. if (bot.y < room.y || bot.y > room.y + room.h) continue;
  1338. const rx = (bot.x - room.x) * scX, ry = (bot.y - room.y) * scY;
  1339. if (bot.isSuspect){
  1340. bctx.globalAlpha = 0.4 + Math.sin(time * 8) * 0.35;
  1341. bctx.fillStyle = '#ff3030'; bctx.beginPath(); bctx.arc(rx, ry, 13, 0, 7); bctx.fill();
  1342. bctx.globalAlpha = 1;
  1343. }
  1344. bctx.fillStyle = bot.color; bctx.beginPath(); bctx.arc(rx, ry, 6, 0, 7); bctx.fill();
  1345. bctx.strokeStyle = bot.isSuspect ? '#ff3030' : '#000'; bctx.lineWidth = 2; bctx.stroke();
  1346. bctx.fillStyle = bot.isSuspect ? '#ff8080' : '#fff';
  1347. bctx.font = 'bold 9px "Segoe UI",sans-serif'; bctx.textAlign = 'center'; bctx.textBaseline = 'bottom';
  1348. bctx.fillText(bot.name, rx, ry - 9);
  1349. if (bot.state === 'sabotage') bctx.fillText('🔧', rx + 12, ry + 4);
  1350. else if (bot.state === 'leak') bctx.fillText('📤', rx + 12, ry + 4);
  1351. }
  1352. if (player.x >= room.x && player.x <= room.x + room.w && player.y >= room.y && player.y <= room.y + room.h){
  1353. const rx = (player.x - room.x) * scX, ry = (player.y - room.y) * scY;
  1354. bctx.fillStyle = '#fff'; bctx.beginPath(); bctx.arc(rx, ry, 7, 0, 7); bctx.fill();
  1355. bctx.strokeStyle = '#4ea1ff'; bctx.lineWidth = 2; bctx.stroke();
  1356. bctx.fillStyle = '#8ee7ff'; bctx.font = 'bold 9px "Segoe UI",sans-serif'; bctx.textAlign = 'center'; bctx.textBaseline = 'bottom';
  1357. bctx.fillText('ВЫ', rx, ry - 9);
  1358. }
  1359. bctx.fillStyle = 'rgba(0,0,0,.06)';
  1360. for (let y = 0; y < buf.height; y += 3) bctx.fillRect(0, y, buf.width, 1);
  1361. const cell = el.camGrid.children[i];
  1362. if (cell){
  1363. const cc = cell.querySelector('canvas');
  1364. if (cc){ const c2 = cc.getContext('2d'); c2.clearRect(0, 0, cc.width, cc.height); c2.drawImage(buf, 0, 0, cc.width, cc.height); }
  1365. const alert = cell.querySelector('.camAlert');
  1366. if (alert) alert.style.display = bots.some(b => !b.isCaught && b.isSuspect && roomAt(b.x, b.y) === room) ? 'block' : 'none';
  1367. }
  1368. }
  1369. }
  1370. function openCameraView(){
  1371. if (!socRoom) return;
  1372. const here = roomAt(player.x, player.y);
  1373. if (!here || !here.isSoc){ showHint('Камеры доступны только в SOC', 3000); return; }
  1374. cameraOpen = true; state = 'camera';
  1375. hideAll(); showScreen('camera');
  1376. buildCamGrid(); updateCamInfo(); updateMobileVisibility();
  1377. }
  1378. function closeCameraView(){
  1379. cameraOpen = false; state = 'playing'; hideAll();
  1380. el.hud.classList.remove('hide');
  1381. el.taskPanel.classList.add('show'); el.logPanel.classList.add('show'); el.minimap.classList.add('show');
  1382. refreshAchievementHUD(); updateMobileVisibility(); focusStage();
  1383. }
  1384. function reportSuspect(){
  1385. const cam = camRooms[activeCameraIdx];
  1386. if (!cam){ showHint('Нет камеры', 2000); return; }
  1387. const sus = bots.find(b => !b.isCaught && b.isSuspect && roomAt(b.x, b.y) === cam);
  1388. if (!sus){ showHint('На этой камере никого не подозревают', 2500); return; }
  1389. const wasLeak = sus.state === 'leak', wasSab = sus.state === 'sabotage';
  1390. sus.isCaught = true; sus.isSuspect = false; sus.state = 'caught';
  1391. caughtCount++; caughtThisShift++; totalCaught++;
  1392. statsAch.totalCaught = totalCaught;
  1393. score += 60;
  1394. addLog('✓ Поймали: ' + sus.name + ' (+60)', 'ok');
  1395. toast('✓ Поймали: ' + sus.name, 'ok');
  1396. if (wasLeak){ addLog('🛡 Предотвращена утечка', 'ok'); toast('🛡 Утечка предотвращена!', 'ok'); }
  1397. if (wasSab){ addLog('🛡 Предотвращён саботаж', 'ok'); }
  1398. updateHUD(); updateCamInfo(); soundCaught(); checkAchievements(statsAch);
  1399. }
  1400. const particlePool = [];
  1401. function getParticle(){ return particlePool.length > 0 ? particlePool.pop() : {}; }
  1402. function releaseParticle(p){ if (particlePool.length < 100) particlePool.push(p); }
  1403. function burst(wx, wy, color, n, spd){
  1404. spd = spd || 1; n = Math.min(n, 10);
  1405. for (let i = 0; i < n; i++){
  1406. const a = Math.random() * Math.PI * 2, s = rand(40, 180) * spd;
  1407. const p = getParticle();
  1408. p.x = wx; p.y = wy; p.z = rand(20, 70);
  1409. p.vx = Math.cos(a)*s; p.vy = Math.sin(a)*s; p.vz = rand(50, 180);
  1410. p.life = 0.75; p.color = color; p.size = rand(2, 4);
  1411. particles.push(p);
  1412. }
  1413. }
  1414. function toast(text, type){
  1415. const w = Math.min(600, text.length * 8 + 34);
  1416. toasts.push({text, type: type || 'ok', life: 4, w});
  1417. if (toasts.length > 3) toasts.shift();
  1418. }
  1419. function nearestIncident(){
  1420. let best = null, bd = Infinity;
  1421. for (const inc of incidents){
  1422. const dx = Math.max(inc.f.x - player.x, 0, player.x - (inc.f.x + inc.f.w));
  1423. const dy = Math.max(inc.f.y - player.y, 0, player.y - (inc.f.y + inc.f.d));
  1424. const d = Math.hypot(dx, dy);
  1425. if (d < bd){ bd = d; best = inc; }
  1426. }
  1427. return {inc: best, d: bd};
  1428. }
  1429. function fixIncident(inc){
  1430. const def = INCIDENTS[inc.type];
  1431. const bonus = Math.round(inc.timeLeft);
  1432. score += 20 + bonus; fixedCount++;
  1433. if (statsAch.shiftErrors === 0) statsAch.fixedNoErrors++;
  1434. const i = incidents.indexOf(inc);
  1435. if (i >= 0) incidents.splice(i, 1);
  1436. const wt = waveTasks.find(w => w.type === inc.type);
  1437. if (wt && wt.done < wt.need) wt.done++;
  1438. burst(inc.x, inc.y, def.color, 10);
  1439. addLog('✓ Закрыто: ' + def.label + ' (+' + (20 + bonus) + ')', 'ok');
  1440. toast(def.icon + ' ' + def.label + ' — закрыт', 'ok');
  1441. updateHUD(); updateTaskUI(); soundOk();
  1442. }
  1443. function leakIncident(inc){
  1444. const def = INCIDENTS[inc.type];
  1445. leaks++; statsAch.shiftErrors++;
  1446. score = Math.max(0, score - 15);
  1447. const i = incidents.indexOf(inc);
  1448. if (i >= 0) incidents.splice(i, 1);
  1449. burst(inc.x, inc.y, '#ff3030', 14, 1.3);
  1450. addLog('✗ УТЕЧКА: ' + def.label, 'bad');
  1451. toast('💀 Утечка: ' + def.label, 'bad');
  1452. updateHUD(); soundAlert();
  1453. dispatch('Внимание! Утечка: ' + def.label);
  1454. if (leaks >= currentDiff.leaksMax) endGame(false);
  1455. }
  1456. let _lastHud = {score:-1, wave:'', fixed:-1, leaks:'', caught:-1, high:-1};
  1457. function updateHUD(){
  1458. if (!el.hudScore) return;
  1459. if (_lastHud.score !== score){ el.hudScore.textContent = score; _lastHud.score = score; }
  1460. const wv = (currentShift + 1) + ' / ' + currentDiff.shifts.length;
  1461. if (_lastHud.wave !== wv){ el.hudWave.textContent = wv; _lastHud.wave = wv; }
  1462. if (_lastHud.fixed !== fixedCount){ el.hudFixed.textContent = fixedCount; _lastHud.fixed = fixedCount; }
  1463. const lk = leaks + ' / ' + currentDiff.leaksMax;
  1464. if (_lastHud.leaks !== lk){
  1465. el.hudLeaks.textContent = lk;
  1466. el.hudLeaks.style.color = leaks >= currentDiff.leaksMax - 1 ? '#ff6b6b' : '#ff8a8a';
  1467. _lastHud.leaks = lk;
  1468. }
  1469. if (_lastHud.caught !== caughtThisShift){ el.hudCaught.textContent = caughtThisShift; _lastHud.caught = caughtThisShift; }
  1470. if (_lastHud.high !== highScore){ el.hudHigh.textContent = highScore; _lastHud.high = highScore; }
  1471. }
  1472. let _lastProgPct = -1;
  1473. function updateProgressBar(){
  1474. if (!el.progFill) return;
  1475. let total = 0, done = 0;
  1476. for (const w of waveTasks){ total += w.need; done += Math.min(w.done, w.need); }
  1477. const pct = total > 0 ? Math.round((done / total) * 100) : 0;
  1478. if (pct !== _lastProgPct){ el.progFill.style.width = pct + '%'; _lastProgPct = pct; }
  1479. }
  1480. function updateTaskUI(){
  1481. if (!el.taskList) return;
  1482. el.taskList.innerHTML = '';
  1483. for (const wt of waveTasks){
  1484. const def = INCIDENTS[wt.type], done = wt.done >= wt.need;
  1485. const li = document.createElement('li');
  1486. if (done) li.className = 'done';
  1487. const s1 = document.createElement('span');
  1488. const ic = document.createElement('span'); ic.style.marginRight = '.4em'; ic.textContent = def.icon;
  1489. const nm = document.createElement('span'); nm.className = 'name'; nm.textContent = def.label;
  1490. s1.appendChild(ic); s1.appendChild(nm);
  1491. const b = document.createElement('b'); b.textContent = wt.done + '/' + wt.need;
  1492. li.appendChild(s1); li.appendChild(b);
  1493. el.taskList.appendChild(li);
  1494. }
  1495. updateProgressBar();
  1496. }
  1497. const screens = {
  1498. menu: el.mainMenuScreen, settings: el.settingsScreen, rules: el.rulesScreen,
  1499. pause: el.pauseScreen, shift: el.shiftScreen, puzzle: el.puzzleScreen,
  1500. audit: el.auditScreen, end: el.endScreen,
  1501. tutorial: el.tutorialScreen, tutdetail: el.tutDetailScreen,
  1502. tutsection: el.tutSectionScreen,
  1503. camera: el.cameraScreen, ach: el.achScreen
  1504. };
  1505. function hideAll(){ for (const k in screens) { if (screens[k]) screens[k].classList.add('hide'); } }
  1506. function showScreen(k){ if (screens[k]) screens[k].classList.remove('hide'); }
  1507. const CODE_ACTION = {
  1508. KeyW:'up', ArrowUp:'up', KeyS:'down', ArrowDown:'down',
  1509. KeyA:'left', ArrowLeft:'left', KeyD:'right', ArrowRight:'right',
  1510. KeyE:'action', Space:'action', Escape:'escape', KeyP:'pause', KeyH:'hint',
  1511. KeyF:'fullscreen', KeyM:'home', KeyC:'camera',
  1512. Enter:'enter', Backspace:'backspace', Delete:'backspace'
  1513. };
  1514. function actionFromKey(k){
  1515. if (!k) return null;
  1516. if (k === ' ' || k === 'Spacebar') return 'action';
  1517. if (k === 'ArrowUp') return 'up';
  1518. if (k === 'ArrowDown') return 'down';
  1519. if (k === 'ArrowLeft') return 'left';
  1520. if (k === 'ArrowRight') return 'right';
  1521. if (k === 'Enter') return 'enter';
  1522. if (k === 'Escape' || k === 'Esc') return 'escape';
  1523. if (k === 'Backspace' || k === 'Delete') return 'backspace';
  1524. if (/^[0-9]$/.test(k)) return k;
  1525. const low = k.toLowerCase();
  1526. if (low === 'w' || low === 'ц') return 'up';
  1527. if (low === 's' || low === 'ы') return 'down';
  1528. if (low === 'a' || low === 'ф') return 'left';
  1529. if (low === 'd' || low === 'в') return 'right';
  1530. if (low === 'e' || low === 'у') return 'action';
  1531. if (low === 'h' || low === 'р') return 'hint';
  1532. if (low === 'f' || low === 'а') return 'fullscreen';
  1533. if (low === 'p' || low === 'з') return 'pause';
  1534. if (low === 'm' || low === 'ь') return 'home';
  1535. if (low === 'c' || low === 'с') return 'camera';
  1536. return null;
  1537. }
  1538. function resolveAction(e){
  1539. if (e.code && CODE_ACTION[e.code]) return CODE_ACTION[e.code];
  1540. return actionFromKey(e.key);
  1541. }
  1542. function handleKeyDown(e){
  1543. if (state === 'puzzle' && puzzle){
  1544. if (e.key === 'Escape'){ e.preventDefault(); closePuzzle(); return; }
  1545. if (puzzleFailedActive && !demoMode){ e.preventDefault(); return; }
  1546. if (e.ctrlKey || e.metaKey || e.altKey) return;
  1547. if (e.key === 'Tab'){ e.preventDefault(); return; }
  1548. if (e.code === 'KeyC' || e.code === 'KeyM' || e.code === 'KeyP' || e.code === 'KeyH' || e.code === 'KeyF'){ e.preventDefault(); return; }
  1549. if (e.key === 'Enter' || e.key === 'Backspace'){
  1550. e.preventDefault();
  1551. if (puzzle.handleKey) puzzle.handleKey(e.key === 'Enter' ? 'enter' : 'backspace');
  1552. return;
  1553. }
  1554. if (puzzle.handleText && e.key && e.key.length === 1){ e.preventDefault(); puzzle.handleText(e.key); return; }
  1555. const action = resolveAction(e);
  1556. if (action && puzzle.handleKey){ if (puzzle.handleKey(action)) e.preventDefault(); }
  1557. return;
  1558. }
  1559. if (state === 'camera'){
  1560. if (e.key === 'Escape'){ e.preventDefault(); closeCameraView(); return; }
  1561. const action = resolveAction(e);
  1562. if (action === 'action' || action === 'enter'){ e.preventDefault(); reportSuspect(); return; }
  1563. if (action === 'camera'){ e.preventDefault(); closeCameraView(); return; }
  1564. if (/^[1-9]$/.test(action || '')){
  1565. const idx = parseInt(action, 10) - 1;
  1566. if (idx >= 0 && idx < camRooms.length){ activeCameraIdx = idx; buildCamGrid(); updateCamInfo(); }
  1567. }
  1568. return;
  1569. }
  1570. const action = resolveAction(e);
  1571. if (!action) return;
  1572. if (['up','down','left','right','action'].includes(action)) e.preventDefault();
  1573. if (action === 'camera' && !e.repeat){ openCameraView(); return; }
  1574. if (action === 'home' && !e.repeat){ exitToMenu(); return; }
  1575. if (action === 'escape'){
  1576. e.preventDefault();
  1577. if (state === 'paused'){ resumeGame(); return; }
  1578. if (state === 'playing'){ pauseGame(); return; }
  1579. if (state === 'settings' || state === 'rules' || state === 'ach'){ state = 'menu'; hideAll(); showScreen('menu'); return; }
  1580. return;
  1581. }
  1582. if (action === 'pause' && !e.repeat){
  1583. if (state === 'playing') pauseGame(); else if (state === 'paused') resumeGame();
  1584. return;
  1585. }
  1586. if (action === 'fullscreen' && !e.repeat){ toggleFullscreen(); return; }
  1587. if (action === 'hint' && !e.repeat && state !== 'paused'){ showContextHint(); return; }
  1588. if (state === 'paused') return;
  1589. if (state === 'playing'){
  1590. if (action === 'up') keys.up = true;
  1591. else if (action === 'down') keys.down = true;
  1592. else if (action === 'left') keys.left = true;
  1593. else if (action === 'right') keys.right = true;
  1594. else if (action === 'action' && !e.repeat) actionPressed = true;
  1595. }
  1596. }
  1597. function handleKeyUp(e){
  1598. const action = resolveAction(e);
  1599. if (!action) return;
  1600. if (action === 'up') keys.up = false;
  1601. else if (action === 'down') keys.down = false;
  1602. else if (action === 'left') keys.left = false;
  1603. else if (action === 'right') keys.right = false;
  1604. }
  1605. window.addEventListener('keydown', handleKeyDown, true);
  1606. window.addEventListener('keyup', handleKeyUp, true);
  1607. function focusStage(){ if (document.activeElement && document.activeElement.blur) document.activeElement.blur(); try { el.stage.focus({preventScroll:true}); } catch(e){ el.stage.focus(); } }
  1608. function toggleFullscreen(){
  1609. const e = document.getElementById('wrap') || document.documentElement;
  1610. const isFs = document.fullscreenElement || document.webkitFullscreenElement;
  1611. if (!isFs){
  1612. const req = e.requestFullscreen || e.webkitRequestFullscreen;
  1613. if (req){ try { const p = req.call(e); if (p && p.catch) p.catch(()=>{}); } catch(err){} }
  1614. } else {
  1615. const ex = document.exitFullscreen || document.webkitExitFullscreen;
  1616. if (ex){ try { const p = ex.call(document); if (p && p.catch) p.catch(()=>{}); } catch(err){} }
  1617. }
  1618. }
  1619. async function exitToMenu(){
  1620. if (state === 'menu') return;
  1621. if (state === 'tutorial' || state === 'tutdetail' || state === 'tutsection'){ demoMode = false; state = 'menu'; hideAll(); showScreen('menu'); return; }
  1622. if (state === 'camera'){ closeCameraView(); return; }
  1623. if (state === 'settings' || state === 'rules' || state === 'ach'){ state = 'menu'; hideAll(); showScreen('menu'); return; }
  1624. const needsConfirm = (state === 'playing' || state === 'puzzle' || state === 'shift' || state === 'paused' || state === 'audit');
  1625. if (needsConfirm){
  1626. const ok = await showModal('Выйти в главное меню?');
  1627. if (!ok) return;
  1628. saveGameState();
  1629. }
  1630. stopPuzzleLoop(); puzzle = null;
  1631. state = 'menu'; pausedFrom = null; stateBeforePuzzle = null; demoMode = false;
  1632. puzzleFailedActive = false; cameraOpen = false;
  1633. keys.up = keys.down = keys.left = keys.right = false;
  1634. hideAll();
  1635. if (el.hud) el.hud.classList.add('hide');
  1636. if (el.taskPanel) el.taskPanel.classList.remove('show');
  1637. if (el.logPanel) el.logPanel.classList.remove('show');
  1638. if (el.achPanel) el.achPanel.classList.remove('show');
  1639. if (el.minimap) el.minimap.classList.remove('show');
  1640. if (el.hintBar) el.hintBar.classList.remove('show');
  1641. hideHintPanel();
  1642. updateMobileVisibility(); updateContinueButton();
  1643. showScreen('menu'); focusStage();
  1644. }
  1645. function pauseGame(){ if (state === 'paused' || state === 'camera') return; pausedFrom = state; state = 'paused'; hideHintPanel(); showScreen('pause'); }
  1646. function resumeGame(){ if (state !== 'paused') return; state = pausedFrom || 'playing'; hideAll(); if (state === 'playing') focusStage(); }
  1647. function showContextHint(){
  1648. if (state === 'playing'){
  1649. const here = roomAt(player.x, player.y);
  1650. if (here && here.isSoc){ showHint('★ SOC · C — камеры · E — инцидент', 3000); return; }
  1651. const {inc, d} = nearestIncident();
  1652. if (!inc){ showHint('Инцидентов рядом нет', 3000); return; }
  1653. const def = INCIDENTS[inc.type];
  1654. showHint(d < 60 ? 'E — открыть: ' + def.label : 'Ближайший: ' + def.icon + ' ' + def.label, 3000);
  1655. } else if (state === 'puzzle'){
  1656. if (puzzle && puzzle.keys){ if (el.pzHint){ el.pzHint.textContent = puzzle.keys; el.pzHint.className = ''; } }
  1657. } else if (state === 'camera'){ showHint('Клик по камере · 1-9 · E — доложить · C — закрыть', 3500); }
  1658. }
  1659. function setupShiftTasks(shift){
  1660. const allTypes = ALL_INCIDENT_TYPES.slice();
  1661. const n = Math.min(shift.count, allTypes.length);
  1662. const chosen = shuffle(allTypes).slice(0, n);
  1663. waveTasks = chosen.map(t => ({type: t, need: 1, done: 0}));
  1664. let rem = shift.count - n;
  1665. while (rem > 0){ waveTasks[Math.floor(Math.random() * waveTasks.length)].need++; rem--; }
  1666. shuffle(waveTasks);
  1667. updateTaskUI();
  1668. }
  1669. function startGame(){
  1670. hideHintPanel();
  1671. currentDiff = DIFF[settings.diff] || DIFF.normal;
  1672. score = 0; leaks = 0; fixedCount = 0; caughtCount = 0;
  1673. caughtThisShift = 0; totalCaught = 0;
  1674. statsAch = { shifts: 0, perfectShift: false, totalCaught: 0, fixedNoErrors: 0, auditPassed: false, score: 0, shiftErrors: 0 };
  1675. currentShift = 0; demoMode = false; puzzleFailedActive = false; cameraOpen = false;
  1676. generateWorld(); initCameras(); spawnBots(); resetAfterWorld();
  1677. hideAll();
  1678. el.hud.classList.remove('hide');
  1679. el.taskPanel.classList.add('show'); el.logPanel.classList.add('show'); el.minimap.classList.add('show');
  1680. startShift(0); updateMobileVisibility(); focusStage();
  1681. }
  1682. function resetAfterWorld(){
  1683. incidents.length = 0; particles.length = 0; toasts.length = 0;
  1684. clearLog(); updateHUD();
  1685. }
  1686. function startShift(idx){
  1687. currentShift = idx;
  1688. const shift = currentDiff.shifts[idx];
  1689. spawnedInShift = 0; shiftSpawnTimer = 1.0;
  1690. incidents.length = 0; caughtThisShift = 0; statsAch.shiftErrors = 0;
  1691. setupShiftTasks(shift);
  1692. spawnBots();
  1693. updateHUD(); state = 'playing'; hideAll();
  1694. el.hud.classList.remove('hide');
  1695. el.taskPanel.classList.add('show'); el.logPanel.classList.add('show'); el.minimap.classList.add('show');
  1696. refreshAchievementHUD();
  1697. addLog('─── СМЕНА ' + (idx + 1) + ' / ' + currentDiff.shifts.length + ' ───', 'sys');
  1698. if (currentDiff.showHints){
  1699. const msgs = ['Смена принята. Вы в SOC. C — камеры.','Сотрудники в офисе. Следите за камерами.','Служба ИБ на связи.','Проверяющий выехал. Не подведите.'];
  1700. setTimeout(() => dispatch(msgs[idx % msgs.length]), 300);
  1701. if (currentDiff.hintsAlwaysVisible){
  1702. setTimeout(() => showHintPanel(
  1703. 'Добро пожаловать на смену ' + (idx + 1) + ' / ' + currentDiff.shifts.length + '!',
  1704. 'Задачи слева · <kbd>C</kbd> камеры · <kbd>WASD</kbd> движение · <kbd>E</kbd> действие'
  1705. ), 800);
  1706. }
  1707. }
  1708. updateMobileVisibility(); focusStage(); saveGameState();
  1709. }
  1710. function showShiftDebrief(){
  1711. state = 'shift'; hideAll();
  1712. el.hud.classList.add('hide');
  1713. el.taskPanel.classList.remove('show'); el.logPanel.classList.remove('show');
  1714. el.achPanel.classList.remove('show'); el.minimap.classList.remove('show');
  1715. hideHintPanel();
  1716. updateMobileVisibility();
  1717. statsAch.shifts = currentShift + 1;
  1718. statsAch.perfectShift = (statsAch.shiftErrors === 0 && leaks === 0);
  1719. statsAch.score = score;
  1720. checkAchievements(statsAch);
  1721. el.shiftFixed.textContent = fixedCount;
  1722. el.shiftLeaks.textContent = leaks;
  1723. el.shiftCaught.textContent = caughtThisShift;
  1724. el.shiftScore.textContent = score;
  1725. el.shiftTitle.textContent = 'Рапорт · смена ' + (currentShift + 1);
  1726. el.shiftMsg.textContent = leaks === 0 ? 'Смена закрыта без утечек. Отличная работа!' : 'Смена закрыта. Утечек: ' + leaks;
  1727. if (currentShift >= currentDiff.shifts.length - 1){
  1728. el.shiftNext.textContent = 'Перейти к аудиту ▶';
  1729. } else {
  1730. el.shiftNext.textContent = 'Следующая смена ▶';
  1731. }
  1732. showScreen('shift');
  1733. }
  1734. function endGame(win){
  1735. state = 'end'; hideAll();
  1736. el.hud.classList.add('hide');
  1737. el.taskPanel.classList.remove('show'); el.logPanel.classList.remove('show');
  1738. el.achPanel.classList.remove('show'); el.minimap.classList.remove('show');
  1739. hideHintPanel();
  1740. updateMobileVisibility();
  1741. if (score > highScore){ highScore = score; saveHigh(); }
  1742. statsAch.score = score;
  1743. statsAch.shifts = win ? currentDiff.shifts.length : currentShift;
  1744. checkAchievements(statsAch);
  1745. el.endTitle.textContent = win ? 'Данные защищены' : 'Утечка данных';
  1746. el.endTitle.className = win ? 'win' : 'lose';
  1747. el.endSub.textContent = win ? 'Смена закрыта' : 'Провал';
  1748. el.stScore.textContent = score; el.stFixed.textContent = fixedCount;
  1749. el.stLeaks.textContent = leaks; el.stCaught.textContent = caughtThisShift;
  1750. el.endMsg.textContent = win ? 'Все инциденты закрыты. Сервис работает.' : 'Слишком много утечек.';
  1751. showScreen('end');
  1752. clearGameState();
  1753. }
  1754. function startAudit(){
  1755. state = 'audit'; hideAll(); showScreen('audit');
  1756. const list = el.auditList; list.innerHTML = '';
  1757. const checks = [
  1758. {ok: leaks === 0, txt: '0 утечек данных'},
  1759. {ok: fixedCount >= currentDiff.shifts.length, txt: 'Все инциденты закрыты'},
  1760. {ok: true, txt: 'SOC работает штатно'},
  1761. {ok: caughtThisShift >= 1, txt: 'Пойман хотя бы 1 нарушитель'}
  1762. ];
  1763. for (const c of checks){
  1764. const d = document.createElement('div'); d.className = 'rule';
  1765. d.innerHTML = (c.ok ? '✅ ' : '⚠️ ') + c.txt;
  1766. list.appendChild(d);
  1767. }
  1768. }
  1769. const TUT_SECTIONS = [
  1770. {
  1771. id:'controls', ic:'🎮', name:'Управление',
  1772. sub:'Клавиши, мышь, мобильный джойстик',
  1773. body: '<div class="lead">Освойте управление — это первое, что нужно оператору ИБ.</div>' +
  1774. '<h3>Движение</h3>' +
  1775. '<div class="rule" style="margin-bottom:.4em"><kbd>W</kbd><kbd>A</kbd><kbd>S</kbd><kbd>D</kbd> — ходьба по офису</div>' +
  1776. '<div class="rule" style="margin-bottom:.4em"><kbd>←</kbd><kbd>↑</kbd><kbd>→</kbd><kbd>↓</kbd> — альтернатива (стрелки)</div>' +
  1777. '<div class="rule" style="margin-bottom:.4em">Ц/Ы/Ф/В — работают в русской раскладке</div>' +
  1778. '<h3>Действия</h3>' +
  1779. '<div class="rule" style="margin-bottom:.4em"><kbd>E</kbd> или <kbd>Space</kbd> — открыть инцидент рядом, войти в камеры (в SOC)</div>' +
  1780. '<div class="rule" style="margin-bottom:.4em"><kbd>C</kbd> — открыть/закрыть камеры (только в комнате SOC)</div>' +
  1781. '<div class="rule" style="margin-bottom:.4em"><kbd>1</kbd>…<kbd>9</kbd> — выбрать камеру по номеру</div>' +
  1782. '<h3>Меню</h3>' +
  1783. '<div class="rule" style="margin-bottom:.4em"><kbd>Esc</kbd> — пауза / выход из головоломки / закрыть камеры</div>' +
  1784. '<div class="rule" style="margin-bottom:.4em"><kbd>M</kbd> — выход в главное меню</div>' +
  1785. '<div class="rule" style="margin-bottom:.4em"><kbd>H</kbd> — подсказка (что рядом)</div>' +
  1786. '<div class="rule" style="margin-bottom:.4em"><kbd>F</kbd> — полный экран</div>' +
  1787. '<h3>Мобильное управление</h3>' +
  1788. '<div>На телефоне/планшете появляется джойстик слева и кнопка <kbd>E</kbd> справа. Включить принудительно можно в настройках.</div>'
  1789. },
  1790. {
  1791. id:'spec', ic:'📋', name:'Спецификация работы',
  1792. sub:'Кто вы, что защищаете, кто угрожает',
  1793. body: '<div class="lead">Вы — оператор службы информационной безопасности (ИБ). Ваша задача — не дать данным утечь.</div>' +
  1794. '<h3>Ваша роль</h3>' +
  1795. '<div>Вы сидите в комнате <b>SOC (Security Operations Center)</b> — центре офиса. Оттуда видно все камеры и оттуда вы выходите в обход.</div>' +
  1796. '<h3>Что защищаем</h3>' +
  1797. '<div>Восемь типов инцидентов, которые нужно закрывать:</div>' +
  1798. '<div class="rule" style="margin-bottom:.3em">📧 <b>Фишинговое письмо</b> — сотрудник открыл подозрительное</div>' +
  1799. '<div class="rule" style="margin-bottom:.3em">🔑 <b>Слабый пароль</b> — доступ к системе под угрозой</div>' +
  1800. '<div class="rule" style="margin-bottom:.3em">📋 <b>Подозрительные логи</b> — кто-то пытается зайти</div>' +
  1801. '<div class="rule" style="margin-bottom:.3em">🚪 <b>Права доступа</b> — у кого-то лишние права</div>' +
  1802. '<div class="rule" style="margin-bottom:.3em">🌐 <b>Открытые порты</b> — сеть не защищена</div>' +
  1803. '<div class="rule" style="margin-bottom:.3em">🔐 <b>Шифрование</b> — данные не зашифрованы</div>' +
  1804. '<div class="rule" style="margin-bottom:.3em">💾 <b>Резервные копии</b> — бэкапы не делаются</div>' +
  1805. '<div class="rule" style="margin-bottom:.3em">🚨 <b>Реагирование</b> — инцидент не обработан</div>' +
  1806. '<h3>Кто угрожает</h3>' +
  1807. '<div>Часть сотрудников — <b>инсайдеры</b>. Они:</div>' +
  1808. '<div class="rule" style="margin-bottom:.3em">🔧 <b>Саботируют</b> — подкладывают инциденты на мебель</div>' +
  1809. '<div class="rule" style="margin-bottom:.3em">📤 <b>Сливают данные</b> — идут к выходу с данными</div>' +
  1810. '<div>Подозрительного сотрудника можно <b>поймать через камеры</b> (кнопка «Доложить»). Это даёт +60 очков и предотвращает утечку.</div>' +
  1811. '<h3>Условия проигрыша</h3>' +
  1812. '<div>6 утечек (на лёгком 8, на сложном 5) — смена провалена. После 4 смен — <b>аудит</b>. Пройти аудит = победить.</div>'
  1813. },
  1814. {
  1815. id:'howto', ic:'🎯', name:'Как играть',
  1816. sub:'Пошаговая инструкция',
  1817. body: '<div class="lead">Пять шагов от старта до победы.</div>' +
  1818. '<h3>Шаг 1. Осмотритесь</h3>' +
  1819. '<div>Вы в SOC. Справа HUD: очки, смена, закрыто, утечки, поймано, рекорд. Слева задачи смены — что именно нужно закрыть.</div>' +
  1820. '<h3>Шаг 2. Проверьте камеры</h3>' +
  1821. '<div>Нажмите <kbd>C</kbd>. Увидите сетку всех комнат в реальном времени. Красным отмечены <b>подозрительные сотрудники</b>. Кликните по камере → <kbd>E</kbd> «Доложить» — поймали нарушителя, +60 очков.</div>' +
  1822. '<h3>Шаг 3. Идите к инциденту</h3>' +
  1823. '<div>На миникарте (снизу справа) цветные точки — это инциденты. Идите к ближайшему. Когда подойдёте вплотную — <kbd>E</kbd>, откроется головоломка.</div>' +
  1824. '<h3>Шаг 4. Решите головоломку</h3>' +
  1825. '<div>Тип головоломки зависит от инцидента. Смотрите раздел «Головоломки» — там всё описано. Ошибка не страшна: просто попробуйте ещё раз.</div>' +
  1826. '<h3>Шаг 5. Следите за таймером</h3>' +
  1827. '<div>У каждого инцидента есть <b>таймер</b> (полоса над мебелью). Если истечёт — утечка. На лёгком таймер долгий (90-60 сек), на сложном — короткий (26-40 сек).</div>' +
  1828. '<h3>Конец смены</h3>' +
  1829. '<div>Когда все задачи смены закрыты и на мебели нет инцидентов — рапорт. После 4 смен — <b>аудит</b>. Пройдёте — победа.</div>'
  1830. },
  1831. {
  1832. id:'puzzles', ic:'🧩', name:'Головоломки',
  1833. sub:'8 типов мини-игр — что делать',
  1834. body: '<div class="lead">Каждый инцидент открывает одну из 8 головоломок. Тип зависит от инцидента.</div>' +
  1835. '<h3>🔢 Кодовый замок (Keypad)</h3>' +
  1836. '<div>Код показан сверху (4 цифры). Введите его на клавиатуре или мышью. <kbd>Enter</kbd> — подтвердить, <kbd>Backspace</kbd> — стереть.</div>' +
  1837. '<h3>🔌 Провода (Wires)</h3>' +
  1838. '<div>Соедините одинаковые цвета: клик на левый, потом на правый. Или клавиши <kbd>1</kbd>–<kbd>4</kbd> — прямой выбор.</div>' +
  1839. '<h3>🎛️ Диски (Dials)</h3>' +
  1840. '<div>Два диска. Кнопки &lt; &gt; поворачивают на 45°. Совместите стрелку с зелёной меткой. Клавиши <kbd>←</kbd><kbd>→</kbd> тоже работают.</div>' +
  1841. '<h3>📊 Ползунки (Sliders)</h3>' +
  1842. '<div>Три ползунка, три зелёные зоны. Кликните по дорожке в нужное место.</div>' +
  1843. '<h3>💳 Карта (Card)</h3>' +
  1844. '<div>Перетащите карту из левого угла в пунктирную зону. Скорость должна быть средней. <kbd>Enter</kbd> — авто-проведение.</div>' +
  1845. '<h3>🎵 Последовательность (Sequence)</h3>' +
  1846. '<div>Четыре кружка. Смотрите, какая последовательность мигает, потом повторите. Клавиши <kbd>1</kbd>–<kbd>4</kbd> = кружки.</div>' +
  1847. '<h3>⚡ Мощность (Power)</h3>' +
  1848. '<div>Полоска с движущимся маркером и зелёной зоной. Нажмите <kbd>Space</kbd> (или клик), когда маркер в зоне. Нужно 3 попадания.</div>' +
  1849. '<h3>📺 Помехи (Flicker)</h3>' +
  1850. '<div>На экране появляются красные помехи. Кликайте по ним — нужно поймать 3.</div>' +
  1851. '<h3>Подсказки</h3>' +
  1852. '<div>На <b>лёгком уровне</b> при открытии головоломки внизу экрана всегда видна подсказка «что делать». На <b>среднем</b> — только первые 3 секунды. На <b>сложном</b> — подсказок нет.</div>'
  1853. }
  1854. ];
  1855. const TUT_PUZZLES = [
  1856. {id:'keypad', ic:'🔢', name:'Кодовый замок', sub:'Введите 4-значный код'},
  1857. {id:'wires', ic:'🔌', name:'Провода', sub:'Соедините одинаковые'},
  1858. {id:'dials', ic:'🎛️', name:'Диски', sub:'Совместите стрелки'},
  1859. {id:'sliders', ic:'📊', name:'Ползунки', sub:'В зелёную зону'},
  1860. {id:'card', ic:'💳', name:'Карта', sub:'Проведи карту'},
  1861. {id:'sequence',ic:'🎵', name:'Последовательность',sub:'Повтори 4 шага'},
  1862. {id:'power', ic:'⚡', name:'Мощность', sub:'Поймай 3 раза'},
  1863. {id:'flicker', ic:'📺', name:'Помехи', sub:'Клик по точке'}
  1864. ];
  1865. function buildTutGrid(){
  1866. if (!el.tutGrid) return;
  1867. el.tutGrid.innerHTML = '';
  1868. for (const s of TUT_SECTIONS){
  1869. const card = document.createElement('div');
  1870. card.className = 'tutCard';
  1871. const ic = document.createElement('span'); ic.className = 'ic'; ic.textContent = s.ic;
  1872. const ti = document.createElement('div'); ti.className = 'ti'; ti.textContent = s.name;
  1873. const sb = document.createElement('div'); sb.style.cssText = 'font-size:.7em;color:#8ba3c7;margin-top:.2em'; sb.textContent = s.sub;
  1874. card.appendChild(ic); card.appendChild(ti); card.appendChild(sb);
  1875. card.onclick = () => showTutSection(s);
  1876. el.tutGrid.appendChild(card);
  1877. }
  1878. for (const p of TUT_PUZZLES){
  1879. const card = document.createElement('div');
  1880. card.className = 'tutCard';
  1881. card.style.borderColor = 'rgba(251,191,36,.3)';
  1882. const ic = document.createElement('span'); ic.className = 'ic'; ic.textContent = p.ic;
  1883. const ti = document.createElement('div'); ti.className = 'ti'; ti.textContent = p.name;
  1884. const sb = document.createElement('div'); sb.style.cssText = 'font-size:.7em;color:#8ba3c7;margin-top:.2em'; sb.textContent = p.sub;
  1885. card.appendChild(ic); card.appendChild(ti); card.appendChild(sb);
  1886. card.onclick = () => showTutDetail(p);
  1887. el.tutGrid.appendChild(card);
  1888. }
  1889. }
  1890. let curTut = null;
  1891. function showTutSection(s){
  1892. hideAll();
  1893. showScreen('tutsection');
  1894. if (el.tutSectionTitle) el.tutSectionTitle.textContent = s.ic + ' ' + s.name;
  1895. if (el.tutSectionSub) el.tutSectionSub.textContent = s.sub;
  1896. if (el.tutSectionBody) el.tutSectionBody.innerHTML = s.body;
  1897. }
  1898. function showTutDetail(t){
  1899. curTut = t;
  1900. hideAll();
  1901. showScreen('tutdetail');
  1902. if (el.tutDetailTitle) el.tutDetailTitle.textContent = t.ic + ' ' + t.name;
  1903. if (el.tutDetailSub) el.tutDetailSub.textContent = t.sub;
  1904. if (el.tutDetailBody){
  1905. el.tutDetailBody.innerHTML = '<div class="lead">Попробуйте пройти мини-игру. Это демо без штрафов.</div>' +
  1906. '<h3>Управление</h3><div>Мышь — клики/перетаскивание. Клавиатура: <kbd>Enter</kbd> подтвердить, <kbd>Backspace</kbd> стереть, <kbd>1-9</kbd> — прямые действия.</div>';
  1907. }
  1908. }
  1909. const pzCanvas = el.pzCanvas;
  1910. const pzCtx = pzCanvas.getContext('2d');
  1911. const PZ_W = 480, PZ_H = 360;
  1912. let puzzleDirty = true;
  1913. 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'};
  1914. 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(); }
  1915. function pzHover(x,y,w,h){ return puzzleMouse.x>=x && puzzleMouse.x<=x+w && puzzleMouse.y>=y && puzzleMouse.y<=y+h; }
  1916. function pzHeader(text, tone){
  1917. pzCtx.fillStyle = PC.card; pzCtx.fillRect(0, 0, PZ_W, 34);
  1918. pzCtx.fillStyle = PC.border; pzCtx.fillRect(0, 33, PZ_W, 1);
  1919. pzCtx.fillStyle = tone === 'ok' ? PC.green : tone === 'warn' ? PC.yellow : tone === 'bad' ? PC.red : PC.blue;
  1920. pzCtx.beginPath(); pzCtx.arc(16, 17, 4, 0, 7); pzCtx.fill();
  1921. pzCtx.font = '600 12px "Segoe UI",sans-serif'; pzCtx.textAlign = 'left'; pzCtx.textBaseline = 'middle';
  1922. pzCtx.fillStyle = PC.textBright; pzCtx.fillText(text, 28, 17);
  1923. }
  1924. function pzFooter(left, right, tone){
  1925. const y = PZ_H - 28;
  1926. pzCtx.fillStyle = PC.card; pzCtx.fillRect(0, y, PZ_W, 28);
  1927. pzCtx.fillStyle = PC.border; pzCtx.fillRect(0, y, PZ_W, 1);
  1928. pzCtx.font = '500 11px "Segoe UI",sans-serif'; pzCtx.textBaseline = 'middle';
  1929. if (left){ pzCtx.textAlign = 'left'; pzCtx.fillStyle = PC.textMute; pzCtx.fillText(left, 14, y+14); }
  1930. 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); }
  1931. }
  1932. function pzButton(x, y, w, h, label, hover, variant){
  1933. let bg, border, fg;
  1934. if (variant === 'primary'){ bg = hover ? '#388bfd' : PC.blueDeep; border = hover ? PC.blue : '#388bfd'; fg = '#fff'; }
  1935. else if (variant === 'ok'){ bg = hover ? '#2ea043' : PC.greenDeep; border = hover ? PC.green : '#2ea043'; fg = '#fff'; }
  1936. else if (variant === 'danger'){ bg = hover ? '#da3633' : '#8e1519'; border = hover ? PC.red : '#da3633'; fg = '#fff'; }
  1937. else { bg = hover ? PC.panelHover : PC.panel; border = hover ? PC.borderLight : PC.border; fg = PC.text; }
  1938. pzCtx.fillStyle = bg; pzRR(x, y, w, h, 6); pzCtx.fill();
  1939. pzCtx.strokeStyle = border; pzCtx.lineWidth = 1; pzRR(x+0.5, y+0.5, w-1, h-1, 6); pzCtx.stroke();
  1940. pzCtx.font = label.length > 2 ? '600 13px "Segoe UI",sans-serif' : '600 18px "Segoe UI",sans-serif';
  1941. pzCtx.fillStyle = fg; pzCtx.textAlign = 'center'; pzCtx.textBaseline = 'middle';
  1942. pzCtx.fillText(label, x + w/2, y + h/2 + 1);
  1943. }
  1944. function makePuzzle(kind){
  1945. switch(kind){
  1946. case 'keypad': return makeKeypad();
  1947. case 'wires': return makeWires();
  1948. case 'dials': return makeDials();
  1949. case 'sliders': return makeSliders();
  1950. case 'card': return makeCard();
  1951. case 'sequence': return makeSequence();
  1952. case 'power': return makePower();
  1953. case 'flicker': return makeFlicker();
  1954. default: return makeKeypad();
  1955. }
  1956. }
  1957. function makeKeypad(){
  1958. const code = String(Math.floor(1000 + Math.random()*9000));
  1959. let entered = '';
  1960. const kW = 72, kH = 42, kG = 8;
  1961. const kx0 = (PZ_W - (kW*3 + kG*2))/2;
  1962. const ky0 = 165;
  1963. const keysArr = [['1','2','3'],['4','5','6'],['7','8','9'],['C','0','OK']];
  1964. function keyRect(r,c){ return {x:kx0+c*(kW+kG), y:ky0+r*(kH+kG), w:kW, h:kH}; }
  1965. function submit(){ if (entered === code) puzzleSolved(); else { entered = ''; puzzleFailed(); } }
  1966. function press(k){
  1967. if (k === 'C'){ entered = ''; beep(300,.08,'square'); }
  1968. else if (k === 'OK'){ submit(); }
  1969. else if (entered.length < 4){ entered += k; beep(600,.05); if (entered === code) setTimeout(puzzleSolved, 250); }
  1970. puzzleDirty = true;
  1971. }
  1972. return {
  1973. keys:'0-9 · Enter · Backspace',
  1974. draw:function(){
  1975. pzCtx.fillStyle = PC.bg; pzCtx.fillRect(0,0,PZ_W,PZ_H);
  1976. pzHeader('ВВЕДИТЕ PIN-КОД', entered.length === 4 ? 'ok' : 'info');
  1977. const cardY = 48;
  1978. pzCtx.fillStyle = PC.card; pzRR(120, cardY, 240, 58, 8); pzCtx.fill();
  1979. pzCtx.font = '600 10px "Segoe UI",sans-serif'; pzCtx.textAlign = 'center'; pzCtx.textBaseline = 'middle'; pzCtx.fillStyle = PC.textMute;
  1980. pzCtx.fillText('КОД', PZ_W/2, cardY + 15);
  1981. pzCtx.font = '700 28px "Consolas",monospace'; pzCtx.fillStyle = PC.yellow; pzCtx.fillText(code, PZ_W/2, cardY + 39);
  1982. const inX = 120, inY = 118, inW = 240, inH = 38;
  1983. pzCtx.fillStyle = '#010409'; pzRR(inX, inY, inW, inH, 6); pzCtx.fill();
  1984. 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();
  1985. const cellW = (inW - 18) / 4;
  1986. for (let i = 0; i < 4; i++){
  1987. const cx2 = inX + 9 + i*(cellW+6) + cellW/2, cy2 = inY + inH/2;
  1988. 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); }
  1989. else { pzCtx.fillStyle = PC.border; pzCtx.beginPath(); pzCtx.arc(cx2, cy2, 3, 0, 7); pzCtx.fill(); }
  1990. }
  1991. for (let r = 0; r < 4; r++) for (let c = 0; c < 3; c++){
  1992. const rr = keyRect(r,c);
  1993. const v = keysArr[r][c] === 'OK' ? 'ok' : keysArr[r][c] === 'C' ? 'danger' : 'default';
  1994. pzButton(rr.x, rr.y, rr.w, rr.h, keysArr[r][c], pzHover(rr.x, rr.y, rr.w, rr.h), v);
  1995. }
  1996. pzFooter('Введите 4-значный код', entered.length + ' / 4', entered.length === 4 ? 'ok' : null);
  1997. },
  1998. down:function(x,y){
  1999. for (let r = 0; r < 4; r++) for (let c = 0; c < 3; c++){
  2000. const rr = keyRect(r,c);
  2001. if (x >= rr.x && x <= rr.x+rr.w && y >= rr.y && y <= rr.y+rr.h){ press(keysArr[r][c]); return true; }
  2002. }
  2003. return false;
  2004. },
  2005. move:function(){}, up:function(){},
  2006. handleKey:function(a){
  2007. if (a === 'enter'){ submit(); return true; }
  2008. if (a === 'backspace'){ entered = entered.slice(0,-1); return true; }
  2009. if (/^[0-9]$/.test(a)){ if (entered.length < 4){ entered += a; beep(600,.05); if (entered === code) setTimeout(puzzleSolved, 250); } return true; }
  2010. return false;
  2011. }
  2012. };
  2013. }
  2014. function makeWires(){
  2015. const colors = [PC.red, PC.blue, PC.yellow, PC.purple];
  2016. const leftX = 90, rightX = PZ_W - 90;
  2017. const yStart = 95, yStep = 62;
  2018. const left = colors.map((c,i) => ({x:leftX, y:yStart+i*yStep, color:c, done:false}));
  2019. const right = colors.slice().sort(() => Math.random()-0.5).map((c,i) => ({x:rightX, y:yStart+i*yStep, color:c, done:false}));
  2020. let picked = -1;
  2021. function drawNode(n, isLeft, idx){
  2022. const h = pzHover(n.x-22, n.y-22, 44, 44);
  2023. const isPicked = isLeft && picked === idx;
  2024. const r = (isPicked || h) ? 13 : 11;
  2025. 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; }
  2026. pzCtx.fillStyle = n.color; pzCtx.beginPath(); pzCtx.arc(n.x, n.y, r, 0, 7); pzCtx.fill();
  2027. pzCtx.fillStyle = PC.bg; pzCtx.beginPath(); pzCtx.arc(n.x, n.y, r*0.45, 0, 7); pzCtx.fill();
  2028. 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(); }
  2029. pzCtx.font = '700 10px "Segoe UI",sans-serif'; pzCtx.textAlign = 'center'; pzCtx.textBaseline = 'middle'; pzCtx.fillStyle = PC.textMute;
  2030. if (!n.done) pzCtx.fillText(String(idx+1), n.x, n.y - r - 10);
  2031. }
  2032. function tryConnect(idx){
  2033. if (picked < 0){ if (!left[idx].done){ picked = idx; beep(500,.05); } }
  2034. else if (!right[idx].done){
  2035. if (left[picked].color === right[idx].color){
  2036. left[picked].done = true; right[idx].done = true; picked = -1; beep(800,.1);
  2037. if (left.every(l => l.done)) setTimeout(puzzleSolved, 300);
  2038. } else { puzzleFailed(); picked = -1; }
  2039. }
  2040. }
  2041. return {
  2042. keys:'Клик левый-правый · 1-4',
  2043. draw:function(){
  2044. pzCtx.fillStyle = PC.bg; pzCtx.fillRect(0,0,PZ_W,PZ_H);
  2045. pzHeader(picked >= 0 ? 'ТЕПЕРЬ ПРАВЫЙ' : 'СОЕДИНИ ПРОВОДА', picked >= 0 ? 'warn' : 'info');
  2046. pzCtx.fillStyle = PC.card; pzRR(50, 60, 80, 260, 8); pzCtx.fill(); pzRR(PZ_W-130, 60, 80, 260, 8); pzCtx.fill();
  2047. for (let i = 0; i < left.length; i++){
  2048. if (left[i].done){
  2049. const R = right.find(r => r.color === left[i].color && r.done);
  2050. if (R){
  2051. pzCtx.strokeStyle = left[i].color; pzCtx.lineWidth = 3; pzCtx.lineCap = 'round';
  2052. pzCtx.beginPath(); pzCtx.moveTo(left[i].x, left[i].y);
  2053. pzCtx.bezierCurveTo(left[i].x + 130, left[i].y, R.x - 130, R.y, R.x, R.y); pzCtx.stroke();
  2054. }
  2055. }
  2056. }
  2057. for (let i = 0; i < left.length; i++) drawNode(left[i], true, i);
  2058. for (let i = 0; i < right.length; i++) drawNode(right[i], false, i);
  2059. pzFooter('Соедини одинаковые цвета', left.filter(l => l.done).length + ' / 4', left.every(l => l.done) ? 'ok' : null);
  2060. },
  2061. down:function(x,y){
  2062. for (let i = 0; i < left.length; i++){
  2063. const ddx = x-left[i].x, ddy = y-left[i].y;
  2064. if (Math.sqrt(ddx*ddx+ddy*ddy) < 22){ if (left[i].done) return false; picked = i; beep(500,.05); return true; }
  2065. }
  2066. if (picked >= 0){
  2067. for (let i = 0; i < right.length; i++){
  2068. const ddx = x-right[i].x, ddy = y-right[i].y;
  2069. if (Math.sqrt(ddx*ddx+ddy*ddy) < 22){ tryConnect(i); return true; }
  2070. }
  2071. }
  2072. return false;
  2073. },
  2074. move:function(){}, up:function(){},
  2075. 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; }
  2076. };
  2077. }
  2078. function makeDials(){
  2079. const targets = [Math.floor(Math.random()*8)*45, Math.floor(Math.random()*8)*45];
  2080. const angles = [Math.floor(Math.random()*8)*45, Math.floor(Math.random()*8)*45];
  2081. const dials = [{x:140, y:170, r:70}, {x:340, y:170, r:70}];
  2082. function angDiff(a,b){ const d = Math.abs(a-b)%360; return Math.min(d, 360-d); }
  2083. function dialOK(i){ return angDiff(angles[i], targets[i]) < 15; }
  2084. function drawDial(i){
  2085. const dd = dials[i], cx = dd.x, cy = dd.y, r = dd.r, ok = dialOK(i);
  2086. pzCtx.fillStyle = '#010409'; pzCtx.beginPath(); pzCtx.arc(cx, cy, r, 0, 7); pzCtx.fill();
  2087. pzCtx.strokeStyle = ok ? PC.green : PC.border; pzCtx.lineWidth = 2; pzCtx.beginPath(); pzCtx.arc(cx, cy, r, 0, 7); pzCtx.stroke();
  2088. const tRad = (targets[i] - 90) * Math.PI/180;
  2089. 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();
  2090. const rRad = (angles[i] - 90) * Math.PI/180;
  2091. pzCtx.strokeStyle = ok ? PC.green : PC.blue; pzCtx.lineWidth = 3; pzCtx.lineCap = 'round';
  2092. pzCtx.beginPath(); pzCtx.moveTo(cx, cy); pzCtx.lineTo(cx + Math.cos(rRad)*(r-28), cy + Math.sin(rRad)*(r-28)); pzCtx.stroke();
  2093. pzCtx.font = '600 10px "Segoe UI",sans-serif'; pzCtx.textAlign = 'center'; pzCtx.textBaseline = 'middle'; pzCtx.fillStyle = ok ? PC.green : PC.textMute;
  2094. pzCtx.fillText('ДИСК ' + (i+1) + (ok ? ' OK' : ''), cx, cy - r - 14);
  2095. const btnW = 44, btnH = 30, gap = 12;
  2096. const bx1 = cx - gap/2 - btnW, bx2 = cx + gap/2, by = cy + r + 12;
  2097. pzButton(bx1, by, btnW, btnH, '<', pzHover(bx1, by, btnW, btnH), 'default');
  2098. pzButton(bx2, by, btnW, btnH, '>', pzHover(bx2, by, btnW, btnH), 'default');
  2099. }
  2100. return {
  2101. keys:'Кнопки < >',
  2102. draw:function(){
  2103. pzCtx.fillStyle = PC.bg; pzCtx.fillRect(0,0,PZ_W,PZ_H);
  2104. const bothOK = dialOK(0) && dialOK(1);
  2105. pzHeader(bothOK ? 'ВСЁ СОВПАЛО' : 'СОВМЕСТИ СТРЕЛКИ', bothOK ? 'ok' : 'info');
  2106. drawDial(0); drawDial(1);
  2107. pzFooter('Метка — зелёный кружок', bothOK ? 'Готово' : null, bothOK ? 'ok' : null);
  2108. },
  2109. down:function(x,y){
  2110. for (let i = 0; i < 2; i++){
  2111. const dd = dials[i], cx = dd.x, cy = dd.y, r = dd.r;
  2112. const btnW = 44, btnH = 30, gap = 12;
  2113. const bx1 = cx - gap/2 - btnW, bx2 = cx + gap/2, by = cy + r + 12;
  2114. if (x >= bx1 && x <= bx1+btnW && y >= by && y <= by+btnH){ angles[i] = (angles[i] - 45 + 360) % 360; beep(500,.06); }
  2115. else if (x >= bx2 && x <= bx2+btnW && y >= by && y <= by+btnH){ angles[i] = (angles[i] + 45) % 360; beep(700,.06); }
  2116. }
  2117. if (dialOK(0) && dialOK(1)) setTimeout(puzzleSolved, 300);
  2118. return true;
  2119. },
  2120. move:function(){}, up:function(){},
  2121. 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; }
  2122. };
  2123. }
  2124. function makeSliders(){
  2125. const targets = [25, 50, 75];
  2126. const values = [15, 85, 35];
  2127. const trackX = 90, trackW = 300, trackH = 6;
  2128. function sliderY(i){ return 105 + i*68; }
  2129. function isOK(i){ return Math.abs(values[i] - targets[i]) < 6; }
  2130. function allOK(){ return isOK(0) && isOK(1) && isOK(2); }
  2131. return {
  2132. keys:'Клик по дорожке',
  2133. draw:function(){
  2134. pzCtx.fillStyle = PC.bg; pzCtx.fillRect(0,0,PZ_W,PZ_H);
  2135. const ok = allOK();
  2136. pzHeader(ok ? 'ВСЁ НА МЕСТЕ' : 'ПОЛЗУНКИ В ЗЕЛЁНУЮ ЗОНУ', ok ? 'ok' : 'info');
  2137. for (let i = 0; i < 3; i++){
  2138. const y = sliderY(i);
  2139. pzCtx.fillStyle = '#010409'; pzRR(trackX, y - trackH/2, trackW, trackH, 3); pzCtx.fill();
  2140. const zx = trackX + (targets[i] - 8)/100*trackW, zw = 16/100*trackW;
  2141. pzCtx.fillStyle = 'rgba(63,185,80,.3)'; pzRR(zx, y - 10, zw, 20, 4); pzCtx.fill();
  2142. const hx = trackX + values[i]/100*trackW;
  2143. pzCtx.fillStyle = isOK(i) ? PC.green : PC.card; pzRR(hx - 8, y - 14, 16, 28, 5); pzCtx.fill();
  2144. pzCtx.font = '600 11px "Consolas",monospace'; pzCtx.textAlign = 'left'; pzCtx.textBaseline = 'middle'; pzCtx.fillStyle = isOK(i) ? PC.green : PC.textDim;
  2145. pzCtx.fillText(Math.round(values[i]) + '%', trackX + trackW + 12, y);
  2146. }
  2147. pzFooter('Клик по дорожке', ok ? 'Готово' : null, ok ? 'ok' : null);
  2148. },
  2149. down:function(x, y){
  2150. for (let i = 0; i < 3; i++){
  2151. const ly = sliderY(i);
  2152. if (y >= ly - 24 && y <= ly + 24 && x >= trackX - 20 && x <= trackX + trackW + 20){
  2153. values[i] = clamp((x - trackX)/trackW * 100, 0, 100); beep(600,.06);
  2154. if (allOK()) setTimeout(puzzleSolved, 300);
  2155. return true;
  2156. }
  2157. }
  2158. return false;
  2159. },
  2160. move:function(){}, up:function(){},
  2161. 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; }
  2162. };
  2163. }
  2164. function makeCard(){
  2165. const card = {x:40, y:190, w:110, h:66, dragging:false};
  2166. const zone = {x:200, y:70, w:230, h:220};
  2167. let lastT = 0, lastX = 0, speed = 0;
  2168. return {
  2169. keys:'Тяни карту · Enter — авто',
  2170. draw:function(){
  2171. pzCtx.fillStyle = PC.bg; pzCtx.fillRect(0,0,PZ_W,PZ_H);
  2172. pzHeader(card.dragging ? 'ПРОВЕДИ КАРТУ' : 'ЗАЖМИ КАРТУ', card.dragging ? 'ok' : 'info');
  2173. pzCtx.fillStyle = 'rgba(88,166,255,.05)'; pzRR(zone.x, zone.y, zone.w, zone.h, 12); pzCtx.fill();
  2174. 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([]);
  2175. const h = pzHover(card.x, card.y, card.w, card.h);
  2176. pzCtx.fillStyle = h || card.dragging ? '#4a86d4' : PC.blueDeep; pzRR(card.x, card.y, card.w, card.h, 8); pzCtx.fill();
  2177. pzCtx.font = '700 11px "Consolas",monospace'; pzCtx.textAlign = 'center'; pzCtx.textBaseline = 'middle'; pzCtx.fillStyle = '#fff';
  2178. pzCtx.fillText('CARD', card.x + card.w/2, card.y + card.h/2);
  2179. pzFooter('Проведи с нормальной скоростью', null, null);
  2180. },
  2181. down:function(x, y){
  2182. 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; }
  2183. return false;
  2184. },
  2185. move:function(x, y){
  2186. if (card.dragging){
  2187. const now = performance.now(), dt = (now - lastT)/1000;
  2188. if (dt > 0.02){ speed = Math.abs((x - lastX)/dt); lastX = x; lastT = now; }
  2189. card.x = clamp(x - card.w/2, 10, PZ_W - card.w - 10);
  2190. card.y = clamp(y - card.h/2, 60, PZ_H - card.h - 60);
  2191. return true;
  2192. }
  2193. return false;
  2194. },
  2195. up:function(){
  2196. if (card.dragging){
  2197. card.dragging = false;
  2198. const cx2 = card.x + card.w/2, cy2 = card.y + card.h/2;
  2199. const inZone = cx2 > zone.x && cx2 < zone.x + zone.w && cy2 > zone.y && cy2 < zone.y + zone.h;
  2200. if (inZone && speed > 250 && speed < 900) setTimeout(puzzleSolved, 250);
  2201. else if (inZone) puzzleFailed();
  2202. return true;
  2203. }
  2204. return false;
  2205. },
  2206. handleKey:function(a){
  2207. 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; }
  2208. return false;
  2209. }
  2210. };
  2211. }
  2212. function makeSequence(){
  2213. const colors = [PC.red, PC.blue, PC.green, PC.yellow];
  2214. const seq = [];
  2215. for (let i = 0; i < 4; i++) seq.push(Math.floor(Math.random()*4));
  2216. let inputIdx = 0, showIdx = 0, showTimer = 0, showPhase = true;
  2217. const btnR = 36, gap = 12;
  2218. const cxs = [PZ_W/2 - btnR - gap, PZ_W/2 + btnR + gap];
  2219. const cys = [130, 130 + btnR*2 + gap*2];
  2220. function btnRect(i){ return {cx: cxs[i%2], cy: cys[(i/2)|0], r:btnR}; }
  2221. return {
  2222. keys:'Повтори последовательность',
  2223. draw:function(){
  2224. pzCtx.fillStyle = PC.bg; pzCtx.fillRect(0,0,PZ_W,PZ_H);
  2225. pzHeader(showPhase ? 'СМОТРИ' : 'ПОВТОРИ', showPhase ? 'warn' : 'info');
  2226. for (let i = 0; i < 4; i++){
  2227. const b = btnRect(i);
  2228. const active = showPhase && showIdx < 4 && seq[showIdx] === i && showTimer < 0.5;
  2229. pzCtx.fillStyle = active ? colors[i] : PC.panel; pzCtx.beginPath(); pzCtx.arc(b.cx, b.cy, b.r, 0, 7); pzCtx.fill();
  2230. pzCtx.strokeStyle = active ? colors[i] : PC.border; pzCtx.lineWidth = 2; pzCtx.beginPath(); pzCtx.arc(b.cx, b.cy, b.r, 0, 7); pzCtx.stroke();
  2231. }
  2232. pzFooter('Повтори 4 шага', showPhase ? 'PLAY' : (inputIdx + ' / 4'), null);
  2233. },
  2234. update:function(dt){
  2235. if (showPhase){ showTimer += dt; if (showTimer > 0.7){ showTimer = 0; showIdx++; if (showIdx >= 4){ showPhase = false; showIdx = 0; } } }
  2236. },
  2237. down:function(x,y){
  2238. if (showPhase) return false;
  2239. for (let i = 0; i < 4; i++){
  2240. const b = btnRect(i);
  2241. const ddx = x-b.cx, ddy = y-b.cy;
  2242. if (Math.sqrt(ddx*ddx+ddy*ddy) < b.r){
  2243. beep(400 + i*100, 0.08);
  2244. if (seq[inputIdx] === i){ inputIdx++; if (inputIdx >= 4) setTimeout(puzzleSolved, 200); }
  2245. else { puzzleFailed(); inputIdx = 0; }
  2246. return true;
  2247. }
  2248. }
  2249. return false;
  2250. },
  2251. move:function(){}, up:function(){},
  2252. handleKey:function(a){
  2253. const n = /^[1-4]$/.test(a) ? parseInt(a,10)-1 : -1;
  2254. if (n >= 0 && n < 4){
  2255. beep(400 + n*100, 0.08);
  2256. if (seq[inputIdx] === n){ inputIdx++; if (inputIdx >= 4) setTimeout(puzzleSolved, 200); }
  2257. else { puzzleFailed(); inputIdx = 0; }
  2258. return true;
  2259. }
  2260. return false;
  2261. }
  2262. };
  2263. }
  2264. function makePower(){
  2265. const target = 0.35; let pos = 0, dir = 1, spd = 0.6, hits = 0, misses = 0, need = 3;
  2266. return {
  2267. keys:'Пробел — стоп',
  2268. draw:function(){
  2269. pzCtx.fillStyle = PC.bg; pzCtx.fillRect(0,0,PZ_W,PZ_H);
  2270. pzHeader('ПОЙМАЙ ЗОНУ ×'+need, 'info');
  2271. const barX = 60, barY = 170, barW = PZ_W-120, barH = 30;
  2272. pzCtx.fillStyle = '#010409'; pzRR(barX, barY, barW, barH, 8); pzCtx.fill();
  2273. pzCtx.fillStyle = 'rgba(63,185,80,.35)'; const zoneX = barX + target*barW - barW*0.08;
  2274. pzRR(zoneX, barY, barW*0.16, barH, 8); pzCtx.fill();
  2275. pzCtx.fillStyle = PC.blue; pzRR(barX + pos*barW - 4, barY - 6, 8, barH + 12, 4); pzCtx.fill();
  2276. pzCtx.font = '600 14px "Segoe UI",sans-serif'; pzCtx.textAlign = 'center'; pzCtx.textBaseline = 'middle'; pzCtx.fillStyle = PC.textBright;
  2277. pzCtx.fillText('ПОПАДАНИЯ: ' + hits + ' / ' + need, PZ_W/2, 100);
  2278. pzFooter('Пробел — стоп', misses > 0 ? 'мимо: ' + misses : null, misses > 0 ? 'bad' : null);
  2279. },
  2280. update:function(dt){ pos += dir * spd * dt; if (pos >= 1){ pos = 1; dir = -1; } if (pos <= 0){ pos = 0; dir = 1; } puzzleDirty = true; },
  2281. down:function(){ return this.tryStop(); },
  2282. move:function(){}, up:function(){},
  2283. tryStop:function(){
  2284. if (Math.abs(pos - target) < 0.08){ hits++; beep(900,.08); if (hits >= need) setTimeout(puzzleSolved, 200); }
  2285. else { misses++; beep(200,.1,'square'); if (misses >= 3) puzzleFailed(); }
  2286. return true;
  2287. },
  2288. handleKey:function(a){ if (a === 'action' || a === 'enter') return this.tryStop(); return false; }
  2289. };
  2290. }
  2291. function makeFlicker(){
  2292. let fx = rand(60, PZ_W-60), fy = rand(90, PZ_H-90), ft = 1.5, clicks = 0;
  2293. const need = 3;
  2294. return {
  2295. keys:'Клик по помехе',
  2296. draw:function(){
  2297. pzCtx.fillStyle = PC.bg; pzCtx.fillRect(0,0,PZ_W,PZ_H);
  2298. pzHeader('СТАБИЛИЗИРУЙ КАМЕРУ ×'+need, 'info');
  2299. pzCtx.fillStyle = PC.card; pzRR(80, 70, PZ_W-160, PZ_H-150, 10); pzCtx.fill();
  2300. if (ft > 0){ pzCtx.fillStyle = 'rgba(248,81,73,.6)'; pzCtx.beginPath(); pzCtx.arc(fx, fy, 18, 0, 7); pzCtx.fill(); }
  2301. pzCtx.font = '600 14px "Segoe UI",sans-serif'; pzCtx.textAlign = 'center'; pzCtx.textBaseline = 'middle'; pzCtx.fillStyle = PC.textBright;
  2302. pzCtx.fillText('ПОМЕХИ: ' + clicks + ' / ' + need, PZ_W/2, 100);
  2303. pzFooter('Клик по красной точке', null, null);
  2304. },
  2305. 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; },
  2306. down:function(x,y){
  2307. const dx = x-fx, dy = y-fy;
  2308. 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; }
  2309. return false;
  2310. },
  2311. move:function(){}, up:function(){},
  2312. handleKey:function(){ return false; }
  2313. };
  2314. }
  2315. function openPuzzle(inc){
  2316. activeIncident = inc;
  2317. const def = INCIDENTS[inc.type];
  2318. const kindMap = {phishing:'keypad', password:'wires', logs:'dials', access:'sliders', ports:'card', cipher:'sequence', backup:'power', response:'flicker'};
  2319. const kind = kindMap[def.tag] || 'keypad';
  2320. puzzle = makePuzzle(kind);
  2321. puzzle.kind = kind;
  2322. puzzleDirty = true;
  2323. stateBeforePuzzle = state; state = 'puzzle';
  2324. el.pzTitle.textContent = def.label;
  2325. el.pzDot.style.background = def.color;
  2326. el.pzKeys.textContent = puzzle.keys || '—';
  2327. const hints = {
  2328. keypad: 'Введите 4-значный код сверху. <kbd>Enter</kbd> — ОК, <kbd>Backspace</kbd> — стереть',
  2329. wires: 'Клик на левый, потом на правый того же цвета. Или <kbd>1</kbd>–<kbd>4</kbd>',
  2330. dials: 'Крутите диски кнопками &lt; &gt; до совпадения с зелёной меткой',
  2331. sliders: 'Кликните по дорожке, чтобы попасть в зелёную зону',
  2332. card: 'Перетащите карту в пунктирную зону. Скорость средняя',
  2333. sequence: 'Смотрите последовательность, потом повторите. <kbd>1</kbd>–<kbd>4</kbd>',
  2334. power: 'Нажмите <kbd>Space</kbd> когда маркер в зелёной зоне. 3 попадания',
  2335. flicker: 'Кликайте по красным помехам. Нужно 3 попадания'
  2336. };
  2337. if (currentDiff.showHints){
  2338. el.pzHint.innerHTML = hints[kind] || '—';
  2339. el.pzHint.className = '';
  2340. if (!currentDiff.hintsAlwaysVisible){
  2341. setTimeout(() => {
  2342. if (state === 'puzzle' && el.pzHint) { el.pzHint.textContent = ''; }
  2343. }, 3500);
  2344. }
  2345. } else {
  2346. el.pzHint.textContent = ''; el.pzHint.className = '';
  2347. }
  2348. hideAll(); showScreen('puzzle'); updateMobileVisibility();
  2349. focusStage(); startPuzzleLoop();
  2350. }
  2351. function closePuzzle(){
  2352. stopPuzzleLoop(); puzzle = null; activeIncident = null;
  2353. state = stateBeforePuzzle || 'playing'; stateBeforePuzzle = null;
  2354. hideAll();
  2355. if (state === 'playing'){ focusStage(); }
  2356. updateMobileVisibility();
  2357. }
  2358. function puzzleSolved(){
  2359. if (!activeIncident) return;
  2360. const inc = activeIncident;
  2361. activeIncident = null;
  2362. el.pzHint.textContent = 'OK'; el.pzHint.className = 'ok';
  2363. beep(880,.1); setTimeout(() => beep(1200,.12), 100);
  2364. setTimeout(() => {
  2365. stopPuzzleLoop(); puzzle = null;
  2366. if (!demoMode) fixIncident(inc);
  2367. state = demoMode ? 'menu' : 'playing'; stateBeforePuzzle = null;
  2368. hideAll();
  2369. if (demoMode){ showScreen('menu'); demoMode = false; } else focusStage();
  2370. updateMobileVisibility();
  2371. }, 300);
  2372. }
  2373. function puzzleFailed(){
  2374. if (demoMode) return;
  2375. if (!activeIncident) return;
  2376. el.pzHint.textContent = 'ОШИБКА'; el.pzHint.className = 'bad';
  2377. beep(200,.15,'square');
  2378. puzzleFailedActive = true;
  2379. setTimeout(() => { puzzleFailedActive = false; }, 800);
  2380. }
  2381. function startPuzzleLoop(){
  2382. if (puzzleRAF) return;
  2383. let lastT = performance.now();
  2384. function tick(now){
  2385. puzzleRAF = requestAnimationFrame(tick);
  2386. const dt = Math.min(0.05, (now - lastT)/1000); lastT = now;
  2387. if (!puzzle) return;
  2388. if (puzzle.update) puzzle.update(dt);
  2389. if (puzzleDirty){ puzzle.draw(); puzzleDirty = false; }
  2390. }
  2391. puzzleRAF = requestAnimationFrame(tick);
  2392. }
  2393. function stopPuzzleLoop(){ if (puzzleRAF){ cancelAnimationFrame(puzzleRAF); puzzleRAF = null; } }
  2394. function pzCoordsFromEvent(e){
  2395. const r = pzCanvas.getBoundingClientRect();
  2396. return {x: (e.clientX - r.left) * (PZ_W / r.width), y: (e.clientY - r.top) * (PZ_H / r.height)};
  2397. }
  2398. pzCanvas.addEventListener('mousedown', e => {
  2399. const p = pzCoordsFromEvent(e); puzzleMouse.x = p.x; puzzleMouse.y = p.y; puzzleMouse.down = true;
  2400. if (puzzle && puzzle.down) puzzle.down(p.x, p.y); puzzleDirty = true;
  2401. });
  2402. pzCanvas.addEventListener('mousemove', e => {
  2403. const p = pzCoordsFromEvent(e); puzzleMouse.x = p.x; puzzleMouse.y = p.y;
  2404. if (puzzle && puzzle.move) puzzle.move(p.x, p.y); puzzleDirty = true;
  2405. });
  2406. window.addEventListener('mouseup', () => {
  2407. puzzleMouse.down = false;
  2408. if (puzzle && puzzle.up) puzzle.up(); puzzleDirty = true;
  2409. });
  2410. function startDemo(kind){
  2411. demoMode = true; state = 'puzzle';
  2412. puzzle = makePuzzle(kind); puzzleDirty = true;
  2413. el.pzTitle.textContent = 'Демо: ' + kind;
  2414. el.pzKeys.textContent = puzzle.keys || '—';
  2415. el.pzHint.textContent = 'Демо — без штрафов'; el.pzHint.className = '';
  2416. hideAll(); showScreen('puzzle');
  2417. focusStage(); startPuzzleLoop();
  2418. }
  2419. let minimapBgDirty = true;
  2420. function updateMinimapBg(){
  2421. if (!minimapBg) minimapBg = document.createElement('canvas');
  2422. minimapBg.width = el.minimap.width; minimapBg.height = el.minimap.height;
  2423. const c = minimapBg.getContext('2d');
  2424. c.fillStyle = '#05080f'; c.fillRect(0, 0, c.canvas.width, c.canvas.height);
  2425. const s = Math.min(c.canvas.width / WORLD_W, c.canvas.height / WORLD_D);
  2426. const ox = (c.canvas.width - WORLD_W*s)/2, oy = (c.canvas.height - WORLD_D*s)/2;
  2427. for (const r of ROOMS){
  2428. c.fillStyle = r.isSoc ? 'rgba(74,222,128,.5)' : 'rgba(60,120,220,.3)';
  2429. c.fillRect(ox + r.x*s, oy + r.y*s, r.w*s, r.h*s);
  2430. c.strokeStyle = r.accent; c.lineWidth = 1;
  2431. c.strokeRect(ox + r.x*s + 0.5, oy + r.y*s + 0.5, r.w*s - 1, r.h*s - 1);
  2432. }
  2433. minimapBgDirty = false;
  2434. }
  2435. function drawMinimap(){
  2436. if (minimapBgDirty) updateMinimapBg();
  2437. const c = el.minimap.getContext('2d');
  2438. c.clearRect(0, 0, el.minimap.width, el.minimap.height);
  2439. if (minimapBg) c.drawImage(minimapBg, 0, 0);
  2440. const s = Math.min(el.minimap.width / WORLD_W, el.minimap.height / WORLD_D);
  2441. const ox = (el.minimap.width - WORLD_W*s)/2, oy = (el.minimap.height - WORLD_D*s)/2;
  2442. for (const inc of incidents){
  2443. c.fillStyle = INCIDENTS[inc.type].color;
  2444. c.beginPath(); c.arc(ox + inc.x*s, oy + inc.y*s, 2, 0, 7); c.fill();
  2445. }
  2446. for (const b of bots){
  2447. if (b.isCaught) continue;
  2448. c.fillStyle = b.isSuspect ? '#ff3030' : b.color;
  2449. c.beginPath(); c.arc(ox + b.x*s, oy + b.y*s, b.isSuspect ? 3 : 2, 0, 7); c.fill();
  2450. }
  2451. c.fillStyle = '#58a6ff';
  2452. c.beginPath(); c.arc(ox + player.x*s, oy + player.y*s, 3.5, 0, 7); c.fill();
  2453. }
  2454. function drawFurniture(f){
  2455. const spr = FURN_SPRITES[f.kind];
  2456. if (!spr) return;
  2457. const dx = f.x - camX - spr.pad;
  2458. const dy = f.y * DEPTH - camY - spr.pad;
  2459. if (dx + spr.w < 0 || dx > W || dy + spr.h < 0 || dy > H) return;
  2460. ctx.drawImage(spr.canvas, dx, dy);
  2461. }
  2462. function drawIncident(inc){
  2463. const f = inc.f;
  2464. const sx = f.x + f.w/2 - camX;
  2465. const sy = f.y * DEPTH - camY + f.d * DEPTH/2;
  2466. const pulse = 0.5 + Math.sin(time * 6 + inc.x * 0.01) * 0.5;
  2467. const def = INCIDENTS[inc.type];
  2468. ctx.strokeStyle = def.color;
  2469. ctx.globalAlpha = 0.4 + pulse * 0.5;
  2470. ctx.lineWidth = 2;
  2471. ctx.strokeRect(f.x - camX - 2, f.y * DEPTH - camY - 2, f.w + 4, f.d * DEPTH + 4);
  2472. ctx.globalAlpha = 1;
  2473. setFont('700 11px "Consolas",monospace');
  2474. const txt = def.tag.toUpperCase().slice(0, 4);
  2475. const tw = ctx.measureText(txt).width + 10;
  2476. const bx = sx - tw/2, by = sy - 42;
  2477. ctx.fillStyle = def.color;
  2478. roundRect(ctx, bx, by, tw, 14, 3); ctx.fill();
  2479. ctx.fillStyle = '#0a0a0a';
  2480. ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  2481. ctx.fillText(txt, sx, by + 7);
  2482. const ratio = clamp(inc.timeLeft / inc.maxTime, 0, 1);
  2483. ctx.fillStyle = 'rgba(0,0,0,.7)';
  2484. ctx.fillRect(sx - 18, sy - 24, 36, 3);
  2485. ctx.fillStyle = ratio < 0.3 ? '#f85149' : ratio < 0.6 ? '#fbbf24' : '#4ade80';
  2486. ctx.fillRect(sx - 18, sy - 24, 36 * ratio, 3);
  2487. }
  2488. function drawBot(b){
  2489. const sx = b.x - camX, sy = b.y * DEPTH - camY;
  2490. ctx.fillStyle = 'rgba(0,0,0,.4)';
  2491. ctx.beginPath(); ctx.ellipse(sx, sy + 4, 11, 4, 0, 0, 7); ctx.fill();
  2492. ctx.fillStyle = b.color;
  2493. roundRect(ctx, sx - 8, sy - 18, 16, 20, 4); ctx.fill();
  2494. ctx.strokeStyle = 'rgba(0,0,0,.4)'; ctx.lineWidth = 1;
  2495. roundRect(ctx, sx - 8, sy - 18, 16, 20, 4); ctx.stroke();
  2496. ctx.fillStyle = '#f5d5b5';
  2497. ctx.beginPath(); ctx.arc(sx, sy - 22, 6, 0, 7); ctx.fill();
  2498. ctx.fillStyle = b.color;
  2499. ctx.beginPath(); ctx.arc(sx, sy - 25, 6, Math.PI, 0); ctx.fill();
  2500. if (b.isSuspect){
  2501. ctx.strokeStyle = 'rgba(255,48,48,' + (0.5 + Math.sin(time * 8) * 0.5) + ')';
  2502. ctx.lineWidth = 2;
  2503. ctx.beginPath(); ctx.arc(sx, sy - 10, 18, 0, 7); ctx.stroke();
  2504. }
  2505. }
  2506. function drawPlayer(){
  2507. const bob = player.moving ? Math.sin(time * 15) * 1.5 : 0;
  2508. const sx = player.x - camX, sy = player.y * DEPTH - camY + bob;
  2509. ctx.fillStyle = 'rgba(0,0,0,.5)';
  2510. ctx.beginPath(); ctx.ellipse(sx, sy + 5, 12, 4, 0, 0, 7); ctx.fill();
  2511. ctx.fillStyle = '#2a7aef';
  2512. roundRect(ctx, sx - 10, sy - 20, 20, 22, 5); ctx.fill();
  2513. ctx.fillStyle = 'rgba(255,255,255,.3)';
  2514. ctx.beginPath();
  2515. ctx.moveTo(sx - 5, sy - 20); ctx.lineTo(sx, sy - 16); ctx.lineTo(sx + 5, sy - 20);
  2516. ctx.closePath(); ctx.fill();
  2517. ctx.fillStyle = '#ffd5b5';
  2518. ctx.beginPath(); ctx.arc(sx, sy - 26, 7, 0, 7); ctx.fill();
  2519. ctx.fillStyle = '#3a2010';
  2520. ctx.beginPath(); ctx.arc(sx, sy - 29, 7, Math.PI, 0); ctx.fill();
  2521. ctx.fillStyle = '#1a1a2a';
  2522. ctx.beginPath(); ctx.arc(sx + player.dir * 2, sy - 26, 1.5, 0, 7); ctx.fill();
  2523. }
  2524. const _drawQueue = [];
  2525. function drawAllEntities(){
  2526. _drawQueue.length = 0;
  2527. for (const f of FURN){
  2528. const sx = f.x - camX, sy = f.y * DEPTH - camY;
  2529. if (sx + f.w < -50 || sx > W+50 || sy + f.d * DEPTH < -100 || sy > H+100) continue;
  2530. _drawQueue.push({t:0, o:f, y:f.y + f.d*0.5});
  2531. }
  2532. for (const inc of incidents) _drawQueue.push({t:1, o:inc, y:inc.f.y + inc.f.d*0.5});
  2533. for (const b of bots) if (!b.isCaught) _drawQueue.push({t:2, o:b, y:b.y});
  2534. if (state === 'playing') _drawQueue.push({t:3, o:player, y:player.y});
  2535. _drawQueue.sort((a,b) => a.y - b.y);
  2536. for (const e of _drawQueue){
  2537. if (e.t === 0) drawFurniture(e.o);
  2538. else if (e.t === 1) drawIncident(e.o);
  2539. else if (e.t === 2) drawBot(e.o);
  2540. else if (e.t === 3) drawPlayer();
  2541. }
  2542. }
  2543. function drawParticles(){
  2544. for (let i = particles.length - 1; i >= 0; i--){
  2545. const p = particles[i];
  2546. p.life -= 1/60;
  2547. if (p.life <= 0){ releaseParticle(p); particles.splice(i, 1); continue; }
  2548. p.x += p.vx * 0.016; p.y += p.vy * 0.016; p.z += p.vz * 0.016;
  2549. p.vz -= 400 * 0.016;
  2550. if (p.z < 0){ p.z = 0; p.vz *= -0.4; }
  2551. p.vx *= 0.96; p.vy *= 0.96;
  2552. ctx.globalAlpha = clamp(p.life / 0.75, 0, 1);
  2553. ctx.fillStyle = p.color;
  2554. ctx.beginPath(); ctx.arc(p.x - camX, p.y * DEPTH - camY - p.z, p.size, 0, 7); ctx.fill();
  2555. }
  2556. ctx.globalAlpha = 1;
  2557. }
  2558. function drawToasts(){
  2559. let y = 80;
  2560. for (const t of toasts){
  2561. const x = W/2 - t.w/2;
  2562. ctx.globalAlpha = clamp(t.life, 0, 1);
  2563. ctx.fillStyle = 'rgba(10,15,26,.95)';
  2564. ctx.fillRect(x, y, t.w, 26);
  2565. ctx.strokeStyle = t.type === 'bad' ? '#f85149' : t.type === 'warn' ? '#fbbf24' : '#4ade80';
  2566. ctx.lineWidth = 1;
  2567. ctx.strokeRect(x + 0.5, y + 0.5, t.w - 1, 25);
  2568. setFont('600 12px "Segoe UI",sans-serif');
  2569. ctx.fillStyle = '#fff';
  2570. ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  2571. ctx.fillText(t.text, W/2, y + 13);
  2572. y += 30;
  2573. }
  2574. ctx.globalAlpha = 1;
  2575. for (let i = toasts.length - 1; i >= 0; i--){
  2576. toasts[i].life -= 1/60;
  2577. if (toasts[i].life <= 0) toasts.splice(i, 1);
  2578. }
  2579. }
  2580. function updatePlayer(dt, speed){
  2581. let dx = 0, dy = 0;
  2582. if (keys.up) dy -= 1; if (keys.down) dy += 1;
  2583. if (keys.left) dx -= 1; if (keys.right) dx += 1;
  2584. player.moving = (dx !== 0 || dy !== 0);
  2585. if (player.moving){
  2586. const l = Math.sqrt(dx*dx + dy*dy); dx /= l; dy /= l;
  2587. const total = speed * dt, steps = Math.max(1, Math.ceil(total / 5));
  2588. const stepLen = total / steps;
  2589. for (let s = 0; s < steps; s++){ player.x += dx * stepLen; player.y += dy * stepLen; collide(player, player.r); }
  2590. if (dx !== 0) player.dir = dx > 0 ? 1 : -1;
  2591. }
  2592. }
  2593. function updateIncidents(dt){
  2594. for (let i = incidents.length - 1; i >= 0; i--){
  2595. incidents[i].timeLeft -= dt;
  2596. if (incidents[i].timeLeft <= 0){ leakIncident(incidents[i]); }
  2597. }
  2598. }
  2599. function updateSpawning(dt){
  2600. shiftSpawnTimer -= dt;
  2601. if (shiftSpawnTimer > 0) return;
  2602. const shift = currentDiff.shifts[currentShift];
  2603. if (spawnedInShift >= shift.count) return;
  2604. shiftSpawnTimer = 3 + Math.random() * 3;
  2605. const pending = waveTasks.filter(w => w.done < w.need);
  2606. if (!pending.length) return;
  2607. const wt = pending[Math.floor(Math.random() * pending.length)];
  2608. const def = INCIDENTS[wt.type];
  2609. const cands = FURN.filter(f => f.tags && f.tags.includes(def.tag) && !incidents.some(i => i.f === f));
  2610. if (!cands.length) return;
  2611. const f = cands[Math.floor(Math.random() * cands.length)];
  2612. const life = shift.time;
  2613. incidents.push({type: wt.type, f, x: f.x + f.w/2, y: f.y + f.d/2, maxTime: life, timeLeft: life});
  2614. spawnedInShift++;
  2615. addLog('Обнаружено: ' + def.label, 'warn');
  2616. }
  2617. function checkShiftComplete(){
  2618. if (state !== 'playing') return;
  2619. if (spawnedInShift < currentDiff.shifts[currentShift].count) return;
  2620. if (incidents.length > 0) return;
  2621. for (const w of waveTasks) if (w.done < w.need) return;
  2622. setTimeout(showShiftDebrief, 800);
  2623. }
  2624. let lastT = performance.now();
  2625. function loop(now){
  2626. const dt = Math.min(0.05, (now - lastT) / 1000); lastT = now;
  2627. time += dt;
  2628. if (state === 'playing'){
  2629. updatePlayer(dt, 280);
  2630. updateBots(dt);
  2631. updateIncidents(dt);
  2632. updateSpawning(dt);
  2633. updateCamera();
  2634. updateHintPanel();
  2635. if (actionPressed){
  2636. actionPressed = false;
  2637. const {inc, d} = nearestIncident();
  2638. if (inc && d < 60) openPuzzle(inc);
  2639. else {
  2640. const here = roomAt(player.x, player.y);
  2641. if (here && here.isSoc) openCameraView();
  2642. }
  2643. }
  2644. checkShiftComplete();
  2645. ctx.fillStyle = '#050810'; ctx.fillRect(0, 0, W, H);
  2646. if (staticReady){
  2647. const sx = camX | 0, sy = camY | 0;
  2648. const sw = Math.min(W, staticCanvas.width - sx);
  2649. const sh = Math.min(H, staticCanvas.height - sy);
  2650. if (sw > 0 && sh > 0) ctx.drawImage(staticCanvas, sx, sy, sw, sh, 0, 0, sw, sh);
  2651. }
  2652. drawAllEntities();
  2653. drawParticles();
  2654. drawToasts();
  2655. drawMinimap();
  2656. } else if (state === 'camera'){
  2657. drawCameras();
  2658. }
  2659. requestAnimationFrame(loop);
  2660. }
  2661. function tryLoadGame(){
  2662. const s = loadGameState();
  2663. if (!s){ showHint('Нет сохранения', 2500); return; }
  2664. settings.diff = s.diff || 'normal';
  2665. applySettingsToUI();
  2666. startGame();
  2667. score = s.score || 0; leaks = s.leaks || 0; fixedCount = s.fixedCount || 0; totalCaught = s.totalCaught || 0;
  2668. currentShift = s.shift || 0;
  2669. updateHUD();
  2670. }
  2671. function bind(id, evt, fn){
  2672. const e = document.getElementById(id);
  2673. if (!e){ console.warn('[BIND FAIL] #' + id + ' not found'); return; }
  2674. e.addEventListener(evt, fn);
  2675. }
  2676. bind('modalYes', 'click', () => { el.modalBack.classList.add('hide'); if (modalResolve){ modalResolve(true); modalResolve = null; } });
  2677. bind('modalNo', 'click', () => { el.modalBack.classList.add('hide'); if (modalResolve){ modalResolve(false); modalResolve = null; } });
  2678. bind('btnPlayGame', 'click', () => { clearGameState(); startGame(); });
  2679. bind('btnContinue', 'click', () => tryLoadGame());
  2680. bind('btnTutorial', 'click', () => { buildTutGrid(); state = 'tutorial'; hideAll(); showScreen('tutorial'); });
  2681. bind('btnPuzzleHelp', 'click', () => { buildTutGrid(); state = 'tutorial'; hideAll(); showScreen('tutorial'); });
  2682. bind('btnSettings', 'click', () => { state = 'settings'; hideAll(); showScreen('settings'); });
  2683. bind('btnAchievements', 'click', () => { renderAchievementsUI(); state = 'ach'; hideAll(); showScreen('ach'); });
  2684. bind('btnAchBack', 'click', () => { state = 'menu'; hideAll(); showScreen('menu'); });
  2685. bind('btnRules', 'click', () => { state = 'rules'; hideAll(); showScreen('rules'); });
  2686. bind('btnRulesBack', 'click', () => { state = 'menu'; hideAll(); showScreen('menu'); });
  2687. bind('btnSettingsBack', 'click', () => { state = 'menu'; hideAll(); showScreen('menu'); });
  2688. bind('btnTutBack', 'click', () => { state = 'menu'; hideAll(); showScreen('menu'); });
  2689. bind('btnTutSectionBack', 'click', () => { hideAll(); showScreen('tutorial'); });
  2690. bind('btnTutTry', 'click', () => { if (curTut) startDemo(curTut.id); });
  2691. bind('btnTutDetailBack', 'click', () => { hideAll(); showScreen('tutorial'); });
  2692. bind('btnResume', 'click', () => resumeGame());
  2693. bind('btnPauseRules', 'click', () => { state = 'rules'; hideAll(); showScreen('rules'); });
  2694. bind('btnExitMenu', 'click', () => exitToMenu());
  2695. bind('btnRestart', 'click', () => { clearGameState(); startGame(); });
  2696. bind('btnMenu', 'click', () => { state = 'end'; exitToMenu(); });
  2697. bind('btnHomeTop', 'click', () => exitToMenu());
  2698. bind('btnPauseTop', 'click', () => { if (state === 'playing') pauseGame(); else if (state === 'paused') resumeGame(); });
  2699. bind('btnHelpTop', 'click', () => showContextHint());
  2700. bind('btnFsTop', 'click', () => toggleFullscreen());
  2701. bind('btnFs', 'click', () => toggleFullscreen());
  2702. bind('camClose', 'click', () => closeCameraView());
  2703. bind('camReport', 'click', () => reportSuspect());
  2704. bind('shiftNext', 'click', () => {
  2705. if (currentShift >= currentDiff.shifts.length - 1) startAudit();
  2706. else startShift(currentShift + 1);
  2707. });
  2708. bind('btnAuditStart', 'click', () => {
  2709. const passed = leaks === 0;
  2710. statsAch.auditPassed = passed;
  2711. checkAchievements(statsAch);
  2712. endGame(passed);
  2713. });
  2714. bind('pzCancel', 'click', closePuzzle);
  2715. bind('btnResetProgress', 'click', async () => {
  2716. const ok = await showModal('Удалить весь прогресс?');
  2717. if (!ok) return;
  2718. try { localStorage.removeItem('shield9_highscore'); localStorage.removeItem('shield9_ach'); localStorage.removeItem('shield9_savestate'); } catch(e){}
  2719. highScore = 0; unlockedAchievements = new Set();
  2720. applySettingsToUI(); renderAchievementsUI(); refreshAchievementHUD(); updateContinueButton();
  2721. toast('Прогресс сброшен', 'info');
  2722. });
  2723. document.querySelectorAll('#segDiff button').forEach(b => {
  2724. b.addEventListener('click', () => { settings.diff = b.dataset.v; saveSettings(); applySettingsToUI(); });
  2725. });
  2726. document.querySelectorAll('#segSound button').forEach(b => {
  2727. b.addEventListener('click', () => { settings.sound = +b.dataset.v; saveSettings(); applySettingsToUI(); });
  2728. });
  2729. document.querySelectorAll('#segMobile button').forEach(b => {
  2730. b.addEventListener('click', () => { settings.mobile = b.dataset.v; saveSettings(); applySettingsToUI(); updateMobileVisibility(); });
  2731. });
  2732. if (el.joyPad){
  2733. const joyPadBtns = el.joyPad.querySelectorAll('.b');
  2734. joyPadBtns.forEach(b => {
  2735. const k = b.dataset.k;
  2736. b.addEventListener('pointerdown', e => { e.preventDefault(); keys[k] = true; });
  2737. b.addEventListener('pointerup', e => { e.preventDefault(); keys[k] = false; });
  2738. b.addEventListener('pointercancel', () => { keys[k] = false; });
  2739. b.addEventListener('pointerleave', () => { keys[k] = false; });
  2740. });
  2741. }
  2742. if (el.btnAction){
  2743. el.btnAction.addEventListener('pointerdown', e => { e.preventDefault(); actionPressed = true; });
  2744. }
  2745. try {
  2746. applySettingsToUI();
  2747. renderAchievementsUI();
  2748. updateContinueButton();
  2749. focusStage();
  2750. requestAnimationFrame(loop);
  2751. console.log('[BOOT] OK');
  2752. } catch(e){
  2753. console.error('[BOOT FAIL]', e);
  2754. const h = document.getElementById('hintBar');
  2755. const t = document.getElementById('hintText');
  2756. if (h && t){ t.textContent = 'ОШИБКА ЗАПУСКА: ' + e.message; h.classList.add('show'); }
  2757. }
  2758. })();
  2759. </script>
  2760. </body>
  2761. </html>