Example #1
0
  public static void main(String[] args) {
    TicTacToe ticTacToe = new TicTacToe(3);

    ticTacToe.play(6);
    ticTacToe.play(3);
    ticTacToe.play(7);
    ticTacToe.play(4);
    ticTacToe.play(8);

    ticTacToe.printBoard();
  }
Example #2
0
 private void doMove(Integer i) {
   if (i == 6) game.move(0, 0);
   else if (i == 3) game.move(0, 1);
   else if (i == 0) game.move(0, 2);
   else if (i == 7) game.move(1, 0);
   else if (i == 4) game.move(1, 1);
   else if (i == 1) game.move(1, 2);
   else if (i == 8) game.move(2, 0);
   else if (i == 5) game.move(2, 1);
   else if (i == 2) game.move(2, 2);
 }
  public static void main(String args[]) {
    // set up game
    TicTacToe game = new TicTacToe();

    // load interface
    // T3Interface t3interface = new T3TextInterface(game);
    T3Interface t3interface = new T3GraphicInterface(game);

    // set interface
    game.setInterface(t3interface);

    // play game
    game.play();
  }
Example #4
0
  private List<TicTacToe> generate(TicTacToe state) {
    List<TicTacToe> states = new ArrayList<>();

    if (!isEnd(state))
      for (int i = 0; i < 9; i++)
        if (state.grid[i] == 0) {
          TicTacToe state1 = new TicTacToe();
          state1.player = (char) ('O' + 'X' - state.player);
          state1.grid = Arrays.copyOf(state.grid, 9);
          state1.grid[i] = state.player;
          states.add(state1);
        }

    return states;
  }
Example #5
0
 public void actionPerformed(ActionEvent e) {
   // handles the actions
   if (restart == e.getSource()) {
     Integer mode = game.getMode();
     if (mode == 1) {
       System.out.println("user");
     } else if (mode == 2) {
       System.out.println("bot");
     }
   } else {
     for (int i = 0; i < 9; i++)
       if (button[i] == e.getSource()) {
         if (game.isGameOver()) label.setText("The game is OVER!");
         else if (button[i].getText() == "") doMove(i);
         else label.setText("That cell is occupied!");
       }
   }
 }
  public String selectPlayers(String[] nameList) {
    String playersName;

    this.displayNameList(); // display the list of names

    // if one player game
    if (Game.ONE_PLAYER.equals(this.game.getGameType())) {
      System.out.println("\tPlease enter the number of the player.");

      // get the players name
      playersName = this.getName(TicTacToe.getNameList());

      if (playersName == null) {
        return Game.QUIT;
      }
      this.game.getPlayerA().setName(playersName);
      this.game.getPlayerB().setName("Computer");
    }

    // else two player game
    else {
      System.out.println("\tPlease enter the number of the first player.");
      // get first players name
      playersName = this.getName(TicTacToe.getNameList());
      if (playersName == null) {
        return Game.QUIT;
      }
      this.game.getPlayerA().setName(playersName);

      // get the second players name
      System.out.println("\tPlease enter the number of the second player.");
      playersName = this.getName(TicTacToe.getNameList());
      if (playersName == null) {
        return Game.QUIT;
      }
      this.game.getPlayerB().setName(playersName);
    }

    return Game.CONTINUE;
  }
  /**
   * find the move that the neural network most likely wants to do
   *
   * @return
   */
  public int getMove() {
    int move = -1;
    double tendancy = -2; /*
		for(int i = 0; i < nn.getInputLayer().getNumNeurons(); i++) {
			nn.setInput(i, ttt.getBoard()[i]);
		//	System.out.println("input "+ttt.getBoard()[i]);
		}
		nn.feedForward();
		for(int i = 0; i < nn.getOutputLayer().getNumNeurons(); i++) {
			System.out.println("output "+i+" : "+nn.getOutput(i));
			if(Math.abs(ttt.getBoard()[i] - nn.getOutput(i)) > 0.2) {
				if(ttt.getBoard()[i] == 0) {
					move = i;
				}
				
			}
		}	*/
    // System.out.println("Neural network picks "+move);

    for (int i = 0; i < nntool.getNN().getInputLayer().getNumNeurons(); i++) {
      nntool.getNN().setInput(i, ttt.getBoard()[i]);
    }
    nntool.getNN().feedForward();
    for (int i = 0; i < nntool.getNN().getInputLayer().getNumNeurons(); i++) {
      if (ttt.getBoard()[i] == 0) { // space is empty
        // System.out.println("output "+i+" "+nntool.getNN().getOutput(i));

        if (nntool.getNN().getOutput(i) > tendancy) {
          tendancy = nntool.getNN().getOutput(i);
          move = i;
        }
        // nn.setInput(i, 0.0); // re empty the value
      }
    }
    return move;
  }
  public String getName(String[] nameList) {

    Scanner inFile = TicTacToe.getInputFile();
    String name = null;
    boolean valid = false;
    do {
      String strNumber = inFile.nextLine();

      if (strNumber.length() < 1) { // was a value entered ?
        new TicTacToeError()
            .displayError("You must enter a name or enter a \"Q\" to quit. Try again.");
        continue;
      }

      strNumber = strNumber.trim(); // trim off all blanks from front and back
      strNumber = strNumber.substring(0, 1); // get only the first character

      if (strNumber.toUpperCase().equals("Q")) { // quit?
        return null;
      }

      if (!strNumber.matches("[0-9]+")) { // is the value entered a number?
        new TicTacToeError().displayError("You must enter a number in the list. Try again.");
        continue;
      }

      int numberSelected = Integer.parseInt(strNumber); // convert string to integer

      // is the number outside the range of the list of names
      if (numberSelected < 1 || numberSelected > nameList.length) {
        new TicTacToeError().displayError("You must enter a number from the list. Try again.");
        continue;
      }

      name = nameList[numberSelected - 1]; // get the name from the list
      valid = true;

    } while (!valid);

    return name;
  }
