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, user-scalable=no">
- <title>Алгоритм сна</title>
- <style>
- /* =========================
- БАЗОВЫЕ СТИЛИ
- ========================= */
- * { box-sizing: border-box; }
- html, body { margin: 0; min-height: 100%; }
- body {
- background:
- radial-gradient(circle at 50% 0%, rgba(76, 70, 150, .26), transparent 34%),
- radial-gradient(circle at 20% 80%, rgba(38, 92, 130, .16), transparent 28%),
- #080b15;
- color: #e9ecff;
- font-family: "Segoe UI", Roboto, system-ui, -apple-system, sans-serif;
- padding: 12px;
- }
- button {
- font: inherit;
- -webkit-tap-highlight-color: transparent;
- }
- /* Основной контейнер намеренно компактный: всё поле всегда видно. */
- #game {
- width: min(720px, 100%);
- margin: 0 auto;
- background: linear-gradient(180deg, #121827, #0e1421);
- border: 1px solid rgba(157, 166, 220, .12);
- border-radius: 24px;
- padding: 14px;
- box-shadow: 0 20px 70px rgba(0,0,0,.45), inset 0 1px rgba(255,255,255,.03);
- }
- header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 10px;
- margin-bottom: 12px;
- }
- h1 {
- margin: 0;
- text-align: center;
- width: 100%;
- font-size: clamp(22px, 5vw, 30px);
- color: #cfd5ff;
- letter-spacing: 2px;
- text-shadow: 0 0 18px rgba(110, 110, 255, .45);
- }
- .restart-top {
- flex: 0 0 auto;
- border: 1px solid #444b69;
- background: #1a2133;
- color: #dfe4ff;
- border-radius: 12px;
- padding: 8px 10px;
- cursor: pointer;
- }
- /* =========================
- ИГРОВАЯ СЦЕНА
- ========================= */
- .scene {
- display: grid;
- grid-template-columns: 145px minmax(0, 1fr);
- gap: 12px;
- align-items: stretch;
- }
- .character-area {
- min-width: 0;
- min-height: 170px;
- border-radius: 18px;
- background: rgba(20, 24, 46, .68);
- border: 1px solid rgba(120, 130, 200, .14);
- display: flex;
- align-items: center;
- justify-content: center;
- padding: 10px;
- }
- .bed {
- position: relative;
- width: 124px;
- height: 76px;
- border-radius: 15px 15px 10px 10px;
- background: linear-gradient(180deg, #69442e, #452919);
- box-shadow: 0 6px 0 #2f1b10, 0 12px 24px rgba(0,0,0,.3);
- }
- .bed::before {
- content: "";
- position: absolute;
- left: 6px;
- top: -15px;
- width: 48px;
- height: 22px;
- border-radius: 12px;
- background: #f1e7dc;
- transform: rotate(-3deg);
- box-shadow: 0 2px 5px rgba(0,0,0,.35);
- }
- .bed::after {
- content: "";
- position: absolute;
- left: 48px;
- top: -7px;
- width: 70px;
- height: 22px;
- border-radius: 9px;
- background: linear-gradient(180deg, #51479a, #342e6a);
- transform: rotate(2deg);
- box-shadow: 0 3px 8px rgba(0,0,0,.45);
- }
- .character {
- position: absolute;
- left: 37px;
- top: -39px;
- font-size: 46px;
- z-index: 5;
- transform-origin: center;
- filter: drop-shadow(0 0 7px rgba(255, 210, 120, .5));
- }
- .character.frame1 { animation: sleep1 .45s ease-in-out; }
- .character.frame2 { animation: sleep2 .45s ease-in-out; }
- .character.frame3 { animation: sleep3 .45s ease-in-out; }
- @keyframes sleep1 { 50% { transform: translateY(-2px) rotate(-1deg); } }
- @keyframes sleep2 { 50% { transform: translateY(2px) rotate(1deg); } }
- @keyframes sleep3 { 50% { transform: translateY(-1px) rotate(0deg); } }
- .play {
- min-width: 0;
- display: flex;
- flex-direction: column;
- gap: 10px;
- }
- /* Зона сознания */
- .conscious {
- height: 110px;
- position: relative;
- overflow: hidden;
- border: 2px dashed #454970;
- background:
- radial-gradient(circle at 50% 70%, rgba(78,73,160,.18), transparent 45%),
- rgba(28, 25, 69, .48);
- border-radius: 17px;
- display: flex;
- align-items: center;
- justify-content: center;
- }
- .conscious-label {
- position: absolute;
- top: 8px;
- left: 10px;
- color: #7f86b6;
- font-size: 10px;
- letter-spacing: .13em;
- text-transform: uppercase;
- pointer-events: none;
- }
- .conscious-tip {
- color: rgba(196, 201, 240, .45);
- text-align: center;
- font-size: 11px;
- line-height: 1.35;
- pointer-events: none;
- }
- /* =========================
- ПОЛЕ ПОДСОЗНАНИЯ
- Главное исправление: НИКАКОГО scroll.
- Размер адаптивный, но всегда квадратный.
- ========================= */
- .board-title {
- display: flex;
- justify-content: space-between;
- align-items: center;
- gap: 8px;
- color: #c5cbe6;
- font-size: 12px;
- padding: 0 2px;
- }
- .board-wrap {
- width: min(100%, 390px);
- aspect-ratio: 1 / 1;
- margin: 0 auto;
- padding: 5px;
- border-radius: 15px;
- background: rgba(33, 37, 67, .72);
- border: 1px solid rgba(123, 133, 191, .20);
- box-shadow: inset 0 0 25px rgba(0,0,0,.18);
- }
- #board {
- width: 100%;
- height: 100%;
- display: grid;
- grid-template-columns: repeat(8, minmax(0, 1fr));
- grid-template-rows: repeat(8, minmax(0, 1fr));
- gap: 3px;
- touch-action: none;
- }
- .cell {
- min-width: 0;
- min-height: 0;
- border-radius: 5px;
- background: rgba(11, 15, 28, .78);
- border: 1px solid rgba(104, 116, 170, .18);
- transition: background .12s, transform .12s;
- }
- .cell.ok { background: rgba(72, 205, 155, .26); border-color: rgba(110, 255, 198, .42); }
- .cell.bad { background: rgba(241, 82, 103, .25); border-color: rgba(255, 112, 130, .45); }
- .cell.filled {
- border-color: rgba(255,255,255,.26);
- box-shadow: inset 0 0 10px rgba(255,255,255,.10);
- }
- .cell.clearing { animation: rowFlash .38s ease forwards; }
- @keyframes rowFlash {
- 0% { opacity: 1; transform: scale(1); filter: brightness(1); }
- 45% { opacity: .95; transform: scale(.82); filter: brightness(2); }
- 100% { opacity: 0; transform: scale(.15); }
- }
- /* Фигура мысли */
- .piece {
- --piece-cell: 32px;
- --piece-gap: 3px;
- position: fixed;
- display: grid;
- gap: var(--piece-gap);
- z-index: 1000;
- cursor: grab;
- touch-action: none;
- user-select: none;
- filter: drop-shadow(0 6px 12px rgba(0,0,0,.55));
- }
- .piece.dragging {
- cursor: grabbing;
- filter: drop-shadow(0 12px 24px rgba(0,0,0,.75));
- }
- .piece-cell {
- border-radius: 7px;
- border: 1px solid rgba(255,255,255,.22);
- background: var(--color);
- box-shadow: inset 0 1px rgba(255,255,255,.12);
- min-width: 0;
- min-height: 0;
- }
- .piece-label {
- position: absolute;
- inset: 0;
- display: flex;
- align-items: center;
- justify-content: center;
- padding: 3px 6px;
- color: #fff;
- text-shadow: 0 1px 3px rgba(0,0,0,.7);
- font-weight: 700;
- font-size: clamp(8px, 1.7vw, 11px);
- line-height: 1.05;
- text-align: center;
- pointer-events: none;
- overflow: hidden;
- }
- /* =========================
- НИЖНЯЯ ПАНЕЛЬ
- ========================= */
- .controls {
- display: grid;
- grid-template-columns: minmax(150px, 1fr) auto auto;
- gap: 8px;
- align-items: center;
- margin-top: 12px;
- }
- .stress-box {
- display: grid;
- grid-template-columns: auto minmax(80px, 1fr) auto;
- gap: 8px;
- align-items: center;
- min-width: 0;
- }
- .stress-label, .stress-value, .rows-counter {
- font-size: 12px;
- white-space: nowrap;
- }
- .stress-bar {
- height: 15px;
- border-radius: 999px;
- overflow: hidden;
- background: #171a2d;
- border: 1px solid #3b3f56;
- }
- #stressFill {
- width: 0%;
- height: 100%;
- background: linear-gradient(90deg, #22c55e, #eab308, #ef4444);
- border-radius: inherit;
- transition: width .25s ease;
- }
- .bonus {
- border: 1px solid #444b69;
- background: #1b2336;
- color: #e5e9ff;
- padding: 9px 11px;
- border-radius: 12px;
- cursor: pointer;
- white-space: nowrap;
- }
- .bonus:hover:not(:disabled) { background: #242e46; }
- .bonus:active:not(:disabled) { transform: scale(.97); }
- .bonus:disabled { opacity: .4; cursor: not-allowed; }
- .info-line {
- display: flex;
- justify-content: center;
- gap: 12px;
- margin-top: 8px;
- color: #7f88aa;
- font-size: 11px;
- text-align: center;
- }
- /* Окончание игры */
- .overlay {
- position: fixed;
- inset: 0;
- z-index: 5000;
- display: none;
- align-items: center;
- justify-content: center;
- padding: 18px;
- background: rgba(4,6,12,.72);
- backdrop-filter: blur(7px);
- }
- .overlay.show { display: flex; }
- .result {
- width: min(430px, 100%);
- border-radius: 21px;
- padding: 26px;
- background: linear-gradient(180deg, #1a2237, #0d1422);
- border: 1px solid rgba(160,170,220,.18);
- box-shadow: 0 24px 70px rgba(0,0,0,.45);
- text-align: center;
- }
- .result h2 { margin: 0 0 8px; font-size: 29px; }
- .result p { margin: 0 0 18px; color: #9ca6c5; line-height: 1.45; }
- .result button {
- border: 0;
- border-radius: 12px;
- background: #8178df;
- color: #fff;
- padding: 11px 18px;
- cursor: pointer;
- font-weight: 700;
- }
- .toast {
- position: fixed;
- left: 50%;
- top: 12%;
- z-index: 6000;
- transform: translate(-50%, -10px);
- opacity: 0;
- pointer-events: none;
- padding: 9px 13px;
- border-radius: 12px;
- color: #eff2ff;
- background: rgba(13,18,32,.95);
- border: 1px solid rgba(255,255,255,.10);
- box-shadow: 0 12px 34px rgba(0,0,0,.35);
- transition: opacity .18s, transform .18s;
- text-align: center;
- white-space: nowrap;
- }
- .toast.show { opacity: 1; transform: translate(-50%, 0); }
- /* Мобильная версия */
- @media (max-width: 560px) {
- body { padding: 7px; }
- #game { padding: 10px; border-radius: 19px; }
- .scene {
- grid-template-columns: 1fr;
- }
- .character-area {
- min-height: 110px;
- }
- .bed { transform: scale(.83); }
- .play { width: 100%; }
- .conscious { height: 86px; }
- .board-wrap { width: min(100%, 350px); }
- .controls {
- grid-template-columns: 1fr 1fr;
- }
- .stress-box {
- grid-column: 1 / -1;
- }
- .bonus { width: 100%; }
- .info-line { flex-wrap: wrap; gap: 5px 10px; }
- }
- @media (max-width: 360px) {
- h1 { font-size: 20px; letter-spacing: 1px; }
- .board-wrap { width: min(100%, 310px); }
- .controls { gap: 6px; }
- .bonus { font-size: 11px; padding: 8px 6px; }
- .stress-label, .rows-counter { font-size: 10px; }
- }
- </style>
- </head>
- <body>
- <div id="game">
- <header>
- <h1>🌙 Алгоритм сна</h1>
- <button class="restart-top" id="restartTop">↻</button>
- </header>
- <section class="scene">
- <div class="character-area">
- <div class="bed">
- <div class="character" id="character">😴</div>
- </div>
- </div>
- <div class="play">
- <div class="conscious" id="conscious">
- <div class="conscious-label">СОЗНАНИЕ</div>
- <div class="conscious-tip" id="consciousTip">
- Перетащи мысль вниз.<br>
- ПКМ или долгое нажатие — повернуть.
- </div>
- </div>
- <div class="board-title">
- <span>🧠 Подсознание</span>
- <span class="rows-counter" id="rowsCounter">Ряды: 0 / 5</span>
- </div>
- <div class="board-wrap">
- <div id="board"></div>
- </div>
- </div>
- </section>
- <section class="controls">
- <div class="stress-box">
- <span class="stress-label">Стресс</span>
- <div class="stress-bar"><div id="stressFill"></div></div>
- <span class="stress-value" id="stressValue">0%</span>
- </div>
- <button class="bonus" id="sheepBtn">🐑 Овцы (2)</button>
- <button class="bonus" id="noiseBtn">🌫️ Шум (2)</button>
- </section>
- <div class="info-line">
- <span>Неудача: +8% стресса</span>
- <span>Линия: −12%</span>
- <span>Победа: 5 линий</span>
- </div>
- </div>
- <div class="toast" id="toast"></div>
- <div class="overlay" id="overlay">
- <div class="result">
- <h2 id="resultTitle">😴 Сон!</h2>
- <p id="resultText"></p>
- <button id="restartResult">Начать заново</button>
- </div>
- </div>
- <script>
- (() => {
- "use strict";
- // =========================
- // КОНФИГУРАЦИЯ
- // =========================
- const COLS = 8;
- const ROWS = 8;
- const TARGET_ROWS = 5;
- const MAX_STRESS = 100;
- const FAIL_STRESS = 8;
- const CLEAR_STRESS = 12;
- const FREEZE_TURNS = 3;
- // Более 20 русских мыслей.
- const THOUGHTS = [
- "не выключил утюг", "дедлайн завтра", "неловкая фраза 2014",
- "забыл ответить", "не закрыл дверь?", "завтра рано вставать",
- "что если опоздаю?", "не оплатил счёт", "надо позвонить",
- "что сказать на встрече?", "а вдруг всё забыл?", "проект не готов",
- "надо было иначе", "почему я это сказал?", "что обо мне думают?",
- "забытые продукты", "не выключил плиту", "а если не получится?",
- "надо лечь раньше", "что-то скрипит", "не ответил на сообщение",
- "что надеть завтра?", "пароль слишком простой", "где ключи?",
- "забытый файл", "срок уже близко", "а точно отправил?",
- "почему я это лайкнул?", "надо помыть посуду", "зарядить телефон"
- ];
- const NORMAL_SHAPES = [
- [[0,0],[0,1],[1,0],[1,1]], // O
- [[0,0],[1,0],[2,0],[2,1]], // L
- [[0,1],[1,0],[1,1],[2,0]], // S
- [[0,0],[1,0],[2,0],[2,1]], // J
- [[0,0],[0,1],[0,2],[1,1]], // T
- [[0,0],[1,0],[1,1],[2,1]], // Z
- [[0,0],[0,1],[1,1],[2,1]], // J-ish
- [[0,0],[0,1],[0,2],[1,2],[2,2]], // penta L
- [[0,0],[1,0],[2,0],[1,1],[1,2]], // penta T
- [[0,0],[1,0],[1,1],[1,2],[2,2]], // penta zig
- [[0,0],[0,1],[1,1],[2,1],[2,0]], // penta U
- [[0,0],[1,0],[2,0]], // 3 line
- [[0,0],[0,1],[0,2]] // 3 column
- ];
- // Маленькая фигура после неудачи.
- const SMALL_SHAPES = [
- [[0,0]],
- [[0,0],[1,0]],
- [[0,0],[0,1]],
- [[0,0],[1,0],[0,1]]
- ];
- const COLORS = [
- "#e2556d", "#4c82d8", "#48a979", "#d39649",
- "#9565c9", "#d36b40", "#3b9ab5", "#a84f91"
- ];
- // =========================
- // СОСТОЯНИЕ
- // =========================
- let board = [];
- let active = null;
- let stress = 0;
- let clearedRows = 0;
- let sheepUses = 2;
- let noiseUses = 2;
- let freezeTurns = 0;
- let gameEnded = false;
- let pieceId = 0;
- let animationTimer = null;
- let toastTimer = null;
- // Данные перетаскивания.
- let drag = null;
- const $ = id => document.getElementById(id);
- const boardEl = $("board");
- const consciousEl = $("conscious");
- const characterEl = $("character");
- const stressFillEl = $("stressFill");
- const stressValueEl = $("stressValue");
- const rowsCounterEl = $("rowsCounter");
- const consciousTipEl = $("consciousTip");
- const sheepBtn = $("sheepBtn");
- const noiseBtn = $("noiseBtn");
- const overlayEl = $("overlay");
- const resultTitleEl = $("resultTitle");
- const resultTextEl = $("resultText");
- const toastEl = $("toast");
- // =========================
- // УТИЛИТЫ
- // =========================
- function random(arr) {
- return arr[Math.floor(Math.random() * arr.length)];
- }
- function rotateShape(cells) {
- // (row, col) -> (col, -row), затем нормализация.
- const rotated = cells.map(([r, c]) => [c, -r]);
- const minR = Math.min(...rotated.map(([r]) => r));
- const minC = Math.min(...rotated.map(([, c]) => c));
- return rotated.map(([r,c]) => [r - minR, c - minC]);
- }
- function bounds(cells) {
- return {
- rows: Math.max(...cells.map(([r]) => r)) + 1,
- cols: Math.max(...cells.map(([,c]) => c)) + 1
- };
- }
- function clone2D(arr) {
- return arr.map(row => row.slice());
- }
- // =========================
- // ИНИЦИАЛИЗАЦИЯ ПОЛЯ
- // =========================
- function createEmptyBoard() {
- return Array.from({ length: ROWS }, () => Array(COLS).fill(null));
- }
- function buildBoard() {
- boardEl.innerHTML = "";
- for (let r = 0; r < ROWS; r++) {
- for (let c = 0; c < COLS; c++) {
- const cell = document.createElement("div");
- cell.className = "cell";
- cell.dataset.row = r;
- cell.dataset.col = c;
- boardEl.appendChild(cell);
- }
- }
- renderBoard();
- }
- function renderBoard() {
- const cells = boardEl.children;
- for (let r = 0; r < ROWS; r++) {
- for (let c = 0; c < COLS; c++) {
- const el = cells[r * COLS + c];
- const value = board[r][c];
- el.classList.remove("filled", "ok", "bad", "clearing");
- el.style.removeProperty("background");
- if (value) {
- el.classList.add("filled");
- el.style.background = `linear-gradient(145deg, ${value.color}, rgba(255,255,255,.08))`;
- }
- }
- }
- }
- // =========================
- // СТРЕСС + ПЕРСОНАЖ
- // =========================
- function setStress(value) {
- stress = Math.max(0, Math.min(MAX_STRESS, value));
- stressFillEl.style.width = `${stress}%`;
- stressValueEl.textContent = `${stress}%`;
- if (stress < 30) {
- characterEl.textContent = "😴";
- consciousTipEl.innerHTML = "Мысли можно аккуратно уложить.<br>ПКМ / долгое нажатие — повернуть.";
- } else if (stress < 70) {
- characterEl.textContent = "😠";
- consciousTipEl.innerHTML = "Он ворочается…<br>Старайся не ошибаться.";
- } else {
- characterEl.textContent = "😡";
- consciousTipEl.innerHTML = "⚠️ Он уже почти проснулся!";
- }
- if (stress >= MAX_STRESS) loseGame();
- }
- function addStress(amount) {
- if (!gameEnded) setStress(stress + amount);
- }
- function subStress(amount) {
- if (!gameEnded) setStress(stress - amount);
- }
- function startCharacterAnimation() {
- clearInterval(animationTimer);
- let frame = 0;
- animationTimer = setInterval(() => {
- frame = (frame + 1) % 3 + 1;
- characterEl.classList.remove("frame1", "frame2", "frame3");
- void characterEl.offsetWidth;
- characterEl.classList.add(`frame${frame}`);
- }, 450);
- }
- // =========================
- // СОЗДАНИЕ МЫСЛИ
- // =========================
- function createPiece(small = false) {
- let cells = structuredClone(random(small ? SMALL_SHAPES : NORMAL_SHAPES));
- const rotations = Math.floor(Math.random() * 4);
- for (let i = 0; i < rotations; i++) cells = rotateShape(cells);
- return {
- id: ++pieceId,
- cells,
- color: random(COLORS),
- text: random(THOUGHTS),
- x: 0,
- y: 0,
- element: null
- };
- }
- function getBoardMetrics() {
- const rect = boardEl.getBoundingClientRect();
- const styles = getComputedStyle(boardEl);
- const gap = parseFloat(styles.gap) || 3;
- const cellW = (rect.width - gap * (COLS - 1)) / COLS;
- const cellH = (rect.height - gap * (ROWS - 1)) / ROWS;
- return { rect, gap, cellW, cellH };
- }
- function getPiecePixelSize(piece) {
- const { cellW, cellH, gap } = getBoardMetrics();
- const b = bounds(piece.cells);
- return {
- width: b.cols * cellW + (b.cols - 1) * gap,
- height: b.rows * cellH + (b.rows - 1) * gap
- };
- }
- function renderPiece() {
- if (!active) return;
- if (!active.element) {
- const p = document.createElement("div");
- p.className = "piece";
- p.dataset.id = active.id;
- consciousEl.appendChild(p);
- active.element = p;
- bindPieceEvents(p);
- }
- const p = active.element;
- const b = bounds(active.cells);
- const { cellW, cellH, gap } = getBoardMetrics();
- p.innerHTML = "";
- p.style.gridTemplateColumns = `repeat(${b.cols}, ${cellW}px)`;
- p.style.gridTemplateRows = `repeat(${b.rows}, ${cellH}px)`;
- p.style.width = `${b.cols * cellW + (b.cols - 1) * gap}px`;
- p.style.height = `${b.rows * cellH + (b.rows - 1) * gap}px`;
- p.style.setProperty("--piece-cell", `${cellW}px`);
- p.style.setProperty("--piece-gap", `${gap}px`);
- p.style.setProperty("--color", active.color);
- active.cells.forEach(([r,c]) => {
- const cell = document.createElement("div");
- cell.className = "piece-cell";
- cell.style.gridRow = r + 1;
- cell.style.gridColumn = c + 1;
- cell.style.background = active.color;
- p.appendChild(cell);
- });
- const label = document.createElement("div");
- label.className = "piece-label";
- label.textContent = active.text;
- p.appendChild(label);
- p.style.left = `${active.x}px`;
- p.style.top = `${active.y}px`;
- }
- function spawnPiece(small = false) {
- if (gameEnded) return;
- if (freezeTurns > 0) {
- freezeTurns--;
- showToast(`🐑 Новых мыслей нет. Осталось ходов: ${freezeTurns}`);
- // Следующая реальная мысль появится после следующего успешного/неуспешного размещения.
- return;
- }
- if (active?.element) active.element.remove();
- active = createPiece(small);
- // Всегда начинаем в сознании. Позицию задаём после вычисления размеров.
- const zoneRect = consciousEl.getBoundingClientRect();
- const temp = getPiecePixelSize(active);
- active.x = Math.max(8, (zoneRect.width - temp.width) / 2);
- active.y = Math.max(20, (zoneRect.height - temp.height) / 2 + 5);
- renderPiece();
- }
- function rotateActive() {
- if (!active || gameEnded || drag) return;
- active.cells = rotateShape(active.cells);
- // После поворота стараемся оставить фигуру в пределах сознания.
- const zoneW = consciousEl.clientWidth;
- const zoneH = consciousEl.clientHeight;
- const size = getPiecePixelSize(active);
- active.x = Math.min(active.x, Math.max(4, zoneW - size.width - 4));
- active.y = Math.min(active.y, Math.max(4, zoneH - size.height - 4));
- renderPiece();
- showToast("🔄 Повернуто");
- }
- // =========================
- // DRAG / TOUCH
- // =========================
- function bindPieceEvents(pieceEl) {
- pieceEl.addEventListener("contextmenu", e => {
- e.preventDefault();
- rotateActive();
- });
- pieceEl.addEventListener("pointerdown", e => {
- if (gameEnded || !active) return;
- e.preventDefault();
- const rect = pieceEl.getBoundingClientRect();
- drag = {
- pointerId: e.pointerId,
- offsetX: e.clientX - rect.left,
- offsetY: e.clientY - rect.top,
- moved: false,
- startX: e.clientX,
- startY: e.clientY,
- holdTimer: null
- };
- pieceEl.setPointerCapture?.(e.pointerId);
- pieceEl.classList.add("dragging");
- // На touch долгое нажатие означает поворот.
- if (e.pointerType === "touch") {
- drag.holdTimer = setTimeout(() => {
- if (drag && !drag.moved) {
- rotateActive();
- drag = null;
- pieceEl.classList.remove("dragging");
- }
- }, 560);
- }
- });
- pieceEl.addEventListener("pointermove", e => {
- if (!drag || drag.pointerId !== e.pointerId || !active) return;
- e.preventDefault();
- const dx = e.clientX - drag.startX;
- const dy = e.clientY - drag.startY;
- if (Math.hypot(dx, dy) > 8) {
- drag.moved = true;
- clearTimeout(drag.holdTimer);
- }
- // Во время перетаскивания фигура остаётся fixed,
- // поэтому ей не мешают overflow родительских контейнеров.
- active.x = e.clientX - drag.offsetX;
- active.y = e.clientY - drag.offsetY;
- pieceEl.style.left = `${active.x}px`;
- pieceEl.style.top = `${active.y}px`;
- updatePreview(pieceEl);
- });
- pieceEl.addEventListener("pointerup", e => {
- if (!drag || drag.pointerId !== e.pointerId) return;
- clearTimeout(drag.holdTimer);
- if (drag.moved) {
- dropPiece(pieceEl);
- }
- pieceEl.classList.remove("dragging");
- drag = null;
- clearPreview();
- });
- pieceEl.addEventListener("pointercancel", () => {
- if (drag) clearTimeout(drag.holdTimer);
- if (pieceEl) pieceEl.classList.remove("dragging");
- drag = null;
- clearPreview();
- returnPieceToConscious();
- });
- }
- function findDropAnchor(pieceEl) {
- const { rect, gap, cellW, cellH } = getBoardMetrics();
- const pr = pieceEl.getBoundingClientRect();
- const size = getPiecePixelSize(active);
- // Берём центр фигуры. Это намного надёжнее, чем требовать,
- // чтобы её левый верхний угол случайно совпал с сеткой.
- const centerX = pr.left + size.width / 2;
- const centerY = pr.top + size.height / 2;
- const localX = centerX - rect.left;
- const localY = centerY - rect.top;
- const b = bounds(active.cells);
- const startX = localX - b.cols * (cellW + gap) / 2;
- const startY = localY - b.rows * (cellH + gap) / 2;
- return {
- col: Math.round(startX / (cellW + gap)),
- row: Math.round(startY / (cellH + gap))
- };
- }
- function canPlace(piece, row, col) {
- for (const [dr, dc] of piece.cells) {
- const r = row + dr;
- const c = col + dc;
- if (r < 0 || r >= ROWS || c < 0 || c >= COLS) return false;
- if (board[r][c]) return false;
- }
- return true;
- }
- function updatePreview(pieceEl) {
- clearPreview();
- if (!active) return;
- const { row, col } = findDropAnchor(pieceEl);
- const good = canPlace(active, row, col);
- active.cells.forEach(([dr, dc]) => {
- const r = row + dr;
- const c = col + dc;
- if (r >= 0 && r < ROWS && c >= 0 && c < COLS) {
- boardEl.children[r * COLS + c].classList.add(good ? "ok" : "bad");
- }
- });
- }
- function clearPreview() {
- [...boardEl.children].forEach(c => c.classList.remove("ok", "bad"));
- }
- function dropPiece(pieceEl) {
- const { row, col } = findDropAnchor(pieceEl);
- if (!canPlace(active, row, col)) {
- addStress(FAIL_STRESS);
- showToast("💥 Не помещается. Стресс +8%");
- // После ошибки активная мысль остаётся доступной,
- // а дополнительная маленькая появится сразу следом.
- returnPieceToConscious();
- setTimeout(() => {
- if (!gameEnded && !active) spawnPiece(true);
- }, 30);
- // Чтобы НЕ создавать вторую фигуру поверх основной:
- if (!gameEnded) {
- const failed = active;
- active = null;
- if (failed?.element) failed.element.remove();
- setTimeout(() => {
- if (!gameEnded) spawnPiece(true);
- }, 180);
- }
- return;
- }
- placePiece(row, col);
- }
- function returnPieceToConscious() {
- if (!active) return;
- const zoneW = consciousEl.clientWidth;
- const size = getPiecePixelSize(active);
- active.x = Math.max(6, (zoneW - size.width) / 2);
- active.y = Math.max(14, (consciousEl.clientHeight - size.height) / 2);
- renderPiece();
- }
- // =========================
- // РАЗМЕЩЕНИЕ ФИГУРЫ
- // =========================
- function placePiece(row, col) {
- const placed = active;
- for (const [dr, dc] of placed.cells) {
- const r = row + dr;
- const c = col + dc;
- board[r][c] = {
- id: placed.id,
- color: placed.color,
- text: placed.text
- };
- }
- if (placed.element) placed.element.remove();
- active = null;
- renderBoard();
- const full = getFullRows();
- if (full.length) {
- animateAndClearRows(full);
- } else {
- subStress(1);
- nextTurn();
- }
- }
- function getFullRows() {
- const full = [];
- for (let r = 0; r < ROWS; r++) {
- if (board[r].every(Boolean)) full.push(r);
- }
- return full;
- }
- // ВАЖНО: очистка реализована как единая операция над строками.
- // Это исправляет старый баг с "пустыми строками" при удалении
- // нескольких заполненных рядов за один ход.
- function animateAndClearRows(rows) {
- const rowSet = new Set(rows);
- rows.forEach(r => {
- for (let c = 0; c < COLS; c++) {
- boardEl.children[r * COLS + c].classList.add("clearing");
- }
- });
- setTimeout(() => {
- // Сохраняем ВСЕ неполные строки в их текущем порядке.
- // Затем добавляем сверху ровно столько пустых строк,
- // сколько было очищено.
- const remaining = board.filter((row, index) => !rowSet.has(index));
- const emptyRows = Array.from(
- { length: rows.length },
- () => Array(COLS).fill(null)
- );
- board = emptyRows.concat(remaining);
- // Здесь никогда не остаются "пустые промежуточные строки":
- // новые пустые строки всегда находятся только сверху.
- clearedRows += rows.length;
- subStress(CLEAR_STRESS * rows.length);
- renderBoard();
- rowsCounterEl.textContent = `Ряды: ${clearedRows} / ${TARGET_ROWS}`;
- showToast(`✨ Очищено рядов: ${rows.length}`);
- if (clearedRows >= TARGET_ROWS) {
- winGame();
- } else {
- nextTurn();
- }
- }, 380);
- }
- function nextTurn() {
- if (gameEnded) return;
- if (freezeTurns > 0) {
- freezeTurns--;
- showToast(`🐑 Новые мысли заморожены. Осталось: ${freezeTurns}`);
- if (freezeTurns > 0) {
- setTimeout(nextTurn, 180);
- } else {
- spawnPiece(false);
- }
- return;
- }
- spawnPiece(false);
- }
- // =========================
- // БОНУСЫ
- // =========================
- function updateButtons() {
- sheepBtn.textContent = `🐑 Овцы (${sheepUses})`;
- noiseBtn.textContent = `🌫️ Шум (${noiseUses})`;
- sheepBtn.disabled = sheepUses <= 0 || gameEnded;
- noiseBtn.disabled = noiseUses <= 0 || gameEnded || !getOccupiedIds().length;
- }
- function useSheep() {
- if (sheepUses <= 0 || gameEnded) return;
- sheepUses--;
- freezeTurns = FREEZE_TURNS;
- subStress(3);
- updateButtons();
- showToast("🐑 Новые мысли заморожены на 3 хода.");
- }
- function getOccupiedIds() {
- const ids = new Set();
- for (const row of board) {
- for (const cell of row) {
- if (cell) ids.add(cell.id);
- }
- }
- return [...ids];
- }
- function useNoise() {
- if (noiseUses <= 0 || gameEnded) return;
- const ids = getOccupiedIds();
- if (!ids.length) return;
- noiseUses--;
- const id = random(ids);
- for (let r = 0; r < ROWS; r++) {
- for (let c = 0; c < COLS; c++) {
- if (board[r][c]?.id === id) board[r][c] = null;
- }
- }
- subStress(5);
- renderBoard();
- updateButtons();
- showToast("🌫️ Белый шум заглушил одну мысль.");
- }
- // =========================
- // СООБЩЕНИЯ / КОНЕЦ ИГРЫ
- // =========================
- function showToast(text) {
- clearTimeout(toastTimer);
- toastEl.textContent = text;
- toastEl.classList.add("show");
- toastTimer = setTimeout(() => toastEl.classList.remove("show"), 1500);
- }
- function winGame() {
- if (gameEnded) return;
- gameEnded = true;
- setStress(0);
- resultTitleEl.textContent = "😴 Персонаж уснул";
- resultTextEl.textContent =
- "Пять полных рядов собраны. Навязчивые мысли уложены в подсознание, и мозг наконец перестал ворочаться.";
- overlayEl.classList.add("show");
- updateButtons();
- }
- function loseGame() {
- if (gameEnded) return;
- gameEnded = true;
- if (active?.element) active.element.remove();
- active = null;
- clearPreview();
- characterEl.textContent = "😡";
- resultTitleEl.textContent = "😡 Он проснулся";
- resultTextEl.textContent =
- "Стресс достиг 100%. Мыслей стало слишком много. Попробуй использовать бонусы раньше и поворачивать неудобные фигуры.";
- overlayEl.classList.add("show");
- updateButtons();
- }
- // =========================
- // ПЕРЕЗАПУСК
- // =========================
- function restart() {
- gameEnded = false;
- stress = 0;
- clearedRows = 0;
- sheepUses = 2;
- noiseUses = 2;
- freezeTurns = 0;
- pieceId = 0;
- drag = null;
- if (active?.element) active.element.remove();
- active = null;
- board = createEmptyBoard();
- rowsCounterEl.textContent = "Ряды: 0 / 5";
- overlayEl.classList.remove("show");
- buildBoard();
- setStress(0);
- updateButtons();
- startCharacterAnimation();
- spawnPiece(false);
- }
- // =========================
- // RESIZE
- // =========================
- window.addEventListener("resize", () => {
- if (!active || !active.element || drag) return;
- const size = getPiecePixelSize(active);
- const zoneW = consciousEl.clientWidth;
- const zoneH = consciousEl.clientHeight;
- active.x = Math.max(4, Math.min(active.x, zoneW - size.width - 4));
- active.y = Math.max(4, Math.min(active.y, zoneH - size.height - 4));
- renderPiece();
- });
- sheepBtn.addEventListener("click", useSheep);
- noiseBtn.addEventListener("click", useNoise);
- $("restartTop").addEventListener("click", restart);
- $("restartResult").addEventListener("click", restart);
- // =========================
- // СТАРТ
- // =========================
- restart();
- })();
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment