Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h1>Tic Tac Toe</h1>
<!--Tic Tac Toe Frame-->
<div class="container master-container pieces-font">
    <!--Tic Tac Toe Row 1-->
    <div class="row">
        <div class="cell col-xs-4 center no-border-top no-border-left" id="0"></div>
        <div class="cell col-xs-4 center no-border-top" id="1"></div>
        <div class="cell col-xs-4 center no-border-top no-border-right" id="2"></div>
    </div>
    <!--Tic Tac Toe Row 2-->
    <div class="row">
        <div class="cell col-xs-4 center no-border-left" id="3"></div>
        <div class="cell col-xs-4 center" id="4"></div>
        <div class="cell col-xs-4 center no-border-right" id="5"></div>
    </div>
    <!--Tic Tac Toe Row 3-->
    <div class="row">
        <div class="cell col-xs-4 center no-border-bottom no-border-left" id="6"></div>
        <div class="cell col-xs-4 center no-border-bottom" id="7"></div>
        <div class="cell col-xs-4 center no-border-bottom no-border-right" id="8"></div>
    </div>
</div>
<div class="victory-defeat-screen">
    <div class="text"></div>
    <button onclick="chooseTeam()">Replay</button>
</div>
<div class="computer-thinking" style="font-size: 5vmax; padding: 25px;">
    The computer is thinking.
    <div class="computer-thinking-text"></div>
</div>
<!--jQuery Dialogue Box-->
<div class="dialog-box-size" id="dialog-box">Please choose either "x" or "o".</div>
<div class="dialog-box-size" id="first-move-box">Who goes first?</div>
              
            
!

CSS

              
                html {
    overflow: scroll;
    overflow-x: hidden;
}

::-webkit-scrollbar {
    width: 0px;
    background: transparent;
}

::-webkit-scrollbar-thumb {
    background: #FF0000;
}

#o {
    border: solid 5px hsla(0, 95%, 35%, 1);
}

body {
    background-color: "--blue";
    background-image: url("https://dl.dropbox.com/s/u8nk467yrqsymze/136548-crumpled-paper-background-1923x2510-for-pc.jpg?dl=0");
    background-position: center;
    background-repeat: no-repeat;
    background-size: stretch;
    font-family: 'Shadows Into Light', cursive;
    font-size: 12vmax;
    font-weight: bold;
}

h1,
h2,
h3,
h4,
h5,
h6 {
    font-size: 8vmax;
    font-weight: bold;
    text-align: center;
}

h1 {
    border-bottom-style: solid;
    border-width: 5px;
    margin: 25px auto;
    width: 70%;
}

button {
    font-size: 5vmin;
    background-color: black;
    color: white;
    border-radius: 20px;
    margin: 2%;
    width: 40%;
}

button:focus {
    outline: none;
}

.fade-in {
    animation: fadein 1.5s;
}

@keyframes fadein {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}


/* Firefox < 16 */

@-moz-keyframes fadein {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}


/* Safari, Chrome and Opera > 12.1 */

@-webkit-keyframes fadein {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}


/* Internet Explorer */

@-ms-keyframes fadein {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}


/* Opera < 12.1 */

@-o-keyframes fadein {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}

.dialog-box-size{
    display: none;
}

.ui-dialog-titlebar-close {
    visibility: hidden;
}

.vertical-align {
    align-items: center;
    display: flex;
}

.center {
    align-items: center;
    display: flex;
    justify-content: center;
}

.master-container {
    position: absolute;
    top: 25%;
    left: 50%;
    -webkit-transform: translateX(-50%);
    transform: translateX(-50%);
}

