Thursday, July 30, 2009

Using C++ to write a tic tac toe game?

Hi I'm writng a c++ program using classes to write a tic tac toe program ( actually it's a Gomoku game, same thing except five in a row instead of 3). I have the board constructed using a 2 D vector, but now I need to come up with a function (isWinner) that will tell me if a player has five in a row, column or diagonal. Does anyone have a suggestion? The header file looks like this:





class Gomoku


{


private:


vector%26lt;vector%26lt;int%26gt; %26gt; board;//sets up multi D vector


int size;


public:


Gomoku();


Gomoku(int h);//Constructor, takes one integer.


void draw(int);//Draws present board position;takes no argument; no return.


bool place (int a, int b, int c);//a=player,b=row,c=column


//puts players stone on board


//returns true/falsebased on whether move was legal or not.


bool isWinner (int d, int e);//d=row, e=column; returns boolean indicating if postion is a winn

Using C++ to write a tic tac toe game?
Well Ill answer this for tic tac toe, and you can extract what I say to fit your Gomoku game.





Because the state space (the possible winning situations) is small in number when it comes to tic tac toe we can compare the current situation against all the possible winning situations.





supposing you represent a X by the integer 1, a O by the integer 0 and a not played yet by -1 then you will have some kind of vector that has some configuration of 1's 0's and -1's in it.





There are 8 possible winning situations for each player (in tic tac toe) for example for player X (or 1) we can compare against:





((1,-,-),(-,1,-),(-,-,1)) -- horizontal


((1,-,-),(1,-,-),(1,-,-)) -- left column


((-,1,-),(-,1,-),(-,1,-)) -- middle column


((-,-,1),(-,-,1),(-,-,1)) -- right column


((1,1,1),(-,-,-),(-,-,-)) -- top row


((-,-,-),(1,1,1),(-,-,-)) -- middle row


((-,-,-),(-,-,-),(1,1,1)) -- bottom row


((-,-,1),(-,1,-),(1,-,-)) -- other horizontal





where eash - is a dont care position (that is we dont care what is in it). You would have the same comparisons against the O player except using 0's instead of 1's. For more complex games this state space can become too large to be effective but for your question it will work effectively and quickly.





good luck.

song downloads

No comments:

Post a Comment