Pen Settings

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. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <body onload="initialize()">
  <h1>Tic Tac Toe</h1>
  <table id="table_game">
    <tr>
      <td class="td_game">
        <div id="cell0" onclick="cellClicked(this.id)" class="fixed">
        </div>  
      </td>
      <td class="td_game">
        <div id="cell1" onclick="cellClicked(this.id)" class="fixed"></div>
      </td>
      <td class="td_game">
        <div id="cell2" onclick="cellClicked(this.id)" class="fixed"></div>
      </td>
    </tr>

    <tr>
      <td class="td_game">
        <div id="cell3" onclick="cellClicked(this.id)" class="fixed"></div>
      </td>
      <td class="td_game">
        <div id="cell4" onclick="cellClicked(this.id)" class="fixed"></div>
      </td>
      <td class="td_game">
        <div id="cell5" onclick="cellClicked(this.id)" class="fixed"></div>
      </td>
    </tr>

    <tr>
      <td class="td_game">
        <div id="cell6" onclick="cellClicked(this.id)" class="fixed"></div>
      </td>
      <td class="td_game">
        <div id="cell7" onclick="cellClicked(this.id)" class="fixed"></div>
      </td>
      <td class="td_game">
        <div id="cell8" onclick="cellClicked(this.id)" class="fixed"></div>
      </td>
    </tr>
  </table>

  <div id="restart" title="Start new game" onclick="restartGame(true)"><span style="vertical-align:top;position:relative;"><i class="fa fa-repeat" aria-hidden="true"></i></span></div>
  <table>
    <tr>
      <th class="th_list">
        Computer
      </th>
      <th class="th_list" style="padding-right:10px;padding-left:10px">
        Draws
      </th>
      <th class="th_list">
        Player
      </th>
    </tr>
    <tr>
      <td class="td_list" id="computer_score">
        0
      </td>
      <td class="td_list" style="padding-right:10px;padding-left:10px" id="tie_score">
        0
      </td>
      <td class="td_list" id="player_score">
        0
      </td>
    </tr>
  </table>
  <!-- The modal dialog for announcing the winner -->
  <div id="winAnnounce" class="modal">
    <!-- Modal content -->
    <div class="modal-content">
<!--       <span class="close" onclick="closeModal('winAnnounce')">&times;
      </span> -->
      <p id="winText"></p>
    </div>
  </div>
  <!-- The dialog for getting feedback from the user -->
  <div id="userFeedback" class="modal">
    <!-- Modal content -->
    <div class="modal-content">
      <p id="questionText"></p>
      <p>
        <button id="yesBtn">
          Yes
        </button>
        &nbsp;
        <button id="noBtn">
          No
        </button>
      </p>
    </div>
  </div>
  <!-- The options dialog -->
  <div id="optionsDlg" class="modal">
    <!-- Modal content -->
    <div class="modal-content">
      <h2>How would you like to play?</h2>
      
      <br>
      <h3>Play as:</h3>
      <label>
        <input type="radio" name="player" id="rx" value="x" checked>
        X (go first)&nbsp;
      </label>
      <label>
        <input type="radio" name="player" id="ro" value="o">
        O
        <br>
      </label>
      <p>
        <button id="okBtn" onclick="getOptions()">
          Play
        </button>
      </p>
    </div>
  </div>
