Tic Tac Toe Game

In this example below you will see how to do a Tic Tac Toe Game with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by duy12, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright duy12 ©

Technologies

  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Tic Tac Toe Game</title>
  
  
  <link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css'>

      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <div class="container">
    <div class="row">
      <div id="root" class="col-sm-4 col-sm-offset-4">
        <div class="row">
          <div id="board">
            <ul class="clearfix text-center">
              <li class="col-xs-4" v-for="(item, index) in board">
                <i @click="addMove(index)" v-if=" item != 'x' && item != 'o' ">&nbsp;</i>
                <i @click="addMove(index)" v-else>{{ item }}</i>
              </li>
            </ul>
            <transition name="fade">
              <div class="choose" v-if="start">
                <p>Would you like to be X or O?</p>
                <p>
                  <span @click="choose('x')" class="sym">X</span>
                  <span @click="choose('o')" class="sym">O</span>
                </p>
              </div>
            </transition>
            <transition name="fade">
              <div class="wrapper" v-if="end">
                <div class="end">
                  <p class="result">{{ result }}</p>
                </div>
              </div>
            </transition>
          </div>
        </div>
      </div>
    </div>
  </div>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/duy12/tic-tac-toe-game-EbeRyE */
body {
    padding-top: 40px;
}
#board {
    position: relative;
}
.wrapper{
    height: 100%;
    width: 100%;
    position: absolute;
    top: 0;
    /* background: rgba(255, 255, 255, 0.1); */
    background-color: rgba(0,0,0,0.7);
    z-index: 5;
}
.highlight {
    background: #000;
}
.highlight i {
    color: greenyellow;
}
.end{
    display: table;
    position: absolute;
    top: 0;
    z-index: 10;
    height: 100%;
    width: 100%;
    color: #fff;
    text-align: center;
    font-size: 2.5em;
    padding: 20px;
    box-sizing: border-box;
}
.result {
    display: table-cell;
    vertical-align: middle;
}
.choose{
    position: absolute;
    top: 0;
    z-index: 10;
    height: 100%;
    width: 100%;
    background-color: grey;
    color: #fff;
    text-align: center;
    font-size: 3em;
    padding: 40px;
    box-sizing: border-box;
}
.choose span{
    font-size: 1.5em;
    font-weight: bold;
    cursor: pointer;
    margin-left: 10px;
    padding:5px 10px;
    border: 1px solid transparent;
}
.sym:hover {
    border: 1px dashed #fff;
    border-radius: 30%;
}
ul.clearfix {
    background-color: rgba(31, 61, 48, 1);
    padding-left: 0;
}
li {
    list-style: none;
    border-right: 1px solid rgba(201, 209, 205, 1);
    border-bottom: 1px solid rgba(201, 209, 205, 1);
    cursor: pointer;
}
li i {
    display: block;
    font-style: normal;
    font-family: "Architects Daughter", "Helvetica", "sans-serif";
    font-size: 8.5rem;
    color: rgba(220,220,220,.7);
}
.fade-enter-active, .fade-leave-active {
    transition: opacity 1s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
    opacity: 0;
}

