tags:

views:

191

answers:

2
+1  Q: 

Game logic issue

Hi, i am making a noughts and crosses game (tic tac toe) and in my logic class i represent the state of the game with a 2d array, but this is the problem, im checking the array like so

 if(gameModel[0][0] == gameModel[1][1] && gameModel[0][0] == gameModel[2][2]){
     return true;
    }
 if(gameModel[2][0] == gameModel[1][1] && gameModel[2][0] == gameModel[0][2]){
     return true;
    }

and so on for all 8 conditions, however, the array is initialised with all values of 0 at the beginning, so it always finds three matching values, how can i get round this problem without having to change the whole of my code

thanks

+5  A: 

In that case you just have to add a check if a value is set:

if (   gameModel[0][0] == gameModel[1][1] 
    && gameModel[0][0] == gameModel[2][2] 
    && gameModel[0][0] != 0) {
 return true;
}
DR
+3  A: 

One thing that jumps out at me with this is... why are you using ints instead of a class to represent this? True this is a simple game, but a Piece class seems to jump out as a fairly obvious class to have.

Also, with int you really have 3 states, presumably something like:

0 = empty
1 = X
2 = Y

So you should check for 0 (empty) before bothering to check for if they are the same value, it will be quicker (who really cares though, this doesn't need to be fast), and make more logical sense (is the square empty? if so then do not bother checking if the squares hold the same values).

Even for simple things like this, especially when you are just starting out, try to embrace OOP, it is a different way of thinking, and it takes practice, so practice as much as you can!

TofuBeer