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: visible;
- 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: 20;
- 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;
- }
- /* Экран выбора сложности */
- .difficulty-overlay {
- position: fixed;
- inset: 0;
- z-index: 7000;
- display: flex;
- align-items: center;
- justify-content: center;
- padding: 18px;
- background: rgba(4, 6, 14, .80);
- backdrop-filter: blur(9px);
- }
- .difficulty-overlay.hidden { display: none; }
- .difficulty-card {
- width: min(560px, 100%);
- padding: 28px;
- border-radius: 24px;
- background:
- radial-gradient(circle at 50% 0%, rgba(104, 91, 196, .22), transparent 42%),
- linear-gradient(180deg, #1a2238, #0d1423);
- border: 1px solid rgba(164, 174, 230, .18);
- box-shadow: 0 28px 90px rgba(0,0,0,.55);
- text-align: center;
- }
- .difficulty-kicker {
- color: #8b91c6;
- font-size: 10px;
- letter-spacing: .2em;
- margin-bottom: 7px;
- }
- .difficulty-card h2 {
- margin: 0 0 8px;
- font-size: clamp(25px, 6vw, 34px);
- }
- .difficulty-card p {
- margin: 0 auto 20px;
- max-width: 440px;
- color: #9ca6c5;
- line-height: 1.45;
- font-size: 13px;
- }
- .difficulty-grid {
- display: grid;
- grid-template-columns: repeat(3, 1fr);
- gap: 10px;
- }
- .difficulty-btn {
- min-height: 112px;
- border-radius: 16px;
- border: 1px solid rgba(255,255,255,.10);
- background: rgba(255,255,255,.045);
- color: #eef1ff;
- cursor: pointer;
- padding: 14px 10px;
- display: flex;
- flex-direction: column;
- justify-content: center;
- gap: 8px;
- transition: transform .18s, background .18s, border-color .18s;
- }
- .difficulty-btn:hover {
- transform: translateY(-2px);
- background: rgba(255,255,255,.085);
- border-color: rgba(255,255,255,.20);
- }
- .difficulty-btn strong { font-size: 14px; }
- .difficulty-btn span { color: #9ca6c5; font-size: 11px; line-height: 1.25; }
- .difficulty-btn.easy { box-shadow: inset 0 -3px 0 rgba(74, 203, 151, .22); }
- .difficulty-btn.normal { box-shadow: inset 0 -3px 0 rgba(232, 183, 77, .22); }
- .difficulty-btn.hard { box-shadow: inset 0 -3px 0 rgba(236, 82, 104, .22); }
- .combo-line {
- display: flex;
- justify-content: center;
- align-items: center;
- gap: 8px;
- margin-top: 5px;
- color: #8b95b4;
- font-size: 11px;
- }
- .combo-line strong { color: #dfe6ff; }
- /* Окончание игры */
- .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 id="difficultyInfo">Сложность: —</span>
- <span>Линия: −12%</span>
- <span>Победа: 5 линий</span>
- </div>
- <div class="combo-line">
- Комбо: <strong id="comboValue">0</strong> ·
- 🐑 и 🌫️ выдаются за успешные ходы и уменьшают стресс
- </div>
- </div>
- <div class="difficulty-overlay" id="difficultyOverlay">
- <div class="difficulty-card">
- <div class="difficulty-kicker">НОВАЯ НОЧЬ</div>
- <h2>Выбери сложность</h2>
- <p>Чем выше сложность, тем сильнее растёт стресс при ошибках.</p>
- <div class="difficulty-grid">
- <button class="difficulty-btn easy" data-difficulty="easy">
- <strong>🌙 Спокойно</strong>
- <span>Ошибка: +5% стресса</span>
- </button>
- <button class="difficulty-btn normal" data-difficulty="normal">
- <strong>😰 Тревожно</strong>
- <span>Ошибка: +9% стресса</span>
- </button>
- <button class="difficulty-btn hard" data-difficulty="hard">
- <strong>🔥 Бессонница</strong>
- <span>Ошибка: +15% стресса</span>
- </button>
- </div>
- </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 CLEAR_STRESS = 12;
- const COMBO_REWARD_EVERY = 3;
- const DIFFICULTIES = {
- easy: { name: "Спокойно", failStress: 5 },
- normal: { name: "Тревожно", failStress: 9 },
- hard: { name: "Бессонница", failStress: 15 }
- };
- const THOUGHTS = [
- "не выключил утюг", "дедлайн завтра", "неловкая фраза 2014",
- "забыл ответить", "не закрыл дверь?", "завтра рано вставать",
- "что если опоздаю?", "не оплатил счёт", "надо позвонить",
- "что сказать на встрече?", "а вдруг всё забыл?", "проект не готов",
- "надо было иначе", "почему я это сказал?", "что обо мне думают?",
- "забытые продукты", "не выключил плиту", "а если не получится?",
- "надо лечь раньше", "что-то скрипит", "не ответил на сообщение",
- "что надеть завтра?", "пароль слишком простой", "где ключи?",
- "забытый файл", "срок уже близко", "а точно отправил?",
- "почему я это лайкнул?", "надо помыть посуду", "зарядить телефон"
- ];
- const NORMAL_SHAPES = [
- [[0,0],[0,1],[1,0],[1,1]],
- [[0,0],[1,0],[2,0],[2,1]],
- [[0,1],[1,0],[1,1],[2,0]],
- [[0,0],[1,0],[2,0],[2,1]],
- [[0,0],[0,1],[0,2],[1,1]],
- [[0,0],[1,0],[1,1],[2,1]],
- [[0,0],[0,1],[1,1],[2,1]],
- [[0,0],[0,1],[0,2],[1,2],[2,2]],
- [[0,0],[1,0],[2,0],[1,1],[1,2]],
- [[0,0],[1,0],[1,1],[1,2],[2,2]],
- [[0,0],[0,1],[1,1],[2,1],[2,0]],
- [[0,0],[1,0],[2,0]],
- [[0,0],[0,1],[0,2]]
- ];
- 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 = 0;
- let noiseUses = 0;
- let combo = 0;
- let gameEnded = true;
- let pieceId = 0;
- let animationTimer = null;
- let toastTimer = null;
- let difficulty = null;
- let drag = null;
- let spawningNextPiece = false;
- 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");
- const difficultyOverlay = $("difficultyOverlay");
- const difficultyInfo = $("difficultyInfo");
- const comboValueEl = $("comboValue");
- // =========================
- // УТИЛИТЫ
- // =========================
- function random(arr) {
- return arr[Math.floor(Math.random() * arr.length)];
- }
- function rotateShape(cells) {
- 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 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";
- 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 cell = cells[r * COLS + c];
- const value = board[r][c];
- cell.classList.remove("filled", "ok", "bad", "clearing");
- cell.style.removeProperty("background");
- if (value) {
- cell.classList.add("filled");
- cell.style.background =
- `linear-gradient(145deg, ${value.color}, rgba(255,255,255,.08))`;
- }
- }
- }
- }
- function findFullRows() {
- const rows = [];
- for (let r = 0; r < ROWS; r++) {
- if (board[r].every(Boolean)) rows.push(r);
- }
- return rows;
- }
- // Ключевой алгоритм очистки:
- // убираем полные строки, а ВСЕ неполные строки падают вниз.
- // Новые пустые строки появляются только сверху.
- function clearRows(rows) {
- const full = new Set(rows);
- const remaining = board.filter((_, index) => !full.has(index));
- const empty = Array.from({length: rows.length}, () => Array(COLS).fill(null));
- board = empty.concat(remaining);
- }
- // =========================
- // СТРЕСС
- // =========================
- 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 reduceStress(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 updateBonusUI() {
- sheepBtn.textContent = `🐑 Овцы (${sheepUses})`;
- noiseBtn.textContent = `🌫️ Шум (${noiseUses})`;
- sheepBtn.disabled = sheepUses <= 0 || gameEnded;
- noiseBtn.disabled = noiseUses <= 0 || gameEnded;
- comboValueEl.textContent = String(combo);
- }
- function onSuccessfulPlacement() {
- combo++;
- if (combo % COMBO_REWARD_EVERY === 0) {
- // Каждые 3 успешных размещения — случайный бонус.
- if (Math.random() < 0.5) {
- sheepUses++;
- showToast("🐑 Комбо! Получены овцы: бонус −10% стресса.");
- } else {
- noiseUses++;
- showToast("🌫️ Комбо! Получен шум: бонус −7% стресса.");
- }
- }
- updateBonusUI();
- }
- function useSheep() {
- if (sheepUses <= 0 || gameEnded) return;
- sheepUses--;
- reduceStress(10);
- updateBonusUI();
- showToast("🐑 Овцы успокоили мысли. Стресс −10%.");
- }
- function useNoise() {
- if (noiseUses <= 0 || gameEnded) return;
- noiseUses--;
- reduceStress(7);
- updateBonusUI();
- showToast("🌫️ Белый шум приглушил тревогу. Стресс −7%.");
- }
- // =========================
- // СОЗДАНИЕ МЫСЛИ
- // =========================
- function createPiece(small = false) {
- let cells = random(small ? SMALL_SHAPES : NORMAL_SHAPES).map(p => p.slice());
- 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,
- homeX: 0,
- homeY: 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;
- // ВАЖНО: фигура находится в body, а не внутри .conscious.
- // Поэтому её можно свободно перетаскивать поверх всей сцены.
- document.body.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-gap", `${gap}px`);
- p.style.setProperty("--color", active.color);
- p.style.left = `${active.x}px`;
- p.style.top = `${active.y}px`;
- 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);
- }
- function spawnPiece(small = false) {
- if (gameEnded) return false;
- spawningNextPiece = true;
- try {
- // Сначала полностью убираем старую фигуру, если она ещё существует.
- if (active?.element) {
- active.element.remove();
- }
- const next = createPiece(small);
- const size = getPiecePixelSize(next);
- const zoneRect = consciousEl.getBoundingClientRect();
- // Новая фигура живёт в viewport (.piece = fixed), поэтому
- // она гарантированно появляется в зоне сознания и может выйти из неё при drag.
- next.x = zoneRect.left + Math.max(6, (zoneRect.width - size.width) / 2);
- next.y = zoneRect.top + Math.max(18, (zoneRect.height - size.height) / 2);
- next.homeX = next.x;
- next.homeY = next.y;
- // Назначаем active только после успешной подготовки новой фигуры.
- active = next;
- renderPiece();
- return true;
- } finally {
- spawningNextPiece = false;
- }
- }
- // Гарантирует, что во время активной игры мысль не останется пустым.
- // Это страховка от случайного сбоя в цепочке создания следующей фигуры.
- function ensureActivePiece() {
- if (!gameEnded && !active && !spawningNextPiece) {
- spawnPiece(false);
- }
- }
- // Поворачивает активную мысль. Во время drag сохраняем точку,
- // возле которой находится палец/курсора, чтобы фигура не прыгала.
- function rotateActive(pointerX = null, pointerY = null) {
- if (!active || gameEnded) return;
- const oldSize = getPiecePixelSize(active);
- let anchorX = active.x + oldSize.width / 2;
- let anchorY = active.y + oldSize.height / 2;
- if (drag && pointerX != null && pointerY != null) {
- anchorX = pointerX - drag.offsetX + oldSize.width / 2;
- anchorY = pointerY - drag.offsetY + oldSize.height / 2;
- }
- active.cells = rotateShape(active.cells);
- const size = getPiecePixelSize(active);
- active.x = anchorX - size.width / 2;
- active.y = anchorY - size.height / 2;
- if (drag && pointerX != null && pointerY != null) {
- drag.offsetX = pointerX - active.x;
- drag.offsetY = pointerY - active.y;
- drag.lastX = pointerX;
- drag.lastY = pointerY;
- }
- // Не даём фигуре полностью исчезнуть за экраном, но разрешаем
- // свободно пересекать границы сознания и игрового поля.
- active.x = Math.max(-size.width + 12, Math.min(active.x, window.innerWidth - 12));
- active.y = Math.max(-size.height + 12, Math.min(active.y, window.innerHeight - 12));
- renderPiece();
- showToast("🔄 Мысль повернулась");
- }
- // =========================
- // DRAG / TOUCH
- // =========================
- function clearPreview() {
- for (const cell of boardEl.children) cell.classList.remove("ok", "bad");
- }
- function boardDropPosition(pieceEl) {
- const {rect, gap, cellW, cellH} = getBoardMetrics();
- const pieceRect = pieceEl.getBoundingClientRect();
- const b = bounds(active.cells);
- // Центр фигуры -> ближайшая клетка верхнего левого угла фигуры.
- const anchorX = pieceRect.left + pieceRect.width / 2 - (b.cols * cellW) / 2;
- const anchorY = pieceRect.top + pieceRect.height / 2 - (b.rows * cellH) / 2;
- return {
- col: Math.round((anchorX - rect.left) / (cellW + gap)),
- row: Math.round((anchorY - rect.top) / (cellH + gap))
- };
- }
- function canPlace(cells, row, col) {
- for (const [r, c] of cells) {
- const rr = row + r;
- const cc = col + c;
- if (rr < 0 || rr >= ROWS || cc < 0 || cc >= COLS) return false;
- if (board[rr][cc]) return false;
- }
- return true;
- }
- function updatePreview(pieceEl) {
- clearPreview();
- if (!active) return;
- const {row, col} = boardDropPosition(pieceEl);
- const ok = canPlace(active.cells, row, col);
- for (const [r, c] of active.cells) {
- const rr = row + r, cc = col + c;
- if (rr >= 0 && rr < ROWS && cc >= 0 && cc < COLS) {
- boardEl.children[rr * COLS + cc].classList.add(ok ? "ok" : "bad");
- }
- }
- }
- function bindPieceEvents(pieceEl) {
- // ПКМ никогда не должен открывать стандартное контекстное меню браузера.
- pieceEl.addEventListener("contextmenu", e => {
- e.preventDefault();
- // Если ЛКМ уже зажата — ПКМ сразу вращает фигуру.
- if (drag && drag.pointerType === "mouse" && drag.primaryHeld) {
- rotateActive(e.clientX, e.clientY);
- }
- });
- pieceEl.addEventListener("mousedown", e => {
- // Надёжный fallback для обычного mouse input.
- // Браузеры иногда не доставляют второй pointerdown на window,
- // когда первый указатель находится в pointer capture.
- if (e.button === 2 && drag && drag.pointerType === "mouse" && drag.primaryHeld) {
- e.preventDefault();
- rotateActive(e.clientX, e.clientY);
- }
- });
- pieceEl.addEventListener("pointerdown", e => {
- if (gameEnded || !active) return;
- e.preventDefault();
- // Второй палец = поворот, первый палец = перетаскивание.
- if (e.pointerType === "touch" && !e.isPrimary) {
- if (drag && drag.pointerType === "touch") {
- rotateActive(e.clientX, e.clientY);
- }
- return;
- }
- // ПКМ не запускает новый drag.
- if (e.pointerType === "mouse" && e.button !== 0) {
- if (e.button === 2 && drag && drag.pointerType === "mouse" && drag.primaryHeld) {
- rotateActive(e.clientX, e.clientY);
- }
- return;
- }
- const rect = pieceEl.getBoundingClientRect();
- drag = {
- pointerId: e.pointerId,
- pointerType: e.pointerType,
- offsetX: e.clientX - rect.left,
- offsetY: e.clientY - rect.top,
- moved: false,
- startX: e.clientX,
- startY: e.clientY,
- lastX: e.clientX,
- lastY: e.clientY,
- primaryHeld: true
- };
- pieceEl.setPointerCapture?.(e.pointerId);
- pieceEl.classList.add("dragging");
- });
- 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) > 6) drag.moved = true;
- drag.lastX = e.clientX;
- drag.lastY = e.clientY;
- active.x = e.clientX - drag.offsetX;
- active.y = e.clientY - drag.offsetY;
- const size = getPiecePixelSize(active);
- active.x = Math.max(-size.width + 12, Math.min(active.x, window.innerWidth - 12));
- active.y = Math.max(-size.height + 12, Math.min(active.y, window.innerHeight - 12));
- 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;
- const wasMoved = drag.moved;
- drag.primaryHeld = false;
- drag = null;
- pieceEl.classList.remove("dragging");
- clearPreview();
- if (wasMoved) dropPiece(pieceEl);
- });
- pieceEl.addEventListener("pointercancel", () => {
- drag = null;
- pieceEl.classList.remove("dragging");
- clearPreview();
- returnPieceHome();
- });
- }
- function returnPieceHome() {
- if (!active || !active.element) return;
- active.x = active.homeX;
- active.y = active.homeY;
- active.element.style.left = `${active.x}px`;
- active.element.style.top = `${active.y}px`;
- }
- // Дополнительный глобальный fallback для ПКМ + ЛКМ.
- window.addEventListener("mousedown", e => {
- if (gameEnded || !active || !drag) return;
- if (e.button === 2 && drag.pointerType === "mouse" && drag.primaryHeld) {
- e.preventDefault();
- rotateActive(e.clientX, e.clientY);
- }
- }, {passive:false});
- // На touch второй палец вращает фигуру.
- window.addEventListener("pointerdown", e => {
- if (gameEnded || !active || !drag) return;
- if (e.pointerType === "touch" && !e.isPrimary && drag.pointerType === "touch") {
- e.preventDefault();
- rotateActive(e.clientX, e.clientY);
- }
- }, {passive:false});
- window.addEventListener("contextmenu", e => {
- if (drag?.pointerType === "mouse" && drag.primaryHeld) e.preventDefault();
- });
- window.addEventListener("keydown", e => {
- if (gameEnded || !active || !drag || drag.pointerType !== "mouse" || !drag.primaryHeld) return;
- if (e.key.toLowerCase() === "r") {
- e.preventDefault();
- rotateActive(drag.lastX, drag.lastY);
- }
- });
- function dropPiece(pieceEl) {
- if (!active || gameEnded) return;
- const {row, col} = boardDropPosition(pieceEl);
- // ОШИБКА НЕ УДАЛЯЕТ МЫСЛЬ.
- // Она остаётся в сознании и ждёт следующей попытки.
- if (!canPlace(active.cells, row, col)) {
- returnPieceHome();
- addStress(difficulty.failStress);
- combo = 0;
- updateBonusUI();
- showToast(`💥 Неудачная попытка: +${difficulty.failStress}% стресса`);
- // После ошибки текущая мысль остаётся активной.
- // Новая фигура не заменяет её и появляется только после успешного размещения.
- return;
- }
- // Корректно размещаем блок.
- active.cells.forEach(([r, c]) => {
- const rr = row + r;
- const cc = col + c;
- board[rr][cc] = {
- id: active.id,
- color: active.color,
- text: active.text
- };
- });
- // Фигура уже заняла клетки поля. Её DOM-элемент больше не нужен.
- if (active.element) active.element.remove();
- const placedPiece = active;
- active = null;
- renderBoard();
- onSuccessfulPlacement();
- const rows = findFullRows();
- if (rows.length) {
- rows.forEach(r => {
- for (let c = 0; c < COLS; c++) {
- boardEl.children[r * COLS + c].classList.add("clearing");
- }
- });
- setTimeout(() => {
- clearRows(rows);
- clearedRows += rows.length;
- reduceStress(CLEAR_STRESS * rows.length);
- rowsCounterEl.textContent = `Ряды: ${clearedRows} / ${TARGET_ROWS}`;
- showToast(`✨ Линия очищена! Стресс −${CLEAR_STRESS * rows.length}%`);
- if (clearedRows >= TARGET_ROWS) {
- winGame();
- } else if (!gameEnded) {
- // Всегда создаём следующую фигуру после завершения анимации.
- spawnPiece(false);
- ensureActivePiece();
- }
- }, 380);
- } else {
- // Стресс от правильного размещения НЕ растёт.
- // Новая фигура появляется сразу после успешного размещения.
- if (!spawnPiece(false)) ensureActivePiece();
- }
- }
- // =========================
- // СОЗДАНИЕ БОНУСОВ ЗА КОМБО
- // =========================
- // Уже реализовано в onSuccessfulPlacement():
- // каждое третье успешное размещение выдаёт овцы или шум.
- // Сам бонус теперь не замораживает и не удаляет фигуры:
- // он просто снижает стресс.
- // =========================
- // КОНЕЦ ИГРЫ
- // =========================
- function winGame() {
- if (gameEnded) return;
- gameEnded = true;
- setStress(0);
- if (active?.element) active.element.remove();
- active = null;
- resultTitleEl.textContent = "😴 Персонаж уснул";
- resultTextEl.textContent =
- `Ты очистил ${clearedRows} линий на сложности «${difficulty.name}». Мысли уложены, стресс сброшен до нуля.`;
- overlayEl.classList.add("show");
- updateBonusUI();
- }
- function loseGame() {
- if (gameEnded) return;
- gameEnded = true;
- if (active?.element) active.element.remove();
- active = null;
- characterEl.textContent = "😡";
- resultTitleEl.textContent = "😡 Он проснулся";
- resultTextEl.textContent =
- `Стресс достиг 100% на сложности «${difficulty.name}». Попробуй делать меньше ошибок и собирать комбо для получения бонусов.`;
- overlayEl.classList.add("show");
- updateBonusUI();
- }
- // =========================
- // НОВАЯ ИГРА
- // =========================
- function startGame(selectedDifficulty) {
- difficulty = DIFFICULTIES[selectedDifficulty];
- difficultyInfo.textContent =
- `Сложность: ${difficulty.name} · ошибка +${difficulty.failStress}%`;
- gameEnded = false;
- stress = 0;
- clearedRows = 0;
- sheepUses = 0;
- noiseUses = 0;
- combo = 0;
- pieceId = 0;
- drag = null;
- board = createEmptyBoard();
- if (active?.element) active.element.remove();
- active = null;
- overlayEl.classList.remove("show");
- difficultyOverlay.classList.add("hidden");
- rowsCounterEl.textContent = "Ряды: 0 / 5";
- buildBoard();
- setStress(0);
- updateBonusUI();
- startCharacterAnimation();
- spawnPiece(false);
- }
- function showDifficulty() {
- gameEnded = true;
- if (active?.element) active.element.remove();
- active = null;
- difficultyOverlay.classList.remove("hidden");
- }
- // =========================
- // RESIZE
- // =========================
- window.addEventListener("resize", () => {
- if (!active || !active.element || drag) return;
- const size = getPiecePixelSize(active);
- active.x = Math.max(-size.width + 12, Math.min(active.x, window.innerWidth - 12));
- active.y = Math.max(-size.height + 12, Math.min(active.y, window.innerHeight - 12));
- renderPiece();
- });
- // =========================
- // КНОПКИ
- // =========================
- difficultyOverlay.querySelectorAll("[data-difficulty]").forEach(btn => {
- btn.addEventListener("click", () => startGame(btn.dataset.difficulty));
- });
- sheepBtn.addEventListener("click", useSheep);
- noiseBtn.addEventListener("click", useNoise);
- $("restartTop").addEventListener("click", showDifficulty);
- $("restartResult").addEventListener("click", showDifficulty);
- // Страховочный цикл: если активная фигура неожиданно исчезла во время игры,
- // следующая мысль создаётся автоматически. При нормальной работе этот код ничего не меняет.
- setInterval(ensureActivePiece, 250);
- // =========================
- // ПЕРВЫЙ ЭКРАН
- // =========================
- buildBoard();
- setStress(0);
- updateBonusUI();
- showDifficulty();
- })();
- </script>
- </body>
- </html>
Add Comment
Please, Sign In to add comment