Human Vs Computer Tic-tac-toe Game Using Js



Now you can create the Tic-Tac-Toe game using JS.In this blog we will teach you how to create tic-tac-toe game Human Vs Computer.

<!DOCTYPE html>
    <html>
        <head>
            <title>Tic-tac-toe Game</title>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-
              sweetalert2/10.6.1/sweetalert2.all.min.js"></script>
            <link src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/10.6.1/sweetalert2.min.css">
            </link> 
        <style type="text/css">
            body{
                  background: #212121;
                  color: #666;
            }
            h1{
                  text-align: center;
                  color: #fff;
            }
            .clearfix{
                  clear: both;
            }
            #box{
                  width: 350px;
                  overflow: auto;
                  margin: 40px auto;
                  background: #666;
                  padding-bottom: 40px;
                  border-radius: 10px;
            }
            #message{
                  background: #333;
                  color: #fff;
            }
            #gameBoard li{
                  float: left;
                  margin: 10px;
                  height: 70px;
                  width: 70px;
                  font-size: 50px;
                  background: #333;
                  color: #ccc;
                  list-style: none;
                  text-align: center;
                  border-radius: 5px;
            }
            #gameBoard li:hover, #reset:hover{
                  cursor: pointer;
                  background: #000;
            }
            #reset{
                  border: 0;
                  background: #444;
                  color: #fff;
                  width: 70%;
                  padding: 15px;
                  border-radius: 5px;
            }
            .o{
                  color: green !important;
            }
           .x{
                  color: red !important;
            }
            footer{
                  display: block;
                  text-align: center;
                  padding-top: 20px;
           }
        </style>
        </head> 
        <body>
                <div class="text-center" id="box">
                      <header>
                            <h1>Play Tic Tac Toe</h1>
                      </header>
                      <div id="message"<div>
                      <ul id="gameBoard"
                              <li class="ticid="0">#<li>
                              <li class="ticid="1">#<li>
                              <li class="ticid="2">#<li>
                              <li class="ticid="3">#<li>
                              <li class="ticid="4">#<li>
                              <li class="ticid="5">#<li>
                              <li class="ticid="6">#<li>
                              <li class="ticid="7">#<li>
                              <li class="ticid="8">#<li>
                      <ul>
                     <div id="clearfix"></div>
                </div>
        </body>
       <script type="text/javascript">
            localStorage['clicked'] = 'no';
            var myVar = localStorage['selected'];
        
           $('.tic').click(function (e) {
    e.preventDefault();
        if ($(this).find('input').length == 0) {
    var symbol  = localStorage['value'];
    var clicked = localStorage['clicked'];
    var id = $(this).attr('id');
        if (clicked == 'no') {
    if (symbol == 'X') {
var symbols = 'O';
    } else {
var symbols = 'X';
    }
 computerTurn(symbol,id,symbols);
$('#'+id).html("<input type='hidden' value='"+symbol+"' class='addedValue'>"+symbol);
        } else {
    localStorage['clicked'] = 'yes';
    return;
        }
        } else {
    alert('Please select another box.');
        }
        });

        function getRandomString(length,randomChars) {
                var result = '';
                for ( var i = 0; i < length; i++ ) {
                       result += randomChars.charAt(Math.floor(Math.random() * randomChars.length));
                }
                return result;
        }

        function computerTurn(symbol,id,computerSyb) {
            localStorage['clicked'] = 'no';
            var ranStr = '';
            setTimeout( function(){
            $('.tic').each(function (i) {
        if ($(this).find('input').length == 0) {
                ranStr += $(this).attr('id');
                }
            })

    var addSyb = getRandomString(1,ranStr);
    $('.tic').each(function (i) {
        if ($(this).find('input').length > 0) {
        $('#'+addSyb).html("<input type='hidden' value='"+computerSyb+"' 
                                    class='addedValue'>"+computerSyb);
        }
    })
var checkWinPro = new Array(["0","1","2"],["3","4","5"],["6","7","8"],["0","3","6"],
                                                ["1","4","7"],["2","5","8"],["0","4","8"],["6","4","2"],["2","4","6"],
                                                ["8","4","0"],["2","1","0"],["5","4","3"],["8","7","6"],["6","3","0"],
                                                ["7","4","1"],["8","5","2"]);
var oLen = 0;
var xLen = 0;
var oAry = [];
var xAry = [];
var oVal = '';
var xVal = '';
$('.tic .addedValue').each(function (i) {
if ($(this).val() == 'O') {
oAry.push($(this).parent().attr('id'));
oLen += $(this).val().length;
oVal = $(this).val();
}else if ($(this).val() == 'X') {
xAry.push($(this).parent().attr('id'));
xLen += $(this).val().length; 
xVal = $(this).val();
}
})

$.each(checkWinPro,function(i,index){
    if ((checkWinPro[i].toString() == oAry.toString()) && oLen >= 3) {
    if (oVal == computerSyb) {
    alert('Computer has won.');
    localStorage['clicked'] = 'no';
    localStorage['selected'] = 'no';
    location.reload();
    return false;
    }else if (oVal == symbol) {
    alert('You has won.');
    localStorage['clicked'] = 'no';
    localStorage['selected'] = 'no';
    location.reload();
    return false;
    }
    }else if(checkWinPro[i].toString() == xAry.toString() && xLen >= 3){
    if (xVal == computerSyb) {
    alert('Computer has won.');
    localStorage['clicked'] = 'no';
    localStorage['selected'] = 'no';
    location.reload();
    return false;
    }else if (xVal == symbol) {
    alert('You has won.');
    localStorage['clicked'] = 'no';
    localStorage['selected'] = 'no';
    location.reload();
    return false;
    }

    }
})
}  , 100 );
}
if (myVar != 'yes') {
Swal.fire({
  title: 'Select symbol',
  input: 'radio',
  inputOptions: {
    'X': 'X',
    'O': 'O',
  },
  inputPlaceholder: 'Select symbol',
  allowOutsideClick: false,
  showCancelButton: true,
  inputValidator: function (value) {
    return new Promise(function (resolve, reject) {
      if (value == 'X' || value == 'O') {
        resolve()
      } else {
        reject('You need to select symbol')
      }
    })
  }
}).then(function (result) {
if (result.isConfirmed == true) {
localStorage['selected'] = 'yes';
localStorage['value'] = result.value;
  Swal.fire({
    icon: 'success',
    html: 'You selected: ' + result.value
  })
}
}).catch(swal.noop);
}
       </script>
</html>

Post a Comment

0 Comments