justclownfish / Игры ЦТ

// ==UserScript==
// @name         Игры ЦТ
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Автоматизатор некоторых текстовых игр для отряда АХ, написан с помощью нейросети
// @author       Далёкая Офелия [1622860]
// @match        https://catwar.net/cw3/
// @license      MIT
// @grant        GM_setValue
// @grant        GM_getValue
// ==/UserScript==

(function () {
  'use strict';

  const games = ["Отражение", "Пропавшее Слово", "Три буквы", "Алфавит", "Поле Чудес"];
  let position = GM_getValue("window_position", {
    x: 100,
    y: 100
  });
  let gameContainer;

  function createWindow() {
    let container = document.createElement("div");
    container.id = "game-selector";
    container.style.position = "fixed";
    container.style.top = position.y + "px";
    container.style.left = position.x + "px";
    container.style.background = "white";
    container.style.border = "1px solid black";
    container.style.padding = "10px";
    container.style.zIndex = "10000";
    container.style.cursor = "move";
    container.style.minWidth = "200px";

    let title = document.createElement("div");
    title.innerText = "Выберите игру:";
    title.style.marginBottom = "10px";
    container.appendChild(title);

    games.forEach(game => {
      let button = document.createElement("button");
      button.innerText = game;
      button.style.display = "block";
      button.style.width = "100%";
      button.style.marginBottom = "5px";
      button.onclick = () => loadGame(game);
      container.appendChild(button);
    });

    makeDraggable(container);
    document.body.appendChild(container);
  }

  function makeDraggable(element) {
    let offsetX, offsetY, isDragging = false;

    element.addEventListener("mousedown", (e) => {
      isDragging = true;
      offsetX = e.clientX - element.offsetLeft;
      offsetY = e.clientY - element.offsetTop;
    });

    document.addEventListener("mousemove", (e) => {
      if (isDragging) {
        let x = e.clientX - offsetX;
        let y = e.clientY - offsetY;
        element.style.left = x + "px";
        element.style.top = y + "px";
      }
    });

    document.addEventListener("mouseup", () => {
      isDragging = false;
      position.x = element.offsetLeft;
      position.y = element.offsetTop;
      GM_setValue("window_position", position);
    });
  }

  function loadGame(game) {
    document.getElementById("game-selector").remove();
    gameContainer = document.createElement("div");
    gameContainer.id = "game-container";
    gameContainer.style.position = "fixed";
    gameContainer.style.top = position.y + "px";
    gameContainer.style.left = position.x + "px";
    gameContainer.style.background = "white";
    gameContainer.style.border = "1px solid black";
    gameContainer.style.padding = "10px";
    gameContainer.style.zIndex = "10000";
    gameContainer.style.minWidth = "200px";

    let title = document.createElement("div");
    title.innerText = "Игра: " + game;
    title.style.marginBottom = "10px";
    gameContainer.appendChild(title);

    let gameContent = document.createElement("div");
    gameContent.id = "game-content";
    gameContainer.appendChild(gameContent);

    if (game === "Поле Чудес") {
      initializePoleChudes(gameContent);
    }
    else if (game === "Алфавит") {
      initializeAlphabet(gameContent);
    }
    else if (game === "Отражение") {
      initializeReflection(gameContent);
    }
    else if (game === "Три буквы") {
      initializeThreeLetters(gameContent);
    }
    else if (game === "Пропавшее Слово") {
      initializeMissingWord(gameContent);
    }

    let backButton = document.createElement("button");
    backButton.innerText = "Назад";
    backButton.style.display = "block";
    backButton.style.marginTop = "5px";
    backButton.onclick = () => {
      gameContainer.remove();
      createWindow();
    };
    gameContainer.appendChild(backButton);

    makeDraggable(gameContainer);
    document.body.appendChild(gameContainer);
  }

  function initializePoleChudes(container) {
    // Создаем заголовок игры
    let instruction = document.createElement("div");
    instruction.innerText = "Введите слово и начните угадывать буквы!";
    container.appendChild(instruction);

    // Создаем поле ввода для загадки
    let wordInput = document.createElement("input");
    wordInput.type = "text";
    wordInput.style.width = "100%";
    wordInput.placeholder = "Введите слово";
    container.appendChild(wordInput);

    // Создаем кнопку для начала игры
    let startButton = document.createElement("button");
    startButton.innerText = "Начать игру";
    startButton.style.display = "block";
    startButton.style.marginTop = "10px";
    container.appendChild(startButton);

    // Создаем поле ввода для угадываемых букв
    let letterInput = document.createElement("input");
    letterInput.type = "text";
    letterInput.maxLength = 1;
    letterInput.style.width = "30%";
    letterInput.placeholder = "Угадайте букву";
    letterInput.disabled = true; // Блокируем поле до начала игры
    container.appendChild(letterInput);

    // Создаем кнопку для ввода буквы
    let guessButton = document.createElement("button");
    guessButton.innerText = "Угадать букву";
    guessButton.style.display = "block";
    guessButton.style.marginTop = "10px";
    guessButton.disabled = true; // Блокируем кнопку до начала игры
    container.appendChild(guessButton);

    // Создаем кнопку для копирования результата
    let copyButton = document.createElement("button");
    copyButton.innerText = "Копировать результат";
    copyButton.style.display = "block";
    copyButton.style.marginTop = "10px";
    copyButton.disabled = true; // Блокируем кнопку до завершения игры
    container.appendChild(copyButton);

    // Создаем блок для отображения результата
    let resultDiv = document.createElement("div");
    resultDiv.style.marginTop = "10px";
    resultDiv.style.fontSize = "24px";
    container.appendChild(resultDiv);

    // Создаем блок для уведомлений
    let notificationDiv = document.createElement("div");
    notificationDiv.style.marginTop = "10px";
    notificationDiv.style.fontSize = "16px";
    notificationDiv.style.color = "green";
    notificationDiv.style.fontWeight = "bold";
    container.appendChild(notificationDiv);

    // Переменные для игры
    let word = ""; // Загаданное слово
    let hiddenWord = []; // Скрытое слово, массив символов
    let guessedLetters = []; // Буквы, которые были угаданы
    let usedLetters = []; // Буквы, которые были уже введены

    // Функция для начала игры
    startButton.onclick = function () {
      word = wordInput.value.trim().toLowerCase();
      if (word) {
        // Скрываем слово, заменяя буквы на "*" и оставляя пробелы
        hiddenWord = word.split('').map(letter => letter === ' ' ? ' ' : '*');
        guessedLetters = hiddenWord.slice(); // Сохраняем скрытое слово
        usedLetters = [];
        resultDiv.innerText = hiddenWord.join(""); // Отображаем скрытое слово
        notificationDiv.innerText = "";
        wordInput.disabled = true; // Блокируем поле для ввода слова
        startButton.disabled = true; // Блокируем кнопку старта
        letterInput.disabled = false; // Разблокируем поле для ввода буквы
        guessButton.disabled = false; // Разблокируем кнопку для угадать букву
        copyButton.disabled = false; // Разблокируем кнопку копирования
      }
      else {
        notificationDiv.innerText = "Пожалуйста, введите слово!";
        notificationDiv.style.color = "red"; // Красный цвет для ошибок
      }
    };

    // Обработчик для угадывания буквы
    guessButton.onclick = function () {
      let guessedLetter = letterInput.value.trim().toLowerCase();
      if (guessedLetter && guessedLetter.length === 1 && /^[а-я]$/i.test(guessedLetter)) {
        if (usedLetters.includes(guessedLetter)) {
          notificationDiv.innerText = "Эта буква уже была введена!";
          notificationDiv.style.color = "red";
          return;
        }

        usedLetters.push(guessedLetter);

        let correctGuess = false;
        // Если буква есть в слове, открываем ее
        for (let i = 0; i < word.length; i++) {
          if (word[i] === guessedLetter) {
            guessedLetters[i] = guessedLetter;
            correctGuess = true;
          }
        }

        hiddenWord = guessedLetters.slice(); // Обновляем скрытое слово

        resultDiv.innerText = hiddenWord.join(""); // Обновляем отображение без пробелов между звёздочками

        if (correctGuess) {
          notificationDiv.innerText = `Вы угадали букву: ${guessedLetter}`;
          notificationDiv.style.color = "green";
        }
        else {
          notificationDiv.innerText = `Буква ${guessedLetter} не найдена!`;
          notificationDiv.style.color = "red";
        }

        letterInput.value = ""; // Очищаем поле для ввода буквы

        // Проверяем, угадано ли все слово
        if (!hiddenWord.includes("*")) {
          notificationDiv.innerText = "Поздравляю! Вы угадали слово!";
          notificationDiv.style.color = "blue";
          letterInput.disabled = true;
          guessButton.disabled = true;
          copyButton.disabled = false; // Кнопка копирования теперь доступна
        }
      }
      else {
        notificationDiv.innerText = "Пожалуйста, введите одну букву!";
        notificationDiv.style.color = "red";
      }
    };

    // Обработчик для копирования результата
    copyButton.onclick = function () {
      let tempTextArea = document.createElement("textarea");
      tempTextArea.value = hiddenWord.join(""); // Копируем скрытое или угаданное слово
      document.body.appendChild(tempTextArea);
      tempTextArea.select();
      document.execCommand("copy");
      document.body.removeChild(tempTextArea);
      notificationDiv.innerText = "Результат скопирован!";
      notificationDiv.style.color = "green";
    };
  }

  function initializeAlphabet(container) {
    // Создаем заголовок игры
    let instruction = document.createElement("div");
    instruction.innerText = "Введите слово (или несколько слов), и я перемешаю буквы в каждом из них!";
    container.appendChild(instruction);

    // Создаем поле ввода
    let inputField = document.createElement("input");
    inputField.type = "text";
    inputField.style.width = "100%";
    inputField.placeholder = "Введите слово или несколько слов";
    container.appendChild(inputField);

    // Создаем кнопку для перемешивания слов
    let shuffleButton = document.createElement("button");
    shuffleButton.innerText = "Перемешать буквы";
    shuffleButton.style.display = "block";
    shuffleButton.style.marginTop = "10px";
    container.appendChild(shuffleButton);

    // Создаем блок для отображения результата
    let resultDiv = document.createElement("div");
    resultDiv.style.marginTop = "10px";
    container.appendChild(resultDiv);

    // Создаем кнопку для копирования результата
    let copyButton = document.createElement("button");
    copyButton.innerText = "Скопировать результат";
    copyButton.style.display = "block";
    copyButton.style.marginTop = "10px";
    container.appendChild(copyButton);

    // Обработчик нажатия кнопки для перемешивания букв
    shuffleButton.onclick = function () {
      let inputText = inputField.value.trim();
      if (inputText) {
        let words = inputText.split(" "); // Разбиваем текст на слова
        let shuffledWords = words.map(word => shuffleWord(word)); // Перемешиваем каждое слово
        resultDiv.innerText = "Перемешанные слова: " + shuffledWords.join(" "); // Выводим результат
      }
      else {
        resultDiv.innerText = "Пожалуйста, введите слово!";
      }
    };

    // Обработчик для копирования текста в буфер обмена
    copyButton.onclick = function () {
      let resultText = resultDiv.innerText.replace("Перемешанные слова: ", "");
      if (resultText) {
        navigator.clipboard.writeText(resultText).then(() => {
          alert("Результат скопирован в буфер обмена!");
        }).catch(err => {
          alert("Не удалось скопировать: " + err);
        });
      }
    };

    // Функция для перемешивания букв в слове
    function shuffleWord(word) {
      let letters = word.split(""); // Разбиваем слово на буквы
      for (let i = letters.length - 1; i > 0; i--) {
        let j = Math.floor(Math.random() * (i + 1)); // Выбираем случайный индекс
        [letters[i], letters[j]] = [letters[j], letters[i]]; // Меняем местами буквы
      }
      return letters.join(""); // Собираем перемешанное слово обратно
    }
  }

  function initializeReflection(container) {
    // Создаем заголовок игры
    let instruction = document.createElement("div");
    instruction.innerText = "Введите слово, и я отразлю его!";
    container.appendChild(instruction);

    // Создаем поле ввода
    let inputField = document.createElement("input");
    inputField.type = "text";
    inputField.style.width = "100%";
    inputField.placeholder = "Введите слово";
    container.appendChild(inputField);

    // Создаем кнопку для отражения слова
    let reflectButton = document.createElement("button");
    reflectButton.innerText = "Отразить слово";
    reflectButton.style.display = "block";
    reflectButton.style.marginTop = "10px";
    container.appendChild(reflectButton);

    // Создаем блок для отображения результата
    let resultDiv = document.createElement("div");
    resultDiv.style.marginTop = "10px";
    container.appendChild(resultDiv);

    // Создаем кнопку копирования результата
    let copyButton = document.createElement("button");
    copyButton.innerText = "Скопировать результат";
    copyButton.style.display = "block";
    copyButton.style.marginTop = "10px";
    container.appendChild(copyButton);

    // Обработчик нажатия кнопки для отражения слова
    reflectButton.onclick = function () {
      let inputWord = inputField.value.trim();
      if (inputWord) {
        let reflectedWord = inputWord.split("").reverse().join(""); // Отражаем слово
        resultDiv.innerText = "Отраженное слово: " + reflectedWord;
      }
      else {
        resultDiv.innerText = "Пожалуйста, введите слово!";
      }
    };

    // Обработчик для копирования текста в буфер обмена
    copyButton.onclick = function () {
      let reflectedWord = resultDiv.innerText.replace("Отраженное слово: ", "");
      if (reflectedWord) {
        navigator.clipboard.writeText(reflectedWord).then(() => {
          alert("Результат скопирован в буфер обмена!");
        }).catch(err => {
          alert("Не удалось скопировать: " + err);
        });
      }
    };

    // Создаем маркер для правого верхнего угла, где будет начинаться перетаскивание
    let resizeHandle = document.createElement("div");
    resizeHandle.style.position = "absolute";
    resizeHandle.style.top = "0";
    resizeHandle.style.right = "0";
    resizeHandle.style.width = "10px";
    resizeHandle.style.height = "10px";
    resizeHandle.style.backgroundColor = "#000"; // Черный квадрат в правом верхнем углу
    resizeHandle.style.cursor = "nwse-resize"; // Указатель в виде стрелки на угол
    container.appendChild(resizeHandle);

    // Перетаскивание окна только через правый верхний угол
    let offsetX, offsetY, isDragging = false;

    // Обработчик нажатия на маркер правого верхнего угла для начала перетаскивания
    resizeHandle.addEventListener("mousedown", (e) => {
      isDragging = true;
      offsetX = e.clientX - container.offsetLeft;
      offsetY = e.clientY - container.offsetTop;
    });

    // Обработчик движения мыши, который позволяет двигать окно только если идет перетаскивание
    document.addEventListener("mousemove", (e) => {
      if (isDragging) {
        let x = e.clientX - offsetX;
        let y = e.clientY - offsetY;
        container.style.left = x + "px";
        container.style.top = y + "px";
      }
    });

    // Обработчик отпускания кнопки мыши, который завершает процесс перетаскивания
    document.addEventListener("mouseup", () => {
      isDragging = false;
    });
  }

  function initializeThreeLetters(container) {
    // Создаем заголовок игры
    let instruction = document.createElement("div");
    instruction.innerText = "Программа сгенерирует три случайные русские буквы!";
    container.appendChild(instruction);

    // Создаем кнопку для генерации букв
    let generateButton = document.createElement("button");
    generateButton.innerText = "Сгенерировать три буквы";
    generateButton.style.display = "block";
    generateButton.style.marginTop = "10px";
    container.appendChild(generateButton);

    // Создаем блок для отображения сгенерированных букв
    let lettersDiv = document.createElement("div");
    lettersDiv.style.marginTop = "10px";
    lettersDiv.style.fontSize = "24px";
    container.appendChild(lettersDiv);

    // Создаем кнопку для копирования букв
    let copyButton = document.createElement("button");
    copyButton.innerText = "Скопировать буквы";
    copyButton.style.display = "block";
    copyButton.style.marginTop = "10px";
    container.appendChild(copyButton);

    // Создаем блок для уведомлений
    let notificationDiv = document.createElement("div");
    notificationDiv.style.marginTop = "10px";
    notificationDiv.style.fontSize = "16px";
    notificationDiv.style.color = "green";
    notificationDiv.style.fontWeight = "bold";
    container.appendChild(notificationDiv);

    // Массив с русскими заглавными буквами
    const alphabet = [
      "А", "Б", "В", "Г", "Д", "Е", "Ё", "Ж", "З", "И", "Й", "К", "Л", "М", "Н", "О",
      "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ы", "Э", "Ю", "Я"
    ];

    // Функция для генерации трех случайных букв
    function generateLetters() {
      let letters = [];
      for (let i = 0; i < 3; i++) {
        let randomIndex = Math.floor(Math.random() * alphabet.length);
        letters.push(alphabet[randomIndex]);
      }
      return letters.join(""); // Объединяем буквы в строку с пробелами
    }

    // Обработчик нажатия кнопки для генерации букв
    generateButton.onclick = function () {
      let randomLetters = generateLetters();
      lettersDiv.innerText = randomLetters;
      notificationDiv.innerText = ""; // Очищаем уведомление
    };

    // Обработчик для копирования букв в буфер обмена
    copyButton.onclick = function () {
      let lettersText = lettersDiv.innerText;
      if (lettersText) {
        navigator.clipboard.writeText(lettersText).then(() => {
          notificationDiv.innerText = "Буквы скопированы в буфер обмена!";
          notificationDiv.style.color = "green"; // Зеленый цвет для успешного сообщения
        }).catch(err => {
          notificationDiv.innerText = "Не удалось скопировать: " + err;
          notificationDiv.style.color = "red"; // Красный цвет для ошибок
        });
      }
      else {
        notificationDiv.innerText = "Сначала сгенерируйте буквы!";
        notificationDiv.style.color = "red"; // Красный цвет для ошибок
      }
    };
  }

  function initializeMissingWord(container) {
    // Создаем заголовок игры
    let instruction = document.createElement("div");
    instruction.innerText = "Введите слово, и я добавлю случайные буквы до и после него!";
    container.appendChild(instruction);

    // Создаем поле ввода для слова
    let inputField = document.createElement("input");
    inputField.type = "text";
    inputField.style.width = "100%";
    inputField.placeholder = "Введите слово";
    container.appendChild(inputField);

    // Создаем кнопку для генерации пропавшего слова
    let generateButton = document.createElement("button");
    generateButton.innerText = "Сгенерировать пропавшее слово";
    generateButton.style.display = "block";
    generateButton.style.marginTop = "10px";
    container.appendChild(generateButton);

    // Создаем блок для отображения результата
    let resultDiv = document.createElement("div");
    resultDiv.style.marginTop = "10px";
    resultDiv.style.fontSize = "24px";
    container.appendChild(resultDiv);

    // Создаем кнопку для копирования результата
    let copyButton = document.createElement("button");
    copyButton.innerText = "Скопировать результат";
    copyButton.style.display = "block";
    copyButton.style.marginTop = "10px";
    container.appendChild(copyButton);

    // Создаем блок для уведомлений
    let notificationDiv = document.createElement("div");
    notificationDiv.style.marginTop = "10px";
    notificationDiv.style.fontSize = "16px";
    notificationDiv.style.color = "green";
    notificationDiv.style.fontWeight = "bold";
    container.appendChild(notificationDiv);

    // Массив с русскими строчными буквами
    const alphabet = [
      "а", "б", "в", "г", "д", "е", "ё", "ж", "з", "и", "й", "к", "л", "м", "н", "о",
      "п", "р", "с", "т", "у", "ф", "х", "ц", "ч", "ш", "щ", "ы", "э", "ю", "я"
    ];

    // Функция для генерации случайных букв
    function generateRandomLetters() {
      let numLetters = Math.floor(Math.random() * (30)) + 3; // Случайное количество букв от 3 до 32
      let letters = [];
      for (let i = 0; i < numLetters; i++) {
        let randomIndex = Math.floor(Math.random() * alphabet.length);
        letters.push(alphabet[randomIndex]);
      }
      return letters.join(""); // Возвращаем строку из случайных букв
    }

    // Обработчик нажатия кнопки для генерации пропавшего слова
    generateButton.onclick = function () {
      let word = inputField.value.trim();
      if (word) {
        let randomBefore = generateRandomLetters(); // Случайные буквы перед словом
        let randomAfter = generateRandomLetters(); // Случайные буквы после слова
        let missingWord = randomBefore + word + randomAfter;
        resultDiv.innerText = "Пропавшее слово: " + missingWord;
        notificationDiv.innerText = ""; // Очищаем уведомление
      }
      else {
        resultDiv.innerText = "";
        notificationDiv.innerText = "Пожалуйста, введите слово!";
        notificationDiv.style.color = "red"; // Красный цвет для ошибок
      }
    };

    // Обработчик для копирования результата в буфер обмена
    copyButton.onclick = function () {
      let resultText = resultDiv.innerText.replace("Пропавшее слово: ", "");
      if (resultText) {
        navigator.clipboard.writeText(resultText).then(() => {
          notificationDiv.innerText = "Результат скопирован в буфер обмена!";
          notificationDiv.style.color = "green"; // Зеленый цвет для успешного сообщения
        }).catch(err => {
          notificationDiv.innerText = "Не удалось скопировать: " + err;
          notificationDiv.style.color = "red"; // Красный цвет для ошибок
        });
      }
      else {
        notificationDiv.innerText = "Сначала сгенерируйте пропавшее слово!";
        notificationDiv.style.color = "red"; // Красный цвет для ошибок
      }
    };
  }

  createWindow();
})();