1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
|
void computerMoved(void);
void isForced(int pos1, int pos2, int pos3, STATE state, int& nextMove);
void computerMove(void)
{
STATE myState = FREE;
int nextMove;
isForced(0, 1, 2, myState, nextMove);
isForced(3, 4, 5, myState, nextMove);
isForced(6, 7, 8, myState, nextMove);
isForced(0, 3, 6, myState, nextMove);
isForced(1, 4, 7, myState, nextMove);
isForced(2, 5, 8, myState, nextMove);
isForced(0, 4, 8, myState, nextMove);
isForced(2, 4, 6, myState, nextMove);
if (myState == LOST) cout << "You win\n";
else if (myState == CANWIN)
{
functionMove(nextMove);
cout << "I win\n";
}
else if (myState == BLOCK)
{
functionMove(nextMove);
cout << "Nice Try\n";
}
else
{
functionFigureItOut(); // There wasn't anything pressing to do
}
}
void isForced(int pos1, int pos2, int pos3, STATE& state, int& nextMove)
{
if (state == LOST) return;
int result = 0;
if (pos1 == 1) //or however you know the player's move
result += 1;
if (pos2 == 1) result += 2;
if (pos3 == 1) result += 4;
//result now has unique values for all combinations of board states
if (result == 7)
{
state = LOST;
return;
}
if (state == CANWIN) return; // no need to figure anything else out
// result is set up to figure out forces, so we do that first
if (result == 3) // pos1 and pos2 are player and pos3 isn't
{
state = BLOCK;
nextMove = pos3;
}
else if (result == 5) // pos1 and pos3
{
state = BLOCK;
nextMove = pos2;
}
else if (result == 6) // pos2 and pos3
{
state = BLOCK;
nextMove = pos1;
}
// now figure out if can win
result = 0;
if (pos1 == 2) // The computers piece
result += 1;
if (pos2 == 2) result += 2;
if (pos3 == 2) result += 4;
if (result == 3)
{
state = CANWIN;
nextMove = pos3;
}
else if (result == 5)
{
state = CANWIN;
nextMove = pos2;
}
else if (result == 6)
{
state = CANWIN;
nextMove = pos1;
}
}
|