Skip to main content
GameDev.net gamedev.net
🔒 Locked

Help please

Started by NUCLEAR RABBIT Aug 18, 2006 at 9:52 PM 2 replies 400+ views
Original Post
NUCLEAR RABBIT
NUCLEAR RABBIT
Hello, I tried creating a function for tic tac toe, that checks possible positions for the computer to win, if its open, the computer wins, but this wont seem to work. The code doesnt generate any errors, but it doesnt work. Please help

void GetCmove(vector<char>& gBoard)
{
	int CMove = 0;
	bool done = false;

	while(!done) {
		CMove = rand() % 8;

		for(int a = 0; a != 3; a++) {
			for(int b = 0; b != 3; b++) {
				for(int c = 0; c != 3; c++) {
					if(gBoard[a] == 'O' && gBoard == 'O' && gBoard[c] != 'X' && gBoard[c] != 'O') {
						gBoard[c] = 'O';
						done = true;
					}
				}
			}
		}

		if(gBoard[CMove] == 'X' || gBoard[CMove] == 'O')
			done = false;
		else {
			gBoard[CMove] = 'O';
			done = true;
		}
	}
}
Scet
Scet
Well this might not be the problem, but I think something might be wrong with this:

gBoard[a] == 'O' && gBoard == 'O'

What happens when a and b are the same number?
JohnBolton
JohnBolton
Here is your code is doing:
    while (!done)    {        1. Set CMove to a random number between 0 and 7, inclusive.        2. Look at gBoard[0], gBoard[1], and gBoard[2]. If two of the elements           are '0' (zero, BTW) and the other is empty then set done to true.        3. Set gBoard[CMove] to '0' if it is empty. Set done to true if it was           empty, otherwise set it to false.    } 
Here are some problems:
  • The value of 'done' set in step 2 is overwritten in step 3, so step 2 really does nothing.
  • Your TTT board has 9 positions (0-8, I assume), but you are only generating random positions 0-7.
  • You need to rethink your code for scanning for winning moves. As Scet pointed out, step 2 breaks when a == b, or b == c, or a == c. It also only checks the first 3 elements of the board.
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!
Driv3MeFar
Driv3MeFar
Scet makes a good point, your for loop logic appears to be incorrect. If you want a to be row 0, b to be row 1, and c to be row 2, then they can't all range from 0-3, at least not if your board is a one dimensional array. The formula for finding the 1d equivalent of a 2d position is
index = (row * columns) + column.

Which means,
0 <= a < 3,
3 <= b < 6,
6 <= c < 9

edit: Man, I'm too slow with everything tonight.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.