Reputation: 7416
I want to understand whether the game is finished or drawn or still playable. But I want to do it with dynamic code.
For example I do it static for 3*3 tictactoe game like this :
private static boolean check_game_state(char[] board)
{
if ( (board[0]==cSymbol && board[1]==cSymbol && board[2]==cSymbol)
|| (board[3]==cSymbol && board[4]==cSymbol && board[5]==cSymbol)
|| (board[6]==cSymbol && board[7]==cSymbol && board[8]==cSymbol)
|| (board[0]==cSymbol && board[3]==cSymbol && board[6]==(cSymbol))
|| (board[1]==(cSymbol) && board[4]==(cSymbol) && board[7]==(cSymbol))
|| (board[2]==(cSymbol) && board[5]==(cSymbol) && board[8]==(cSymbol))
|| (board[0]==(cSymbol) && board[4]==(cSymbol) && board[8]==(cSymbol))
|| (board[2]==(cSymbol) && board[4]==(cSymbol) && board[6]==(cSymbol)))
{
if (cSymbol == 'X')
{
state = 5; //player 1 win
}
else if (cSymbol == 'O')
{
state = 4; player 2 win
}
}
}
I want to it dynamically for a 4*4 or 5*5 or higher board. But how can I do it? Is it possible?
Upvotes: 2
Views: 470
Reputation: 28812
Instead of hard-coding the indices, you need to access the elements in a loop. E.g. instead of
boolean test = (board[0]==cSymbol && board[1]==cSymbol && board[2]==cSymbol);
You would do something like
boolean test = true;
for (int i = 0; i < length; ++i) {
test = test && board[i] == cSymbol ;
}
where length
is the size of the board (e.g. 5, 6), same as square root of the board.length
You need to either calculate this from the array length or pass it to the function along with the array itself
This will set test
to true only if all elements were equal to cSymbol
, false
otherwise.
Update: I give you the calculation for the rows; you will need to adopt this to the columns (hint: calculate index i+j*length
), main dialonal (index: i*length+i
) and sub-diagonal (index: i*length+(length-1-i)
). The index i*length + j
translates to the i
th row, j
th column:
private static boolean check_game_state(char[] board, int length)
{
bool row = false;
for (int i = 0; i < length; ++i) {
bool innerRow = true;
for (int j = 0; j < length; ++j) { // calculate the ith row
innerRow = innerRow && board[i*length+j] == cSymbol;
}
row = row || innerRow;
}
if (row)
{
// somebody won...
}
}
Upvotes: 1
Reputation: 3304
If you don't want to hard code it, you should implement some algorithm of searching winning positions etc. Take a look at http://www.codeproject.com/Articles/43622/Solve-Tic-Tac-Toe-with-the-MiniMax-algorithm for instance.
Upvotes: 0
Reputation: 7844
You can't hard code your check conditions then. You will have to have 3
separate cases:
You can use simple loops in all those cases which run from 0
to N
(size of your game). I would say, keep a track of the current cell which is being filled. Say that is x,y
. Now use this coordinate and check that particular row
and column
. And if x == y
then its on the forward diagonal so you check for it. Similarly check for the reverse diagonal.
Upvotes: 1