-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsource.cpp
More file actions
487 lines (415 loc) · 13.9 KB
/
Copy pathsource.cpp
File metadata and controls
487 lines (415 loc) · 13.9 KB
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
#define NOMINMAX
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <algorithm>
#include <iostream>
// Defining some constants
#define IDC_BUTTON_START 101 // starting ID for buttons
#define SIZE 3 // size of the board
HWND buttons[SIZE][SIZE]; // button handles
int board[SIZE][SIZE] = {0}; // game state
bool turn = true; // true for 'X', false for 'O'
int boardWidth = SIZE * 100;
int boardHeight = SIZE * 100;
HBRUSH hBrushBlue = CreateSolidBrush(RGB(0, 0, 255)); // Blue for 'X'
HBRUSH hBrushRed = CreateSolidBrush(RGB(255, 0, 0)); // Red for 'O'
HBRUSH hBrushDefault = CreateSolidBrush(RGB(0, 0, 0)); // Black for empty cells
// Function prototypes
void UpdateButtonFontSize(HWND button, int buttonWidth, int buttonHeight);
int minimax(int board[SIZE][SIZE], int alpha, int beta, bool isMax);
void findBestMove(int board[SIZE][SIZE], int *bestI, int *bestJ);
void HandleButtonClick(WPARAM wParam, HWND hwnd);
void UpdateBoard(int i, int j);
int CheckWinner();
void HandleGameEnd(int winner, HWND hwnd);
void CheckTie(HWND hwnd);
void ResetGame();
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) // Window procedure
{
switch (uMsg) // Handle window messages
{
case WM_CLOSE: // Handle window close event
std::cout << "exiting from window close" << std::endl;
PostQuitMessage(0);
return 0;
case WM_DRAWITEM: // Handle button draw event
{
LPDRAWITEMSTRUCT lpDIS = (LPDRAWITEMSTRUCT)lParam; // Get draw item struct from lParam
if (lpDIS->CtlType == ODT_BUTTON) // If the draw item is a button
{
char text[10];
GetWindowText(lpDIS->hwndItem, text, sizeof(text));
// Set the color based on the text
if (strcmp(text, "X") == 0)
{
FillRect(lpDIS->hDC, &lpDIS->rcItem, hBrushBlue);
}
else if (strcmp(text, "O") == 0)
{
FillRect(lpDIS->hDC, &lpDIS->rcItem, hBrushRed);
}
else
{
FillRect(lpDIS->hDC, &lpDIS->rcItem, hBrushDefault);
}
// Draw the text
SetBkMode(lpDIS->hDC, TRANSPARENT);
DrawText(lpDIS->hDC, text, -1, &lpDIS->rcItem, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
// Draw the border for the button
HBRUSH hBrushBorder = CreateSolidBrush(RGB(128, 128, 128));
FrameRect(lpDIS->hDC, &lpDIS->rcItem, hBrushBorder);
DeleteObject(hBrushBorder); // Clean up the brush after using it
}
return TRUE;
}
break;
case WM_SIZE:
{
int width = LOWORD(lParam); // Width of the resized window
int height = HIWORD(lParam); // Height of the resized window
// Calculate button width and height based on the new window size
int buttonWidth = width / SIZE;
int buttonHeight = height / SIZE;
// Reposition and resize buttons
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
SetWindowPos(buttons[i][j], NULL,
j * buttonWidth, i * buttonHeight,
buttonWidth, buttonHeight,
SWP_NOZORDER);
// Update the button font size
UpdateButtonFontSize(buttons[i][j], buttonWidth, buttonHeight);
}
}
}
break;
case WM_SHOWWINDOW:
if (wParam == TRUE) // Window is being shown
{
RECT rect;
GetClientRect(hwnd, &rect); // Get the client area of the window
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
// Calculate button width and height based on the window size
int buttonWidth = width / SIZE;
int buttonHeight = height / SIZE;
// Create and position the buttons
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
// Create the button, set its ID, and position it in the window
buttons[i][j] = CreateWindow(
"BUTTON", "",
WS_VISIBLE | WS_CHILD | BS_OWNERDRAW,
j * buttonWidth, i * buttonHeight,
buttonWidth, buttonHeight,
hwnd, (HMENU)(INT_PTR)(IDC_BUTTON_START + i * SIZE + j),
(HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE), NULL);
}
}
}
break;
case WM_DESTROY: // Handle window destroy event
DeleteObject(hBrushRed);
DeleteObject(hBrushBlue);
DeleteObject(hBrushDefault);
return 0;
case WM_COMMAND:
HandleButtonClick(wParam, hwnd);
return 0;
default: // Handle any messages the switch statement didn't
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
return 0;
}
// Entry point
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
const char CLASS_NAME[] = "Tic-Tac-Toe"; // Window class name
WNDCLASS wc = {}; // Window class
wc.lpfnWndProc = WindowProc; // Window procedure
wc.hInstance = hInstance; // Instance handle
wc.lpszClassName = CLASS_NAME; // Set the class name
RegisterClass(&wc); // Register the window class
RECT winRect = {0, 0, boardWidth, boardHeight};
AdjustWindowRect(&winRect, WS_OVERLAPPEDWINDOW, FALSE);
// Get the screen resolution
int screenWidth = GetSystemMetrics(SM_CXSCREEN);
int screenHeight = GetSystemMetrics(SM_CYSCREEN);
// Calculate the window position
int windowWidth = winRect.right - winRect.left;
int windowHeight = winRect.bottom - winRect.top;
// Center the window
int xPos = (screenWidth - windowWidth) / 2;
int yPos = (screenHeight - windowHeight) / 2;
// Create the window
HWND hwnd = CreateWindowEx(
0, // Optional window styles.
CLASS_NAME, // Window class
"Tic-Tac-Toe", // Window text
WS_OVERLAPPEDWINDOW, // Window style
xPos, yPos, // Window position (centered)
windowWidth, windowHeight,
NULL, // Parent window
NULL, // Menu
hInstance, // Instance handle
NULL // Additional application data
);
if (hwnd == NULL) // If window creation fails, return 0
{
return 0;
}
ShowWindow(hwnd, nCmdShow); // Show the window
MSG msg = {};
while (GetMessage(&msg, NULL, 0, 0)) // Message loop
{
TranslateMessage(&msg); // Translate virtual-key messages into character messages
DispatchMessage(&msg); // Dispatches a message to a window procedure
}
return 0;
}
void HandleButtonClick(WPARAM wParam, HWND hwnd)
{
if (LOWORD(wParam) >= IDC_BUTTON_START && LOWORD(wParam) < IDC_BUTTON_START + SIZE * SIZE)
{
int id = LOWORD(wParam) - IDC_BUTTON_START; // Get the button ID
int i = id / SIZE;
int j = id % SIZE;
if (board[i][j] == 0)
{
UpdateBoard(i, j);
if (!turn) // If it's the computer's turn
{
int bestI, bestJ; // Best move coordinates
int winner = CheckWinner();
if (winner != 0)
{
HandleGameEnd(winner, hwnd);
return;
}
findBestMove(board, &bestI, &bestJ); // Find the best move for the computer, sending the address of bestI and bestJ
UpdateBoard(bestI, bestJ);
}
int winner = CheckWinner();
if (winner != 0)
{
HandleGameEnd(winner, hwnd);
}
else
{
CheckTie(hwnd);
}
}
}
}
void UpdateButtonFontSize(HWND button, int buttonWidth, int buttonHeight)
{
// Calculate the font size based on button dimensions
int fontSize = std::min(buttonWidth, buttonHeight) / 2;
// Set font size for the text on the button
HFONT hFont = CreateFont(fontSize, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
OUT_OUTLINE_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, VARIABLE_PITCH, TEXT("Arial"));
SendMessage(button, WM_SETFONT, WPARAM(hFont), TRUE);
}
void UpdateBoard(int i, int j)
{
board[i][j] = turn ? 1 : 2; // 1 for 'X', 2 for 'O'
SetWindowText(buttons[i][j], turn ? "X" : "O");
turn = !turn; // Switch turns
}
int CheckWinner()
{
// Check rows
for (int i = 0; i < SIZE; i++)
{
if (board[i][0] != 0 && board[i][0] == board[i][1] && board[i][1] == board[i][2])
{
return board[i][0];
}
}
// Check columns
for (int j = 0; j < SIZE; j++)
{
if (board[0][j] != 0 && board[0][j] == board[1][j] && board[1][j] == board[2][j])
{
return board[0][j];
}
}
// Check diagonals
if (board[0][0] != 0 && board[0][0] == board[1][1] && board[1][1] == board[2][2])
{
return board[0][0];
}
if (board[0][2] != 0 && board[0][2] == board[1][1] && board[1][1] == board[2][0])
{
return board[0][2];
}
// Check if the board is full
bool isBoardFull = true;
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
if (board[i][j] == 0)
{
isBoardFull = false;
break; // exit the inner loop as soon as an empty cell is found
}
}
if (!isBoardFull)
break; // exit the outer loop as soon as an empty cell is found
}
if (isBoardFull)
return 3;
return 0;
}
void HandleGameEnd(int winner, HWND hwnd)
{
char text[20];
// check winner, 1 = Player 1, 2 = Computer
// if winner = 3, then it's a tie
if (winner == 3)
sprintf(text, "Tie!\nPlay Again?");
else
sprintf(text, "Player %d wins!\nPlay Again?", winner);
int result = MessageBox(hwnd, text, "Game Over", MB_YESNO);
if (result == IDYES)
{
ResetGame();
}
else
{
PostQuitMessage(0);
}
}
void CheckTie(HWND hwnd)
{
bool tie = true;
bool breakOuterLoop = false; // Flag to break out of the outer loop
for (int i = 0; i < SIZE && !breakOuterLoop; i++)
{
for (int j = 0; j < SIZE; j++)
{
if (board[i][j] == 0)
{
tie = false;
breakOuterLoop = true; // Set the flag when an empty cell is found
break;
}
}
}
if (tie)
{
int result = MessageBox(hwnd, "Tie!\nPlay Again?", "Game Over", MB_YESNO);
if (result == IDYES)
{
ResetGame();
}
else
{
PostQuitMessage(0);
}
}
}
void ResetGame()
{
turn = true;
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
board[i][j] = 0;
SetWindowText(buttons[i][j], "");
}
}
}
int minimax(int board[SIZE][SIZE], int alpha, int beta, bool isMax)
{
int winner = CheckWinner();
if (winner == 1)
return -10;
if (winner == 2)
return 10;
if (winner == 3)
return 0;
bool tie = true;
for (int i = 0; i < SIZE && tie; i++)
for (int j = 0; j < SIZE; j++)
if (board[i][j] == 0)
tie = false;
if (tie)
{
return 0;
}
if (isMax)
{
int bestScore = -9999;
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
if (board[i][j] == 0)
{
board[i][j] = 2; // Try the computer's move
int score = minimax(board, alpha, beta, false); // Start minimax for the player's turn
board[i][j] = 0; // Reset the move
bestScore = std::max(bestScore, score);
alpha = std::max(alpha, bestScore);
if (beta <= alpha)
break;
}
}
}
return bestScore;
}
else
{
int bestScore = 9999;
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
if (board[i][j] == 0)
{
board[i][j] = 1; // Try the player's move
int score = minimax(board, alpha, beta, true); // Start minimax for the computer's turn
board[i][j] = 0; // Reset the move
bestScore = std::min(bestScore, score);
beta = std::min(beta, bestScore);
if (beta <= alpha)
break;
}
}
}
return bestScore;
}
}
void findBestMove(int board[SIZE][SIZE], int *bestI, int *bestJ)
{
int alpha = -9999;
int beta = 9999;
int bestScore = -9999;
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
if (board[i][j] == 0)
{ // If cell is empty
board[i][j] = 2; // Try the computer's move
int score = minimax(board, alpha, beta, false); // Start minimax for the player's turn
board[i][j] = 0; // Reset the move
if (score > bestScore)
{
bestScore = score;
*bestI = i;
*bestJ = j;
}
}
}
}
}