Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList Comparison- TicTacToe

Tags:

java

arraylist

I am trying to make a really simple Tic-Tac-Toe game. I have stored values of "X" and "O" in a 0-8 ArrayList (3x3 square, essentially). I can do the following for each instance of a winning situation:

if ((newBoard().get(0)).equals("X") &&
    (newBoard().get(1)).equals("X") && 
    (newBoard().get(2)).equals("X")){
System.out.println("Player-X has won!");
return true;

However, this is going to take a TON of code! I thought about creating new ArrayLists that contain the situations in which "X" has won (3-in-roe) and then copy and paste, replace "X" with "O", then compare these with the current ArrayList board that the user is 'interacting with.' That's all good, but I don't know how to compare them. I looked at the API, but I couldn't find anything that could do what I want, which is to compare to ArrayLists, but only for the specified indexes.

Anything pertaining to making this situation a bit smaller, code-wise, will be greatly appreciated. Thanks!

like image 384
Mr_CryptoPrime Avatar asked Aug 09 '26 01:08

Mr_CryptoPrime


1 Answers

Well, one option is not to think of all the winning boards, but all the winning required locations. For example:

private static final int[][] LINES_OF_THREE = {
  { 0, 1, 2 }, // Horizontals
  { 3, 4, 5 },
  { 6, 7, 8 },
  { 0, 3, 6 }, // Verticals
  { 1, 4, 7 },
  { 2, 5, 8 },
  { 0, 4, 8 }, // Diagonals
  { 6, 4, 2 }
};

Then something like:

for (int[] line : LINES_OF_THREE) {
  boolean won = true;
  for (int place : line) {
    // player = "O" or "X"
    if (!newBoard.get(place).equals(player)) { 
      won = false;
      break;
    }
  }
  if (won) {
    // Yippee!
  }
}
like image 106
Jon Skeet Avatar answered Aug 11 '26 16:08

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!