Ejemplo n.º 1
0
  /**
   * Starts a game of TicTacToe
   *
   * @return
   */
  private Player startGame() {

    display.out(board.toString());
    Player winningPlayer = new Player(0, R.none);
    Player currentPlayer = player1;
    boolean isPlaying = true;

    while (isPlaying) {

      if (!currentPlayer.isAI()) {
        board.addPlayerAt(playerMove(), currentPlayer);
      } else {
        try {
          Thread.sleep(1000);
        } catch (Exception e) {
          System.out.print(e.getMessage());
        }
        board.addPlayerAt(compMove(), currentPlayer);
      }
      if (board.testVictory()) {
        isPlaying = false;
        winningPlayer = currentPlayer;
        display.out(String.format(R.winnerIs, winningPlayer.getName()));
      } else if (testDraw()) {
        isPlaying = false;
        display.out(R.draw);
      } else {
        currentPlayer = (currentPlayer == player1) ? player2 : player1;
      }
      display.out(board.toString());
    }
    return winningPlayer;
  }
Ejemplo n.º 2
0
 /**
  * Ask and returns for player for a move
  *
  * @return players move
  */
 private int playerMove() {
   display.out(R.playerMove);
   int move = -1;
   while (move == -1) {
     try {
       move = Integer.parseInt(br.readLine());
     } catch (Exception e) {
       System.out.println(e.getMessage());
     }
     if ((move < 1 || move > 9) || !board.isEmptyAt(move - 1)) {
       display.out(R.invalidMove);
       move = -1;
     }
   }
   return move - 1;
 }
Ejemplo n.º 3
0
 /**
  * Gets and returns a AI move
  *
  * @return
  */
 private int compMove() {
   int compMove = CompAI.bestMove(board, player2, player1);
   while (!board.isEmptyAt(compMove)) {
     compMove = CompAI.bestMove(board, player2, player1);
   }
   display.out(String.format(R.compPlays, compMove));
   return compMove;
 }
Ejemplo n.º 4
0
 private char antherGame(String question) {
   display.out(question);
   try {
     String antherGame = br.readLine();
     return (antherGame != null) ? antherGame.charAt(0) : 'n';
   } catch (Exception e) {
     System.out.println(e.getMessage());
   }
   return 'n';
 }
Ejemplo n.º 5
0
  public void startMatch() {

    if (antherGame(R.StartQuestion) == n) {
      return;
    }
    player1 = new Player(1, R.player1Name, false, R.player1Mark);
    player2 = new Player(2, R.player2Name, true, R.player2Mark);
    board = new Board(player1, player2);

    display.out(R.instructions);
    display.out(R.numPad);
    display.out(R.begin);

    do {
      board.reset();
      Player winningPlayer = startGame();
      winningPlayer.addWin();
      display.score(winningPlayer, player1, player2);
      display.out(board.toString());
    } while (antherGame(R.startAnotherGame) != R.n);

    display.out(R.gameOver);
    ;
  }