How can I check 3 elements of a single-dimensional array are equal to a specific value?
Background: I am trying to check for the winner of a game of tic-tac-toe (noughts and crosses). In other words check for any lines in a 3×3 grid flattened into a single dimensional array.
Here is the code I have tried:
Attempt 1:
switch ()
{
case board[(6&3&0) || (7&4&1)]: case board[7&4&1]: case board[8&5&2]: case board[0&1&2]: case board[3&4&5]: case board[6&7&8]: case board[6&4&2]: case board[8&4&0]:
System.out.println("Equal to x")
break;
}
Attempt 2:
if (board[7] , board[4] , board[1] == 'X')
system.out.println("Equal");
Attempt 3:
if ( board[6&3&0] == 'X' || board[7&4&1] == 'X' || board[8&5&2] == 'X' || board[0&1&2] == 'X' || board[3&4&5] == 'X' || board[6&7&8] == 'X' || board[6&4&2] == 'X' || board[8&4&0] == 'X') {
System.out.println("Equal to x");
}else if
( board[6&3&0] == 'O' || board[7&4&1] == 'O' || board[8&5&2] == 'O' || board[0&1&2] == 'O' || board[3&4&5] == 'O' || board[6&7&8] == 'X' || board[6&4&2] == 'O' || board[8&4&0] == 'O'){
System.out.println("Equal to o!");
}
Your “playing-field” for tic-tac-toe looks like this:
With 0-8 being the indices in a
char[]array:To check if we have three ‘x’ in a row:
This should get you started.
EDIT: And this will compile: