Skip to content
The Chat Archive
o1-mini-2024-09-12· OpenAI WildChat-4.8M (AI2)

Напиши мне игру шашки со всеми правилами классическими. Меню и Настройками всевозможными…

  1. User

    Напиши мне игру шашки со всеми правилами классическими. Меню и Настройками всевозможными и алгоритмом, который будет меня выигрывать всегда. Должно быть адаптировано под мобильные устройства и все в одном файле HTML

  2. Assistant

    Создание полноценной игры в шашки с всеми классическими правилами, меню, настройками и мощным ИИ в одном HTML-файле требует интеграции HTML, CSS и JavaScript. Ниже представлен пример такого файла. Обратите внимание, что создание ИИ, который всегда выигрывает, чрезвычайно сложно из-за сложности самой игры. Однако приведённый ниже алгоритм использует минимакс с альфа-бета отсечением для создания конкурентоспособного ИИ.

    <!DOCTYPE html>
    <html lang="ru">
    <head>
        <meta charset="UTF-8">
        <title>Шашки</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <style>
            body {
                font-family: Arial, sans-serif;
                text-align: center;
                margin: 0;
                padding: 0;
                background-color: #f0f0f0;
            }
            #menu, #settings, #game {
                display: none;
                padding: 20px;
            }
            #menu.active, #settings.active, #game.active {
                display: block;
            }
            .button {
                padding: 10px 20px;
                margin: 10px;
                font-size: 16px;
                cursor: pointer;
            }
            #board {
                display: grid;
                grid-template-columns: repeat(8, 45px);
                grid-template-rows: repeat(8, 45px);
                justify-content: center;
                margin: 20px auto;
                border: 2px solid #333;
            }
            .cell {
                width: 45px;
                height: 45px;
                box-sizing: border-box;
                position: relative;
            }
            .black {
                background-color: #769656;
            }
            .white {
                background-color: #eeeed2;
            }
            .piece {
                width: 35px;
                height: 35px;
                border-radius: 50%;
                margin: 5px auto;
                cursor: pointer;
                position: absolute;
                top: 0;
                left: 0;
            }
            .red {
                background-color: red;
            }
            .black-piece {
                background-color: black;
            }
            .king {
                border: 2px solid gold;
            }
            /* Responsive Design */
            @media (max-width: 600px) {
                #board {
                    grid-template-columns: repeat(8, 35px);
                    grid-template-rows: repeat(8, 35px);
                }
                .cell {
                    width: 35px;
                    height: 35px;
                }
                .piece {
                    width: 25px;
                    height: 25px;
                    margin: 5px auto;
                }
            }
        </style>
    </head>
    <body>
    
        <div id="menu" class="active">
            <h1>Шашки</h1>
            <button class="button" onclick="startGame()">Начать игру</button>
            <button class="button" onclick="showSettings()">Настройки</button>
        </div>
    
        <div id="settings">
            <h2>Настройки</h2>
            <label for="difficulty">Сложность ИИ:</label>
            <select id="difficulty">
                <option value="2">Лёгкая</option>
                <option value="4">Средняя</option>
                <option value="6">Сложная</option>
            </select><br><br>
            <button class="button" onclick="saveSettings()">Сохранить</button>
            <button class="button" onclick="backToMenu()">Назад</button>
        </div>
    
        <div id="game">
            <h2>Ходит: <span id="currentPlayer">Красные</span></h2>
            <div id="board"></div>
            <button class="button" onclick="exitGame()">Выйти</button>
        </div>
    
        <script>
            const menu = document.getElementById('menu');
            const settingsDiv = document.getElementById('settings');
            const gameDiv = document.getElementById('game');
            const boardElement = document.getElementById('board');
            const currentPlayerElement = document.getElementById('currentPlayer');
    
            let board = [];
            let currentPlayer = 'red';
            let selectedPiece = null;
            let possibleMoves = [];
            let aiDifficulty = 4; // Default difficulty
    
            function showMenu() {
                menu.classList.add('active');
                settingsDiv.classList.remove('active');
                gameDiv.classList.remove('active');
            }
    
            function showSettings() {
                menu.classList.remove('active');
                settingsDiv.classList.add('active');
                gameDiv.classList.remove('active');
            }
    
            function backToMenu() {
                showMenu();
            }
    
            function saveSettings() {
                const difficultySelect = document.getElementById('difficulty');
                aiDifficulty = parseInt(difficultySelect.value);
                alert('Настройки сохранены!');
            }
    
            function startGame() {
                menu.classList.remove('active');
                settingsDiv.classList.remove('active');
                gameDiv.classList.add('active');
                initializeBoard();
                renderBoard();
                currentPlayer = 'red';
                currentPlayerElement.textContent = 'Красные';
                if (currentPlayer === 'black') {
                    aiMove();
                }
            }
    
            function exitGame() {
                showMenu();
            }
    
            function initializeBoard() {
                board = [];
                for (let row = 0; row < 8; row++) {
                    board[row] = [];
                    for (let col = 0; col < 8; col++) {
                        if ((row + col) % 2 === 1) {
                            if (row < 3) {
                                board[row][col] = { player: 'black', king: false };
                            } else if (row > 4) {
                                board[row][col] = { player: 'red', king: false };
                            } else {
                                board[row][col] = null;
                            }
                        } else {
                            board[row][col] = null;
                        }
                    }
                }
            }
    
            function renderBoard() {
                boardElement.innerHTML = '';
                for (let row = 0; row < 8; row++) {
                    for (let col = 0; col < 8; col++) {
                        const cell = document.createElement('div');
                        cell.classList.add('cell');
                        cell.classList.add((row + col) % 2 === 1 ? 'black' : 'white');
                        cell.dataset.row = row;
                        cell.dataset.col = col;
    
                        const piece = board[row][col];
                        if (piece) {
                            const pieceDiv = document.createElement('div');
                            pieceDiv.classList.add('piece');
                            pieceDiv.classList.add(piece.player === 'red' ? 'red' : 'black-piece');
                            if (piece.king) {
                                pieceDiv.classList.add('king');
                            }
                            pieceDiv.addEventListener('click', () => selectPiece(row, col));
                            cell.appendChild(pieceDiv);
                        }
    
                        boardElement.appendChild(cell);
                    }
                }
            }
    
            function selectPiece(row, col) {
                if (board[row][col] && board[row][col].player === currentPlayer) {
                    selectedPiece = { row, col };
                    possibleMoves = getValidMoves(row, col);
                    highlightPossibleMoves();
                } else if (selectedPiece) {
                    const move = possibleMoves.find(m => m.to.row === row && m.to.col === col);
                    if (move) {
                        makeMove(selectedPiece.row, selectedPiece.col, move.to.row, move.to.col, move.capture);
                    }
                    selectedPiece = null;
                    possibleMoves = [];
                    renderBoard();
                    switchPlayer();
                }
            }
    
            function highlightPossibleMoves() {
                renderBoard();
                possibleMoves.forEach(move => {
                    const cell = document.querySelector(`.cell[data-row='${move.to.row}'][data-col='${move.to.col}']`);
                    if (cell) {
                        cell.style.backgroundColor = '#a9a9a9';
                        cell.addEventListener('click', () => makeMove(selectedPiece.row, selectedPiece.col, move.to.row, move.to.col, move.capture));
                    }
                });
            }
    
            function getValidMoves(row, col) {
                const piece = board[row][col];
                if (!piece) return [];
    
                const directions = piece.player === 'red' || piece.king ? [[-1, -1], [-1, 1]] : [];
                if (piece.player === 'black' || piece.king) {
                    directions.push([1, -1], [1, 1]);
                }
    
                const moves = [];
                directions.forEach(dir => {
                    const newRow = row + dir[0];
                    const newCol = col + dir[1];
                    if (isInBounds(newRow, newCol)) {
                        if (!board[newRow][newCol]) {
                            moves.push({ to: { row: newRow, col: newCol }, capture: null });
                        } else {
                            const opponent = board[newRow][newCol].player;
                            if (opponent !== piece.player) {
                                const jumpRow = newRow + dir[0];
                                const jumpCol = newCol + dir[1];
                                if (isInBounds(jumpRow, jumpCol) && !board[jumpRow][jumpCol]) {
                                    moves.push({ to: { row: jumpRow, col: jumpCol }, capture: { row: newRow, col: newCol } });
                                }
                            }
                        }
                    }
                });
                return moves;
            }
    
            function isInBounds(row, col) {
                return row >= 0 && row < 8 && col >= 0 && col < 8;
            }
    
            function makeMove(fromRow, fromCol, toRow, toCol, capture) {
                board[toRow][toCol] = board[fromRow][fromCol];
                board[fromRow][fromCol] = null;
    
                if (capture) {
                    board[capture.row][capture.col] = null;
                }
    
                // Коронация
                if ((board[toRow][toCol].player === 'red' && toRow === 0) ||
                    (board[toRow][toCol].player === 'black' && toRow === 7)) {
                    board[toRow][toCol].king = true;
                }
            }
    
            function switchPlayer() {
                currentPlayer = currentPlayer === 'red' ? 'black' : 'red';
                currentPlayerElement.textContent = currentPlayer === 'red' ? 'Красные' : 'Черные';
                renderBoard();
                if (currentPlayer === 'black') {
                    setTimeout(aiMove, 500);
                }
            }
    
            // AI Implementation (Минимакс с альфа-бета отсечением)
            function aiMove() {
                const depth = aiDifficulty;
                const move = minimax(board, depth, -Infinity, Infinity, true).move;
                if (move) {
                    makeMove(move.from.row, move.from.col, move.to.row, move.to.col, move.capture);
                    switchPlayer();
                }
            }
    
            function minimax(boardState, depth, alpha, beta, maximizingPlayer) {
                if (depth === 0 || isGameOver(boardState)) {
                    return { score: evaluateBoard(boardState) };
                }
    
                if (maximizingPlayer) {
                    let maxEval = -Infinity;
                    let bestMove = null;
                    const moves = getAllValidMoves(boardState, 'black');
                    for (let move of moves) {
                        const newBoard = cloneBoard(boardState);
                        applyMove(newBoard, move);
                        const evalResult = minimax(newBoard, depth - 1, alpha, beta, false).score;
                        if (evalResult > maxEval) {
                            maxEval = evalResult;
                            bestMove = move;
                        }
                        alpha = Math.max(alpha, evalResult);
                        if (beta <= alpha) break;
                    }
                    return { score: maxEval, move: bestMove };
                } else {
                    let minEval = Infinity;
                    let bestMove = null;
                    const moves = getAllValidMoves(boardState, 'red');
                    for (let move of moves) {
                        const newBoard = cloneBoard(boardState);
                        applyMove(newBoard, move);
                        const evalResult = minimax(newBoard, depth - 1, alpha, beta, true).score;
                        if (evalResult < minEval) {
                            minEval = evalResult;
                            bestMove = move;
                        }
                        beta = Math.min(beta, evalResult);
                        if (beta <= alpha) break;
                    }
                    return { score: minEval, move: bestMove };
                }
            }
    
            function getAllValidMoves(boardState, player) {
                let allMoves = [];
                for (let row = 0; row < 8; row++) {
                    for (let col = 0; col < 8; col++) {
                        const piece = boardState[row][col];
                        if (piece && piece.player === player) {
                            const moves = getValidMovesForPiece(boardState, row, col);
                            moves.forEach(move => {
                                allMoves.push({ from: { row, col }, to: move.to, capture: move.capture });
                            });
                        }
                    }
                }
                return allMoves;
            }
    
            function getValidMovesForPiece(boardState, row, col) {
                const piece = boardState[row][col];
                if (!piece) return [];
    
                const directions = piece.player === 'red' || piece.king ? [[-1, -1], [-1, 1]] : [];
                if (piece.player === 'black' || piece.king) {
                    directions.push([1, -1], [1, 1]);
                }
    
                const moves = [];
                directions.forEach(dir => {
                    const newRow = row + dir[0];
                    const newCol = col + dir[1];
                    if (isInBounds(newRow, newCol)) {
                        if (!boardState[newRow][newCol]) {
                            moves.push({ to: { row: newRow, col: newCol }, capture: null });
                        } else {
                            const opponent = boardState[newRow][newCol].player;
                            if (opponent !== piece.player) {
                                const jumpRow = newRow + dir[0];
                                const jumpCol = newCol + dir[1];
                                if (isInBounds(jumpRow, jumpCol) && !boardState[jumpRow][jumpCol]) {
                                    moves.push({ to: { row: jumpRow, col: jumpCol }, capture: { row: newRow, col: newCol } });
                                }
                            }
                        }
                    }
                });
                return moves;
            }
    
            function applyMove(boardState, move) {
                const piece = boardState[move.from.row][move.from.col];
                boardState[move.to.row][move.to.col] = piece;
                boardState[move.from.row][move.from.col] = null;
    
                if (move.capture) {
                    boardState[move.capture.row][move.capture.col] = null;
                }
    
                // Коронация
                if ((piece.player === 'red' && move.to.row === 0) ||
                    (piece.player === 'black' && move.to.row === 7)) {
                    piece.king = true;
                }
            }
    
            function cloneBoard(boardState) {
                return boardState.map(row => row.map(cell => cell ? { player: cell.player, king: cell.king } : null));
            }
    
            function evaluateBoard(boardState) {
                let score = 0;
                for (let row = 0; row < 8; row++) {
                    for (let col = 0; col < 8; col++) {
                        const piece = boardState[row][col];
                        if (piece) {
                            let value = piece.king ? 3 : 1;
                            if (piece.player === 'black') {
                                score += value;
                            } else {
                                score -= value;
                            }
                        }
                    }
                }
                return score;
            }
    
            function isGameOver(boardState) {
                const redPieces = boardState.flat().filter(piece => piece && piece.player === 'red').length;
                const blackPieces = boardState.flat().filter(piece => piece && piece.player === 'black').length;
                return redPieces === 0 || blackPieces === 0;
            }
    
        </script>
    </body>
    </html>
    

    Объяснение Кода

    1. HTML Структура:

      • Меню: Начальный экран с кнопками "Начать игру" и "Настройки".
      • Настройки: Позволяют выбрать сложность ИИ.
      • Игра: Отображает игровую доску и текущее состояние игры.
    2. CSS Стилизация:

      • Доска создаётся с использованием CSS Grid.
      • Параметры адаптивности обеспечены через медиазапросы для экранов шириной до 600px.
    3. JavaScript Логика:

      • Инициализация Доски: Шашки расставляются по классическим правилам.
      • Обработка Ходов Игрока: Игрок выбирает шашку, после чего отображаются возможные ходы.
      • ИИ: Использует алгоритм минимакс с альфа-бета отсечением. Глубина поиска (сложность) настраивается через меню настроек.
      • Оценка Доски: Простая функция оценки, учитывающая количество и тип шашек.

    Важные Замечания

    • ИИ Не Гарантированно Выигрывает: Реализация действительно сильного ИИ требует более сложных алгоритмов и оптимизаций. Текущий ИИ предоставляет достойный уровень сложности, но не гарантирует постоянную победу.

    • Улучшения:

      • Добавить более сложные эвристики для оценки позиций.
      • Реализовать обязательный захват шашек.
      • Добавить поддержку множественных последовательных ходов при возможности.
      • Добавить анимации для ходов и захватов.
      • Реализовать сохранение и загрузку игры.

    Этот пример служит базовой основой для игры в шашки и может быть расширен функционалом по вашему усмотрению.