@font-face {
    font-family: "Crayon Crumble";
    src: url(https://dl.dropbox.com/s/3y4yu730xnrc6v5/DK%20Crayon%20Crumble.ttf?dl=0) format("truetype");
}

.col-xs-4 {
    border: solid;
    height: 15vmax;
}

.no-border-top {
    border-top: none;
}

.no-border-bottom {
    border-bottom: none;
}

.no-border-left {
    border-left: none;
}

.no-border-right {
    border-right: none;
}

.computer-thinking,
.victory-defeat-screen {
    display: none;
    width: 700px;
    top: 120px;
    background-color: rgba(255, 255, 255, 1);
    outline: none;
    position: absolute;
    left: 50%;
    -webkit-transform: translateX(-50%);
    transform: translateX(-50%);
    text-align: center;
    border-radius: 30px;
    font-size: 7vmax;
    box-shadow: 1px 1px 30px 5px;
}

.pieces-font {
    font-family: "Crayon Crumble";
    font-size: 12vmax;
}

.ui-dialog {
    font-size: 60px;
    position: absolute;
    box-shadow: 1px 1px 30px 5px;
    background-color: rgba(255, 255, 255, 1);
    text-align: center;
    border-radius: 30px;
    outline: none;
    overflow: hidden;
    padding-top: 20px;
}

.ui-dialog-titlebar {
    display: none;
}

@media screen and (max-width: 770px) {
    .ui-dialog {
        font-size: 4.5vmax;
        max-width: 300px;
    }
    .victory-defeat-screen,
    .computer-thinking {
        font-size: 4.5vmax;
        max-width: 300px;
    }
    .master-container {
        width: 95%;
    }
}
              
            
!

JS

              
                // Global Variables
var origBoard;
var gameState = "playing";
var huPlayer;
var aiPlayer;
const winCombos = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [6, 4, 2]
];
const cells = document.querySelectorAll('.cell');
var victoryDefeatScreen = document.querySelector('.victory-defeat-screen');
var computerThinking = document.querySelector('.computer-thinking');

chooseTeam();

// Player Chooses X or O
function chooseTeam() {
    victoryDefeatScreen.style.display = "none";
    for (i = 0; i < cells.length; i++) {
        cells[i].innerHTML = "";
        cells[i].style.removeProperty("background-image");
        //cells[i].style.removeProperty("background-color");
    }

    $("#dialog-box").dialog({
        position: { my: "center top", at: "center center-100", of: window, collision: "none" },
        width: 700,
        modal: true,
        autoOpen: true,
        buttons: {
            "X": function() { //submit
                $(this).dialog("close");
                huPlayer = "x";
                aiPlayer = "o";
                $("#first-move-box").dialog('open');
            },
            "O": function() { //cancel
                $(this).dialog("close");
                huPlayer = "o";
                aiPlayer = "x";
                $("#first-move-box").dialog('open');
            }
        }
    });
    $("#first-move-box").dialog({
        position: { my: "center top", at: "center center-100", of: window, collision: "none" },
        width: 700,
        modal: true,
        autoOpen: false,
        buttons: {
            "Me": function() { //submit
                $(this).dialog("close");
                startGame();
            },
            "Computer": function() { //cancel                
                $(this).dialog("close");
                startGame();
                computerThinking.style.display = "block";
                computerThinking.style.animation = "fadein 1.5s";
                setTimeout(function() {
                    turn(bestSpot(), aiPlayer);
                }, 1);
            }
        }
    });
}
$(window).resize(function() {
    $("#dialog-box, #first-move-box").dialog("option", "position", { my: "center top", at: "center center-100", of: window });
});

// Start the game, clear last game
function startGame() {
    gameState = "playing";
    origBoard = Array.from(Array(9).keys());
    for (i = 0; i < cells.length; i++) {
        //cells[i].innerHTML = "";
        cells[i].addEventListener("click", turnClick, false);
        //cells[i].style.removeProperty("background-color");
    }
}

// When player clicks on square...
function turnClick(squareClick) {
    if (origBoard[squareClick.target.id] === huPlayer || aiPlayer) {
        for (i = 0; i < cells.length; i++) {
            cells[i].removeEventListener("click", turnClick, false);
        }
    }
    turn(squareClick.target.id, huPlayer);
    setTimeout(function() {
        if (gameState === "playing") {
            for (var i = 0; i < emptySquares().length; i++) {
                document.getElementById(emptySquares()[i].toString()).addEventListener("click", turnClick, false);
            }
            turn(bestSpot(), aiPlayer);
        }
    }, 1500);
}

//...it triggers the players symbol to be on board
function turn(squareId, player) {
    computerThinking.style.display = "none";
    origBoard[squareId] = player;
    document.getElementById(squareId).innerHTML = "<span class=\"fade-in\">" + player + "</span>";
    let gameWon = null;
    gameWon = checkWin(origBoard, player);
    if (gameWon) {
        gameState = "complete";
        gameOver(gameWon);
    }
    checkDraw(origBoard);
}