</body>
            
          
!
            
              body {
    background: linear-gradient(320deg, #8e08d9, #f2c307);
    background-size: 400% 400%;
    -webkit-animation: AnimationName 30s ease infinite;
    -moz-animation: AnimationName 30s ease infinite;
    animation: AnimationName 30s ease infinite;
    color: rgb(230, 230, 230);
    text-align: center;
    font-family: 'Indie Flower', 'Comic Sans', cursive;
    font-size: 0.7em;
}

@-webkit-keyframes AnimationName {
    0%{background-position:0% 14%}
    50%{background-position:100% 87%}
    100%{background-position:0% 14%}
}
@-moz-keyframes AnimationName {
    0%{background-position:0% 14%}
    50%{background-position:100% 87%}
    100%{background-position:0% 14%}
}
@keyframes AnimationName { 
    0%{background-position:0% 14%}
    50%{background-position:100% 87%}
    100%{background-position:0% 14%}
}

h1 {
    line-height: 2rem;
    margin-top: 2rem;
    margin-bottom: 2rem;
    padding-bottom: 5px;
    font-size: 2.8em;
    font-weight: bold;
}
h2 {
    font-size: 1.3em;
    font-weight: bold;
    padding: 0;
    margin: 0;

}
h3 {
    font-size: 1.1em;
    text-decoration: underline;
    text-decoration-style: dashed;
    padding: 0;
    margin: 10px 0 2px 0;
}
table {
    margin: 2% auto;
    border-collapse: collapse;
}
#table_game {
    position: relative;
    font-size: 120px;
    margin: 1% auto;
    border-collapse: collapse;
}
.td_game {
    border: 2px solid rgb(230, 230, 230);
    width: 90px;
    height: 90px;
    padding: 0;
    vertical-align: middle;
    text-align: center;
}
.fixed {
    width: 90px;
    height: 90px;
    line-height: 90px;
    display: block;
    overflow: hidden;
    cursor: pointer;
}
.td_list {
    text-align: center;
    font-size: 1.3em;
    font-weight: bold;
}
.th_list {
    font-size: 1.3em;
    font-weight: bold;
    text-align: center;
    text-decoration: underline;
}
#restart {
    font-size: 1rem;
    width: 1em;
    height: 1.5rem;
    cursor: pointer;
    margin: 0 auto;
    overflow: hidden;
}
.x {
    color: darksalmon;
    position: relative;
    top: -8px;
    font-size: 1.2em;
    cursor: default;
}
.o {
    color: aquamarine;
    position: relative;
    top: -7px;
    font-size: 1.0em;
    cursor: default;
}

/* modal background */
.modal {
    display: none;
    position: fixed;
    z-index: 1;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto; /* enable scroll if needed */
    background-color: black; /* fallback color */
    background-color: rgba(0, 0, 0, 0.6);
}

/* modal content */
.modal-content {
    background-color: rgb(240, 240, 240);
    color: rgb(32, 32, 32);
    font-size: 2em;
    font-weight: bold;
    /* 16 % from the top and centered */
    margin: 16% auto;
    padding: 20px;
    border: 2px solid black;
    border-radius: 10px;
    width: 380px;
    max-width: 80%;
}
.modal-content p {
    margin: 0;
    padding: 0;
}

/* close button for modal dialog */
.close {
    color: rgb(170, 170, 170);
    float: right;
    position: relative;
    top: -25px;
    right: -10px;
    font-size: 34px;
    font-weight: bold;
}
.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}

.win-color {
    background-color: rgb(240, 240, 240);
}

            
          
!
            
              // with the help of this example https://codepen.io/janschreiber/pen/xZbEvM?q=tic+tac+toe&limit=all&type=type-pens

// EVENT BINDINGS

document.onkeypress = function (e) {
    e = e || window.event
    let modal = document.getElementsByClassName("modal")[0]
    if (e.keyCode === 27) {
        modal.style.display = "none"
    }
}

window.onclick = function (e) {
    const modal = document.getElementsByClassName("modal")[0]
    if (e.target === modal) {
        modal.style.display = "none"
    }
}

// HELPER FUNCTIONS

function sumArray(array) {
    let sum = 0
    let i = 0
    for (i = 0; i < array.length; i++) {
        sum += array[i]
    }
    return sum
}

function isInArray(element, array) {
    if (array.indexOf(element) > -1) {
        return true
    }
    return false
}

function shuffleArray(array) {
    let counter = array.length
    let temp
    let index
    
    while (counter > 0) {
        index = Math.floor(Math.random() * counter)
        counter--
        temp = array[counter]
        array[counter] = array[index]
        array[index] = temp
    }
    return array
}

function intRandom(min, max) {
    let rand = min + Math.random() * (max + 1 - min)
    return Math.floor(rand)
}

// GLOBAL VARIABLES
let moves = 0
let winner = 0
let x = 1
let o = 3
let player = x
let computer = o
let whoseTurn = x
let gameOver = false
let score = {
        ties: 0,
        player: 0,
        computer: 0
    }

let xText = `<span class="x">&times;</class>`
let oText = `<span class="o">o</class>`
let playerText = xText
let computerText = oText
let difficulty = 1
let myGrid = null


// GRID OBJECT

// Grid constructor

function Grid() {
    this.cells = new Array(9)
}

Grid.prototype.getFreeCellIndices = function () {
    let i = 0
    let resultArray = []
    for (i = 0; i < this.cells.length; i++) {
        if (this.cells[i] === 0) {
            resultArray.push(i);
        }
    }
    return resultArray
}

