Source: logic/LogicBoard.js

/**
 * @author    Wolfgang Kowarschick <kowa@hs-augsburg.de>
 * @copyright 2017 - 2018
 * @license   CC-BY-NC-SA-4.0
 */

/**
 * @class
 */
class LogicBoard
{ /**
   * @param {Array.<Array.<ModelToken>>} p_board
   */
  constructor(p_board)
  { this.v_board = p_board;
    this.v_next   = { 'cross': 'circle', 'circle': 'cross' };
    this.v_player = 'cross';

    this.reset();
  }
  
  /**
   * @method LogicBoard#reset
   * @description
   *   Resets the board.
   */
  reset()
  { const
      c_board            = this.v_board,
      c_lines_horizontal = [[],[],[]],
      c_lines_vertical   = [[],[],[]],
      c_lines_diagonal   = [[],[]];
     
    for (let i=0; i<3; i++)
    { for (let j=0; j<3; j++)
      { c_lines_horizontal[j].push({i: i, j: j, owner: null});
        c_lines_vertical[i]  .push({i: i, j: j, owner: null});
      }
      c_lines_diagonal[0].push({i: i, j: i,   owner: null});
      c_lines_diagonal[1].push({i: i, j: 2-i, owner: null});
    }
    
    for (let i=0; i<3; i++ )
    { for (let j=0; j<3; j++ )
      { c_board[i][j].reset(); }
    }
    
    for (let l_line of         c_lines_horizontal
                        .concat(c_lines_vertical)
                        .concat(c_lines_diagonal)
        )
    { for (let l_cell of l_line)
      { c_board[l_cell.i][l_cell.j].lines.push(l_line); }
    }
  }
  
  /**
   * @method mLogicBoard#move
   * @description
   *   Does one move of the game.
   * @param {ModelToken} p_token
   */
  move(p_token)
  { const 
      c_board       = this.v_board,
      c_player      = this.v_player,
      c_next_player = this.v_next[c_player],
      c_lines       = p_token.lines;
  
    if (c_player === '') // game over, don't handle moves any longer
    { return; }
  
    if (p_token.type === '')
    // the square is empty (otherwise the move is ignored)
    { p_token.type = c_player; // put the player's token on the square
      
      // test whether this move was a winner move
      let l_winner_line;
      for (let l_line of c_lines)
      { l_winner_line = l_line;
      
        for (let l_cell of l_line)
        { if (l_cell.i === p_token.i && l_cell.j === p_token.j)
          { // c_player is the new owner of the line
            l_cell.owner = c_player;
          }
          else if (l_cell.owner !== c_player)
          { // this line surely is no winner line
            l_winner_line = null;
          }
        }

        if (l_winner_line != null) // game over
        { // display the winner tokens by making them bold
          for (let l_cell of l_winner_line)
          { c_board[l_cell.i][l_cell.j].type = c_player + 'Bold'; }
        
          // disable playing further by removing the current player
          this.v_player = '';
        }
        else // it's the next player's turn
        { this.v_player = c_next_player; }
      }
    }
  }
}

/** @ignore */
export {LogicBoard};