Skip to content Skip to sidebar Skip to footer

How To Alert Winner In Tic Tac Toe?

I am having trouble trying to alert the winner, among other things. I also am trying to alert when the user trys to click on a button that has already been pressed, but have no ide

Solution 1:

This is what i came up with:

function isGameOver() {
  for (var i = 0; i < grid.length; i++) {

      if(grid[i][0] == grid[i][1] && grid[i][0]==grid[i][2] && grid[i][0]!=0){
        alert(grid[i][0]+" Wins");
        _win=1;
        return;
      }
  }
  for (var i = 0; i < grid.length; i++) {

      if(grid[0][i] == grid[1][i] && grid[0][i]==grid[2][i]  && grid[0][i]!=0){
        alert(grid[0][i]+" Wins");
        _win=1;
        return;
      }
  }

  if(grid[0][0]==grid[1][1] && grid[0][0] == grid[2][2]  && grid[0][0]!=0){
    alert(grid[0][0]+" Wins");
    _win=1;
        return;
  }

  if(grid[0][2]==grid[1][1] && grid[0][2] == grid[2][0]  && grid[2][0]!=0){
    alert(grid[1][1]+" Wins");
    _win=1;
        return;
  }

}

Working fiddle

This will check whether data in a single column or in a single row or in diagonals should be same. And if a user wins then he can not click on anything else.

Solution 2:

By using lodash, you can abstract a bunch of the pieces of this. I went ahead and re-coded it to show you how I'd do it. This will allow you to make the board whatever size you want and allow for up to 4 players.

enter image description here

Here's a jsfiddle:

https://jsfiddle.net/mckinleymedia/gqqse6cw/18/

Here's all the HTML you need:

<divclass="gameboard"></div>

Here's the script:

var game = function( options ){
  options = options || [];
  var target = options.target || '.gameboard',
      size = options.size || [ 3, 3 ],
      players = options.players || 2,
      toWin = options.toWin || 3,
      symbols = [ 'o', 'x', '+', '!' ],
      current,
      grid,
      setup = function () {
        $(target).empty();
        current = 0;
        grid = [];
        _.each(_.range(size[0]), function(r) {
          var row = $('<div>')
          .addClass('row');
          grid.push([]),
            _.each(_.range(size[1]), function(c) {
            grid[r].push(undefined),
              row.append( 
              $('<button>')
              .addClass('square open')
              .attr('data-pos',r + ',' + c)
              .html('&nbsp;')
            );
          })
          $(target).append(row );
        });
        $(target).append(
          $('<div>')
          .addClass('player')
          .append(
            $('<span>')
            .html('Player')
          )
          .append(
            $('<span>')
            .addClass('symbol')
            .html(symbols[0])
          )
        );
        $('.square').click( function(){ 
          if (!($(this).hasClass('disabled'))) makeMove(this) 
            });
      },
      makeMove = function (btn) {
        var btn = $(btn)
        .addClass('disabled')
        .html(symbols[current]),
            pos = btn.attr('data-pos').split(',');
        grid[pos[0]][pos[1]] = current;
        checkBoard();
      },
      checkBoard = function () {
        var winners = [];
        checkArray()
        winners = checkArray(grid,winners); // check rows
        winners = checkArray(_.zip.apply(_, grid) ,winners,'vert'); // check columnsvar diag = [],
            diagReverse = [],
            i = 0,
            di = 0,
            map = [],
            mapR = [];
        _.each(grid, function(g, gk){
          _.each(g, function(cell, ck){
            di = ck + i;
            diag[di] = diag[di] || [];
            diagReverse[di] = diagReverse[di] || [];
            map[di] = map[di] || [];
            mapR[di] = mapR[di] || [];
            diag[di].push(grid[gk][ck]);
            diagReverse[di].push( grid[ grid.length - gk - 1 ][ ck ]
                                );
            map[di].push([gk,ck]);
            mapR[di].push([(grid.length - gk - 1), ck]);
          });
          i++;
        });
        winners = checkArray(diag ,winners, map); // check diagonal
        winners = checkArray(diagReverse ,winners, mapR); // check reverse diagonalif ( winners.length > 0 ) playerWin(winners);
        current++;
        current = current % players;
        $(target + ' .symbol')
          .html(symbols[current]);      
      },
      checkArray = function (arr,winners,map) {
        map = map || 0;
        var winner = [],
            setRow = [],
            count = 0,
            cur = -1;
        _.each(arr, function(g, key){
          count = 0;
          _.each(g, function(cell, ckey){
            if (cell===undefined || cell !== cur) {
              count = 0;
              setRow = [];
            }
            cur = cell;
            count++;
            if (map) {
              if ( map === 'vert'){
                setRow.push([ckey,key]);
              } elseif ( _.isArray(map)) {
                setRow.push([map[key][ckey]]);
              }
            } else {
              setRow.push([key,ckey]);
            }
            if (count >= toWin) winner = winner.concat(setRow);
          });
        });
        if ( winner.length > 0 ) winners = winners.concat(winner);
        return winners;
      },
      playerWin = function (winners) {
        $('.gameboard button')
          .addClass('disabled');
        _.each(winners, function(w){
          $('.gameboard button[data-pos="' + w.join() + '"]')
            .addClass('win');
        });
        $(target).append(
          $('<div>')
          .addClass('winner')
          .append(
            $('<h1>')
            .html('Congratulations, player ' + symbols[current] + '!')
          )
          .append(
            $('<button>')
            .addClass('replay')
            .html('Play Again?')
          )
        );
        $('.replay').click ( function(){
          setup();
        });
      };
  setup();
}
game();

Post a Comment for "How To Alert Winner In Tic Tac Toe?"