Grid.prototype.getRowValues = function (index) {
    if (index !== 0 && index !== 1 && index !== 2) {
        return undefined
    }
    let i = index * 3
    return this.cells.slice(i, i + 3)
};

Grid.prototype.getRowIndices = function (index) {
    if (index !== 0 && index !== 1 && index !== 2) {
        return undefined
    }
    let row = []
    index = index * 3
    row.push(index)
    row.push(index + 1)
    row.push(index + 2)
    return row
}

Grid.prototype.getColumnValues = function (index) {
    if (index !== 0 && index !== 1 && index !== 2) {
        return undefined
    }
    let i
    let column = []
    for (i = index; i < this.cells.length; i += 3) {
        column.push(this.cells[i])
    }
    return column
}

Grid.prototype.getColumnIndices = function (index) {
    if (index !== 0 && index !== 1 && index !== 2) {
        return undefined
    }
    let i
    let column = []
    for (i = index; i < this.cells.length; i += 3) {
        column.push(i)
    }
    return column
}

Grid.prototype.getDiagValues = function (arg) {
    let cells = []
    if (arg !== 1 && arg !== 0) {
        console.error("Wrong arg for getDiagValues!")
        return undefined
    } else if (arg === 0) {
        cells.push(this.cells[0])
        cells.push(this.cells[4])
        cells.push(this.cells[8])
    } else {
        cells.push(this.cells[2])
        cells.push(this.cells[4])
        cells.push(this.cells[6])
    }
    return cells
};

Grid.prototype.getDiagIndices = function (arg) {
    if (arg !== 1 && arg !== 0) {
        console.error("Wrong arg for getDiagIndices!")
        return undefined
    } else if (arg === 0) {
        return [0, 4, 8]
    } else {
        return [2, 4, 6]
    }
}

Grid.prototype.getFirstWithTwoInARow = function (agent) {
    if (agent !== computer && agent !== player) {
        return undefined
    }
    let sum = agent * 2
    let freeCells = shuffleArray(this.getFreeCellIndices())
    for (let i = 0; i < freeCells.length; i++) {
        for (let j = 0; j < 3; j++) {
            var rowV = this.getRowValues(j)
            var rowI = this.getRowIndices(j)
            var colV = this.getColumnValues(j)
            var colI = this.getColumnIndices(j)
            if (sumArray(rowV) == sum && isInArray(freeCells[i], rowI)) {
                return freeCells[i]
            } else if (sumArray(colV) == sum && isInArray(freeCells[i], colI)) {
                return freeCells[i]
            }
        }
        for (j = 0; j < 2; j++) {
            let diagV = this.getDiagValues(j)
            let diagI = this.getDiagIndices(j)
            if (sumArray(diagV) == sum && isInArray(freeCells[i], diagI)) {
                return freeCells[i]
            }
        }
    }
    return false
};

Grid.prototype.reset = function () {
    for (let i = 0; i < this.cells.length; i++) {
        this.cells[i] = 0
    }
    return true
};

// MAIN FUNCTIONS

function initialize() {
    myGrid = new Grid()
    moves = 0
    winner = 0
    gameOver = false
    whoseTurn = player
    for (let i = 0; i <= myGrid.cells.length - 1; i++) {
        myGrid.cells[i] = 0
    }
    setTimeout(showOptions, 500)
}

function assignRoles() {
    askUser("Do you want to go first?")
    document.getElementById("yesBtn").addEventListener("click", makePlayerX);
    document.getElementById("noBtn").addEventListener("click", makePlayerO);
}

function makePlayerX() {
    player = x
    computer = o
    whoseTurn = player
    playerText = xText
    computerText = oText
    document.getElementById("userFeedback").style.display = "none"
    document.getElementById("yesBtn").removeEventListener("click", makePlayerX)
    document.getElementById("noBtn").removeEventListener("click", makePlayerO)
}

function makePlayerO() {
    player = o
    computer = x
    whoseTurn = computer
    playerText = oText
    computerText = xText
    setTimeout(makeComputerMove, 400)
    document.getElementById("userFeedback").style.display = "none"
    document.getElementById("yesBtn").removeEventListener("click", makePlayerX)
    document.getElementById("noBtn").removeEventListener("click", makePlayerO)
}

