Code Monkey home page Code Monkey logo

tic-tac-toe-challenge's Introduction

Submit your results!

tic-tac-toe-challenge's People

Contributors

nickrox99 avatar

Watchers

 avatar

tic-tac-toe-challenge's Issues

Wyatt Saltzman D645582 - Submission

I didn't have write access to the repo so had to put my code in this issue.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tic Tac Toe</title>
    <style>
        /* CSS Styles */
        body {
            background-color: #f3f3f3;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }

        .container {
            text-align: center;
        }

        .board {
            display: grid;
            grid-template-columns: repeat(3, 100px);
            grid-template-rows: repeat(3, 100px);
            gap: 2px;
            background-color: #8b5a2b; /* Brown */
            border: 5px solid #6b4423; /* Darker Brown */
            border-radius: 10px;
        }

        .cell {
            background-color: #b5651d; /* Darker Brown */
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2em;
            cursor: pointer;
            color: #fff;
            transition: background-color 0.3s ease-in-out;
        }

        .cell:hover {
            background-color: #9e6f3b; /* Lighter Brown */
        }

        .status {
            text-align: center;
            margin-top: 20px;
            font-size: 1.2em;
            color: #6b4423; /* Darker Brown */
        }

        .score {
            margin-top: 20px;
            font-size: 1.2em;
            color: #6b4423; /* Darker Brown */
        }

        button {
            background-color: #9e6f3b; /* Lighter Brown */
            color: #fff;
            border: none;
            border-radius: 5px;
            padding: 10px 20px;
            font-size: 1em;
            cursor: pointer;
            transition: background-color 0.3s ease-in-out;
        }

        button:hover {
            background-color: #b5651d; /* Darker Brown */
        }
        h1 {
            font-size: 2em;
            color: #6b4423; /* Darker Brown */
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Play Tic Tac Toe</h1>
        <label for="modeSelect">Mode:</label>
        <select id="modeSelect" onchange="changeMode()">
            <option value="pvp">Player vs. Player</option>
            <option value="pvc">Player vs. Computer</option>
        </select>
        <br>
        <label for="difficultySelect">Difficulty:</label> <!-- Added -->
        <select id="difficultySelect" onchange="changeMode()"> <!-- Added -->
            <option value="easy">Easy</option>
            <option value="medium">Medium</option>
            <option value="hard">Hard</option>
        </select>
        <div id="board" class="board">
            <div class="cell" onclick="handleCellClick(0)"></div>
            <div class="cell" onclick="handleCellClick(1)"></div>
            <div class="cell" onclick="handleCellClick(2)"></div>
            <div class="cell" onclick="handleCellClick(3)"></div>
            <div class="cell" onclick="handleCellClick(4)"></div>
            <div class="cell" onclick="handleCellClick(5)"></div>
            <div class="cell" onclick="handleCellClick(6)"></div>
            <div class="cell" onclick="handleCellClick(7)"></div>
            <div class="cell" onclick="handleCellClick(8)"></div>
        </div>
        <div id="status" class="status">Player vs. Player mode</div>
        <div id="score" class="score">Scores: X - 0 | O - 0</div> <!-- Added -->
        <button onclick="resetGame()">Reset Game</button>
    </div>
    <script>
        // JavaScript code
        const board = document.getElementById('board');
        const status = document.getElementById('status');
        const scoreDisplay = document.getElementById('score'); // Added
        const modeSelect = document.getElementById('modeSelect');
        const difficultySelect = document.getElementById('difficultySelect'); // Added
        let currentPlayer = 'X';
        let gameActive = true;
        let gameState = ['', '', '', '', '', '', '', '', ''];
        let scores = { X: 0, O: 0 }; // Added

        const winPatterns = [
            [0, 1, 2],
            [3, 4, 5],
            [6, 7, 8],
            [0, 3, 6],
            [1, 4, 7],
            [2, 5, 8],
            [0, 4, 8],
            [2, 4, 6]
        ];

        // Difficulty levels
        const difficultyLevels = {
            easy: 0.2, // AI has a 20% chance to make a random move
            medium: 0.5, // AI has a 50% chance to make a random move
            hard: 1 // AI always makes optimal moves
        };

        // Added - Function to change game mode and difficulty
        function changeMode() {
            if (modeSelect.value === 'pvp') {
                resetGame();
                status.innerText = 'Player vs. Player mode';
            } else if (modeSelect.value === 'pvc') {
                resetGame();
                status.innerText = 'Player vs. Computer mode';
                // Only start AI's move if it's AI's turn (currentPlayer === 'O')
                if (currentPlayer === 'O') {
                    playAI();
                }
            }
        }

        // Added - Function to get AI move based on difficulty level
        function getAIMove() {
            const emptyCells = gameState.reduce((acc, val, index) => {
                if (val === '') acc.push(index);
                return acc;
            }, []);

            // AI behavior based on difficulty level
            const random = Math.random();
            const difficulty = difficultyLevels[difficultySelect.value];
            if (random > difficulty) {
                // Random move
                const randomIndex = Math.floor(Math.random() * emptyCells.length);
                return emptyCells[randomIndex];
            } else {
                // Optimal move
                return getOptimalMove();
            }
        }

        // Added - Function to get AI's optimal move
        function getOptimalMove() {
            // Add logic to determine optimal move (e.g., using minimax algorithm)
            // For simplicity, return a random empty cell for now
            const emptyCells = gameState.reduce((acc, val, index) => {
                if (val === '') acc.push(index);
                return acc;
            }, []);

            const randomIndex = Math.floor(Math.random() * emptyCells.length);
            return emptyCells[randomIndex];
        }

        function handleCellClick(cellIndex) {
            if (!gameActive || gameState[cellIndex] !== '') return;

            gameState[cellIndex] = currentPlayer;
            document.getElementsByClassName('cell')[cellIndex].innerText = currentPlayer;

            if (checkWin(currentPlayer)) {
                status.innerText = `${currentPlayer} wins!`;
                scores[currentPlayer]++; // Update scores
                updateScoreDisplay(); // Update score display
                gameActive = false;
                return;
            }

            if (checkDraw()) {
                status.innerText = 'Draw!';
                gameActive = false;
                return;
            }

            currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
            status.innerText = `${currentPlayer}'s turn`;

            if (modeSelect.value === 'pvc' && currentPlayer === 'O' && gameActive) {
                playAI();
            }
        }

        function checkWin(player) {
            return winPatterns.some(pattern => {
                return pattern.every(index => {
                    return gameState[index] === player;
                });
            });
        }

        function checkDraw() {
            return gameState.every(cell => cell !== '');
        }

        function resetGame() {
            gameState = ['', '', '', '', '', '', '', '', ''];
            currentPlayer = 'X';
            gameActive = true;
            status.innerText = `${currentPlayer}'s turn`;
            document.querySelectorAll('.cell').forEach(cell => {
                cell.innerText = '';
            });
        }

        // Added - Function to trigger AI's move
        function playAI() {
            const cellIndex = getAIMove();
            setTimeout(() => {
                handleCellClick(cellIndex);
            }, 500);
        }

        // Added - Function to update score display
        function updateScoreDisplay() {
            scoreDisplay.innerText = `Scores: X - ${scores['X']} | O - ${scores['O']}`;
        }
    </script>
</body>
</html>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.