Hasli4

Untitled

Aug 17th, 2026
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 43.45 KB | None | 0 0
  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.0, viewport-fit=cover">
  6. <title>Алгоритм сна</title>
  7. <style>
  8. * { box-sizing: border-box; }
  9. :root {
  10. --bg: #090d18;
  11. --panel: rgba(20, 27, 47, .88);
  12. --panel2: rgba(13, 19, 35, .94);
  13. --line: rgba(151, 177, 225, .16);
  14. --text: #ecf4ff;
  15. --muted: #8ea0bc;
  16. --accent: #7ad6ff;
  17. --cell: min(7vw, 54px);
  18. }
  19. html, body {
  20. margin: 0;
  21. min-height: 100%;
  22. background:
  23. radial-gradient(circle at 50% -10%, #203251 0, #0b1020 42%, #070a13 100%);
  24. color: var(--text);
  25. font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
  26. overflow-x: hidden;
  27. }
  28. body {
  29. min-height: 100vh;
  30. display: flex;
  31. justify-content: center;
  32. padding: 14px;
  33. }
  34. button { font: inherit; }
  35.  
  36. .game {
  37. width: min(1180px, 100%);
  38. display: flex;
  39. flex-direction: column;
  40. gap: 12px;
  41. }
  42. header {
  43. display: flex;
  44. align-items: center;
  45. justify-content: space-between;
  46. gap: 12px;
  47. }
  48. .title-wrap h1 {
  49. margin: 0;
  50. font-size: clamp(22px, 4vw, 34px);
  51. letter-spacing: .03em;
  52. }
  53. .title-wrap p {
  54. margin: 4px 0 0;
  55. color: var(--muted);
  56. font-size: 13px;
  57. }
  58. .restart {
  59. border: 1px solid rgba(135, 180, 235, .25);
  60. color: #e9f7ff;
  61. background: rgba(255,255,255,.06);
  62. border-radius: 12px;
  63. padding: 10px 14px;
  64. cursor: pointer;
  65. touch-action: manipulation;
  66. }
  67. .restart:hover { background: rgba(255,255,255,.11); }
  68.  
  69. .top-area {
  70. display: grid;
  71. grid-template-columns: minmax(0, 1fr) 250px;
  72. gap: 12px;
  73. align-items: stretch;
  74. }
  75. .consciousness, .side-panel, .subconscious-panel {
  76. border: 1px solid var(--line);
  77. background: linear-gradient(180deg, rgba(30, 40, 66, .82), rgba(12, 17, 30, .92));
  78. border-radius: 18px;
  79. box-shadow: 0 18px 50px rgba(0,0,0,.22), inset 0 1px rgba(255,255,255,.04);
  80. }
  81.  
  82. .consciousness {
  83. position: relative;
  84. min-height: 330px;
  85. overflow: hidden;
  86. }
  87. .scene-label {
  88. position: absolute;
  89. left: 16px;
  90. top: 12px;
  91. color: var(--muted);
  92. font-size: 12px;
  93. text-transform: uppercase;
  94. letter-spacing: .16em;
  95. z-index: 3;
  96. pointer-events: none;
  97. }
  98. .window-glow {
  99. position: absolute;
  100. width: 180px;
  101. height: 120px;
  102. right: 8%;
  103. top: 20px;
  104. background: radial-gradient(circle, rgba(111,169,255,.18), transparent 70%);
  105. pointer-events: none;
  106. }
  107. .bed {
  108. position: absolute;
  109. left: 5%;
  110. right: 5%;
  111. bottom: 26px;
  112. height: 150px;
  113. }
  114. .headboard {
  115. position: absolute;
  116. left: 2%;
  117. bottom: 52px;
  118. width: 13%;
  119. height: 90px;
  120. border-radius: 18px 18px 5px 5px;
  121. background: linear-gradient(180deg, #423552, #2b273f);
  122. border: 1px solid rgba(255,255,255,.08);
  123. }
  124. .mattress {
  125. position: absolute;
  126. left: 10%;
  127. right: 0;
  128. bottom: 44px;
  129. height: 66px;
  130. border-radius: 18px 22px 12px 12px;
  131. background: linear-gradient(180deg, #dbe5ef 0%, #b8c7d8 55%, #8798ab 100%);
  132. box-shadow: 0 10px 0 #5a6477, 0 18px 28px rgba(0,0,0,.35);
  133. }
  134. .blanket {
  135. position: absolute;
  136. left: 38%;
  137. right: 3%;
  138. bottom: 50px;
  139. height: 56px;
  140. border-radius: 24px 18px 14px 14px;
  141. background: linear-gradient(135deg, #4f6ca2, #324b78);
  142. box-shadow: inset 0 8px 18px rgba(255,255,255,.06);
  143. transform: skewX(-5deg);
  144. }
  145. .pillow {
  146. position: absolute;
  147. left: 14%;
  148. bottom: 82px;
  149. width: 22%;
  150. height: 38px;
  151. border-radius: 18px;
  152. background: #e7eef7;
  153. box-shadow: inset 0 -7px 14px rgba(86,101,125,.28);
  154. z-index: 2;
  155. }
  156. .character {
  157. position: absolute;
  158. left: 22%;
  159. bottom: 91px;
  160. width: 88px;
  161. height: 68px;
  162. z-index: 5;
  163. display: grid;
  164. place-items: center;
  165. user-select: none;
  166. pointer-events: none;
  167. }
  168. .character .face {
  169. width: 68px;
  170. height: 58px;
  171. border-radius: 50% 50% 44% 44%;
  172. background: linear-gradient(180deg, #f3c999, #d89761);
  173. border: 2px solid rgba(0,0,0,.15);
  174. position: relative;
  175. box-shadow: 0 10px 18px rgba(0,0,0,.2);
  176. }
  177. .eye, .brow, .mouth {
  178. position: absolute;
  179. left: 50%;
  180. transform: translateX(-50%);
  181. }
  182. .eye { top: 23px; width: 9px; height: 5px; border-radius: 50%; }
  183. .eye.left { left: 27%; }
  184. .eye.right { left: 73%; }
  185. .brow { width: 19px; height: 4px; border-radius: 4px; top: 16px; }
  186. .brow.left { left: 28%; }
  187. .brow.right { left: 72%; }
  188. .mouth { top: 38px; width: 24px; height: 9px; border-bottom: 3px solid #7c3d32; border-radius: 0 0 50% 50%; }
  189.  
  190. .state-sleep .eye { background: #563c39; }
  191. .state-sleep .eye::after {
  192. content: "—";
  193. position: absolute; left: -2px; top: -6px;
  194. font-size: 13px; color: #563c39;
  195. }
  196. .state-sleep .brow { background: transparent; border-top: 2px solid #915b47; }
  197. .state-sleep .mouth { border-bottom: 2px solid #7c3d32; }
  198. .state-irritated .eye { background: #452e30; height: 3px; }
  199. .state-irritated .brow { background: #633333; transform: translateX(-50%) rotate(10deg); }
  200. .state-irritated .mouth { border-bottom: 0; border-top: 3px solid #7c3d32; border-radius: 50%; }
  201. .state-angry .eye { background: #9a2222; height: 8px; }
  202. .state-angry .brow { background: #4f2323; }
  203. .state-angry .mouth { width: 25px; height: 12px; border-bottom: 3px solid #682122; border-radius: 50%; }
  204.  
  205. .character[data-frame="1"] { transform: translateY(-2px) rotate(-1deg); }
  206. .character[data-frame="2"] { transform: translateY(2px) rotate(1deg); }
  207. .character[data-frame="3"] { transform: translateY(-1px) rotate(0deg); }
  208.  
  209. .hint {
  210. position: absolute;
  211. left: 50%;
  212. top: 50%;
  213. transform: translate(-50%, -10%);
  214. color: rgba(223,235,255,.55);
  215. font-size: 13px;
  216. text-align: center;
  217. pointer-events: none;
  218. z-index: 1;
  219. }
  220.  
  221. .thought {
  222. position: absolute;
  223. display: grid;
  224. touch-action: none;
  225. cursor: grab;
  226. user-select: none;
  227. z-index: 10;
  228. filter: drop-shadow(0 12px 18px rgba(0,0,0,.24));
  229. transition: filter .15s ease;
  230. }
  231. .thought.dragging {
  232. cursor: grabbing;
  233. filter: drop-shadow(0 18px 32px rgba(0,0,0,.38));
  234. z-index: 50;
  235. }
  236. .thought-cell, .board-cell {
  237. width: var(--cell);
  238. height: var(--cell);
  239. }
  240. .thought-cell {
  241. display: grid;
  242. place-items: center;
  243. border: 1px solid rgba(255,255,255,.12);
  244. border-radius: 8px;
  245. background: var(--block-color, #5979a8);
  246. box-shadow: inset 0 1px rgba(255,255,255,.11);
  247. overflow: hidden;
  248. }
  249. .thought-text {
  250. grid-column: 1 / 99;
  251. grid-row: 1 / 99;
  252. align-self: center;
  253. justify-self: center;
  254. width: max(90px, 130%);
  255. max-width: 280px;
  256. padding: 3px 7px;
  257. font-size: 11px;
  258. line-height: 1.1;
  259. text-align: center;
  260. color: white;
  261. text-shadow: 0 1px 2px rgba(0,0,0,.45);
  262. pointer-events: none;
  263. }
  264.  
  265. .side-panel {
  266. padding: 14px;
  267. display: flex;
  268. flex-direction: column;
  269. gap: 13px;
  270. }
  271. .stat-card {
  272. background: rgba(5,9,18,.3);
  273. border: 1px solid rgba(255,255,255,.06);
  274. border-radius: 14px;
  275. padding: 11px;
  276. }
  277. .stat-head {
  278. display: flex;
  279. justify-content: space-between;
  280. gap: 10px;
  281. font-size: 12px;
  282. color: var(--muted);
  283. margin-bottom: 7px;
  284. }
  285. .stress-value { font-weight: 700; color: #f5fbff; }
  286. .stress-track {
  287. height: 14px;
  288. border-radius: 999px;
  289. overflow: hidden;
  290. background: #090e1a;
  291. border: 1px solid rgba(255,255,255,.07);
  292. }
  293. .stress-fill {
  294. width: 0%;
  295. height: 100%;
  296. border-radius: inherit;
  297. background: linear-gradient(90deg, #4ed8a6, #ffd45a 60%, #ff5d6c);
  298. transition: width .25s ease;
  299. }
  300. .rows {
  301. font-size: 12px;
  302. color: var(--muted);
  303. }
  304. .rows strong { color: var(--text); }
  305.  
  306. .bonus-title {
  307. font-size: 12px;
  308. color: var(--muted);
  309. text-transform: uppercase;
  310. letter-spacing: .11em;
  311. }
  312. .bonus {
  313. border: 1px solid rgba(255,255,255,.08);
  314. background: rgba(255,255,255,.045);
  315. color: var(--text);
  316. padding: 11px;
  317. border-radius: 12px;
  318. text-align: left;
  319. cursor: pointer;
  320. display: flex;
  321. justify-content: space-between;
  322. align-items: center;
  323. gap: 8px;
  324. touch-action: manipulation;
  325. }
  326. .bonus:hover:not(:disabled) { background: rgba(255,255,255,.09); }
  327. .bonus:disabled { opacity: .4; cursor: not-allowed; }
  328. .bonus small { color: var(--muted); }
  329. .controls-hint {
  330. font-size: 11px;
  331. color: #7788a2;
  332. line-height: 1.4;
  333. margin-top: auto;
  334. }
  335.  
  336. .subconscious-panel {
  337. padding: 14px;
  338. }
  339. .sub-head {
  340. display: flex;
  341. justify-content: space-between;
  342. align-items: center;
  343. margin-bottom: 10px;
  344. gap: 10px;
  345. }
  346. .sub-title {
  347. font-size: 14px;
  348. font-weight: 700;
  349. }
  350. .next-thought {
  351. color: var(--muted);
  352. font-size: 12px;
  353. }
  354. .grid-wrap {
  355. display: flex;
  356. justify-content: center;
  357. overflow: auto;
  358. padding-bottom: 2px;
  359. }
  360. .subconscious-grid {
  361. display: grid;
  362. grid-template-columns: repeat(10, var(--cell));
  363. grid-template-rows: repeat(8, var(--cell));
  364. width: calc(var(--cell) * 10);
  365. height: calc(var(--cell) * 8);
  366. gap: 2px;
  367. padding: 2px;
  368. border-radius: 14px;
  369. background: rgba(106,129,173,.12);
  370. border: 1px solid rgba(151,177,225,.15);
  371. touch-action: none;
  372. }
  373. .board-cell {
  374. border-radius: 7px;
  375. background: rgba(110, 139, 188, .08);
  376. border: 1px solid rgba(152,181,224,.08);
  377. transition: background .12s ease, transform .12s ease;
  378. }
  379. .board-cell.preview-ok { background: rgba(98,221,165,.24); }
  380. .board-cell.preview-bad { background: rgba(255,95,107,.28); }
  381. .board-cell.filled {
  382. background: var(--fill-color, #5979a8);
  383. border-color: rgba(255,255,255,.13);
  384. box-shadow: inset 0 1px rgba(255,255,255,.13);
  385. }
  386. .board-cell.clearing { animation: clearCell .34s ease forwards; }
  387. @keyframes clearCell {
  388. 0% { transform: scale(1); filter: brightness(1); opacity: 1; }
  389. 55% { transform: scale(1.18); filter: brightness(1.7); opacity: .82; }
  390. 100% { transform: scale(.15); opacity: 0; }
  391. }
  392.  
  393. .floating-message {
  394. position: fixed;
  395. left: 50%;
  396. top: 16%;
  397. transform: translateX(-50%) translateY(-8px);
  398. background: rgba(13,19,34,.92);
  399. border: 1px solid rgba(255,255,255,.1);
  400. padding: 10px 14px;
  401. border-radius: 12px;
  402. z-index: 500;
  403. opacity: 0;
  404. pointer-events: none;
  405. transition: opacity .18s, transform .18s;
  406. box-shadow: 0 15px 40px rgba(0,0,0,.28);
  407. }
  408. .floating-message.show {
  409. opacity: 1;
  410. transform: translateX(-50%) translateY(0);
  411. }
  412. .overlay {
  413. position: fixed;
  414. inset: 0;
  415. background: rgba(3,6,12,.72);
  416. backdrop-filter: blur(8px);
  417. display: none;
  418. align-items: center;
  419. justify-content: center;
  420. z-index: 400;
  421. padding: 20px;
  422. }
  423. .overlay.show { display: flex; }
  424. .result-card {
  425. width: min(450px, 100%);
  426. background: linear-gradient(180deg, #18223a, #0d1426);
  427. border: 1px solid rgba(255,255,255,.11);
  428. border-radius: 22px;
  429. padding: 28px;
  430. text-align: center;
  431. box-shadow: 0 25px 70px rgba(0,0,0,.45);
  432. }
  433. .result-card h2 { margin: 0 0 8px; font-size: 30px; }
  434. .result-card p { margin: 0 0 18px; color: var(--muted); line-height: 1.5; }
  435. .result-card button {
  436. border: 0;
  437. background: #78d4ff;
  438. color: #07101a;
  439. padding: 12px 18px;
  440. border-radius: 12px;
  441. font-weight: 800;
  442. cursor: pointer;
  443. }
  444.  
  445. @media (max-width: 850px) {
  446. .top-area { grid-template-columns: 1fr; }
  447. .side-panel { order: -1; }
  448. .consciousness { min-height: 300px; }
  449. .hint { top: 45%; width: 80%; }
  450. :root { --cell: min(8.6vw, 52px); }
  451. }
  452. @media (max-width: 540px) {
  453. body { padding: 8px; }
  454. header { align-items: flex-start; }
  455. .title-wrap p { max-width: 240px; }
  456. .side-panel { display: grid; grid-template-columns: repeat(2, 1fr); }
  457. .side-panel .stat-card { grid-column: 1 / -1; }
  458. .bonus-title { grid-column: 1 / -1; }
  459. .bonus { min-height: 58px; }
  460. .controls-hint { grid-column: 1 / -1; }
  461. .consciousness { min-height: 270px; }
  462. .bed { left: 1%; right: 1%; }
  463. .character { left: 19%; }
  464. .thought-text { font-size: 9px; }
  465. }
  466. </style>
  467. </head>
  468. <body>
  469. <div class="game">
  470. <header>
  471. <div class="title-wrap">
  472. <h1>🌙 Алгоритм сна</h1>
  473. <p>Уложи навязчивые мысли в подсознание без пробелов.</p>
  474. </div>
  475. <button class="restart" id="restartBtn">↻ Заново</button>
  476. </header>
  477.  
  478. <section class="top-area">
  479. <div class="consciousness" id="consciousness">
  480. <div class="scene-label">СОЗНАНИЕ</div>
  481. <div class="window-glow"></div>
  482.  
  483. <div class="bed">
  484. <div class="headboard"></div>
  485. <div class="mattress"></div>
  486. <div class="blanket"></div>
  487. <div class="pillow"></div>
  488.  
  489. <div class="character state-sleep" id="character" data-frame="1">
  490. <div class="face">
  491. <div class="brow left"></div>
  492. <div class="brow right"></div>
  493. <div class="eye left"></div>
  494. <div class="eye right"></div>
  495. <div class="mouth"></div>
  496. </div>
  497. </div>
  498. </div>
  499. <div class="hint" id="hint">Перетащи мысль в подсознание.<br>Правый клик или долгое нажатие — повернуть.</div>
  500. </div>
  501.  
  502. <aside class="side-panel">
  503. <div class="stat-card">
  504. <div class="stat-head">
  505. <span>Стресс</span>
  506. <span class="stress-value" id="stressValue">0%</span>
  507. </div>
  508. <div class="stress-track"><div class="stress-fill" id="stressFill"></div></div>
  509. <div class="rows" style="margin-top:8px;">Заполнено рядов: <strong id="rowsValue">0 / 5</strong></div>
  510. </div>
  511.  
  512. <div class="bonus-title">Бонусы</div>
  513. <button class="bonus" id="sheepBtn">
  514. <span>🐑 Считать овец</span><small id="sheepCount">2</small>
  515. </button>
  516. <button class="bonus" id="noiseBtn">
  517. <span>🌫️ Белый шум</span><small id="noiseCount">2</small>
  518. </button>
  519.  
  520. <div class="controls-hint">
  521. 🖱️ Перетащи мышью<br>
  522. 📱 На телефоне — пальцем<br>
  523. 🔄 ПКМ / долгое нажатие — поворот
  524. </div>
  525. </aside>
  526. </section>
  527.  
  528. <section class="subconscious-panel">
  529. <div class="sub-head">
  530. <div class="sub-title">🧠 ПОДСОЗНАНИЕ · 10 × 8</div>
  531. <div class="next-thought" id="nextThought">Новая мысль готовится…</div>
  532. </div>
  533. <div class="grid-wrap">
  534. <div class="subconscious-grid" id="grid"></div>
  535. </div>
  536. </section>
  537. </div>
  538.  
  539. <div class="floating-message" id="floatingMessage"></div>
  540.  
  541. <div class="overlay" id="resultOverlay">
  542. <div class="result-card">
  543. <h2 id="resultTitle">Ты заснул</h2>
  544. <p id="resultText"></p>
  545. <button id="resultRestart">Попробовать ещё раз</button>
  546. </div>
  547. </div>
  548.  
  549. <script>
  550. (() => {
  551. "use strict";
  552.  
  553. // -----------------------------
  554. // Настройки игры
  555. // -----------------------------
  556. const COLS = 10;
  557. const ROWS = 8;
  558. const TARGET_ROWS = 5;
  559. const MAX_STRESS = 100;
  560.  
  561. // Не менее 20 русских фраз для случайных мыслей.
  562. const THOUGHT_PHRASES = [
  563. "не выключил утюг", "дедлайн завтра", "неловкая фраза 2014",
  564. "ответил не тому человеку", "где мои ключи?", "почему я это сказал",
  565. "забыл отправить файл", "а вдруг не закрыл дверь", "завтра рано вставать",
  566. "нужно купить молоко", "не обновил резюме", "мне кто-то звонил",
  567. "зачем я это лайкнул", "пароль слишком простой", "письмо без ответа",
  568. "что было в том сне?", "опять потратил деньги", "надо помыть посуду",
  569. "звонок в 9:00", "не зарядил телефон", "а точно выключил плиту?",
  570. "что если опоздаю?", "завтра контрольная", "где мой второй носок",
  571. "почему он так посмотрел?", "надо ответить маме", "я забыл название",
  572. "это можно было сказать лучше", "срок уже близко", "не забудь документы"
  573. ];
  574.  
  575. // Разные цвета — разные категории мыслей.
  576. const COLOR_POOL = [
  577. "#b84f62", "#4f78be", "#4c9a76", "#9d7a42", "#8857a6",
  578. "#c0643c", "#3d8ea7", "#a25186"
  579. ];
  580.  
  581. // Набор фигур в координатах x,y.
  582. const SHAPES = [
  583. [[0,0]],
  584. [[0,0],[1,0]],
  585. [[0,0],[0,1],[1,1]],
  586. [[0,0],[1,0],[2,0]],
  587. [[0,0],[1,0],[0,1],[1,1]], // O
  588. [[0,0],[1,0],[2,0],[1,1]], // T
  589. [[0,0],[0,1],[0,2],[1,2]], // L
  590. [[0,0],[1,0],[2,0],[2,1]], // J
  591. [[0,0],[1,0],[1,1],[2,1]], // S
  592. [[1,0],[2,0],[0,1],[1,1]], // Z
  593. [[0,0],[0,1],[1,1],[2,1]], // J-ish
  594. [[0,0],[1,0],[2,0],[0,1],[0,2]], // Penta L
  595. [[0,0],[1,0],[2,0],[1,1],[1,2]], // Penta T
  596. [[0,0],[1,0],[1,1],[2,1],[2,2]], // Zig 5
  597. [[0,0],[0,1],[0,2],[1,2],[2,2]], // Long L
  598. [[0,0],[0,1],[1,1],[2,1],[2,0]], // U
  599. ];
  600.  
  601. const state = {
  602. board: Array.from({length: ROWS}, () => Array(COLS).fill(null)),
  603. active: null,
  604. stress: 0,
  605. clearedRows: 0,
  606. sheep: 2,
  607. noise: 2,
  608. freezeTurns: 0,
  609. gameOver: false,
  610. spawnTimer: null,
  611. animTimer: null,
  612. frame: 1,
  613. holdTimer: null,
  614. drag: null,
  615. messageTimer: null
  616. };
  617.  
  618. const el = {
  619. consciousness: document.getElementById("consciousness"),
  620. grid: document.getElementById("grid"),
  621. character: document.getElementById("character"),
  622. stressFill: document.getElementById("stressFill"),
  623. stressValue: document.getElementById("stressValue"),
  624. rowsValue: document.getElementById("rowsValue"),
  625. sheepBtn: document.getElementById("sheepBtn"),
  626. noiseBtn: document.getElementById("noiseBtn"),
  627. sheepCount: document.getElementById("sheepCount"),
  628. noiseCount: document.getElementById("noiseCount"),
  629. floatingMessage: document.getElementById("floatingMessage"),
  630. resultOverlay: document.getElementById("resultOverlay"),
  631. resultTitle: document.getElementById("resultTitle"),
  632. resultText: document.getElementById("resultText"),
  633. resultRestart: document.getElementById("resultRestart"),
  634. restartBtn: document.getElementById("restartBtn"),
  635. hint: document.getElementById("hint"),
  636. nextThought: document.getElementById("nextThought")
  637. };
  638.  
  639. // -----------------------------
  640. // Базовые функции
  641. // -----------------------------
  642. function rand(min, max) {
  643. return Math.floor(Math.random() * (max - min + 1)) + min;
  644. }
  645.  
  646. function randomChoice(arr) {
  647. return arr[Math.floor(Math.random() * arr.length)];
  648. }
  649.  
  650. function shuffle(arr) {
  651. const copy = arr.slice();
  652. for (let i = copy.length - 1; i > 0; i--) {
  653. const j = Math.floor(Math.random() * (i + 1));
  654. [copy[i], copy[j]] = [copy[j], copy[i]];
  655. }
  656. return copy;
  657. }
  658.  
  659. function cloneCells(cells) {
  660. return cells.map(([x, y]) => [x, y]);
  661. }
  662.  
  663. function normalizeCells(cells) {
  664. const minX = Math.min(...cells.map(c => c[0]));
  665. const minY = Math.min(...cells.map(c => c[1]));
  666. return cells.map(([x, y]) => [x - minX, y - minY]);
  667. }
  668.  
  669. function rotateCells(cells) {
  670. // Поворот вокруг начала координат + нормализация.
  671. const rotated = cells.map(([x, y]) => [-y, x]);
  672. return normalizeCells(rotated);
  673. }
  674.  
  675. function getBounds(cells) {
  676. return {
  677. w: Math.max(...cells.map(c => c[0])) + 1,
  678. h: Math.max(...cells.map(c => c[1])) + 1
  679. };
  680. }
  681.  
  682. function occupiedArea() {
  683. let n = 0;
  684. for (const row of state.board)
  685. for (const cell of row)
  686. if (cell) n++;
  687. return n;
  688. }
  689.  
  690. function isValidPlacement(cells, x, y) {
  691. for (const [cx, cy] of cells) {
  692. const bx = x + cx;
  693. const by = y + cy;
  694. if (bx < 0 || bx >= COLS || by < 0 || by >= ROWS) return false;
  695. if (state.board[by][bx]) return false;
  696. }
  697. return true;
  698. }
  699.  
  700. // -----------------------------
  701. // Создание игрового поля
  702. // -----------------------------
  703. function buildGrid() {
  704. el.grid.innerHTML = "";
  705. for (let y = 0; y < ROWS; y++) {
  706. for (let x = 0; x < COLS; x++) {
  707. const cell = document.createElement("div");
  708. cell.className = "board-cell";
  709. cell.dataset.x = String(x);
  710. cell.dataset.y = String(y);
  711. el.grid.appendChild(cell);
  712. }
  713. }
  714. renderGrid();
  715. }
  716.  
  717. function renderGrid() {
  718. const cells = el.grid.children;
  719. for (let y = 0; y < ROWS; y++) {
  720. for (let x = 0; x < COLS; x++) {
  721. const idx = y * COLS + x;
  722. const cellEl = cells[idx];
  723. const value = state.board[y][x];
  724. cellEl.classList.remove("filled");
  725. cellEl.style.removeProperty("--fill-color");
  726. if (value) {
  727. cellEl.classList.add("filled");
  728. cellEl.style.setProperty("--fill-color", value.color);
  729. }
  730. }
  731. }
  732. }
  733.  
  734. // -----------------------------
  735. // Стресс и состояние персонажа
  736. // -----------------------------
  737. function changeStress(amount) {
  738. state.stress = Math.max(0, Math.min(MAX_STRESS, state.stress + amount));
  739. updateStressUI();
  740.  
  741. if (state.stress >= 100) {
  742. finish(false);
  743. }
  744. }
  745.  
  746. function updateStressUI() {
  747. el.stressValue.textContent = `${state.stress}%`;
  748. el.stressFill.style.width = `${state.stress}%`;
  749.  
  750. let stateName = "sleep";
  751. if (state.stress >= 70) stateName = "angry";
  752. else if (state.stress >= 30) stateName = "irritated";
  753. el.character.className = `character state-${stateName}`;
  754.  
  755. if (state.stress < 30) {
  756. el.hint.innerHTML = "Тише… мысли можно уложить.<br>Правый клик или долгое нажатие — повернуть.";
  757. } else if (state.stress < 70) {
  758. el.hint.innerHTML = "Он ворочается… Укладывай мысли аккуратнее!";
  759. } else {
  760. el.hint.innerHTML = "⚠️ Ещё немного — и он проснётся!";
  761. }
  762. }
  763.  
  764. // -----------------------------
  765. // Анимация персонажа: 3 состояния × 3 кадра
  766. // -----------------------------
  767. function startCharacterAnimation() {
  768. clearInterval(state.animTimer);
  769. state.animTimer = setInterval(() => {
  770. state.frame = state.frame % 3 + 1;
  771. el.character.dataset.frame = String(state.frame);
  772. }, 520);
  773. }
  774.  
  775. // -----------------------------
  776. // Случайная мысль / блок
  777. // -----------------------------
  778. function makeThought(extra = false) {
  779. const baseShape = extra
  780. ? randomChoice(SHAPES.filter(s => s.length <= 3))
  781. : randomChoice(SHAPES);
  782.  
  783. let cells = cloneCells(baseShape);
  784. const rotations = rand(0, 3);
  785. for (let i = 0; i < rotations; i++) cells = rotateCells(cells);
  786.  
  787. const thought = {
  788. id: `${Date.now()}-${Math.random()}`,
  789. cells,
  790. color: randomChoice(COLOR_POOL),
  791. text: randomChoice(THOUGHT_PHRASES),
  792. x: 20,
  793. y: 42,
  794. extra
  795. };
  796. return thought;
  797. }
  798.  
  799. function renderActiveThought() {
  800. if (!state.active) return;
  801. const thought = state.active;
  802.  
  803. let node = thought.node;
  804. if (!node) {
  805. node = document.createElement("div");
  806. node.className = "thought";
  807. el.consciousness.appendChild(node);
  808. thought.node = node;
  809. }
  810.  
  811. node.innerHTML = "";
  812. const bounds = getBounds(thought.cells);
  813. node.style.width = `calc(var(--cell) * ${bounds.w})`;
  814. node.style.height = `calc(var(--cell) * ${bounds.h})`;
  815. node.style.gridTemplateColumns = `repeat(${bounds.w}, var(--cell))`;
  816. node.style.gridTemplateRows = `repeat(${bounds.h}, var(--cell))`;
  817.  
  818. thought.cells.forEach(([x, y]) => {
  819. const c = document.createElement("div");
  820. c.className = "thought-cell";
  821. c.style.gridColumn = String(x + 1);
  822. c.style.gridRow = String(y + 1);
  823. c.style.setProperty("--block-color", thought.color);
  824. node.appendChild(c);
  825. });
  826.  
  827. const text = document.createElement("div");
  828. text.className = "thought-text";
  829. text.textContent = thought.text;
  830. node.appendChild(text);
  831.  
  832. node.style.left = `${thought.x}px`;
  833. node.style.top = `${thought.y}px`;
  834. bindThoughtEvents(node, thought);
  835. }
  836.  
  837. function spawnThought(extra = false) {
  838. if (state.gameOver) return;
  839. if (state.active && state.active.node) state.active.node.remove();
  840.  
  841. // При заморозке мысль не появляется.
  842. if (state.freezeTurns > 0) {
  843. state.freezeTurns--;
  844. state.nextQueued = makeThought(false);
  845. el.nextThought.textContent = "🐑 Овцы заглушают новые мысли…";
  846. renderBoardMessage();
  847. scheduleNextTurn();
  848. return;
  849. }
  850.  
  851. state.active = makeThought(extra);
  852. // Появление сверху, каждый раз в немного новом месте.
  853. const sceneRect = el.consciousness.getBoundingClientRect();
  854. const thoughtRectWidth = Math.max(70, getBounds(state.active.cells).w * parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--cell")));
  855. state.active.x = Math.max(18, (sceneRect.width - thoughtRectWidth) / 2 + rand(-80, 80));
  856. state.active.y = 52 + rand(-6, 12);
  857. el.nextThought.textContent = `Мысль: «${state.active.text}»`;
  858. renderActiveThought();
  859. }
  860.  
  861. function scheduleNextTurn() {
  862. clearTimeout(state.spawnTimer);
  863. state.spawnTimer = setTimeout(() => {
  864. spawnThought(false);
  865. }, 260);
  866. }
  867.  
  868. function renderBoardMessage() {
  869. if (state.freezeTurns > 0) {
  870. el.nextThought.textContent = `🐑 Новые мысли заморожены ещё на ${state.freezeTurns} х.`;
  871. }
  872. }
  873.  
  874. // -----------------------------
  875. // Drag & drop + touch
  876. // -----------------------------
  877. function bindThoughtEvents(node, thought) {
  878. // Чтобы не дублировать обработчики после каждого рендера,
  879. // добавляем их только один раз.
  880. if (node.dataset.bound === "1") return;
  881. node.dataset.bound = "1";
  882.  
  883. node.addEventListener("contextmenu", e => {
  884. e.preventDefault();
  885. rotateActiveThought();
  886. });
  887.  
  888. node.addEventListener("pointerdown", e => {
  889. if (state.gameOver || state.active !== thought) return;
  890. e.preventDefault();
  891. node.setPointerCapture?.(e.pointerId);
  892. node.classList.add("dragging");
  893.  
  894. const rect = node.getBoundingClientRect();
  895. state.drag = {
  896. pointerId: e.pointerId,
  897. startX: e.clientX,
  898. startY: e.clientY,
  899. offsetX: e.clientX - rect.left,
  900. offsetY: e.clientY - rect.top,
  901. moved: false,
  902. node
  903. };
  904.  
  905. // Долгое нажатие на touch = поворот, если почти не двигались.
  906. if (e.pointerType === "touch") {
  907. clearTimeout(state.holdTimer);
  908. state.holdTimer = setTimeout(() => {
  909. if (state.drag && !state.drag.moved) rotateActiveThought();
  910. }, 560);
  911. }
  912. });
  913.  
  914. node.addEventListener("pointermove", e => {
  915. if (!state.drag || state.drag.pointerId !== e.pointerId) return;
  916. e.preventDefault();
  917.  
  918. const dx = e.clientX - state.drag.startX;
  919. const dy = e.clientY - state.drag.startY;
  920. if (Math.hypot(dx, dy) > 8) {
  921. state.drag.moved = true;
  922. clearTimeout(state.holdTimer);
  923. }
  924.  
  925. const sceneRect = el.consciousness.getBoundingClientRect();
  926. const nodeRect = node.getBoundingClientRect();
  927. const newLeft = e.clientX - sceneRect.left - state.drag.offsetX;
  928. const newTop = e.clientY - sceneRect.top - state.drag.offsetY;
  929. thought.x = newLeft;
  930. thought.y = newTop;
  931. node.style.left = `${newLeft}px`;
  932. node.style.top = `${newTop}px`;
  933.  
  934. // Превью появляется, когда фигура находится над полем.
  935. showPlacementPreview(node);
  936. });
  937.  
  938. const finishDrag = e => {
  939. if (!state.drag || state.drag.pointerId !== e.pointerId) return;
  940. clearTimeout(state.holdTimer);
  941. node.classList.remove("dragging");
  942.  
  943. const dropped = tryDropActive(node);
  944. state.drag = null;
  945.  
  946. if (!dropped && !state.gameOver) {
  947. // Возвращаем мысль на верх.
  948. thought.x = Math.max(20, (el.consciousness.clientWidth - getBounds(thought.cells).w * parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--cell"))) / 2);
  949. thought.y = 50;
  950. node.style.left = `${thought.x}px`;
  951. node.style.top = `${thought.y}px`;
  952. }
  953. };
  954.  
  955. node.addEventListener("pointerup", finishDrag);
  956. node.addEventListener("pointercancel", finishDrag);
  957. }
  958.  
  959. function rotateActiveThought() {
  960. if (!state.active || state.gameOver) return;
  961. clearTimeout(state.holdTimer);
  962. state.active.cells = rotateCells(state.active.cells);
  963. renderActiveThought();
  964. showMessage("🔄 Мысль повернулась");
  965. }
  966.  
  967. function gridMetrics() {
  968. const gridRect = el.grid.getBoundingClientRect();
  969. const style = getComputedStyle(el.grid);
  970. const gap = parseFloat(style.gap) || 2;
  971. const cellW = (gridRect.width - gap * 2 - gap * (COLS - 1)) / COLS;
  972. const cellH = (gridRect.height - gap * 2 - gap * (ROWS - 1)) / ROWS;
  973. return { gridRect, gap, cellW, cellH };
  974. }
  975.  
  976. function findAnchor(node, thought) {
  977. const nodeRect = node.getBoundingClientRect();
  978. const { gridRect, cellW, cellH } = gridMetrics();
  979.  
  980. const centerX = nodeRect.left + nodeRect.width / 2;
  981. const centerY = nodeRect.top + nodeRect.height / 2;
  982.  
  983. const bounds = getBounds(thought.cells);
  984. const leftGuess = centerX - (bounds.w * cellW) / 2;
  985. const topGuess = centerY - (bounds.h * cellH) / 2;
  986.  
  987. const x = Math.round((leftGuess - gridRect.left - 2) / (cellW + 2));
  988. const y = Math.round((topGuess - gridRect.top - 2) / (cellH + 2));
  989. return { x, y };
  990. }
  991.  
  992. function clearPreview() {
  993. for (const cell of el.grid.children) {
  994. cell.classList.remove("preview-ok", "preview-bad");
  995. }
  996. }
  997.  
  998. function showPlacementPreview(node) {
  999. clearPreview();
  1000. if (!state.active) return;
  1001.  
  1002. const {x, y} = findAnchor(node, state.active);
  1003. const ok = isValidPlacement(state.active.cells, x, y);
  1004.  
  1005. state.active.preview = {x, y, ok};
  1006. for (const [cx, cy] of state.active.cells) {
  1007. const bx = x + cx, by = y + cy;
  1008. if (bx >= 0 && bx < COLS && by >= 0 && by < ROWS) {
  1009. el.grid.children[by * COLS + bx].classList.add(ok ? "preview-ok" : "preview-bad");
  1010. }
  1011. }
  1012. }
  1013.  
  1014. function tryDropActive(node) {
  1015. clearPreview();
  1016. if (!state.active) return false;
  1017.  
  1018. const {x, y} = findAnchor(node, state.active);
  1019. if (!isValidPlacement(state.active.cells, x, y)) {
  1020. changeStress(8);
  1021. showMessage("💥 Мысль не поместилась! Стресс +8%");
  1022. spawnExtraThought();
  1023. return false;
  1024. }
  1025.  
  1026. // Заносим клетки фигуры в подсознание.
  1027. state.active.cells.forEach(([cx, cy]) => {
  1028. const bx = x + cx, by = y + cy;
  1029. state.board[by][bx] = {
  1030. color: state.active.color,
  1031. text: state.active.text
  1032. };
  1033. });
  1034.  
  1035. if (state.active.node) state.active.node.remove();
  1036. state.active = null;
  1037. renderGrid();
  1038.  
  1039. const completed = findFullRows();
  1040. if (completed.length) {
  1041. clearRowsAnimated(completed);
  1042. } else {
  1043. // Правильное размещение — небольшой шанс/ощущение спокойствия.
  1044. changeStress(-1);
  1045. scheduleNextTurn();
  1046. }
  1047. return true;
  1048. }
  1049.  
  1050. function spawnExtraThought() {
  1051. // Дополнительный маленький блок появляется при неудачном ходе.
  1052. clearTimeout(state.spawnTimer);
  1053. state.spawnTimer = setTimeout(() => {
  1054. spawnThought(true);
  1055. }, 170);
  1056. }
  1057.  
  1058. // -----------------------------
  1059. // Очистка заполненных рядов
  1060. // -----------------------------
  1061. function findFullRows() {
  1062. const rows = [];
  1063. for (let y = 0; y < ROWS; y++) {
  1064. if (state.board[y].every(Boolean)) rows.push(y);
  1065. }
  1066. return rows;
  1067. }
  1068.  
  1069. function clearRowsAnimated(rows) {
  1070. const cells = el.grid.children;
  1071. const indices = [];
  1072. rows.forEach(y => {
  1073. for (let x = 0; x < COLS; x++) indices.push(y * COLS + x);
  1074. });
  1075. indices.forEach(i => cells[i].classList.add("clearing"));
  1076.  
  1077. setTimeout(() => {
  1078. // Удаляем строки снизу вверх, чтобы не сломать индексы.
  1079. for (const y of rows.slice().sort((a,b) => b-a)) {
  1080. state.board.splice(y, 1);
  1081. state.board.unshift(Array(COLS).fill(null));
  1082. }
  1083.  
  1084. state.clearedRows += rows.length;
  1085. changeStress(-Math.min(28, rows.length * 11));
  1086. renderGrid();
  1087. el.rowsValue.textContent = `${state.clearedRows} / ${TARGET_ROWS}`;
  1088. showMessage(`✨ Ряд очищен! Стресс −${Math.min(28, rows.length * 11)}%`);
  1089.  
  1090. if (state.clearedRows >= TARGET_ROWS) {
  1091. finish(true);
  1092. } else {
  1093. scheduleNextTurn();
  1094. }
  1095. }, 340);
  1096. }
  1097.  
  1098. // -----------------------------
  1099. // Бонусы
  1100. // -----------------------------
  1101. function useSheep() {
  1102. if (state.gameOver || state.sheep <= 0) return;
  1103. state.sheep--;
  1104. state.freezeTurns += 3;
  1105. el.sheepCount.textContent = String(state.sheep);
  1106. el.sheepBtn.disabled = state.sheep <= 0;
  1107. changeStress(-4);
  1108. showMessage("🐑 Три хода без новых мыслей.");
  1109. renderBoardMessage();
  1110. }
  1111.  
  1112. function useWhiteNoise() {
  1113. if (state.gameOver || state.noise <= 0) return;
  1114.  
  1115. const occupied = [];
  1116. for (let y = 0; y < ROWS; y++) {
  1117. for (let x = 0; x < COLS; x++) {
  1118. if (state.board[y][x]) occupied.push([x,y]);
  1119. }
  1120. }
  1121.  
  1122. if (!occupied.length) {
  1123. showMessage("🌫️ В подсознании пока нечего заглушать.");
  1124. return;
  1125. }
  1126.  
  1127. state.noise--;
  1128. const [x,y] = randomChoice(occupied);
  1129. state.board[y][x] = null;
  1130. el.noiseCount.textContent = String(state.noise);
  1131. el.noiseBtn.disabled = state.noise <= 0;
  1132. renderGrid();
  1133. changeStress(-5);
  1134. showMessage("🌫️ Белый шум заглушил одну мысль.");
  1135. }
  1136.  
  1137. // -----------------------------
  1138. // Конец игры
  1139. // -----------------------------
  1140. function finish(win) {
  1141. if (state.gameOver) return;
  1142. state.gameOver = true;
  1143. clearTimeout(state.spawnTimer);
  1144. clearInterval(state.animTimer);
  1145. clearTimeout(state.holdTimer);
  1146.  
  1147. if (state.active?.node) state.active.node.remove();
  1148. clearPreview();
  1149.  
  1150. if (win) {
  1151. el.resultTitle.textContent = "😴 Ты заснул";
  1152. el.resultText.textContent = "Все пять рядов собраны. Мысли уложены плотно, мозг наконец перестал крутиться вокруг одного и того же.";
  1153. } else {
  1154. state.stress = 100;
  1155. updateStressUI();
  1156. el.resultTitle.textContent = "😡 Он проснулся";
  1157. el.resultText.textContent = "Стресс достиг 100%. Мысли оказались слишком неудобными. Попробуй заново и используй бонусы.";
  1158. }
  1159.  
  1160. el.resultOverlay.classList.add("show");
  1161. }
  1162.  
  1163. function showMessage(text) {
  1164. clearTimeout(state.messageTimer);
  1165. el.floatingMessage.textContent = text;
  1166. el.floatingMessage.classList.add("show");
  1167. state.messageTimer = setTimeout(() => {
  1168. el.floatingMessage.classList.remove("show");
  1169. }, 1600);
  1170. }
  1171.  
  1172. // -----------------------------
  1173. // Перезапуск
  1174. // -----------------------------
  1175. function resetGame() {
  1176. clearTimeout(state.spawnTimer);
  1177. clearInterval(state.animTimer);
  1178. clearTimeout(state.holdTimer);
  1179.  
  1180. state.board = Array.from({length: ROWS}, () => Array(COLS).fill(null));
  1181. state.active = null;
  1182. state.stress = 0;
  1183. state.clearedRows = 0;
  1184. state.sheep = 2;
  1185. state.noise = 2;
  1186. state.freezeTurns = 0;
  1187. state.gameOver = false;
  1188. state.drag = null;
  1189. state.frame = 1;
  1190.  
  1191. el.resultOverlay.classList.remove("show");
  1192. el.sheepCount.textContent = "2";
  1193. el.noiseCount.textContent = "2";
  1194. el.sheepBtn.disabled = false;
  1195. el.noiseBtn.disabled = false;
  1196. el.rowsValue.textContent = "0 / 5";
  1197. el.nextThought.textContent = "Новая мысль готовится…";
  1198.  
  1199. buildGrid();
  1200. updateStressUI();
  1201. startCharacterAnimation();
  1202. spawnThought(false);
  1203. }
  1204.  
  1205. // -----------------------------
  1206. // Клавиатура: полезно на ПК
  1207. // -----------------------------
  1208. document.addEventListener("keydown", e => {
  1209. if (state.gameOver) return;
  1210. if (e.key.toLowerCase() === "r") rotateActiveThought();
  1211. if (e.key === "Escape" && state.active?.node) {
  1212. state.active.x = 20;
  1213. state.active.y = 50;
  1214. state.active.node.style.left = "20px";
  1215. state.active.node.style.top = "50px";
  1216. clearPreview();
  1217. }
  1218. });
  1219.  
  1220. // -----------------------------
  1221. // Кнопки
  1222. // -----------------------------
  1223. el.sheepBtn.addEventListener("click", useSheep);
  1224. el.noiseBtn.addEventListener("click", useWhiteNoise);
  1225. el.restartBtn.addEventListener("click", resetGame);
  1226. el.resultRestart.addEventListener("click", resetGame);
  1227.  
  1228. // Подстройка масштаба клеток при изменении ширины окна.
  1229. window.addEventListener("resize", () => {
  1230. if (state.active) {
  1231. // Если активная фигура существует, её положение просто ограничиваем.
  1232. const sceneW = el.consciousness.clientWidth;
  1233. const bounds = getBounds(state.active.cells);
  1234. const cell = parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--cell"));
  1235. state.active.x = Math.min(state.active.x, sceneW - bounds.w * cell - 8);
  1236. state.active.x = Math.max(8, state.active.x);
  1237. state.active.node.style.left = `${state.active.x}px`;
  1238. }
  1239. });
  1240.  
  1241. // Старт игры сразу после загрузки.
  1242. resetGame();
  1243. })();
  1244. </script>
  1245. </body>
  1246. </html>
Advertisement
Add Comment
Please, Sign In to add comment