// Check to see if game has been won
function checkWin(currBoard, player) {
    var played = currBoard.reduce(function(acc, curVal, ind) {
        if (curVal === player) {
            return acc.concat(ind);
        } else {
            return acc;
        }
    }, []);

    // Function called in .every method 
    function winCondition(curVal) {
        return played.indexOf(curVal) !== -1;
    }
    for (i = 0; i < winCombos.length; i++) {
        if (winCombos[i].every(winCondition)) {
            let victoryPath = { index: winCombos[i], player: player };
            return victoryPath;
        }
    }
    return null;
}

// On gameover highlight victory path and make cells unclickable
function gameOver(gameWon) {
    for (i = 0; i < cells.length; i++) {
        cells[i].removeEventListener("click", turnClick, false);
    }
    setTimeout(function() {
        victoryDefeatScreen.style.display = "block";
        for (j = 0; j < gameWon.index.length; j++) {
            document.getElementById(gameWon.index[j]).style.backgroundImage = "url('https://dl.dropboxusercontent.com/s/0w3e6nu4mbfe8ih/32998832-abstract-pencil-scribbles-background-texture-Stock-Photo.jpg?dl=0')";
        }
        declareWinner(gameWon);
    }, 2500);
}

// Declare Winner and posts winner to board
function declareWinner(gameWon) {
    if (gameWon.player === huPlayer) {
        document.querySelector(".text").innerHTML = "You Win!";
    } else if (gameWon.player === aiPlayer) {
        document.querySelector(".text").innerHTML = "You Lose";
    } else if (gameWon.player === "Draw") {
        document.querySelector(".text").innerHTML = "Draw";
    }
}

// Figures out which squares are empty
function emptySquares() {
    return origBoard.filter(function(curElem) {
        return typeof curElem == 'number';
    });
}

// Calls minimax and returns index of best move
function bestSpot() {
    return minimax(origBoard, aiPlayer).index;
}

// Checks to see if there is a tie and displays Tie text on board
function checkDraw(origBoard) {
    if (emptySquares().length === 0) {
        gameState = "complete";
        let gameWon = { player: "Draw" };
        setTimeout(function() {
            victoryDefeatScreen.style.display = "block";
            for (i = 0; i < cells.length; i++) {
                cells[i].removeEventListener("click", turnClick, false);
                //cells[i].style.backgroundColor = "green";
                cells[i].style.backgroundImage = "url('https://dl.dropboxusercontent.com/s/0w3e6nu4mbfe8ih/32998832-abstract-pencil-scribbles-background-texture-Stock-Photo.jpg?dl=0')";
            }
        }, 2500);
        declareWinner(gameWon);
        return true;
    }
    return false;
}

// Minimax function for determining computer players best move
function minimax(tempBoard, player) {
    var availMoves = emptySquares();
    if (checkWin(tempBoard, huPlayer)) {
        return { score: -10 };
    } else if (checkWin(tempBoard, aiPlayer)) {
        return { score: 10 };
    } else if (availMoves.length === 0) {
        return { score: 0 };
    }

    var posMoves = [];

    for (var i = 0; i < availMoves.length; i++) {
        var move = {};
        move.index = tempBoard[availMoves[i]];
        tempBoard[availMoves[i]] = player;

        if (player == aiPlayer) {
            var result = minimax(tempBoard, huPlayer);
            move.score = result.score;
        } else {
            var result = minimax(tempBoard, aiPlayer);
            move.score = result.score;
        }

        // resets board to before looping
        tempBoard[availMoves[i]] = move.index;

        // adds move to moves possibles moves array
        posMoves.push(move);
    }

    // Best move for AI
    var aiGodMove;
    if (player === aiPlayer) {
        var highestScore = -1000;
        for (var i = 0; i < posMoves.length; i++) {
            if (posMoves[i].score > highestScore) {
                highestScore = posMoves[i].score;
                aiGodMove = posMoves[i];
            }
        }
    } else {
        var lowestScore = 1000;
        for (var i = 0; i < posMoves.length; i++) {
            if (posMoves[i].score < lowestScore) {
                lowestScore = posMoves[i].score;
                aiGodMove = posMoves[i];
            }
        }
    }
    return aiGodMove;
}
              
            
!
999px

Console