function cellClicked(id) {
    let idName = id.toString()
    let cell = parseInt(idName[idName.length - 1])
    if (myGrid.cells[cell] > 0 || whoseTurn !== player || gameOver) {
        return false
    }
    moves += 1
    document.getElementById(id).innerHTML = playerText
    let rand = Math.random()
    if (rand < 0.3) {
        document.getElementById(id).style.transform = "rotate(180deg)"
    } else if (rand > 0.6) {
        document.getElementById(id).style.transform = "rotate(90deg)"
    }
    document.getElementById(id).style.cursor = "default"
    myGrid.cells[cell] = player
    if (moves >= 5) {
        winner = checkWin()
    }
    if (winner === 0) {
        whoseTurn = computer
        makeComputerMove()
    }
    return true
}

function restartGame(ask) {
    if (moves > 0) {
        var response = confirm("Are you sure you want to start over?");
        if (response === false) {
            return
        }
    }
    gameOver = false
    moves = 0
    winner = 0
    whoseTurn = x
    myGrid.reset()
    for (let i = 0; i <= 8; i++) {
        let id = "cell" + i.toString()
        document.getElementById(id).innerHTML = ""
        document.getElementById(id).style.cursor = "pointer"
        document.getElementById(id).classList.remove("win-color")
    }
    if (ask === true) {
        setTimeout(showOptions, 200)
    } else if (whoseTurn == computer) {
        setTimeout(makeComputerMove, 800)
    }
}

function makeComputerMove() {
    if (gameOver) {
        return false
    }
    let cell = -1
    let myArr = []
    let corners = [0,2,6,8]
    if (moves >= 3) {
        cell = myGrid.getFirstWithTwoInARow(computer)
        if (cell === false) {
            cell = myGrid.getFirstWithTwoInARow(player)
        }
        if (cell === false) {
            if (myGrid.cells[4] === 0) {
                cell = 4
            } else {
                myArr = myGrid.getFreeCellIndices();
                cell = myArr[intRandom(0, myArr.length - 1)]
            }
        }
        // Avoid a catch-22 situation:
        if (moves == 3 && myGrid.cells[4] == computer && player == x) {
            if (myGrid.cells[7] == player && (myGrid.cells[0] == player || myGrid.cells[2] == player)) {
                myArr = [6,8]
                cell = myArr[intRandom(0,1)]
            }
            else if (myGrid.cells[5] == player && (myGrid.cells[0] == player || myGrid.cells[6] == player)) {
                myArr = [2,8]
                cell = myArr[intRandom(0,1)]
            }
            else if (myGrid.cells[3] == player && (myGrid.cells[2] == player || myGrid.cells[8] == player)) {
                myArr = [0,6]
                cell = myArr[intRandom(0,1)]
            }
            else if (myGrid.cells[1] == player && (myGrid.cells[6] == player || myGrid.cells[8] == player)) {
                myArr = [0,2]
                cell = myArr[intRandom(0,1)]
            }
        }
        else if (moves == 3 && myGrid.cells[4] == player && player == x) {
            if (myGrid.cells[2] == player && myGrid.cells[6] == computer) {
                cell = 8
            }
            else if (myGrid.cells[0] == player && myGrid.cells[8] == computer) {
                cell = 6
            }
            else if (myGrid.cells[8] == player && myGrid.cells[0] == computer) {
                cell = 2
            }
            else if (myGrid.cells[6] == player && myGrid.cells[2] == computer) {
                cell = 0
            }
        }
    } else if (moves === 1 && myGrid.cells[4] == player) {
        // if player is X and played center, play one of the corners
        cell = corners[intRandom(0,3)]
    } else if (moves === 2 && myGrid.cells[4] == player && computer == x) {
        // if player is O and played center, take two opposite corners
        if (myGrid.cells[0] == computer) {
            cell = 8
        }
        else if (myGrid.cells[2] == computer) {
            cell = 6
        }
        else if (myGrid.cells[6] == computer) {
            cell = 2
        }
        else if (myGrid.cells[8] == computer) {
            cell = 0
        }
    } else if (moves === 0 && intRandom(1,10) < 8) {
        // if computer is X, start with one of the corners sometimes
        cell = corners[intRandom(0,3)]
    } else {
        // choose the center of the board if possible
        if (myGrid.cells[4] === 0) {
            cell = 4
        } else {
            myArr = myGrid.getFreeCellIndices();
            cell = myArr[intRandom(0, myArr.length - 1)]
        }
    }
    let id = "cell" + cell.toString()
    document.getElementById(id).innerHTML = computerText
    document.getElementById(id).style.cursor = "default"

    let rand = Math.random()
    if (rand < 0.3) {
        document.getElementById(id).style.transform = "rotate(180deg)"
    } else if (rand > 0.6) {
        document.getElementById(id).style.transform = "rotate(90deg)"
    }
    myGrid.cells[cell] = computer
    moves += 1
    if (moves >= 5) {
        winner = checkWin()
    }
    if (winner === 0 && !gameOver) {
        whoseTurn = player
    }
}