/**
 * JFrame for tic-tac-toe board
 *
 * @author Jerry
 */
public class TicTacToeFrame extends JFrame {

  // Whose turn it is
  private char whoseTurn = 'X';
  TicTacToe intro = new TicTacToe();
  String player1Name = intro.getPlayer1Name();
  String player2Name = intro.getPlayer2Name();
  int gameType = intro.getGameType();

  // Creates cell grid
  Cell[][] cells = new Cell[3][3];

  // Creates status label
  JLabel gameStatusLabel = new JLabel("X's turn to play"); // panel 2 whose turn
  JLabel gameStatusLabel2 = new JLabel(player1Name + "\n\n: X"); // panel 2 who is x
  JLabel gameStatusLabel3 = new JLabel(player2Name + "\n\n: O"); // panel 2 who is O

  /** Arg Constructor */
  public TicTacToeFrame() {

    // Creates a panel for grid layout
    // http://www.java-tips.org/java-se-tips-100019/15-javax-swing/1751-how-to-make-split-pane-using-swing8.html
    JPanel gameBoardPanel = new JPanel(new GridLayout(3, 3, 0, 0)); // panel 1
    JPanel gameStatusPanel = new JPanel(); // panel 2

    // JLabel gameStatusLabel = new JLabel("Area 2");
    // gameBoardPanel.add(j1);
    gameStatusPanel.add(gameStatusLabel2);
    gameStatusPanel.add(gameStatusLabel3);
    gameStatusPanel.add(gameStatusLabel);
    JSplitPane splitPane =
        new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, gameBoardPanel, gameStatusPanel);
    splitPane.setResizeWeight(0.9);
    splitPane.setOneTouchExpandable(true);
    getContentPane().add(splitPane);

