Hasli4

Untitled

Aug 17th, 2026
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 39.33 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, user-scalable=no">
  6. <title>Алгоритм сна</title>
  7. <style>
  8. /* =========================
  9. БАЗОВЫЕ СТИЛИ
  10. ========================= */
  11. * { box-sizing: border-box; }
  12. html, body { margin: 0; min-height: 100%; }
  13. body {
  14. background:
  15. radial-gradient(circle at 50% 0%, rgba(76, 70, 150, .26), transparent 34%),
  16. radial-gradient(circle at 20% 80%, rgba(38, 92, 130, .16), transparent 28%),
  17. #080b15;
  18. color: #e9ecff;
  19. font-family: "Segoe UI", Roboto, system-ui, -apple-system, sans-serif;
  20. padding: 12px;
  21. }
  22. button {
  23. font: inherit;
  24. -webkit-tap-highlight-color: transparent;
  25. }
  26.  
  27. /* Основной контейнер намеренно компактный: всё поле всегда видно. */
  28. #game {
  29. width: min(720px, 100%);
  30. margin: 0 auto;
  31. background: linear-gradient(180deg, #121827, #0e1421);
  32. border: 1px solid rgba(157, 166, 220, .12);
  33. border-radius: 24px;
  34. padding: 14px;
  35. box-shadow: 0 20px 70px rgba(0,0,0,.45), inset 0 1px rgba(255,255,255,.03);
  36. }
  37.  
  38. header {
  39. display: flex;
  40. align-items: center;
  41. justify-content: space-between;
  42. gap: 10px;
  43. margin-bottom: 12px;
  44. }
  45. h1 {
  46. margin: 0;
  47. text-align: center;
  48. width: 100%;
  49. font-size: clamp(22px, 5vw, 30px);
  50. color: #cfd5ff;
  51. letter-spacing: 2px;
  52. text-shadow: 0 0 18px rgba(110, 110, 255, .45);
  53. }
  54. .restart-top {
  55. flex: 0 0 auto;
  56. border: 1px solid #444b69;
  57. background: #1a2133;
  58. color: #dfe4ff;
  59. border-radius: 12px;
  60. padding: 8px 10px;
  61. cursor: pointer;
  62. }
  63.  
  64. /* =========================
  65. ИГРОВАЯ СЦЕНА
  66. ========================= */
  67. .scene {
  68. display: grid;
  69. grid-template-columns: 145px minmax(0, 1fr);
  70. gap: 12px;
  71. align-items: stretch;
  72. }
  73.  
  74. .character-area {
  75. min-width: 0;
  76. min-height: 170px;
  77. border-radius: 18px;
  78. background: rgba(20, 24, 46, .68);
  79. border: 1px solid rgba(120, 130, 200, .14);
  80. display: flex;
  81. align-items: center;
  82. justify-content: center;
  83. padding: 10px;
  84. }
  85.  
  86. .bed {
  87. position: relative;
  88. width: 124px;
  89. height: 76px;
  90. border-radius: 15px 15px 10px 10px;
  91. background: linear-gradient(180deg, #69442e, #452919);
  92. box-shadow: 0 6px 0 #2f1b10, 0 12px 24px rgba(0,0,0,.3);
  93. }
  94. .bed::before {
  95. content: "";
  96. position: absolute;
  97. left: 6px;
  98. top: -15px;
  99. width: 48px;
  100. height: 22px;
  101. border-radius: 12px;
  102. background: #f1e7dc;
  103. transform: rotate(-3deg);
  104. box-shadow: 0 2px 5px rgba(0,0,0,.35);
  105. }
  106. .bed::after {
  107. content: "";
  108. position: absolute;
  109. left: 48px;
  110. top: -7px;
  111. width: 70px;
  112. height: 22px;
  113. border-radius: 9px;
  114. background: linear-gradient(180deg, #51479a, #342e6a);
  115. transform: rotate(2deg);
  116. box-shadow: 0 3px 8px rgba(0,0,0,.45);
  117. }
  118.  
  119. .character {
  120. position: absolute;
  121. left: 37px;
  122. top: -39px;
  123. font-size: 46px;
  124. z-index: 5;
  125. transform-origin: center;
  126. filter: drop-shadow(0 0 7px rgba(255, 210, 120, .5));
  127. }
  128. .character.frame1 { animation: sleep1 .45s ease-in-out; }
  129. .character.frame2 { animation: sleep2 .45s ease-in-out; }
  130. .character.frame3 { animation: sleep3 .45s ease-in-out; }
  131. @keyframes sleep1 { 50% { transform: translateY(-2px) rotate(-1deg); } }
  132. @keyframes sleep2 { 50% { transform: translateY(2px) rotate(1deg); } }
  133. @keyframes sleep3 { 50% { transform: translateY(-1px) rotate(0deg); } }
  134.  
  135. .play {
  136. min-width: 0;
  137. display: flex;
  138. flex-direction: column;
  139. gap: 10px;
  140. }
  141.  
  142. /* Зона сознания */
  143. .conscious {
  144. height: 110px;
  145. position: relative;
  146. overflow: hidden;
  147. border: 2px dashed #454970;
  148. background:
  149. radial-gradient(circle at 50% 70%, rgba(78,73,160,.18), transparent 45%),
  150. rgba(28, 25, 69, .48);
  151. border-radius: 17px;
  152. display: flex;
  153. align-items: center;
  154. justify-content: center;
  155. }
  156. .conscious-label {
  157. position: absolute;
  158. top: 8px;
  159. left: 10px;
  160. color: #7f86b6;
  161. font-size: 10px;
  162. letter-spacing: .13em;
  163. text-transform: uppercase;
  164. pointer-events: none;
  165. }
  166. .conscious-tip {
  167. color: rgba(196, 201, 240, .45);
  168. text-align: center;
  169. font-size: 11px;
  170. line-height: 1.35;
  171. pointer-events: none;
  172. }
  173.  
  174. /* =========================
  175. ПОЛЕ ПОДСОЗНАНИЯ
  176. Главное исправление: НИКАКОГО scroll.
  177. Размер адаптивный, но всегда квадратный.
  178. ========================= */
  179. .board-title {
  180. display: flex;
  181. justify-content: space-between;
  182. align-items: center;
  183. gap: 8px;
  184. color: #c5cbe6;
  185. font-size: 12px;
  186. padding: 0 2px;
  187. }
  188.  
  189. .board-wrap {
  190. width: min(100%, 390px);
  191. aspect-ratio: 1 / 1;
  192. margin: 0 auto;
  193. padding: 5px;
  194. border-radius: 15px;
  195. background: rgba(33, 37, 67, .72);
  196. border: 1px solid rgba(123, 133, 191, .20);
  197. box-shadow: inset 0 0 25px rgba(0,0,0,.18);
  198. }
  199. #board {
  200. width: 100%;
  201. height: 100%;
  202. display: grid;
  203. grid-template-columns: repeat(8, minmax(0, 1fr));
  204. grid-template-rows: repeat(8, minmax(0, 1fr));
  205. gap: 3px;
  206. touch-action: none;
  207. }
  208. .cell {
  209. min-width: 0;
  210. min-height: 0;
  211. border-radius: 5px;
  212. background: rgba(11, 15, 28, .78);
  213. border: 1px solid rgba(104, 116, 170, .18);
  214. transition: background .12s, transform .12s;
  215. }
  216. .cell.ok { background: rgba(72, 205, 155, .26); border-color: rgba(110, 255, 198, .42); }
  217. .cell.bad { background: rgba(241, 82, 103, .25); border-color: rgba(255, 112, 130, .45); }
  218. .cell.filled {
  219. border-color: rgba(255,255,255,.26);
  220. box-shadow: inset 0 0 10px rgba(255,255,255,.10);
  221. }
  222. .cell.clearing { animation: rowFlash .38s ease forwards; }
  223. @keyframes rowFlash {
  224. 0% { opacity: 1; transform: scale(1); filter: brightness(1); }
  225. 45% { opacity: .95; transform: scale(.82); filter: brightness(2); }
  226. 100% { opacity: 0; transform: scale(.15); }
  227. }
  228.  
  229. /* Фигура мысли */
  230. .piece {
  231. --piece-cell: 32px;
  232. --piece-gap: 3px;
  233. position: fixed;
  234. display: grid;
  235. gap: var(--piece-gap);
  236. z-index: 1000;
  237. cursor: grab;
  238. touch-action: none;
  239. user-select: none;
  240. filter: drop-shadow(0 6px 12px rgba(0,0,0,.55));
  241. }
  242. .piece.dragging {
  243. cursor: grabbing;
  244. filter: drop-shadow(0 12px 24px rgba(0,0,0,.75));
  245. }
  246. .piece-cell {
  247. border-radius: 7px;
  248. border: 1px solid rgba(255,255,255,.22);
  249. background: var(--color);
  250. box-shadow: inset 0 1px rgba(255,255,255,.12);
  251. min-width: 0;
  252. min-height: 0;
  253. }
  254. .piece-label {
  255. position: absolute;
  256. inset: 0;
  257. display: flex;
  258. align-items: center;
  259. justify-content: center;
  260. padding: 3px 6px;
  261. color: #fff;
  262. text-shadow: 0 1px 3px rgba(0,0,0,.7);
  263. font-weight: 700;
  264. font-size: clamp(8px, 1.7vw, 11px);
  265. line-height: 1.05;
  266. text-align: center;
  267. pointer-events: none;
  268. overflow: hidden;
  269. }
  270.  
  271. /* =========================
  272. НИЖНЯЯ ПАНЕЛЬ
  273. ========================= */
  274. .controls {
  275. display: grid;
  276. grid-template-columns: minmax(150px, 1fr) auto auto;
  277. gap: 8px;
  278. align-items: center;
  279. margin-top: 12px;
  280. }
  281. .stress-box {
  282. display: grid;
  283. grid-template-columns: auto minmax(80px, 1fr) auto;
  284. gap: 8px;
  285. align-items: center;
  286. min-width: 0;
  287. }
  288. .stress-label, .stress-value, .rows-counter {
  289. font-size: 12px;
  290. white-space: nowrap;
  291. }
  292. .stress-bar {
  293. height: 15px;
  294. border-radius: 999px;
  295. overflow: hidden;
  296. background: #171a2d;
  297. border: 1px solid #3b3f56;
  298. }
  299. #stressFill {
  300. width: 0%;
  301. height: 100%;
  302. background: linear-gradient(90deg, #22c55e, #eab308, #ef4444);
  303. border-radius: inherit;
  304. transition: width .25s ease;
  305. }
  306. .bonus {
  307. border: 1px solid #444b69;
  308. background: #1b2336;
  309. color: #e5e9ff;
  310. padding: 9px 11px;
  311. border-radius: 12px;
  312. cursor: pointer;
  313. white-space: nowrap;
  314. }
  315. .bonus:hover:not(:disabled) { background: #242e46; }
  316. .bonus:active:not(:disabled) { transform: scale(.97); }
  317. .bonus:disabled { opacity: .4; cursor: not-allowed; }
  318.  
  319. .info-line {
  320. display: flex;
  321. justify-content: center;
  322. gap: 12px;
  323. margin-top: 8px;
  324. color: #7f88aa;
  325. font-size: 11px;
  326. text-align: center;
  327. }
  328.  
  329. /* Окончание игры */
  330. .overlay {
  331. position: fixed;
  332. inset: 0;
  333. z-index: 5000;
  334. display: none;
  335. align-items: center;
  336. justify-content: center;
  337. padding: 18px;
  338. background: rgba(4,6,12,.72);
  339. backdrop-filter: blur(7px);
  340. }
  341. .overlay.show { display: flex; }
  342. .result {
  343. width: min(430px, 100%);
  344. border-radius: 21px;
  345. padding: 26px;
  346. background: linear-gradient(180deg, #1a2237, #0d1422);
  347. border: 1px solid rgba(160,170,220,.18);
  348. box-shadow: 0 24px 70px rgba(0,0,0,.45);
  349. text-align: center;
  350. }
  351. .result h2 { margin: 0 0 8px; font-size: 29px; }
  352. .result p { margin: 0 0 18px; color: #9ca6c5; line-height: 1.45; }
  353. .result button {
  354. border: 0;
  355. border-radius: 12px;
  356. background: #8178df;
  357. color: #fff;
  358. padding: 11px 18px;
  359. cursor: pointer;
  360. font-weight: 700;
  361. }
  362.  
  363. .toast {
  364. position: fixed;
  365. left: 50%;
  366. top: 12%;
  367. z-index: 6000;
  368. transform: translate(-50%, -10px);
  369. opacity: 0;
  370. pointer-events: none;
  371. padding: 9px 13px;
  372. border-radius: 12px;
  373. color: #eff2ff;
  374. background: rgba(13,18,32,.95);
  375. border: 1px solid rgba(255,255,255,.10);
  376. box-shadow: 0 12px 34px rgba(0,0,0,.35);
  377. transition: opacity .18s, transform .18s;
  378. text-align: center;
  379. white-space: nowrap;
  380. }
  381. .toast.show { opacity: 1; transform: translate(-50%, 0); }
  382.  
  383. /* Мобильная версия */
  384. @media (max-width: 560px) {
  385. body { padding: 7px; }
  386. #game { padding: 10px; border-radius: 19px; }
  387. .scene {
  388. grid-template-columns: 1fr;
  389. }
  390. .character-area {
  391. min-height: 110px;
  392. }
  393. .bed { transform: scale(.83); }
  394. .play { width: 100%; }
  395. .conscious { height: 86px; }
  396. .board-wrap { width: min(100%, 350px); }
  397. .controls {
  398. grid-template-columns: 1fr 1fr;
  399. }
  400. .stress-box {
  401. grid-column: 1 / -1;
  402. }
  403. .bonus { width: 100%; }
  404. .info-line { flex-wrap: wrap; gap: 5px 10px; }
  405. }
  406.  
  407. @media (max-width: 360px) {
  408. h1 { font-size: 20px; letter-spacing: 1px; }
  409. .board-wrap { width: min(100%, 310px); }
  410. .controls { gap: 6px; }
  411. .bonus { font-size: 11px; padding: 8px 6px; }
  412. .stress-label, .rows-counter { font-size: 10px; }
  413. }
  414. </style>
  415. </head>
  416. <body>
  417. <div id="game">
  418. <header>
  419. <h1>🌙 Алгоритм сна</h1>
  420. <button class="restart-top" id="restartTop">↻</button>
  421. </header>
  422.  
  423. <section class="scene">
  424. <div class="character-area">
  425. <div class="bed">
  426. <div class="character" id="character">😴</div>
  427. </div>
  428. </div>
  429.  
  430. <div class="play">
  431. <div class="conscious" id="conscious">
  432. <div class="conscious-label">СОЗНАНИЕ</div>
  433. <div class="conscious-tip" id="consciousTip">
  434. Перетащи мысль вниз.<br>
  435. ПКМ или долгое нажатие — повернуть.
  436. </div>
  437. </div>
  438.  
  439. <div class="board-title">
  440. <span>🧠 Подсознание</span>
  441. <span class="rows-counter" id="rowsCounter">Ряды: 0 / 5</span>
  442. </div>
  443.  
  444. <div class="board-wrap">
  445. <div id="board"></div>
  446. </div>
  447. </div>
  448. </section>
  449.  
  450. <section class="controls">
  451. <div class="stress-box">
  452. <span class="stress-label">Стресс</span>
  453. <div class="stress-bar"><div id="stressFill"></div></div>
  454. <span class="stress-value" id="stressValue">0%</span>
  455. </div>
  456.  
  457. <button class="bonus" id="sheepBtn">🐑 Овцы (2)</button>
  458. <button class="bonus" id="noiseBtn">🌫️ Шум (2)</button>
  459. </section>
  460.  
  461. <div class="info-line">
  462. <span>Неудача: +8% стресса</span>
  463. <span>Линия: −12%</span>
  464. <span>Победа: 5 линий</span>
  465. </div>
  466. </div>
  467.  
  468. <div class="toast" id="toast"></div>
  469.  
  470. <div class="overlay" id="overlay">
  471. <div class="result">
  472. <h2 id="resultTitle">😴 Сон!</h2>
  473. <p id="resultText"></p>
  474. <button id="restartResult">Начать заново</button>
  475. </div>
  476. </div>
  477.  
  478. <script>
  479. (() => {
  480. "use strict";
  481.  
  482. // =========================
  483. // КОНФИГУРАЦИЯ
  484. // =========================
  485. const COLS = 8;
  486. const ROWS = 8;
  487. const TARGET_ROWS = 5;
  488. const MAX_STRESS = 100;
  489. const FAIL_STRESS = 8;
  490. const CLEAR_STRESS = 12;
  491. const FREEZE_TURNS = 3;
  492.  
  493. // Более 20 русских мыслей.
  494. const THOUGHTS = [
  495. "не выключил утюг", "дедлайн завтра", "неловкая фраза 2014",
  496. "забыл ответить", "не закрыл дверь?", "завтра рано вставать",
  497. "что если опоздаю?", "не оплатил счёт", "надо позвонить",
  498. "что сказать на встрече?", "а вдруг всё забыл?", "проект не готов",
  499. "надо было иначе", "почему я это сказал?", "что обо мне думают?",
  500. "забытые продукты", "не выключил плиту", "а если не получится?",
  501. "надо лечь раньше", "что-то скрипит", "не ответил на сообщение",
  502. "что надеть завтра?", "пароль слишком простой", "где ключи?",
  503. "забытый файл", "срок уже близко", "а точно отправил?",
  504. "почему я это лайкнул?", "надо помыть посуду", "зарядить телефон"
  505. ];
  506.  
  507. const NORMAL_SHAPES = [
  508. [[0,0],[0,1],[1,0],[1,1]], // O
  509. [[0,0],[1,0],[2,0],[2,1]], // L
  510. [[0,1],[1,0],[1,1],[2,0]], // S
  511. [[0,0],[1,0],[2,0],[2,1]], // J
  512. [[0,0],[0,1],[0,2],[1,1]], // T
  513. [[0,0],[1,0],[1,1],[2,1]], // Z
  514. [[0,0],[0,1],[1,1],[2,1]], // J-ish
  515. [[0,0],[0,1],[0,2],[1,2],[2,2]], // penta L
  516. [[0,0],[1,0],[2,0],[1,1],[1,2]], // penta T
  517. [[0,0],[1,0],[1,1],[1,2],[2,2]], // penta zig
  518. [[0,0],[0,1],[1,1],[2,1],[2,0]], // penta U
  519. [[0,0],[1,0],[2,0]], // 3 line
  520. [[0,0],[0,1],[0,2]] // 3 column
  521. ];
  522.  
  523. // Маленькая фигура после неудачи.
  524. const SMALL_SHAPES = [
  525. [[0,0]],
  526. [[0,0],[1,0]],
  527. [[0,0],[0,1]],
  528. [[0,0],[1,0],[0,1]]
  529. ];
  530.  
  531. const COLORS = [
  532. "#e2556d", "#4c82d8", "#48a979", "#d39649",
  533. "#9565c9", "#d36b40", "#3b9ab5", "#a84f91"
  534. ];
  535.  
  536. // =========================
  537. // СОСТОЯНИЕ
  538. // =========================
  539. let board = [];
  540. let active = null;
  541. let stress = 0;
  542. let clearedRows = 0;
  543. let sheepUses = 2;
  544. let noiseUses = 2;
  545. let freezeTurns = 0;
  546. let gameEnded = false;
  547. let pieceId = 0;
  548. let animationTimer = null;
  549. let toastTimer = null;
  550.  
  551. // Данные перетаскивания.
  552. let drag = null;
  553.  
  554. const $ = id => document.getElementById(id);
  555. const boardEl = $("board");
  556. const consciousEl = $("conscious");
  557. const characterEl = $("character");
  558. const stressFillEl = $("stressFill");
  559. const stressValueEl = $("stressValue");
  560. const rowsCounterEl = $("rowsCounter");
  561. const consciousTipEl = $("consciousTip");
  562. const sheepBtn = $("sheepBtn");
  563. const noiseBtn = $("noiseBtn");
  564. const overlayEl = $("overlay");
  565. const resultTitleEl = $("resultTitle");
  566. const resultTextEl = $("resultText");
  567. const toastEl = $("toast");
  568.  
  569. // =========================
  570. // УТИЛИТЫ
  571. // =========================
  572. function random(arr) {
  573. return arr[Math.floor(Math.random() * arr.length)];
  574. }
  575.  
  576. function rotateShape(cells) {
  577. // (row, col) -> (col, -row), затем нормализация.
  578. const rotated = cells.map(([r, c]) => [c, -r]);
  579. const minR = Math.min(...rotated.map(([r]) => r));
  580. const minC = Math.min(...rotated.map(([, c]) => c));
  581. return rotated.map(([r,c]) => [r - minR, c - minC]);
  582. }
  583.  
  584. function bounds(cells) {
  585. return {
  586. rows: Math.max(...cells.map(([r]) => r)) + 1,
  587. cols: Math.max(...cells.map(([,c]) => c)) + 1
  588. };
  589. }
  590.  
  591. function clone2D(arr) {
  592. return arr.map(row => row.slice());
  593. }
  594.  
  595. // =========================
  596. // ИНИЦИАЛИЗАЦИЯ ПОЛЯ
  597. // =========================
  598. function createEmptyBoard() {
  599. return Array.from({ length: ROWS }, () => Array(COLS).fill(null));
  600. }
  601.  
  602. function buildBoard() {
  603. boardEl.innerHTML = "";
  604. for (let r = 0; r < ROWS; r++) {
  605. for (let c = 0; c < COLS; c++) {
  606. const cell = document.createElement("div");
  607. cell.className = "cell";
  608. cell.dataset.row = r;
  609. cell.dataset.col = c;
  610. boardEl.appendChild(cell);
  611. }
  612. }
  613. renderBoard();
  614. }
  615.  
  616. function renderBoard() {
  617. const cells = boardEl.children;
  618. for (let r = 0; r < ROWS; r++) {
  619. for (let c = 0; c < COLS; c++) {
  620. const el = cells[r * COLS + c];
  621. const value = board[r][c];
  622.  
  623. el.classList.remove("filled", "ok", "bad", "clearing");
  624. el.style.removeProperty("background");
  625.  
  626. if (value) {
  627. el.classList.add("filled");
  628. el.style.background = `linear-gradient(145deg, ${value.color}, rgba(255,255,255,.08))`;
  629. }
  630. }
  631. }
  632. }
  633.  
  634. // =========================
  635. // СТРЕСС + ПЕРСОНАЖ
  636. // =========================
  637. function setStress(value) {
  638. stress = Math.max(0, Math.min(MAX_STRESS, value));
  639. stressFillEl.style.width = `${stress}%`;
  640. stressValueEl.textContent = `${stress}%`;
  641.  
  642. if (stress < 30) {
  643. characterEl.textContent = "😴";
  644. consciousTipEl.innerHTML = "Мысли можно аккуратно уложить.<br>ПКМ / долгое нажатие — повернуть.";
  645. } else if (stress < 70) {
  646. characterEl.textContent = "😠";
  647. consciousTipEl.innerHTML = "Он ворочается…<br>Старайся не ошибаться.";
  648. } else {
  649. characterEl.textContent = "😡";
  650. consciousTipEl.innerHTML = "⚠️ Он уже почти проснулся!";
  651. }
  652.  
  653. if (stress >= MAX_STRESS) loseGame();
  654. }
  655.  
  656. function addStress(amount) {
  657. if (!gameEnded) setStress(stress + amount);
  658. }
  659.  
  660. function subStress(amount) {
  661. if (!gameEnded) setStress(stress - amount);
  662. }
  663.  
  664. function startCharacterAnimation() {
  665. clearInterval(animationTimer);
  666. let frame = 0;
  667. animationTimer = setInterval(() => {
  668. frame = (frame + 1) % 3 + 1;
  669. characterEl.classList.remove("frame1", "frame2", "frame3");
  670. void characterEl.offsetWidth;
  671. characterEl.classList.add(`frame${frame}`);
  672. }, 450);
  673. }
  674.  
  675. // =========================
  676. // СОЗДАНИЕ МЫСЛИ
  677. // =========================
  678. function createPiece(small = false) {
  679. let cells = structuredClone(random(small ? SMALL_SHAPES : NORMAL_SHAPES));
  680. const rotations = Math.floor(Math.random() * 4);
  681. for (let i = 0; i < rotations; i++) cells = rotateShape(cells);
  682.  
  683. return {
  684. id: ++pieceId,
  685. cells,
  686. color: random(COLORS),
  687. text: random(THOUGHTS),
  688. x: 0,
  689. y: 0,
  690. element: null
  691. };
  692. }
  693.  
  694. function getBoardMetrics() {
  695. const rect = boardEl.getBoundingClientRect();
  696. const styles = getComputedStyle(boardEl);
  697. const gap = parseFloat(styles.gap) || 3;
  698. const cellW = (rect.width - gap * (COLS - 1)) / COLS;
  699. const cellH = (rect.height - gap * (ROWS - 1)) / ROWS;
  700. return { rect, gap, cellW, cellH };
  701. }
  702.  
  703. function getPiecePixelSize(piece) {
  704. const { cellW, cellH, gap } = getBoardMetrics();
  705. const b = bounds(piece.cells);
  706. return {
  707. width: b.cols * cellW + (b.cols - 1) * gap,
  708. height: b.rows * cellH + (b.rows - 1) * gap
  709. };
  710. }
  711.  
  712. function renderPiece() {
  713. if (!active) return;
  714.  
  715. if (!active.element) {
  716. const p = document.createElement("div");
  717. p.className = "piece";
  718. p.dataset.id = active.id;
  719. consciousEl.appendChild(p);
  720. active.element = p;
  721. bindPieceEvents(p);
  722. }
  723.  
  724. const p = active.element;
  725. const b = bounds(active.cells);
  726. const { cellW, cellH, gap } = getBoardMetrics();
  727.  
  728. p.innerHTML = "";
  729. p.style.gridTemplateColumns = `repeat(${b.cols}, ${cellW}px)`;
  730. p.style.gridTemplateRows = `repeat(${b.rows}, ${cellH}px)`;
  731. p.style.width = `${b.cols * cellW + (b.cols - 1) * gap}px`;
  732. p.style.height = `${b.rows * cellH + (b.rows - 1) * gap}px`;
  733. p.style.setProperty("--piece-cell", `${cellW}px`);
  734. p.style.setProperty("--piece-gap", `${gap}px`);
  735. p.style.setProperty("--color", active.color);
  736.  
  737. active.cells.forEach(([r,c]) => {
  738. const cell = document.createElement("div");
  739. cell.className = "piece-cell";
  740. cell.style.gridRow = r + 1;
  741. cell.style.gridColumn = c + 1;
  742. cell.style.background = active.color;
  743. p.appendChild(cell);
  744. });
  745.  
  746. const label = document.createElement("div");
  747. label.className = "piece-label";
  748. label.textContent = active.text;
  749. p.appendChild(label);
  750.  
  751. p.style.left = `${active.x}px`;
  752. p.style.top = `${active.y}px`;
  753. }
  754.  
  755. function spawnPiece(small = false) {
  756. if (gameEnded) return;
  757.  
  758. if (freezeTurns > 0) {
  759. freezeTurns--;
  760. showToast(`🐑 Новых мыслей нет. Осталось ходов: ${freezeTurns}`);
  761. // Следующая реальная мысль появится после следующего успешного/неуспешного размещения.
  762. return;
  763. }
  764.  
  765. if (active?.element) active.element.remove();
  766. active = createPiece(small);
  767.  
  768. // Всегда начинаем в сознании. Позицию задаём после вычисления размеров.
  769. const zoneRect = consciousEl.getBoundingClientRect();
  770. const temp = getPiecePixelSize(active);
  771. active.x = Math.max(8, (zoneRect.width - temp.width) / 2);
  772. active.y = Math.max(20, (zoneRect.height - temp.height) / 2 + 5);
  773.  
  774. renderPiece();
  775. }
  776.  
  777. function rotateActive() {
  778. if (!active || gameEnded || drag) return;
  779. active.cells = rotateShape(active.cells);
  780.  
  781. // После поворота стараемся оставить фигуру в пределах сознания.
  782. const zoneW = consciousEl.clientWidth;
  783. const zoneH = consciousEl.clientHeight;
  784. const size = getPiecePixelSize(active);
  785. active.x = Math.min(active.x, Math.max(4, zoneW - size.width - 4));
  786. active.y = Math.min(active.y, Math.max(4, zoneH - size.height - 4));
  787.  
  788. renderPiece();
  789. showToast("🔄 Повернуто");
  790. }
  791.  
  792. // =========================
  793. // DRAG / TOUCH
  794. // =========================
  795. function bindPieceEvents(pieceEl) {
  796. pieceEl.addEventListener("contextmenu", e => {
  797. e.preventDefault();
  798. rotateActive();
  799. });
  800.  
  801. pieceEl.addEventListener("pointerdown", e => {
  802. if (gameEnded || !active) return;
  803. e.preventDefault();
  804.  
  805. const rect = pieceEl.getBoundingClientRect();
  806. drag = {
  807. pointerId: e.pointerId,
  808. offsetX: e.clientX - rect.left,
  809. offsetY: e.clientY - rect.top,
  810. moved: false,
  811. startX: e.clientX,
  812. startY: e.clientY,
  813. holdTimer: null
  814. };
  815.  
  816. pieceEl.setPointerCapture?.(e.pointerId);
  817. pieceEl.classList.add("dragging");
  818.  
  819. // На touch долгое нажатие означает поворот.
  820. if (e.pointerType === "touch") {
  821. drag.holdTimer = setTimeout(() => {
  822. if (drag && !drag.moved) {
  823. rotateActive();
  824. drag = null;
  825. pieceEl.classList.remove("dragging");
  826. }
  827. }, 560);
  828. }
  829. });
  830.  
  831. pieceEl.addEventListener("pointermove", e => {
  832. if (!drag || drag.pointerId !== e.pointerId || !active) return;
  833. e.preventDefault();
  834.  
  835. const dx = e.clientX - drag.startX;
  836. const dy = e.clientY - drag.startY;
  837. if (Math.hypot(dx, dy) > 8) {
  838. drag.moved = true;
  839. clearTimeout(drag.holdTimer);
  840. }
  841.  
  842. // Во время перетаскивания фигура остаётся fixed,
  843. // поэтому ей не мешают overflow родительских контейнеров.
  844. active.x = e.clientX - drag.offsetX;
  845. active.y = e.clientY - drag.offsetY;
  846.  
  847. pieceEl.style.left = `${active.x}px`;
  848. pieceEl.style.top = `${active.y}px`;
  849.  
  850. updatePreview(pieceEl);
  851. });
  852.  
  853. pieceEl.addEventListener("pointerup", e => {
  854. if (!drag || drag.pointerId !== e.pointerId) return;
  855. clearTimeout(drag.holdTimer);
  856.  
  857. if (drag.moved) {
  858. dropPiece(pieceEl);
  859. }
  860.  
  861. pieceEl.classList.remove("dragging");
  862. drag = null;
  863. clearPreview();
  864. });
  865.  
  866. pieceEl.addEventListener("pointercancel", () => {
  867. if (drag) clearTimeout(drag.holdTimer);
  868. if (pieceEl) pieceEl.classList.remove("dragging");
  869. drag = null;
  870. clearPreview();
  871. returnPieceToConscious();
  872. });
  873. }
  874.  
  875. function findDropAnchor(pieceEl) {
  876. const { rect, gap, cellW, cellH } = getBoardMetrics();
  877. const pr = pieceEl.getBoundingClientRect();
  878. const size = getPiecePixelSize(active);
  879.  
  880. // Берём центр фигуры. Это намного надёжнее, чем требовать,
  881. // чтобы её левый верхний угол случайно совпал с сеткой.
  882. const centerX = pr.left + size.width / 2;
  883. const centerY = pr.top + size.height / 2;
  884.  
  885. const localX = centerX - rect.left;
  886. const localY = centerY - rect.top;
  887.  
  888. const b = bounds(active.cells);
  889. const startX = localX - b.cols * (cellW + gap) / 2;
  890. const startY = localY - b.rows * (cellH + gap) / 2;
  891.  
  892. return {
  893. col: Math.round(startX / (cellW + gap)),
  894. row: Math.round(startY / (cellH + gap))
  895. };
  896. }
  897.  
  898. function canPlace(piece, row, col) {
  899. for (const [dr, dc] of piece.cells) {
  900. const r = row + dr;
  901. const c = col + dc;
  902. if (r < 0 || r >= ROWS || c < 0 || c >= COLS) return false;
  903. if (board[r][c]) return false;
  904. }
  905. return true;
  906. }
  907.  
  908. function updatePreview(pieceEl) {
  909. clearPreview();
  910. if (!active) return;
  911.  
  912. const { row, col } = findDropAnchor(pieceEl);
  913. const good = canPlace(active, row, col);
  914.  
  915. active.cells.forEach(([dr, dc]) => {
  916. const r = row + dr;
  917. const c = col + dc;
  918. if (r >= 0 && r < ROWS && c >= 0 && c < COLS) {
  919. boardEl.children[r * COLS + c].classList.add(good ? "ok" : "bad");
  920. }
  921. });
  922. }
  923.  
  924. function clearPreview() {
  925. [...boardEl.children].forEach(c => c.classList.remove("ok", "bad"));
  926. }
  927.  
  928. function dropPiece(pieceEl) {
  929. const { row, col } = findDropAnchor(pieceEl);
  930.  
  931. if (!canPlace(active, row, col)) {
  932. addStress(FAIL_STRESS);
  933. showToast("💥 Не помещается. Стресс +8%");
  934.  
  935. // После ошибки активная мысль остаётся доступной,
  936. // а дополнительная маленькая появится сразу следом.
  937. returnPieceToConscious();
  938. setTimeout(() => {
  939. if (!gameEnded && !active) spawnPiece(true);
  940. }, 30);
  941.  
  942. // Чтобы НЕ создавать вторую фигуру поверх основной:
  943. if (!gameEnded) {
  944. const failed = active;
  945. active = null;
  946. if (failed?.element) failed.element.remove();
  947. setTimeout(() => {
  948. if (!gameEnded) spawnPiece(true);
  949. }, 180);
  950. }
  951. return;
  952. }
  953.  
  954. placePiece(row, col);
  955. }
  956.  
  957. function returnPieceToConscious() {
  958. if (!active) return;
  959. const zoneW = consciousEl.clientWidth;
  960. const size = getPiecePixelSize(active);
  961. active.x = Math.max(6, (zoneW - size.width) / 2);
  962. active.y = Math.max(14, (consciousEl.clientHeight - size.height) / 2);
  963. renderPiece();
  964. }
  965.  
  966. // =========================
  967. // РАЗМЕЩЕНИЕ ФИГУРЫ
  968. // =========================
  969. function placePiece(row, col) {
  970. const placed = active;
  971.  
  972. for (const [dr, dc] of placed.cells) {
  973. const r = row + dr;
  974. const c = col + dc;
  975. board[r][c] = {
  976. id: placed.id,
  977. color: placed.color,
  978. text: placed.text
  979. };
  980. }
  981.  
  982. if (placed.element) placed.element.remove();
  983. active = null;
  984.  
  985. renderBoard();
  986. const full = getFullRows();
  987.  
  988. if (full.length) {
  989. animateAndClearRows(full);
  990. } else {
  991. subStress(1);
  992. nextTurn();
  993. }
  994. }
  995.  
  996. function getFullRows() {
  997. const full = [];
  998. for (let r = 0; r < ROWS; r++) {
  999. if (board[r].every(Boolean)) full.push(r);
  1000. }
  1001. return full;
  1002. }
  1003.  
  1004. // ВАЖНО: очистка реализована как единая операция над строками.
  1005. // Это исправляет старый баг с "пустыми строками" при удалении
  1006. // нескольких заполненных рядов за один ход.
  1007. function animateAndClearRows(rows) {
  1008. const rowSet = new Set(rows);
  1009. rows.forEach(r => {
  1010. for (let c = 0; c < COLS; c++) {
  1011. boardEl.children[r * COLS + c].classList.add("clearing");
  1012. }
  1013. });
  1014.  
  1015. setTimeout(() => {
  1016. // Сохраняем ВСЕ неполные строки в их текущем порядке.
  1017. // Затем добавляем сверху ровно столько пустых строк,
  1018. // сколько было очищено.
  1019. const remaining = board.filter((row, index) => !rowSet.has(index));
  1020. const emptyRows = Array.from(
  1021. { length: rows.length },
  1022. () => Array(COLS).fill(null)
  1023. );
  1024. board = emptyRows.concat(remaining);
  1025.  
  1026. // Здесь никогда не остаются "пустые промежуточные строки":
  1027. // новые пустые строки всегда находятся только сверху.
  1028. clearedRows += rows.length;
  1029. subStress(CLEAR_STRESS * rows.length);
  1030. renderBoard();
  1031. rowsCounterEl.textContent = `Ряды: ${clearedRows} / ${TARGET_ROWS}`;
  1032.  
  1033. showToast(`✨ Очищено рядов: ${rows.length}`);
  1034.  
  1035. if (clearedRows >= TARGET_ROWS) {
  1036. winGame();
  1037. } else {
  1038. nextTurn();
  1039. }
  1040. }, 380);
  1041. }
  1042.  
  1043. function nextTurn() {
  1044. if (gameEnded) return;
  1045.  
  1046. if (freezeTurns > 0) {
  1047. freezeTurns--;
  1048. showToast(`🐑 Новые мысли заморожены. Осталось: ${freezeTurns}`);
  1049. if (freezeTurns > 0) {
  1050. setTimeout(nextTurn, 180);
  1051. } else {
  1052. spawnPiece(false);
  1053. }
  1054. return;
  1055. }
  1056.  
  1057. spawnPiece(false);
  1058. }
  1059.  
  1060. // =========================
  1061. // БОНУСЫ
  1062. // =========================
  1063. function updateButtons() {
  1064. sheepBtn.textContent = `🐑 Овцы (${sheepUses})`;
  1065. noiseBtn.textContent = `🌫️ Шум (${noiseUses})`;
  1066. sheepBtn.disabled = sheepUses <= 0 || gameEnded;
  1067. noiseBtn.disabled = noiseUses <= 0 || gameEnded || !getOccupiedIds().length;
  1068. }
  1069.  
  1070. function useSheep() {
  1071. if (sheepUses <= 0 || gameEnded) return;
  1072. sheepUses--;
  1073. freezeTurns = FREEZE_TURNS;
  1074. subStress(3);
  1075. updateButtons();
  1076. showToast("🐑 Новые мысли заморожены на 3 хода.");
  1077. }
  1078.  
  1079. function getOccupiedIds() {
  1080. const ids = new Set();
  1081. for (const row of board) {
  1082. for (const cell of row) {
  1083. if (cell) ids.add(cell.id);
  1084. }
  1085. }
  1086. return [...ids];
  1087. }
  1088.  
  1089. function useNoise() {
  1090. if (noiseUses <= 0 || gameEnded) return;
  1091.  
  1092. const ids = getOccupiedIds();
  1093. if (!ids.length) return;
  1094.  
  1095. noiseUses--;
  1096. const id = random(ids);
  1097.  
  1098. for (let r = 0; r < ROWS; r++) {
  1099. for (let c = 0; c < COLS; c++) {
  1100. if (board[r][c]?.id === id) board[r][c] = null;
  1101. }
  1102. }
  1103.  
  1104. subStress(5);
  1105. renderBoard();
  1106. updateButtons();
  1107. showToast("🌫️ Белый шум заглушил одну мысль.");
  1108. }
  1109.  
  1110. // =========================
  1111. // СООБЩЕНИЯ / КОНЕЦ ИГРЫ
  1112. // =========================
  1113. function showToast(text) {
  1114. clearTimeout(toastTimer);
  1115. toastEl.textContent = text;
  1116. toastEl.classList.add("show");
  1117. toastTimer = setTimeout(() => toastEl.classList.remove("show"), 1500);
  1118. }
  1119.  
  1120. function winGame() {
  1121. if (gameEnded) return;
  1122. gameEnded = true;
  1123. setStress(0);
  1124. resultTitleEl.textContent = "😴 Персонаж уснул";
  1125. resultTextEl.textContent =
  1126. "Пять полных рядов собраны. Навязчивые мысли уложены в подсознание, и мозг наконец перестал ворочаться.";
  1127. overlayEl.classList.add("show");
  1128. updateButtons();
  1129. }
  1130.  
  1131. function loseGame() {
  1132. if (gameEnded) return;
  1133. gameEnded = true;
  1134. if (active?.element) active.element.remove();
  1135. active = null;
  1136. clearPreview();
  1137.  
  1138. characterEl.textContent = "😡";
  1139. resultTitleEl.textContent = "😡 Он проснулся";
  1140. resultTextEl.textContent =
  1141. "Стресс достиг 100%. Мыслей стало слишком много. Попробуй использовать бонусы раньше и поворачивать неудобные фигуры.";
  1142. overlayEl.classList.add("show");
  1143. updateButtons();
  1144. }
  1145.  
  1146. // =========================
  1147. // ПЕРЕЗАПУСК
  1148. // =========================
  1149. function restart() {
  1150. gameEnded = false;
  1151. stress = 0;
  1152. clearedRows = 0;
  1153. sheepUses = 2;
  1154. noiseUses = 2;
  1155. freezeTurns = 0;
  1156. pieceId = 0;
  1157. drag = null;
  1158.  
  1159. if (active?.element) active.element.remove();
  1160. active = null;
  1161.  
  1162. board = createEmptyBoard();
  1163. rowsCounterEl.textContent = "Ряды: 0 / 5";
  1164. overlayEl.classList.remove("show");
  1165.  
  1166. buildBoard();
  1167. setStress(0);
  1168. updateButtons();
  1169. startCharacterAnimation();
  1170. spawnPiece(false);
  1171. }
  1172.  
  1173. // =========================
  1174. // RESIZE
  1175. // =========================
  1176. window.addEventListener("resize", () => {
  1177. if (!active || !active.element || drag) return;
  1178.  
  1179. const size = getPiecePixelSize(active);
  1180. const zoneW = consciousEl.clientWidth;
  1181. const zoneH = consciousEl.clientHeight;
  1182.  
  1183. active.x = Math.max(4, Math.min(active.x, zoneW - size.width - 4));
  1184. active.y = Math.max(4, Math.min(active.y, zoneH - size.height - 4));
  1185. renderPiece();
  1186. });
  1187.  
  1188. sheepBtn.addEventListener("click", useSheep);
  1189. noiseBtn.addEventListener("click", useNoise);
  1190. $("restartTop").addEventListener("click", restart);
  1191. $("restartResult").addEventListener("click", restart);
  1192.  
  1193. // =========================
  1194. // СТАРТ
  1195. // =========================
  1196. restart();
  1197. })();
  1198. </script>
  1199. </body>
  1200. </html>
Advertisement
Add Comment
Please, Sign In to add comment