function checkWin() {
    winner = 0

    // rows
    for (let i = 0; i <= 2; i++) {
        let row = myGrid.getRowValues(i)
        if (row[0] > 0 && row[0] == row[1] && row[0] == row[2]) {
            if (row[0] == computer) {
                score.computer++
                winner = computer
            } else {
                score.player++
                winner = player
            }

            let tmpAr = myGrid.getRowIndices(i)
            for (let j = 0; j < tmpAr.length; j++) {
                let str = "cell" + tmpAr[j]
                document.getElementById(str).classList.add("win-color")
            }
            setTimeout(endGame, 1000, winner)
            return winner
        }
    }

    // columns
    for (i = 0; i <= 2; i++) {
        let col = myGrid.getColumnValues(i)
        if (col[0] > 0 && col[0] == col[1] && col[0] == col[2]) {
            if (col[0] == computer) {
                score.computer++
                winner = computer
            } else {
                score.player++
                winner = player
            }

            let tmpAr = myGrid.getColumnIndices(i)
            for (let j = 0; j < tmpAr.length; j++) {
                let str = "cell" + tmpAr[j]
                document.getElementById(str).classList.add("win-color")
            }
            setTimeout(endGame, 1000, winner)
            return winner
        }
    }

    // diagonals
    for (i = 0; i <= 1; i++) {
        let diagonal = myGrid.getDiagValues(i)
        if (diagonal[0] > 0 && diagonal[0] == diagonal[1] && diagonal[0] == diagonal[2]) {
            if (diagonal[0] == computer) {
                score.computer++
                winner = computer
            } else {
                score.player++
                winner = player
            }

            let tmpAr = myGrid.getDiagIndices(i)
            for (var j = 0; j < tmpAr.length; j++) {
                let str = "cell" + tmpAr[j]
                document.getElementById(str).classList.add("win-color")
            }
            setTimeout(endGame, 1000, winner)
            return winner
        }
    }

    let myArr = myGrid.getFreeCellIndices()
    if (myArr.length === 0) {
        winner = 10
        score.ties++
        endGame(winner)
        return winner
    }

    return winner
}

function announceWinner(text) {
    document.getElementById("winText").innerHTML = text
    document.getElementById("winAnnounce").style.display = "block"
    setTimeout(closeModal, 1400, "winAnnounce")
}

function askUser(text) {
    document.getElementById("questionText").innerHTML = text
    document.getElementById("userFeedback").style.display = "block"
}

function showOptions() {
    if (player == o) {
        document.getElementById("rx").checked = false
        document.getElementById("ro").checked = true
    }
    else if (player == x) {
        document.getElementById("rx").checked = true
        document.getElementById("ro").checked = false
    }
    document.getElementById("optionsDlg").style.display = "block"
}

function getOptions() {
    if (document.getElementById('rx').checked === true) {
        player = x
        computer = o
        whoseTurn = player
        playerText = xText
        computerText = oText
    }
    else {
        player = o
        computer = x
        whoseTurn = computer
        playerText = oText
        computerText = xText
        setTimeout(makeComputerMove, 400)
    }
    document.getElementById("optionsDlg").style.display = "none"
}

function closeModal(id) {
    document.getElementById(id).style.display = "none"
}

function endGame(who) {
    if (who == player) {
        announceWinner("Congratulations, you won!")
    } else if (who == computer) {
        announceWinner("Computer wins!")
    } else {
        announceWinner("It's a tie!")
    }
    gameOver = true
    whoseTurn = 0
    moves = 0
    winner = 0
    document.getElementById("computer_score").innerHTML = score.computer
    document.getElementById("tie_score").innerHTML = score.ties
    document.getElementById("player_score").innerHTML = score.player
    for (let i = 0; i <= 8; i++) {
        let id = "cell" + i.toString()
        document.getElementById(id).style.cursor = "default"
    }
    setTimeout(restartGame, 800)
}

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console