игра.html 134 KB

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