Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="ru">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
- <title>Алгоритм сна</title>
- <style>
- * { box-sizing: border-box; }
- :root {
- --bg: #090d18;
- --panel: rgba(20, 27, 47, .88);
- --panel2: rgba(13, 19, 35, .94);
- --line: rgba(151, 177, 225, .16);
- --text: #ecf4ff;
- --muted: #8ea0bc;
- --accent: #7ad6ff;
- --cell: min(7vw, 54px);
- }
- html, body {
- margin: 0;
- min-height: 100%;
- background:
- radial-gradient(circle at 50% -10%, #203251 0, #0b1020 42%, #070a13 100%);
- color: var(--text);
- font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
- overflow-x: hidden;
- }
- body {
- min-height: 100vh;
- display: flex;
- justify-content: center;
- padding: 14px;
- }
- button { font: inherit; }
- .game {
- width: min(1180px, 100%);
- display: flex;
- flex-direction: column;
- gap: 12px;
- }
- header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 12px;
- }
- .title-wrap h1 {
- margin: 0;
- font-size: clamp(22px, 4vw, 34px);
- letter-spacing: .03em;
- }
- .title-wrap p {
- margin: 4px 0 0;
- color: var(--muted);
- font-size: 13px;
- }
- .restart {
- border: 1px solid rgba(135, 180, 235, .25);
- color: #e9f7ff;
- background: rgba(255,255,255,.06);
- border-radius: 12px;
- padding: 10px 14px;
- cursor: pointer;
- touch-action: manipulation;
- }
- .restart:hover { background: rgba(255,255,255,.11); }
- .top-area {
- display: grid;
- grid-template-columns: minmax(0, 1fr) 250px;
- gap: 12px;
- align-items: stretch;
- }
- .consciousness, .side-panel, .subconscious-panel {
- border: 1px solid var(--line);
- background: linear-gradient(180deg, rgba(30, 40, 66, .82), rgba(12, 17, 30, .92));
- border-radius: 18px;
- box-shadow: 0 18px 50px rgba(0,0,0,.22), inset 0 1px rgba(255,255,255,.04);
- }
- .consciousness {
- position: relative;
- min-height: 330px;
- overflow: hidden;
- }
- .scene-label {
- position: absolute;
- left: 16px;
- top: 12px;
- color: var(--muted);
- font-size: 12px;
- text-transform: uppercase;
- letter-spacing: .16em;
- z-index: 3;
- pointer-events: none;
- }
- .window-glow {
- position: absolute;
- width: 180px;
- height: 120px;
- right: 8%;
- top: 20px;
- background: radial-gradient(circle, rgba(111,169,255,.18), transparent 70%);
- pointer-events: none;
- }
- .bed {
- position: absolute;
- left: 5%;
- right: 5%;
- bottom: 26px;
- height: 150px;
- }
- .headboard {
- position: absolute;
- left: 2%;
- bottom: 52px;
- width: 13%;
- height: 90px;
- border-radius: 18px 18px 5px 5px;
- background: linear-gradient(180deg, #423552, #2b273f);
- border: 1px solid rgba(255,255,255,.08);
- }
- .mattress {
- position: absolute;
- left: 10%;
- right: 0;
- bottom: 44px;
- height: 66px;
- border-radius: 18px 22px 12px 12px;
- background: linear-gradient(180deg, #dbe5ef 0%, #b8c7d8 55%, #8798ab 100%);
- box-shadow: 0 10px 0 #5a6477, 0 18px 28px rgba(0,0,0,.35);
- }
- .blanket {
- position: absolute;
- left: 38%;
- right: 3%;
- bottom: 50px;
- height: 56px;
- border-radius: 24px 18px 14px 14px;
- background: linear-gradient(135deg, #4f6ca2, #324b78);
- box-shadow: inset 0 8px 18px rgba(255,255,255,.06);
- transform: skewX(-5deg);
- }
- .pillow {
- position: absolute;
- left: 14%;
- bottom: 82px;
- width: 22%;
- height: 38px;
- border-radius: 18px;
- background: #e7eef7;
- box-shadow: inset 0 -7px 14px rgba(86,101,125,.28);
- z-index: 2;
- }
- .character {
- position: absolute;
- left: 22%;
- bottom: 91px;
- width: 88px;
- height: 68px;
- z-index: 5;
- display: grid;
- place-items: center;
- user-select: none;
- pointer-events: none;
- }
- .character .face {
- width: 68px;
- height: 58px;
- border-radius: 50% 50% 44% 44%;
- background: linear-gradient(180deg, #f3c999, #d89761);
- border: 2px solid rgba(0,0,0,.15);
- position: relative;
- box-shadow: 0 10px 18px rgba(0,0,0,.2);
- }
- .eye, .brow, .mouth {
- position: absolute;
- left: 50%;
- transform: translateX(-50%);
- }
- .eye { top: 23px; width: 9px; height: 5px; border-radius: 50%; }
- .eye.left { left: 27%; }
- .eye.right { left: 73%; }
- .brow { width: 19px; height: 4px; border-radius: 4px; top: 16px; }
- .brow.left { left: 28%; }
- .brow.right { left: 72%; }
- .mouth { top: 38px; width: 24px; height: 9px; border-bottom: 3px solid #7c3d32; border-radius: 0 0 50% 50%; }
- .state-sleep .eye { background: #563c39; }
- .state-sleep .eye::after {
- content: "—";
- position: absolute; left: -2px; top: -6px;
- font-size: 13px; color: #563c39;
- }
- .state-sleep .brow { background: transparent; border-top: 2px solid #915b47; }
- .state-sleep .mouth { border-bottom: 2px solid #7c3d32; }
- .state-irritated .eye { background: #452e30; height: 3px; }
- .state-irritated .brow { background: #633333; transform: translateX(-50%) rotate(10deg); }
- .state-irritated .mouth { border-bottom: 0; border-top: 3px solid #7c3d32; border-radius: 50%; }
- .state-angry .eye { background: #9a2222; height: 8px; }
- .state-angry .brow { background: #4f2323; }
- .state-angry .mouth { width: 25px; height: 12px; border-bottom: 3px solid #682122; border-radius: 50%; }
- .character[data-frame="1"] { transform: translateY(-2px) rotate(-1deg); }
- .character[data-frame="2"] { transform: translateY(2px) rotate(1deg); }
- .character[data-frame="3"] { transform: translateY(-1px) rotate(0deg); }
- .hint {
- position: absolute;
- left: 50%;
- top: 50%;
- transform: translate(-50%, -10%);
- color: rgba(223,235,255,.55);
- font-size: 13px;
- text-align: center;
- pointer-events: none;
- z-index: 1;
- }
- .thought {
- position: absolute;
- display: grid;
- touch-action: none;
- cursor: grab;
- user-select: none;
- z-index: 10;
- filter: drop-shadow(0 12px 18px rgba(0,0,0,.24));
- transition: filter .15s ease;
- }
- .thought.dragging {
- cursor: grabbing;
- filter: drop-shadow(0 18px 32px rgba(0,0,0,.38));
- z-index: 50;
- }
- .thought-cell, .board-cell {
- width: var(--cell);
- height: var(--cell);
- }
- .thought-cell {
- display: grid;
- place-items: center;
- border: 1px solid rgba(255,255,255,.12);
- border-radius: 8px;
- background: var(--block-color, #5979a8);
- box-shadow: inset 0 1px rgba(255,255,255,.11);
- overflow: hidden;
- }
- .thought-text {
- grid-column: 1 / 99;
- grid-row: 1 / 99;
- align-self: center;
- justify-self: center;
- width: max(90px, 130%);
- max-width: 280px;
- padding: 3px 7px;
- font-size: 11px;
- line-height: 1.1;
- text-align: center;
- color: white;
- text-shadow: 0 1px 2px rgba(0,0,0,.45);
- pointer-events: none;
- }
- .side-panel {
- padding: 14px;
- display: flex;
- flex-direction: column;
- gap: 13px;
- }
- .stat-card {
- background: rgba(5,9,18,.3);
- border: 1px solid rgba(255,255,255,.06);
- border-radius: 14px;
- padding: 11px;
- }
- .stat-head {
- display: flex;
- justify-content: space-between;
- gap: 10px;
- font-size: 12px;
- color: var(--muted);
- margin-bottom: 7px;
- }
- .stress-value { font-weight: 700; color: #f5fbff; }
- .stress-track {
- height: 14px;
- border-radius: 999px;
- overflow: hidden;
- background: #090e1a;
- border: 1px solid rgba(255,255,255,.07);
- }
- .stress-fill {
- width: 0%;
- height: 100%;
- border-radius: inherit;
- background: linear-gradient(90deg, #4ed8a6, #ffd45a 60%, #ff5d6c);
- transition: width .25s ease;
- }
- .rows {
- font-size: 12px;
- color: var(--muted);
- }
- .rows strong { color: var(--text); }
- .bonus-title {
- font-size: 12px;
- color: var(--muted);
- text-transform: uppercase;
- letter-spacing: .11em;
- }
- .bonus {
- border: 1px solid rgba(255,255,255,.08);
- background: rgba(255,255,255,.045);
- color: var(--text);
- padding: 11px;
- border-radius: 12px;
- text-align: left;
- cursor: pointer;
- display: flex;
- justify-content: space-between;
- align-items: center;
- gap: 8px;
- touch-action: manipulation;
- }
- .bonus:hover:not(:disabled) { background: rgba(255,255,255,.09); }
- .bonus:disabled { opacity: .4; cursor: not-allowed; }
- .bonus small { color: var(--muted); }
- .controls-hint {
- font-size: 11px;
- color: #7788a2;
- line-height: 1.4;
- margin-top: auto;
- }
- .subconscious-panel {
- padding: 14px;
- }
- .sub-head {
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin-bottom: 10px;
- gap: 10px;
- }
- .sub-title {
- font-size: 14px;
- font-weight: 700;
- }
- .next-thought {
- color: var(--muted);
- font-size: 12px;
- }
- .grid-wrap {
- display: flex;
- justify-content: center;
- overflow: auto;
- padding-bottom: 2px;
- }
- .subconscious-grid {
- display: grid;
- grid-template-columns: repeat(10, var(--cell));
- grid-template-rows: repeat(8, var(--cell));
- width: calc(var(--cell) * 10);
- height: calc(var(--cell) * 8);
- gap: 2px;
- padding: 2px;
- border-radius: 14px;
- background: rgba(106,129,173,.12);
- border: 1px solid rgba(151,177,225,.15);
- touch-action: none;
- }
- .board-cell {
- border-radius: 7px;
- background: rgba(110, 139, 188, .08);
- border: 1px solid rgba(152,181,224,.08);
- transition: background .12s ease, transform .12s ease;
- }
- .board-cell.preview-ok { background: rgba(98,221,165,.24); }
- .board-cell.preview-bad { background: rgba(255,95,107,.28); }
- .board-cell.filled {
- background: var(--fill-color, #5979a8);
- border-color: rgba(255,255,255,.13);
- box-shadow: inset 0 1px rgba(255,255,255,.13);
- }
- .board-cell.clearing { animation: clearCell .34s ease forwards; }
- @keyframes clearCell {
- 0% { transform: scale(1); filter: brightness(1); opacity: 1; }
- 55% { transform: scale(1.18); filter: brightness(1.7); opacity: .82; }
- 100% { transform: scale(.15); opacity: 0; }
- }
- .floating-message {
- position: fixed;
- left: 50%;
- top: 16%;
- transform: translateX(-50%) translateY(-8px);
- background: rgba(13,19,34,.92);
- border: 1px solid rgba(255,255,255,.1);
- padding: 10px 14px;
- border-radius: 12px;
- z-index: 500;
- opacity: 0;
- pointer-events: none;
- transition: opacity .18s, transform .18s;
- box-shadow: 0 15px 40px rgba(0,0,0,.28);
- }
- .floating-message.show {
- opacity: 1;
- transform: translateX(-50%) translateY(0);
- }
- .overlay {
- position: fixed;
- inset: 0;
- background: rgba(3,6,12,.72);
- backdrop-filter: blur(8px);
- display: none;
- align-items: center;
- justify-content: center;
- z-index: 400;
- padding: 20px;
- }
- .overlay.show { display: flex; }
- .result-card {
- width: min(450px, 100%);
- background: linear-gradient(180deg, #18223a, #0d1426);
- border: 1px solid rgba(255,255,255,.11);
- border-radius: 22px;
- padding: 28px;
- text-align: center;
- box-shadow: 0 25px 70px rgba(0,0,0,.45);
- }
- .result-card h2 { margin: 0 0 8px; font-size: 30px; }
- .result-card p { margin: 0 0 18px; color: var(--muted); line-height: 1.5; }
- .result-card button {
- border: 0;
- background: #78d4ff;
- color: #07101a;
- padding: 12px 18px;
- border-radius: 12px;
- font-weight: 800;
- cursor: pointer;
- }
- @media (max-width: 850px) {
- .top-area { grid-template-columns: 1fr; }
- .side-panel { order: -1; }
- .consciousness { min-height: 300px; }
- .hint { top: 45%; width: 80%; }
- :root { --cell: min(8.6vw, 52px); }
- }
- @media (max-width: 540px) {
- body { padding: 8px; }
- header { align-items: flex-start; }
- .title-wrap p { max-width: 240px; }
- .side-panel { display: grid; grid-template-columns: repeat(2, 1fr); }
- .side-panel .stat-card { grid-column: 1 / -1; }
- .bonus-title { grid-column: 1 / -1; }
- .bonus { min-height: 58px; }
- .controls-hint { grid-column: 1 / -1; }
- .consciousness { min-height: 270px; }
- .bed { left: 1%; right: 1%; }
- .character { left: 19%; }
- .thought-text { font-size: 9px; }
- }
- </style>
- </head>
- <body>
- <div class="game">
- <header>
- <div class="title-wrap">
- <h1>🌙 Алгоритм сна</h1>
- <p>Уложи навязчивые мысли в подсознание без пробелов.</p>
- </div>
- <button class="restart" id="restartBtn">↻ Заново</button>
- </header>
- <section class="top-area">
- <div class="consciousness" id="consciousness">
- <div class="scene-label">СОЗНАНИЕ</div>
- <div class="window-glow"></div>
- <div class="bed">
- <div class="headboard"></div>
- <div class="mattress"></div>
- <div class="blanket"></div>
- <div class="pillow"></div>
- <div class="character state-sleep" id="character" data-frame="1">
- <div class="face">
- <div class="brow left"></div>
- <div class="brow right"></div>
- <div class="eye left"></div>
- <div class="eye right"></div>
- <div class="mouth"></div>
- </div>
- </div>
- </div>
- <div class="hint" id="hint">Перетащи мысль в подсознание.<br>Правый клик или долгое нажатие — повернуть.</div>
- </div>
- <aside class="side-panel">
- <div class="stat-card">
- <div class="stat-head">
- <span>Стресс</span>
- <span class="stress-value" id="stressValue">0%</span>
- </div>
- <div class="stress-track"><div class="stress-fill" id="stressFill"></div></div>
- <div class="rows" style="margin-top:8px;">Заполнено рядов: <strong id="rowsValue">0 / 5</strong></div>
- </div>
- <div class="bonus-title">Бонусы</div>
- <button class="bonus" id="sheepBtn">
- <span>🐑 Считать овец</span><small id="sheepCount">2</small>
- </button>
- <button class="bonus" id="noiseBtn">
- <span>🌫️ Белый шум</span><small id="noiseCount">2</small>
- </button>
- <div class="controls-hint">
- 🖱️ Перетащи мышью<br>
- 📱 На телефоне — пальцем<br>
- 🔄 ПКМ / долгое нажатие — поворот
- </div>
- </aside>
- </section>
- <section class="subconscious-panel">
- <div class="sub-head">
- <div class="sub-title">🧠 ПОДСОЗНАНИЕ · 10 × 8</div>
- <div class="next-thought" id="nextThought">Новая мысль готовится…</div>
- </div>
- <div class="grid-wrap">
- <div class="subconscious-grid" id="grid"></div>
- </div>
- </section>
- </div>
- <div class="floating-message" id="floatingMessage"></div>
- <div class="overlay" id="resultOverlay">
- <div class="result-card">
- <h2 id="resultTitle">Ты заснул</h2>
- <p id="resultText"></p>
- <button id="resultRestart">Попробовать ещё раз</button>
- </div>
- </div>
- <script>
- (() => {
- "use strict";
- // -----------------------------
- // Настройки игры
- // -----------------------------
- const COLS = 10;
- const ROWS = 8;
- const TARGET_ROWS = 5;
- const MAX_STRESS = 100;
- // Не менее 20 русских фраз для случайных мыслей.
- const THOUGHT_PHRASES = [
- "не выключил утюг", "дедлайн завтра", "неловкая фраза 2014",
- "ответил не тому человеку", "где мои ключи?", "почему я это сказал",
- "забыл отправить файл", "а вдруг не закрыл дверь", "завтра рано вставать",
- "нужно купить молоко", "не обновил резюме", "мне кто-то звонил",
- "зачем я это лайкнул", "пароль слишком простой", "письмо без ответа",
- "что было в том сне?", "опять потратил деньги", "надо помыть посуду",
- "звонок в 9:00", "не зарядил телефон", "а точно выключил плиту?",
- "что если опоздаю?", "завтра контрольная", "где мой второй носок",
- "почему он так посмотрел?", "надо ответить маме", "я забыл название",
- "это можно было сказать лучше", "срок уже близко", "не забудь документы"
- ];
- // Разные цвета — разные категории мыслей.
- const COLOR_POOL = [
- "#b84f62", "#4f78be", "#4c9a76", "#9d7a42", "#8857a6",
- "#c0643c", "#3d8ea7", "#a25186"
- ];
- // Набор фигур в координатах x,y.
- const SHAPES = [
- [[0,0]],
- [[0,0],[1,0]],
- [[0,0],[0,1],[1,1]],
- [[0,0],[1,0],[2,0]],
- [[0,0],[1,0],[0,1],[1,1]], // O
- [[0,0],[1,0],[2,0],[1,1]], // T
- [[0,0],[0,1],[0,2],[1,2]], // L
- [[0,0],[1,0],[2,0],[2,1]], // J
- [[0,0],[1,0],[1,1],[2,1]], // S
- [[1,0],[2,0],[0,1],[1,1]], // Z
- [[0,0],[0,1],[1,1],[2,1]], // J-ish
- [[0,0],[1,0],[2,0],[0,1],[0,2]], // Penta L
- [[0,0],[1,0],[2,0],[1,1],[1,2]], // Penta T
- [[0,0],[1,0],[1,1],[2,1],[2,2]], // Zig 5
- [[0,0],[0,1],[0,2],[1,2],[2,2]], // Long L
- [[0,0],[0,1],[1,1],[2,1],[2,0]], // U
- ];
- const state = {
- board: Array.from({length: ROWS}, () => Array(COLS).fill(null)),
- active: null,
- stress: 0,
- clearedRows: 0,
- sheep: 2,
- noise: 2,
- freezeTurns: 0,
- gameOver: false,
- spawnTimer: null,
- animTimer: null,
- frame: 1,
- holdTimer: null,
- drag: null,
- messageTimer: null
- };
- const el = {
- consciousness: document.getElementById("consciousness"),
- grid: document.getElementById("grid"),
- character: document.getElementById("character"),
- stressFill: document.getElementById("stressFill"),
- stressValue: document.getElementById("stressValue"),
- rowsValue: document.getElementById("rowsValue"),
- sheepBtn: document.getElementById("sheepBtn"),
- noiseBtn: document.getElementById("noiseBtn"),
- sheepCount: document.getElementById("sheepCount"),
- noiseCount: document.getElementById("noiseCount"),
- floatingMessage: document.getElementById("floatingMessage"),
- resultOverlay: document.getElementById("resultOverlay"),
- resultTitle: document.getElementById("resultTitle"),
- resultText: document.getElementById("resultText"),
- resultRestart: document.getElementById("resultRestart"),
- restartBtn: document.getElementById("restartBtn"),
- hint: document.getElementById("hint"),
- nextThought: document.getElementById("nextThought")
- };
- // -----------------------------
- // Базовые функции
- // -----------------------------
- function rand(min, max) {
- return Math.floor(Math.random() * (max - min + 1)) + min;
- }
- function randomChoice(arr) {
- return arr[Math.floor(Math.random() * arr.length)];
- }
- function shuffle(arr) {
- const copy = arr.slice();
- for (let i = copy.length - 1; i > 0; i--) {
- const j = Math.floor(Math.random() * (i + 1));
- [copy[i], copy[j]] = [copy[j], copy[i]];
- }
- return copy;
- }
- function cloneCells(cells) {
- return cells.map(([x, y]) => [x, y]);
- }
- function normalizeCells(cells) {
- const minX = Math.min(...cells.map(c => c[0]));
- const minY = Math.min(...cells.map(c => c[1]));
- return cells.map(([x, y]) => [x - minX, y - minY]);
- }
- function rotateCells(cells) {
- // Поворот вокруг начала координат + нормализация.
- const rotated = cells.map(([x, y]) => [-y, x]);
- return normalizeCells(rotated);
- }
- function getBounds(cells) {
- return {
- w: Math.max(...cells.map(c => c[0])) + 1,
- h: Math.max(...cells.map(c => c[1])) + 1
- };
- }
- function occupiedArea() {
- let n = 0;
- for (const row of state.board)
- for (const cell of row)
- if (cell) n++;
- return n;
- }
- function isValidPlacement(cells, x, y) {
- for (const [cx, cy] of cells) {
- const bx = x + cx;
- const by = y + cy;
- if (bx < 0 || bx >= COLS || by < 0 || by >= ROWS) return false;
- if (state.board[by][bx]) return false;
- }
- return true;
- }
- // -----------------------------
- // Создание игрового поля
- // -----------------------------
- function buildGrid() {
- el.grid.innerHTML = "";
- for (let y = 0; y < ROWS; y++) {
- for (let x = 0; x < COLS; x++) {
- const cell = document.createElement("div");
- cell.className = "board-cell";
- cell.dataset.x = String(x);
- cell.dataset.y = String(y);
- el.grid.appendChild(cell);
- }
- }
- renderGrid();
- }
- function renderGrid() {
- const cells = el.grid.children;
- for (let y = 0; y < ROWS; y++) {
- for (let x = 0; x < COLS; x++) {
- const idx = y * COLS + x;
- const cellEl = cells[idx];
- const value = state.board[y][x];
- cellEl.classList.remove("filled");
- cellEl.style.removeProperty("--fill-color");
- if (value) {
- cellEl.classList.add("filled");
- cellEl.style.setProperty("--fill-color", value.color);
- }
- }
- }
- }
- // -----------------------------
- // Стресс и состояние персонажа
- // -----------------------------
- function changeStress(amount) {
- state.stress = Math.max(0, Math.min(MAX_STRESS, state.stress + amount));
- updateStressUI();
- if (state.stress >= 100) {
- finish(false);
- }
- }
- function updateStressUI() {
- el.stressValue.textContent = `${state.stress}%`;
- el.stressFill.style.width = `${state.stress}%`;
- let stateName = "sleep";
- if (state.stress >= 70) stateName = "angry";
- else if (state.stress >= 30) stateName = "irritated";
- el.character.className = `character state-${stateName}`;
- if (state.stress < 30) {
- el.hint.innerHTML = "Тише… мысли можно уложить.<br>Правый клик или долгое нажатие — повернуть.";
- } else if (state.stress < 70) {
- el.hint.innerHTML = "Он ворочается… Укладывай мысли аккуратнее!";
- } else {
- el.hint.innerHTML = "⚠️ Ещё немного — и он проснётся!";
- }
- }
- // -----------------------------
- // Анимация персонажа: 3 состояния × 3 кадра
- // -----------------------------
- function startCharacterAnimation() {
- clearInterval(state.animTimer);
- state.animTimer = setInterval(() => {
- state.frame = state.frame % 3 + 1;
- el.character.dataset.frame = String(state.frame);
- }, 520);
- }
- // -----------------------------
- // Случайная мысль / блок
- // -----------------------------
- function makeThought(extra = false) {
- const baseShape = extra
- ? randomChoice(SHAPES.filter(s => s.length <= 3))
- : randomChoice(SHAPES);
- let cells = cloneCells(baseShape);
- const rotations = rand(0, 3);
- for (let i = 0; i < rotations; i++) cells = rotateCells(cells);
- const thought = {
- id: `${Date.now()}-${Math.random()}`,
- cells,
- color: randomChoice(COLOR_POOL),
- text: randomChoice(THOUGHT_PHRASES),
- x: 20,
- y: 42,
- extra
- };
- return thought;
- }
- function renderActiveThought() {
- if (!state.active) return;
- const thought = state.active;
- let node = thought.node;
- if (!node) {
- node = document.createElement("div");
- node.className = "thought";
- el.consciousness.appendChild(node);
- thought.node = node;
- }
- node.innerHTML = "";
- const bounds = getBounds(thought.cells);
- node.style.width = `calc(var(--cell) * ${bounds.w})`;
- node.style.height = `calc(var(--cell) * ${bounds.h})`;
- node.style.gridTemplateColumns = `repeat(${bounds.w}, var(--cell))`;
- node.style.gridTemplateRows = `repeat(${bounds.h}, var(--cell))`;
- thought.cells.forEach(([x, y]) => {
- const c = document.createElement("div");
- c.className = "thought-cell";
- c.style.gridColumn = String(x + 1);
- c.style.gridRow = String(y + 1);
- c.style.setProperty("--block-color", thought.color);
- node.appendChild(c);
- });
- const text = document.createElement("div");
- text.className = "thought-text";
- text.textContent = thought.text;
- node.appendChild(text);
- node.style.left = `${thought.x}px`;
- node.style.top = `${thought.y}px`;
- bindThoughtEvents(node, thought);
- }
- function spawnThought(extra = false) {
- if (state.gameOver) return;
- if (state.active && state.active.node) state.active.node.remove();
- // При заморозке мысль не появляется.
- if (state.freezeTurns > 0) {
- state.freezeTurns--;
- state.nextQueued = makeThought(false);
- el.nextThought.textContent = "🐑 Овцы заглушают новые мысли…";
- renderBoardMessage();
- scheduleNextTurn();
- return;
- }
- state.active = makeThought(extra);
- // Появление сверху, каждый раз в немного новом месте.
- const sceneRect = el.consciousness.getBoundingClientRect();
- const thoughtRectWidth = Math.max(70, getBounds(state.active.cells).w * parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--cell")));
- state.active.x = Math.max(18, (sceneRect.width - thoughtRectWidth) / 2 + rand(-80, 80));
- state.active.y = 52 + rand(-6, 12);
- el.nextThought.textContent = `Мысль: «${state.active.text}»`;
- renderActiveThought();
- }
- function scheduleNextTurn() {
- clearTimeout(state.spawnTimer);
- state.spawnTimer = setTimeout(() => {
- spawnThought(false);
- }, 260);
- }
- function renderBoardMessage() {
- if (state.freezeTurns > 0) {
- el.nextThought.textContent = `🐑 Новые мысли заморожены ещё на ${state.freezeTurns} х.`;
- }
- }
- // -----------------------------
- // Drag & drop + touch
- // -----------------------------
- function bindThoughtEvents(node, thought) {
- // Чтобы не дублировать обработчики после каждого рендера,
- // добавляем их только один раз.
- if (node.dataset.bound === "1") return;
- node.dataset.bound = "1";
- node.addEventListener("contextmenu", e => {
- e.preventDefault();
- rotateActiveThought();
- });
- node.addEventListener("pointerdown", e => {
- if (state.gameOver || state.active !== thought) return;
- e.preventDefault();
- node.setPointerCapture?.(e.pointerId);
- node.classList.add("dragging");
- const rect = node.getBoundingClientRect();
- state.drag = {
- pointerId: e.pointerId,
- startX: e.clientX,
- startY: e.clientY,
- offsetX: e.clientX - rect.left,
- offsetY: e.clientY - rect.top,
- moved: false,
- node
- };
- // Долгое нажатие на touch = поворот, если почти не двигались.
- if (e.pointerType === "touch") {
- clearTimeout(state.holdTimer);
- state.holdTimer = setTimeout(() => {
- if (state.drag && !state.drag.moved) rotateActiveThought();
- }, 560);
- }
- });
- node.addEventListener("pointermove", e => {
- if (!state.drag || state.drag.pointerId !== e.pointerId) return;
- e.preventDefault();
- const dx = e.clientX - state.drag.startX;
- const dy = e.clientY - state.drag.startY;
- if (Math.hypot(dx, dy) > 8) {
- state.drag.moved = true;
- clearTimeout(state.holdTimer);
- }
- const sceneRect = el.consciousness.getBoundingClientRect();
- const nodeRect = node.getBoundingClientRect();
- const newLeft = e.clientX - sceneRect.left - state.drag.offsetX;
- const newTop = e.clientY - sceneRect.top - state.drag.offsetY;
- thought.x = newLeft;
- thought.y = newTop;
- node.style.left = `${newLeft}px`;
- node.style.top = `${newTop}px`;
- // Превью появляется, когда фигура находится над полем.
- showPlacementPreview(node);
- });
- const finishDrag = e => {
- if (!state.drag || state.drag.pointerId !== e.pointerId) return;
- clearTimeout(state.holdTimer);
- node.classList.remove("dragging");
- const dropped = tryDropActive(node);
- state.drag = null;
- if (!dropped && !state.gameOver) {
- // Возвращаем мысль на верх.
- thought.x = Math.max(20, (el.consciousness.clientWidth - getBounds(thought.cells).w * parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--cell"))) / 2);
- thought.y = 50;
- node.style.left = `${thought.x}px`;
- node.style.top = `${thought.y}px`;
- }
- };
- node.addEventListener("pointerup", finishDrag);
- node.addEventListener("pointercancel", finishDrag);
- }
- function rotateActiveThought() {
- if (!state.active || state.gameOver) return;
- clearTimeout(state.holdTimer);
- state.active.cells = rotateCells(state.active.cells);
- renderActiveThought();
- showMessage("🔄 Мысль повернулась");
- }
- function gridMetrics() {
- const gridRect = el.grid.getBoundingClientRect();
- const style = getComputedStyle(el.grid);
- const gap = parseFloat(style.gap) || 2;
- const cellW = (gridRect.width - gap * 2 - gap * (COLS - 1)) / COLS;
- const cellH = (gridRect.height - gap * 2 - gap * (ROWS - 1)) / ROWS;
- return { gridRect, gap, cellW, cellH };
- }
- function findAnchor(node, thought) {
- const nodeRect = node.getBoundingClientRect();
- const { gridRect, cellW, cellH } = gridMetrics();
- const centerX = nodeRect.left + nodeRect.width / 2;
- const centerY = nodeRect.top + nodeRect.height / 2;
- const bounds = getBounds(thought.cells);
- const leftGuess = centerX - (bounds.w * cellW) / 2;
- const topGuess = centerY - (bounds.h * cellH) / 2;
- const x = Math.round((leftGuess - gridRect.left - 2) / (cellW + 2));
- const y = Math.round((topGuess - gridRect.top - 2) / (cellH + 2));
- return { x, y };
- }
- function clearPreview() {
- for (const cell of el.grid.children) {
- cell.classList.remove("preview-ok", "preview-bad");
- }
- }
- function showPlacementPreview(node) {
- clearPreview();
- if (!state.active) return;
- const {x, y} = findAnchor(node, state.active);
- const ok = isValidPlacement(state.active.cells, x, y);
- state.active.preview = {x, y, ok};
- for (const [cx, cy] of state.active.cells) {
- const bx = x + cx, by = y + cy;
- if (bx >= 0 && bx < COLS && by >= 0 && by < ROWS) {
- el.grid.children[by * COLS + bx].classList.add(ok ? "preview-ok" : "preview-bad");
- }
- }
- }
- function tryDropActive(node) {
- clearPreview();
- if (!state.active) return false;
- const {x, y} = findAnchor(node, state.active);
- if (!isValidPlacement(state.active.cells, x, y)) {
- changeStress(8);
- showMessage("💥 Мысль не поместилась! Стресс +8%");
- spawnExtraThought();
- return false;
- }
- // Заносим клетки фигуры в подсознание.
- state.active.cells.forEach(([cx, cy]) => {
- const bx = x + cx, by = y + cy;
- state.board[by][bx] = {
- color: state.active.color,
- text: state.active.text
- };
- });
- if (state.active.node) state.active.node.remove();
- state.active = null;
- renderGrid();
- const completed = findFullRows();
- if (completed.length) {
- clearRowsAnimated(completed);
- } else {
- // Правильное размещение — небольшой шанс/ощущение спокойствия.
- changeStress(-1);
- scheduleNextTurn();
- }
- return true;
- }
- function spawnExtraThought() {
- // Дополнительный маленький блок появляется при неудачном ходе.
- clearTimeout(state.spawnTimer);
- state.spawnTimer = setTimeout(() => {
- spawnThought(true);
- }, 170);
- }
- // -----------------------------
- // Очистка заполненных рядов
- // -----------------------------
- function findFullRows() {
- const rows = [];
- for (let y = 0; y < ROWS; y++) {
- if (state.board[y].every(Boolean)) rows.push(y);
- }
- return rows;
- }
- function clearRowsAnimated(rows) {
- const cells = el.grid.children;
- const indices = [];
- rows.forEach(y => {
- for (let x = 0; x < COLS; x++) indices.push(y * COLS + x);
- });
- indices.forEach(i => cells[i].classList.add("clearing"));
- setTimeout(() => {
- // Удаляем строки снизу вверх, чтобы не сломать индексы.
- for (const y of rows.slice().sort((a,b) => b-a)) {
- state.board.splice(y, 1);
- state.board.unshift(Array(COLS).fill(null));
- }
- state.clearedRows += rows.length;
- changeStress(-Math.min(28, rows.length * 11));
- renderGrid();
- el.rowsValue.textContent = `${state.clearedRows} / ${TARGET_ROWS}`;
- showMessage(`✨ Ряд очищен! Стресс −${Math.min(28, rows.length * 11)}%`);
- if (state.clearedRows >= TARGET_ROWS) {
- finish(true);
- } else {
- scheduleNextTurn();
- }
- }, 340);
- }
- // -----------------------------
- // Бонусы
- // -----------------------------
- function useSheep() {
- if (state.gameOver || state.sheep <= 0) return;
- state.sheep--;
- state.freezeTurns += 3;
- el.sheepCount.textContent = String(state.sheep);
- el.sheepBtn.disabled = state.sheep <= 0;
- changeStress(-4);
- showMessage("🐑 Три хода без новых мыслей.");
- renderBoardMessage();
- }
- function useWhiteNoise() {
- if (state.gameOver || state.noise <= 0) return;
- const occupied = [];
- for (let y = 0; y < ROWS; y++) {
- for (let x = 0; x < COLS; x++) {
- if (state.board[y][x]) occupied.push([x,y]);
- }
- }
- if (!occupied.length) {
- showMessage("🌫️ В подсознании пока нечего заглушать.");
- return;
- }
- state.noise--;
- const [x,y] = randomChoice(occupied);
- state.board[y][x] = null;
- el.noiseCount.textContent = String(state.noise);
- el.noiseBtn.disabled = state.noise <= 0;
- renderGrid();
- changeStress(-5);
- showMessage("🌫️ Белый шум заглушил одну мысль.");
- }
- // -----------------------------
- // Конец игры
- // -----------------------------
- function finish(win) {
- if (state.gameOver) return;
- state.gameOver = true;
- clearTimeout(state.spawnTimer);
- clearInterval(state.animTimer);
- clearTimeout(state.holdTimer);
- if (state.active?.node) state.active.node.remove();
- clearPreview();
- if (win) {
- el.resultTitle.textContent = "😴 Ты заснул";
- el.resultText.textContent = "Все пять рядов собраны. Мысли уложены плотно, мозг наконец перестал крутиться вокруг одного и того же.";
- } else {
- state.stress = 100;
- updateStressUI();
- el.resultTitle.textContent = "😡 Он проснулся";
- el.resultText.textContent = "Стресс достиг 100%. Мысли оказались слишком неудобными. Попробуй заново и используй бонусы.";
- }
- el.resultOverlay.classList.add("show");
- }
- function showMessage(text) {
- clearTimeout(state.messageTimer);
- el.floatingMessage.textContent = text;
- el.floatingMessage.classList.add("show");
- state.messageTimer = setTimeout(() => {
- el.floatingMessage.classList.remove("show");
- }, 1600);
- }
- // -----------------------------
- // Перезапуск
- // -----------------------------
- function resetGame() {
- clearTimeout(state.spawnTimer);
- clearInterval(state.animTimer);
- clearTimeout(state.holdTimer);
- state.board = Array.from({length: ROWS}, () => Array(COLS).fill(null));
- state.active = null;
- state.stress = 0;
- state.clearedRows = 0;
- state.sheep = 2;
- state.noise = 2;
- state.freezeTurns = 0;
- state.gameOver = false;
- state.drag = null;
- state.frame = 1;
- el.resultOverlay.classList.remove("show");
- el.sheepCount.textContent = "2";
- el.noiseCount.textContent = "2";
- el.sheepBtn.disabled = false;
- el.noiseBtn.disabled = false;
- el.rowsValue.textContent = "0 / 5";
- el.nextThought.textContent = "Новая мысль готовится…";
- buildGrid();
- updateStressUI();
- startCharacterAnimation();
- spawnThought(false);
- }
- // -----------------------------
- // Клавиатура: полезно на ПК
- // -----------------------------
- document.addEventListener("keydown", e => {
- if (state.gameOver) return;
- if (e.key.toLowerCase() === "r") rotateActiveThought();
- if (e.key === "Escape" && state.active?.node) {
- state.active.x = 20;
- state.active.y = 50;
- state.active.node.style.left = "20px";
- state.active.node.style.top = "50px";
- clearPreview();
- }
- });
- // -----------------------------
- // Кнопки
- // -----------------------------
- el.sheepBtn.addEventListener("click", useSheep);
- el.noiseBtn.addEventListener("click", useWhiteNoise);
- el.restartBtn.addEventListener("click", resetGame);
- el.resultRestart.addEventListener("click", resetGame);
- // Подстройка масштаба клеток при изменении ширины окна.
- window.addEventListener("resize", () => {
- if (state.active) {
- // Если активная фигура существует, её положение просто ограничиваем.
- const sceneW = el.consciousness.clientWidth;
- const bounds = getBounds(state.active.cells);
- const cell = parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--cell"));
- state.active.x = Math.min(state.active.x, sceneW - bounds.w * cell - 8);
- state.active.x = Math.max(8, state.active.x);
- state.active.node.style.left = `${state.active.x}px`;
- }
- });
- // Старт игры сразу после загрузки.
- resetGame();
- })();
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment