Add AI to Tic Tac Toe

Hey,
I need to make it so that my Tic tac toe board is against the computer rather than against another person so can anyone help me with how I should edit my code? I will be adding more to the switch statement in due time.

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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

char board1[3][3] = { '1','2','3','4','5','6','7','8','9' };
char player = 'X';
void draw1()
{
	for (int i = 0; i < 3; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			cout << board1[i][j] << " | ";
		}
		cout << endl;
	}
	cout << endl;
}
void input1()
{
	int a;
	cout << "Press number you want to input: ";
	cin >> a;
	if (a == 1)
	{
		if (board1[0][0] == '1')
			board1[0][0] = player;
		else
		{
			cout << "Field is in use!" << endl;
			input1();
		}
	}
	else if (a == 2)
	{
		if (board1[0][1] == '2')
			board1[0][1] = player;
		else
		{
			cout << "Field is in use!" << endl;
			input1();
		}
	}
	else if (a == 3)
	{
		if (board1[0][2] == '3')
			board1[0][2] = player;
		else
		{
			cout << "Field is in use!" << endl;
			input1();
		}
	}
	else if (a == 4)
	{
		if (board1[1][0] == '4')
			board1[1][0] = player;
		else
		{
			cout << "Field is in use!" << endl;
			input1();
		}
	}
	else if (a == 5)
	{
		if (board1[1][1] == '5')
			board1[1][1] = player;
		else
		{
			cout << "Field is in use!" << endl;
			input1();
		}
	}
	else if (a == 6)
	{
		if (board1[1][2] == '6')
			board1[1][2] = player;
		else
		{
			cout << "Field is in use!" << endl;
			input1();
		}
	}
	else if (a == 7)
	{
		if (board1[2][0] == '7')
			board1[2][0] = player;
		else
		{
			cout << "Field is in use!" << endl;
			input1();
		}
	}
	else if (a == 8)
	{
		if (board1[2][1] == '8')
			board1[2][1] = player;
		else
		{
			cout << "Field is in use!" << endl;
			input1();
		}
	}
	else if (a == 9)
	{
		if (board1[2][2] == '9')
			board1[2][2] = player;
		else
		{
			cout << "Field is in use!" << endl;
			input1();
		}
	}
}
void toggleplayer1()
{
	if (player == 'X')
		player = 'O';
	else
		player = 'X';
}
char win1()
{
	if (board1[0][0] == 'X'&&board1[0][1] == 'X'&&board1[0][2] == 'X')//horizontal
		return 'X';
	if (board1[1][0] == 'X'&&board1[1][1] == 'X'&&board1[1][2] == 'X')//horizontal
		return 'X';
	if (board1[2][0] == 'X'&&board1[2][1] == 'X'&&board1[2][2] == 'X')//horizontal
		return 'X';
	if (board1[0][0] == 'X'&&board1[1][1] == 'X'&&board1[2][2] == 'X')//diaganol
		return 'X';
	if (board1[2][0] == 'X'&&board1[1][1] == 'X'&&board1[0][2] == 'X')//diaganol
		return 'X';
	if (board1[0][0] == 'X'&&board1[1][0] == 'X'&&board1[2][0] == 'X')//vertical
		return 'X';
	if (board1[0][1] == 'X'&&board1[1][1] == 'X'&&board1[2][1] == 'X')//vertical
		return 'X';
	if (board1[0][2] == 'X'&&board1[1][2] == 'X'&&board1[2][2] == 'X')//vertical
		return 'X';
	//s
	if (board1[0][0] == 'O'&&board1[0][1] == 'O'&&board1[0][2] == 'O')//horizontal
		return 'O';
	if (board1[1][0] == 'O'&&board1[1][1] == 'O'&&board1[1][2] == 'O')//horizontal
		return 'O';
	if (board1[2][0] == 'O'&&board1[2][1] == 'O'&&board1[2][2] == 'O')//horizontal
		return 'O';
	if (board1[0][0] == 'O'&&board1[1][1] == 'O'&&board1[2][2] == 'O')//diaganol
		return 'O';
	if (board1[2][0] == 'O'&&board1[1][1] == 'O'&&board1[0][2] == 'O')//diaganol
		return 'O';
	if (board1[0][0] == 'O'&&board1[1][0] == 'O'&&board1[2][0] == 'O')//vertical
		return 'O';
	if (board1[0][1] == 'O'&&board1[1][1] == 'O'&&board1[2][1] == 'O')//vertical
		return 'O';
	if (board1[0][2] == 'O'&&board1[1][2] == 'O'&&board1[2][2] == 'O')//vertical
		return 'O';

	return '/';

}
int main()
{
	bool movemade;
	int space;
	bool availability;
	int number;
	srand(time(NULL));
	number = rand() % 2;
	if (number == 0)
		player = 'X';
	else
		player = 'O';
	n = 0;
	int board = 0;
	while (1)
	{
		do
		{
			cout << "Choose Board:";
			cin >> board;
			draw1();
			switch (board)
			{
			case 1:
				draw1();
				if (win1() == 'X')
				{
					cout << "X wins board 1!" << endl;
				}
				else if (win1() == 'O')
				{
					cout << "O wins board 1!" << endl;
				}
				else if (win1() == '/' && n == 9)
					cout << "NO winner!" << endl;
				input1();
				toggleplayer1();
				break;

		} while (board != 2);
	}

	system("pause");
}
Just implement the strategy that you would use to play optimally. Google "tic tac toe winning strategy".
create a variable that will store the number of players. If it is 1 player create a check in your game loop for this value. At the right point in the game loop you can test the variable with something like...

1
2
if (numPlayers == 1 && player == 'O') {
cout << "it is the computer's turn!" << endl;


Once you get that working correctly you can start to implement AI strategy. You might start with random moves at first but gradually get more complex.
TTT has a lot of repeated patterns that you mirror or rotate the board to match. These are called transposition tables. It turns out that a very small number of lookup tables will give you a solid base AI... you simply get the current position, match it, and that gives you the next best move. There are other ways to do it, but that one, while a little tedious, works great.

Also, try to make everything relative to the size of a side. I could change my side from 3 to 5, for example, and it'd still work.

Just hacked out something a lil dirty in the win checks, but appears to be working, to demonstrate a random AI movement and a different way to setup the drawing of the board.

To let comp go first, you'd comment out line 279 and uncomment 281, 282:
Running at https://repl.it/repls/LowestUtilizedDatabase
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <cstdlib>
#include <ctime>
using namespace std;

string operator*(const string& s, const unsigned int n) {
    stringstream out;
    for (int x=1; x<=n; ++x)
        out << s;
    return out.str();
}

string operator*(const unsigned int n, const string& s) { return s * n; }


class TicTacToe
{
    
enum Move
{
    X,
    O
};
    
public:
    TicTacToe() :
        to_move_(Move::X),
        num_moves_(0),
        game_over_(false),
        winner_("No One")
    {
        empty_row_ = string(" ")*side_ + ("|" + string(" ")*side_)*(side_-1);
        space_ = string(" ")*(side_/2);
        divider_ = string("-")*(side_*side_ + side_-1);
        
        board_.reserve(side_);
        for (int x=1; x<=side_; ++x)
        {
            vector<string> vec;
            vec.reserve(side_);
            for (int y=1; y<=side_; ++y)
                vec.push_back(default_symbol_);
            board_.push_back(vec);
        }
    }
    
    
    
    void DrawRow(vector<string>& row)
    {
        for (int x=1; x<=side_/2; ++x)
        {
            cout << empty_row_ << endl;
        }
        for (int i=0; i<side_-1; ++i)
        {
            cout << space_ << row[i] << space_ << "|";
        }
        cout << space_ << row[side_-1] << endl;
        
        for (int x=1; x<=side_/2; ++x)
        {
            cout << empty_row_ << endl;
        }
    }

    // Draw the board
    void Draw()
    {
        for (int r=0; r<side_-1; ++r)
        {
            DrawRow(board_[r]);
            cout << divider_ << endl;
        }
        DrawRow(board_[side_-1]);
        cout << endl;
    }
    
    void CheckGameOver(int row, int col)
    {
        if (num_moves_ == side_*side_)
            game_over_ = true;
        
        // Check if it was a winning move
        string symbol = board_[row][col];
        
        // Check row
        bool found_winner = true;
        int down = col-1;
        int up = col+1;
        while (down>=0 || up<side_)
        {
            if (down>=0)
            {
                if (board_[row][down] != symbol)
                {
                    found_winner = false;
                    break;
                }
            }
            if (up<side_)
            {
                if (board_[row][up] != symbol)
                {
                    found_winner = false;
                    break;
                }
            }
            down--;
            up++;
        }
        if (found_winner)
        {
            game_over_ = true;
            winner_ = symbol;
            return;
        }
        
        // Check column
        found_winner = true;
        down = row-1;
        up = row+1;
        while (down>=0 || up<side_)
        {
            if (down>=0)
            {
                if (board_[down][col] != symbol)
                {
                    found_winner = false;
                    break;
                }
            }
            if (up<side_)
            {
                if (board_[up][col] != symbol)
                {
                    found_winner = false;
                    break;
                }
            }
            down--;
            up++;
        }
        if (found_winner)
        {
            game_over_ = true;
            winner_ = symbol;
            return;
        }
        
        // Diagonals check
        if (row==0 || col==0 || row==side_-1 || col==side_-1)
        {
            found_winner = true;
            for (int r=0, c=0; r<side_, c<side_; ++r, ++c)
            {
                if (board_[r][c] != symbol)
                {
                    found_winner = false;
                    break;
                }
            }
            if (found_winner)
            {
                game_over_ = true;
                winner_ = symbol;
                return;
            }
            
            found_winner = true;
            for (int r=side_-1, c=0; r>=0, c<side_; --r, ++c)
            {
                if (board_[r][c] != symbol)
                {
                    found_winner = false;
                    break;
                }
            }
            if (found_winner)
            {
                game_over_ = true;
                winner_ = symbol;
                return;
            }
        }
    }
    
    bool IsGameOver()
    {
        return game_over_;
    }
    
    string Winner()
    {
        return winner_;
    }
    
    // Prompt row and column of move
    void PromptPlayerMove()
    {
        if (game_over_)
            return;

        int row, col;
        
        while (true)
        {
            cout << "Row? ";
            cin >> row;
            cout << "Col? ";
            cin >> col;
        
            if (! (0<=row && row<side_ && 0<=col && col<side_) )
            {
                cout << "Input out of range (0-"<<(side_-1)<<")\n";
                continue;
            }
            if (board_[row][col]!=default_symbol_)
            {
                cout << "Square ["<<row<<", "<<col<<"] is taken!\n";
                continue;
            }
            break;
        }
        board_[row][col] = to_move_ == Move::X ? "X" : "O";
        num_moves_ += 1;
        CheckGameOver(row, col);
        to_move_ = (to_move_ == Move::X ? Move::O : Move::X);
    }
    
    void MakeCompMove()
    {
        if (game_over_)
            return;
            
        vector<pair<int,int>> avail_moves;
        for (int r=0; r<side_; ++r)
        {
            for (int c=0; c<side_; ++c)
            {
                if (board_[r][c]==default_symbol_)
                    avail_moves.emplace_back(r,c);
            }
        }
        
        srand(std::time(nullptr)); 
        pair<int,int> move = avail_moves[rand() % avail_moves.size()];
        board_[move.first][move.second] = to_move_ == Move::X ? "X" : "O";
        cout << "Comp plays to ("<<move.first<<", "<<move.second<<").\n";
        num_moves_ += 1;
        CheckGameOver(move.first, move.second);
        to_move_ = (to_move_ == Move::X ? Move::O : Move::X);
    }

private:
    vector<vector<string>> board_;
    const unsigned int side_ = 3;
    const string default_symbol_ = "˘";
    
    string empty_row_;
    string divider_;
    string space_;
    Move to_move_;
    int num_moves_;
    bool game_over_;
    string winner_;
};

int main()
{
    TicTacToe t;
  
    while (!t.IsGameOver())
    {
        t.Draw();
        t.PromptPlayerMove();
        t.MakeCompMove();
        //t.Draw();
        //t.PromptPlayerMove();
    }
    cout << "Game is over!  Winner is "<<t.Winner() << endl;
    t.Draw();
  
    return 0;
}
Last edited on
Topic archived. No new replies allowed.