    // Adds 9 cells to grid layout
    for (int i = 0; i < 3; i++) {
      for (int k = 0; k < 3; k++) {
        gameBoardPanel.add(cells[i][k] = new Cell());
      }
    }
  }

  /**
   * Determines if game board is full
   *
   * @return True, if game board is full. False if not.
   */
  public boolean boardIsFull() {

    for (int i = 0; i < 3; i++) {
      for (int k = 0; k < 3; k++) {
        if (cells[i][k].getToken() == ' ') {
          return false;
        }
      }
    }
    return true;
  }

  /**
   * Determines if given token has won
   *
   * @param token, to test for winning
   * @return True, if token has won. False if not.
   */
  public boolean hasWon(char token) {

    // Checks every row
    for (int i = 0; i < 3; i++) {
      if (cells[i][0].getToken() == token
          && cells[i][1].getToken() == token
          && cells[i][2].getToken() == token) {
        return true;
      }
    }

    // Checks every column
    for (int k = 0; k < 3; k++) {
      if (cells[0][k].getToken() == token
          && cells[1][k].getToken() == token
          && cells[2][k].getToken() == token) {
        return true;
      }
    }

    // Checks diagonals
    if (cells[0][0].getToken() == token
        && cells[1][1].getToken() == token
        && cells[2][2].getToken() == token) {
      return true;
    }
    if (cells[0][2].getToken() == token
        && cells[1][1].getToken() == token
        && cells[2][0].getToken() == token) {
      return true;
    }
    return false;
  }

  /**
   * Defines a cell on the tic-tac-toe game board
   *
   * @author Jerry
   */
  public class Cell extends JPanel {

    // Token of the cell
    private char token = ' ';

    public Cell() {

      // Sets border of the cell and adds listener for mouse click
      setBorder(new LineBorder(Color.RED, 1));
      addMouseListener(new MyMouseListener());
    }

    /**
     * Gets the token of a cell.
     *
     * @return token value of the cell.
     */
    public char getToken() {
      return token;
    }

    /**
     * Sets the token of a cell
     *
     * @param token, used as token value
     */
    public void setToken(char token) {
      this.token = token;
      repaint();
    }

    // @Override
    /*
    /**
     * Draws X and O's
     */
    protected void paintComponent(Graphics g) {

      super.paintComponent(g);
      if (token == 'X') {
        g.drawLine(10, 10, getWidth() - 10, getHeight() - 10);
        g.drawLine(10, getHeight() - 10, getWidth() - 10, 10);
      } else if (token == 'O') {
        g.drawOval(10, 10, getWidth() - 20, getHeight() - 20);
      }
    }

    /** Called when a mouse click action is performed */
    private class MyMouseListener extends MouseAdapter {

      @Override
      public void mouseClicked(MouseEvent e) {

        // Cell is empty and game not over
        if (token == ' ' && whoseTurn != ' ') {
          setToken(whoseTurn);
        }

        // Check game status
        if (hasWon(whoseTurn)) {
          gameStatusLabel.setText(whoseTurn + " won! Game over!");
          whoseTurn = ' ';
        } else if (boardIsFull()) {
          gameStatusLabel.setText("It's a tie!");
          whoseTurn = ' ';
        } else {

          if (whoseTurn == 'X') {
            whoseTurn = 'O';
          } else {
            whoseTurn = 'X';
          }

          gameStatusLabel.setText(whoseTurn + "'s turn!");
        }
      }
    } // End of MyMouseListener class
  } // End of Cell class
} // End of TicTacToeFrame class
 public static void main(String... pumpkins) {
   // Pass 0 for no ai, 1 for ai as X and -1 for ai as O
   TicTacToe TTT = new TicTacToe(-1);
   TTT.run();
 }
 public SelectPlayersView(Game game) {
   this.game = game;
   playerList = TicTacToe.getPlayerList();
 }
  public NNTicTacToeSimple() {

    nntool = new NeuralNetworkTool();
    nntool.addTrainData("traindata/tictactoe.xml");
    nntool.initToTrainDataSpecifications(0);
    nntool.trainNNWithReinforcement();
    System.out.println("***************************************************");
    System.out.println(nntool.toStringInput());
    System.out.println("***************************************************");
    System.out.println(nntool.toStringOutput());

    int maxCycles = 5000;

    ttt = new TicTacToe();
    int count = 0;
    int move = -2;

    move = -2;
    count = 0;
    while (
    /*error > desiredError &&*/ count < maxCycles) {

      ttt.newGame();
      System.out.println("New Game");
      while (ttt.checkWin() == -2) {
        if (ttt.getTurn() == 1) {
          // System.out.println("Neural Networks TURN");
          for (int i = 0; i < nntool.getNN().getInputLayer().getNumNeurons(); i++) {
            //	System.out.println("ttt.getBoard()[i] ="+ttt.getBoard()[i]);
            nntool.getNN().setInput(i, ttt.getBoard()[i]);
          }
          move = getMove();
          if (move > -1) {
            ttt.getBoard()[move] = ttt.P1VALUE;
            nntool.getNN().setInput(move, ttt.P1VALUE);
          }
          ttt.setTurn(2);
          ttt.repaint();
        }
      }

      if (ttt.checkWin() == ttt.P1WIN) {
        System.out.println("Neural Network Wins!");
      } else if (ttt.checkWin() == ttt.P2WIN) {
        System.out.println("You Win!"); /*
				if(move > -1) {
					System.out.println("NN learning from mistake");
					//System.out.println("Confidence in last move ["+nntool.getNN().getOutput(move)+"]");
					nntool.getNN().getOutputLayer().setNeuronError(move,1);
					for(int i = 0; i < nntool.getNN().getOutputLayer().getNumNeurons(); i++) {
						//	System.out.println("ttt.getBoard()[i] ="+ttt.getBoard()[i]);
						nntool.getNN().setTeacherSignal(i, 0);
					}
					nntool.getNN().setTeacherSignal(ttt.getP2LastMove(), 1);
					nntool.getNN().backPropagate();
				}*/
      } else if (ttt.checkWin() == 0) {
        System.out.println("Draw!");
      }
      //	error = 0;
      count++;
      ttt.newGame();
    }
  }
  public static void main(String[] args) {
    /* Instantiate a Scanner to read standard input */
    Scanner stdIn = new Scanner(System.in);

    /* Assume we want to play forever */
    boolean doYouWantToPlay = true;

    /* Loop until we don't want to play */
    while (doYouWantToPlay) {
      /* Explain how to play the game */
      System.out.println(
          "Welcome to Tic Tac Toe! You are about to go against "
              + "the master of Tic Tac Toe.  Are you ready?  I hope so!\n BUT FIRST, you"
              + " must pick what character you want to be and which character I will be");
      System.out.println();
      /* Enter your marker for the game */
      System.out.println("Enter a single character that will represent you on the board (X/O)");
      char playerToken = stdIn.next().charAt(0);
      /* Enter your opponents marker */
      System.out.println(
          "Enter a single character that will represent your opponent on the board(X/O)");
      char opponentToken = stdIn.next().charAt(0);

      /* Create a new game */
      TicTacToe game = new TicTacToe(playerToken, opponentToken);

      /* Create a new AI character */
      AI ai = new AI();

      /* Print the index board */
      System.out.println();
      System.out.println(
          "Now we can start the game.  To play, enter a number and your token shall be put "
              + "in its place.\nThe numbers go from 1-9, left to right. We shall see who will win this round.");
      TicTacToe.printIndexBoard();
      System.out.println();

      /* Let's play */
      /* Loop until the game is over */
      while (game.gameOver().equals("notOver")) {
        /* Is it the users turn? */
        if (game.currentMarker == game.userMarker) {
          /* User turn */
          System.out.println("It's your turn!  Enter a spot for your token");
          int spot = stdIn.nextInt();
          /* While the spot is invalid */
          while (!game.playTurn(spot)) {
            System.out.println(
                "Try again. "
                    + spot
                    + " is invalid.  This spot is already taken"
                    + " or it is out of range");
            /* Get another spot */
            spot = stdIn.nextInt();
          }
          System.out.println("You picked " + spot + "!");
        } else {
          System.out.println("It's my turn!");
          /* AI takes a turn */
          int aiSpot = ai.pickSpot(game);
          /* Play the spot */
          game.playTurn(aiSpot);
          System.out.println("I picked " + aiSpot + "!");
        }
        /* Print out the game board */
        System.out.println("The game board now looks like");
        game.printBoard();
      }
      /* Print out the results of the game */
      System.out.println(game.gameOver());
      System.out.println();
      /* Setup another game? */
      System.out.println(
          "Do you want to play again?  Enter Y if you do."
              + " Enter anything else if you are tired of me.");
      /* Read the user response */
      char response = stdIn.next().charAt(0);
      /* Play again if the user responds Y */
      doYouWantToPlay = (response == 'Y');
      System.out.println();
      System.out.println();
    }
  }