/*Downloaded from https://www.codeseek.co/duy12/tic-tac-toe-game-EbeRyE */
app = new Vue({
    el: '#root',
    data: {
        // board: [0, 1, 'o', 'o', 4, 'o', 6, 'x', 'x'],
        board: [0, 1, 2, 3, 4, 5, 6, 7, 8],
        player: 'x',
        computer: 'o',
        start: true,
        end: false,
        result: '',
        x: 9999,
        first: false
    },
    mounted: function () {
        this.comFirst();

    },
    methods: {
        comFirst: function () {
            var rd = Math.floor((Math.random() * 2) + 1);console.log(rd);
            this.first = rd == 1 ? true : false;

            if (this.first) {
                var random = Math.floor((Math.random() * 2) + 1),
                    move;
                if (random == 1) {
                    move = 4;
                } else {
                    let arr = [0, 2, 6, 8],
                        k = Math.floor((Math.random() * 4));
                    move = arr[k];
                }
                // addmove
                this.board[move] = this.computer;
                document.getElementsByTagName('i')[move].innerHTML = this.computer;
            }

        },
        choose: function (symbol) {
            this.player = symbol;
            this.computer = symbol == 'x' ? 'o' : 'x';
            this.start = false;
        },
        reset: function () {
            this.board = [0, 1, 2, 3, 4, 5, 6, 7, 8];
            var arr = document.getElementsByTagName('i');
            for (let i = 0; i < arr.length; i++)
                arr[i].innerHTML = "&nbsp;";
            this.end = false;
            if(this.x != 9999)
                this.highlight(this.x);

            setTimeout(this.comFirst, 500);


        },
        endGame: function (result) {
            this.end = true;
            this.result = result;
        },
        highlight: function (index) {
            var indexes = [0, [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]];
            var listNode = document.getElementsByTagName('li');
            if (this.end) {
                indexes[index].forEach(function (i) {
                    listNode[i].classList.add("highlight");
                });
            } else {
                indexes[index].forEach(function (i) {
                    listNode[i].classList.remove("highlight");
                });
            }
        },
        addMove: function (k) {
            if (this.board[k] == k) {
                this.board[k] = this.player;
                document.getElementsByTagName('i')[k].innerHTML = this.board[k];
                if (this.winning(this.board, this.player) !== false) {
                    setTimeout(this.endGame("You win!"), 300);
                    this.x = this.winning(this.board, this.player);
                    this.highlight(this.x);
                    setTimeout(this.reset, 2500);
                } else if (this.checkTie(this.board)) {
                    setTimeout(this.endGame("Tie game!"), 300);
                    setTimeout(this.reset, 2500);
                } else {
                    var move = this.findBestMove(this.board);
                    // addmove
                    this.board[move] = this.computer;
                    document.getElementsByTagName('i')[move].innerHTML = this.computer;
                    if (this.winning(this.board, this.computer)) {
                        setTimeout(this.endGame("You lose!"), 300);
                        this.x = this.winning(this.board, this.computer);
                        this.highlight(this.x);
                        setTimeout(this.reset, 2500);
                    } else if (this.checkTie(this.board)) {
                        setTimeout(this.endGame("Tie game!"), 300);
                        setTimeout(this.reset, 2500);
                    }
                }
            }
        },
        winning: function (board, player) {
            if (board[0] == player && board[1] == player && board[2] == player)
                return 1;
            else if (board[3] == player && board[4] == player && board[5] == player)
                return 2;
            else if (board[6] == player && board[7] == player && board[8] == player)
                return 3;
            else if (board[0] == player && board[3] == player && board[6] == player)
                return 4;
            else if (board[1] == player && board[4] == player && board[7] == player)
                return 5;
            else if (board[2] == player && board[5] == player && board[8] == player)
                return 6;
            else if (board[0] == player && board[4] == player && board[8] == player)
                return 7;
            else if (board[2] == player && board[4] == player && board[6] == player)
                return 8;
            else
                return false;
        },
        findBestMove: function (board) {
            var bestMove,
                bestScore = -1000;
            for (let i = 0; i < board.length; i++) {
                if (board[i] != 'x' && board[i] != 'o') {
                    board[i] = this.computer;// make the move

                    var val = this.minimax(board, this.player, -1000, 1000);
                    board[i] = i; //undo move

                    if (val > bestScore) {
                        bestScore = val;
                        bestMove = i;
                    }
                }
            }
            return bestMove;
        },
        checkTie: function (board) {
            for (let i = 0; i < board.length; i++) {
                if (board[i] != 'x' && board[i] != 'o') {
                    return false;
                }
            }
            return true;
        },
        minimax: function (newBoard, player, alpha, beta) {
            if (this.winning(newBoard, this.player))
                return -10;
            else if (this.winning(newBoard, this.computer))
                return 10;
            else if (this.checkTie(newBoard) === true)
                return 0;

            if (player == this.computer) {
                var best = -1000;
                for (let i = 0; i < newBoard.length; i++) {
                    if (newBoard[i] != 'x' && newBoard[i] != 'o') {
                        newBoard[i] = player;
                        best = Math.max(best, this.minimax(newBoard, this.player, alpha, beta));//console.log(best);
                        alpha = Math.max(alpha, best);
                        newBoard[i] = i;
                        if (beta <= alpha)
                            break;
                    }
                }
                return best;
            } else {
                var best = 1000;
                for (let i = 0; i < newBoard.length; i++) {
                    if (newBoard[i] != 'x' && newBoard[i] != 'o') {
                        newBoard[i] = player;
                        best = Math.min(best, this.minimax(newBoard, this.computer, alpha, beta));
                        beta = Math.min(beta, best);
                        newBoard[i] = i;
                        if (beta <= alpha)
                            break;
                    }
                }
                return best;
            }
        }
    }
});

Comments