• 0

Now my c++ tictactoe has some AI to it and will play against a computer


Question

I am also taking an Artificial Intelligence class so I decided to add AI to my c++ project.Unfort I used abunch of IF statements to it.... Is there a better way to do this?

download here:

http://togermano.com/homework/cpp/tonysAItictactoe.exe


#include <windows.h>
//#include <stdlib.h>
#include <time.h>
#include <stdio.h>
// Made By Anthony Germano For Elms College Final Project
#define BUTTON1 100
#define BUTTON2 200
#define BUTTON3 300
#define BUTTON4 400
#define BUTTON5 500
#define BUTTON6 600
#define BUTTON7 700
#define BUTTON8 800
#define BUTTON9 900
#define BUTTON10 1000
int v1;
int compturnstop;
char const* b1 = "1";
char const* b2 = "2";
char const* b3 = "3";
char const* b4 = "4";
char const* b5 = "5";
char const* b6 = "6";
char const* b7 = "7";
char const* b8 = "8";
char const* b9 = "9";
char const* t1 = "1";
char const* t2 = "2";
char const* t3 = "3";
char const* t4 = "4";
char const* t5 = "5";
char const* t6 = "6";
char const* t7 = "7";
char const* t8 = "8";
char const* t9 = "9";
char win[16] = " wins"; //for msgbox
char out1[16] = ""; //for msgbox
char const* winner = "N"; //variable for if the last move is a winner and uses all buttons it doesnt say winner and tie
char const* tic = "X";
void enablebuttons(HWND hwnd){
EnableWindow(GetDlgItem(hwnd, BUTTON1), true);
EnableWindow(GetDlgItem(hwnd, BUTTON2), true);
EnableWindow(GetDlgItem(hwnd, BUTTON3), true);
EnableWindow(GetDlgItem(hwnd, BUTTON4), true);
EnableWindow(GetDlgItem(hwnd, BUTTON5), true);
EnableWindow(GetDlgItem(hwnd, BUTTON6), true);
EnableWindow(GetDlgItem(hwnd, BUTTON7), true);
EnableWindow(GetDlgItem(hwnd, BUTTON8), true);
EnableWindow(GetDlgItem(hwnd, BUTTON9), true);

}

void changetic(){
if (tic == "X"){
tic = "O";}
else if (tic == "O"){
tic = "X";
}
}
void disablebuttons(HWND hwnd){
EnableWindow(GetDlgItem(hwnd, BUTTON1), false);
EnableWindow(GetDlgItem(hwnd, BUTTON2), false);
EnableWindow(GetDlgItem(hwnd, BUTTON3), false);
EnableWindow(GetDlgItem(hwnd, BUTTON4), false);
EnableWindow(GetDlgItem(hwnd, BUTTON5), false);
EnableWindow(GetDlgItem(hwnd, BUTTON6), false);
EnableWindow(GetDlgItem(hwnd, BUTTON7), false);
EnableWindow(GetDlgItem(hwnd, BUTTON8), false);
EnableWindow(GetDlgItem(hwnd, BUTTON9), false);

}
void checkwin(HWND hwnd){
if (b1 == b2 && b1 == b3){
winner = "Y";
strcat(out1, b1);
strcat(out1, win);
disablebuttons(hwnd);
MessageBoxA(hwnd,out1,"TicTacToe",MB_OK|MB_ICONINFORMATION);}

if (b4 == b5 && b4 == b6){
winner = "Y";
strcat(out1, b4);
strcat(out1, win);
disablebuttons(hwnd);
MessageBoxA(hwnd,out1,"TicTacToe",MB_OK|MB_ICONINFORMATION);}
if (b7 == b8 && b7 == b9){
winner = "Y";
strcat(out1, b7);
strcat(out1, win);
disablebuttons(hwnd);
MessageBoxA(hwnd,out1,"TicTacToe",MB_OK|MB_ICONINFORMATION);}

if (b1 == b4 && b1 == b7){
winner = "Y";
strcat(out1, b1);
strcat(out1, win);
disablebuttons(hwnd);
MessageBoxA(hwnd,out1,"TicTacToe",MB_OK|MB_ICONINFORMATION);}
if (b2 == b5 && b2 == b8){
winner = "Y";
strcat(out1, b2);
strcat(out1, win);
disablebuttons(hwnd);
MessageBoxA(hwnd,out1,"TicTacToe",MB_OK|MB_ICONINFORMATION);}
if (b3 == b6 && b3 == b9){
winner = "Y";
strcat(out1, b3);
strcat(out1, win);
disablebuttons(hwnd);
MessageBoxA(hwnd,out1,"TicTacToe",MB_OK|MB_ICONINFORMATION);}
if (b1 == b5 && b1 == b9){
winner = "Y";
strcat(out1, b1);
strcat(out1, win);
disablebuttons(hwnd);
MessageBoxA(hwnd,out1,"TicTacToe",MB_OK|MB_ICONINFORMATION);}
if (b3 == b5 && b3 == b7){
winner = "Y";
strcat(out1, b3);
strcat(out1, win);
disablebuttons(hwnd);
MessageBoxA(hwnd,out1,"TicTacToe",MB_OK|MB_ICONINFORMATION);}
if (t1 == t2 && t3 == t4 && t5 == t6 && t7 == t8 && t7 == t9 && winner == "N"){

winner = "Y";
MessageBoxA(hwnd,"It is a Tie!!!","TicTacToe",MB_OK|MB_ICONINFORMATION);}


}
void computerturn(HWND hwnd){
int compturnstop = 0;
if (winner == "N"){

if (b1 == b2 && t3 != "U" && compturnstop == 0){
compturnstop = 3;
b3 = tic;
t3 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON3), false);
SetDlgItemText(hwnd, BUTTON3, tic);
checkwin(hwnd);
changetic();

}
if (b2 == b3 && t1 != "U" && compturnstop == 0){
compturnstop = 1;
b1 = tic;
t1 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON1), false);
SetDlgItemText(hwnd, BUTTON1, tic);
checkwin(hwnd);
changetic();

}
if (b4 == b5 && t6 != "U" && compturnstop == 0){
compturnstop = 6;
b6 = tic;
t6 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON6), false);
SetDlgItemText(hwnd, BUTTON6, tic);
checkwin(hwnd);
changetic();

}
if (b6 == b5 && t4 != "U" && compturnstop == 0){
compturnstop = 4;
b4 = tic;
t4 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON4), false);
SetDlgItemText(hwnd, BUTTON4, tic);
checkwin(hwnd);
changetic();

}
if (b6 == b8 && t9 != "U" && compturnstop == 0){
compturnstop = 9;
b9 = tic;
t9 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON9), false);
SetDlgItemText(hwnd, BUTTON9, tic);
checkwin(hwnd);
changetic();

}
if (b9 == b8 && t7 != "U" && compturnstop == 0){
compturnstop = 7;
b7 = tic;
t7 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON7), false);
SetDlgItemText(hwnd, BUTTON7, tic);
checkwin(hwnd);
changetic();

}
if (b1 == b4 && t7 != "U" && compturnstop == 0){
compturnstop = 7;
b7 = tic;
t7 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON7), false);
SetDlgItemText(hwnd, BUTTON7, tic);
checkwin(hwnd);
changetic();

}
if (b7 == b3 && t1 != "U" && compturnstop == 0){
compturnstop = 1;
b1 = tic;
t1 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON1), false);
SetDlgItemText(hwnd, BUTTON1, tic);
checkwin(hwnd);
changetic();

}

if (b2 == b5 && t8 != "U" && compturnstop == 0){
compturnstop = 8;
b8 = tic;
t8 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON8), false);
SetDlgItemText(hwnd, BUTTON8, tic);
checkwin(hwnd);
changetic();

}
if (b8 == b5 && t2 != "U" && compturnstop == 0){
compturnstop = 2;
b2 = tic;
t2 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON2), false);
SetDlgItemText(hwnd, BUTTON2, tic);
checkwin(hwnd);
changetic();

}
if (b3 == b6 && t9 != "U" && compturnstop == 0){
compturnstop = 9;
b9 = tic;
t9 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON9), false);
SetDlgItemText(hwnd, BUTTON9, tic);
checkwin(hwnd);
changetic();

}
if (b9 == b6 && t3 != "U" && compturnstop == 0){
compturnstop = 3;
b3 = tic;
t3 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON3), false);
SetDlgItemText(hwnd, BUTTON3, tic);
checkwin(hwnd);
changetic();

}
if (b1 == b3 && t2 != "U" && compturnstop == 0){
compturnstop = 2;
b2 = tic;
t2 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON2), false);
SetDlgItemText(hwnd, BUTTON2, tic);
checkwin(hwnd);
changetic();

}
if (b4 == b6 && t5 != "U" && compturnstop == 0){
compturnstop = 5;
b5 = tic;
t5 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON5), false);
SetDlgItemText(hwnd, BUTTON5, tic);
checkwin(hwnd);
changetic();

}
if (b7 == b9 && t8 != "U" && compturnstop == 0){
compturnstop = 8;
b8 = tic;
t8 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON8), false);
SetDlgItemText(hwnd, BUTTON8, tic);
checkwin(hwnd);
changetic();

}
if (b1 == b7 && t4 != "U" && compturnstop == 0){
compturnstop = 4;
b4 = tic;
t4 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON4), false);
SetDlgItemText(hwnd, BUTTON4, tic);
checkwin(hwnd);
changetic();

}
if (b2 == b8 && t5 != "U" && compturnstop == 0){
compturnstop = 5;
b5 = tic;
t5 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON5), false);
SetDlgItemText(hwnd, BUTTON5, tic);
checkwin(hwnd);
changetic();

}
if (b3 == b9 && t6 != "U" && compturnstop == 0){
compturnstop = 6;
b6 = tic;
t6 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON6), false);
SetDlgItemText(hwnd, BUTTON6, tic);
checkwin(hwnd);
changetic();

}
if (b3 == b5 && t7 != "U" && compturnstop == 0){
compturnstop = 6;
b7 = tic;
t7 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON7), false);
SetDlgItemText(hwnd, BUTTON7, tic);
checkwin(hwnd);
changetic();

}
if (b7 == b5 && t3 != "U" && compturnstop == 0){
compturnstop = 3;
b3 = tic;
t3 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON3), false);
SetDlgItemText(hwnd, BUTTON3, tic);
checkwin(hwnd);
changetic();

}
if (b1 == b5 && t9 != "U" && compturnstop == 0){
compturnstop = 9;
b9 = tic;
t9 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON9), false);
SetDlgItemText(hwnd, BUTTON9, tic);
checkwin(hwnd);
changetic();

}
if (b9 == b5 && t1 != "U" && compturnstop == 0){
compturnstop = 1;
b1 = tic;
t1 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON1), false);
SetDlgItemText(hwnd, BUTTON1, tic);
checkwin(hwnd);
changetic();

}

if (t5 == "5" && compturnstop == 0){
compturnstop = 5;
b5 = tic;
t5 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON5), false);
SetDlgItemText(hwnd, BUTTON5, tic);
checkwin(hwnd);
changetic();

}
if (t1 == "1" && compturnstop == 0){
compturnstop = 1;
b1 = tic;
t1 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON1), false);
SetDlgItemText(hwnd, BUTTON1, tic);
checkwin(hwnd);
changetic();

}
if (t3 == "3" && compturnstop == 0){
compturnstop = 3;
b3 = tic;
t3 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON3), false);
SetDlgItemText(hwnd, BUTTON3, tic);
checkwin(hwnd);
changetic();

}
if (t5 == "5" && compturnstop == 0){
compturnstop = 5;
b5 = tic;
t5 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON5), false);
SetDlgItemText(hwnd, BUTTON5, tic);
checkwin(hwnd);
changetic();

}
if (t7 == "7" && compturnstop == 0){
compturnstop = 7;
b7 = tic;
t7 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON7), false);
SetDlgItemText(hwnd, BUTTON7, tic);
checkwin(hwnd);
changetic();

}
if (t9 == "9" && compturnstop == 0){
compturnstop = 5;
b9 = tic;
t9 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON9), false);
SetDlgItemText(hwnd, BUTTON9, tic);
checkwin(hwnd);
changetic();

}
if (compturnstop == 0){
// MessageBoxA(hwnd,"Computer never took a turn","TicTacToe",MB_OK|MB_ICONINFORMATION);}

if (t1 != "U"){

compturnstop = 1;
b1 = tic;
t1 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON1), false);
SetDlgItemText(hwnd, BUTTON1, tic);
checkwin(hwnd);
changetic();
}
if (t2 != "U"){

compturnstop = 2;
b2 = tic;
t2 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON2), false);
SetDlgItemText(hwnd, BUTTON2, tic);
checkwin(hwnd);
changetic();
}
if (t3 != "U"){

compturnstop = 3;
b3 = tic;
t3 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON3), false);
SetDlgItemText(hwnd, BUTTON3, tic);
checkwin(hwnd);
changetic();
}
if (t4 != "U"){

compturnstop = 4;
b4 = tic;
t4 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON4), false);
SetDlgItemText(hwnd, BUTTON4, tic);
checkwin(hwnd);
changetic();
}
if (t5 != "U"){

compturnstop = 5;
b5 = tic;
t5 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON5), false);
SetDlgItemText(hwnd, BUTTON5, tic);
checkwin(hwnd);
changetic();
}
if (t6 != "U"){

compturnstop = 6;
b6 = tic;
t6 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON6), false);
SetDlgItemText(hwnd, BUTTON6, tic);
checkwin(hwnd);
changetic();
}
if (t6 != "U"){

compturnstop = 7;
b7 = tic;
t7 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON7), false);
SetDlgItemText(hwnd, BUTTON7, tic);
checkwin(hwnd);
changetic();
}
if (t6 != "U"){

compturnstop = 8;
b8 = tic;
t8 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON8), false);
SetDlgItemText(hwnd, BUTTON8, tic);
checkwin(hwnd);
changetic();
}
if (t9 != "U"){

compturnstop = 9;
b9 = tic;
t9 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON9), false);
SetDlgItemText(hwnd, BUTTON9, tic);
checkwin(hwnd);
changetic();
}
}

}
}
/* Declare Windows procedure */
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);
/* Make the class name into a global variable */
char szClassName[ ] = "WindowsApp";
int WINAPI WinMain (HINSTANCE hThisInstance,
HINSTANCE hPrevInstance,
LPSTR lpszArgument,
int nFunsterStil)
{
HWND hwnd; /* This is the handle for our window */
MSG messages; /* Here messages to the application are saved */
WNDCLASSEX wincl; /* Data structure for the windowclass */
/* The Window structure */
wincl.hInstance = hThisInstance;
wincl.lpszClassName = szClassName;
wincl.lpfnWndProc = WindowProcedure; /* This function is called by windows */
wincl.style = CS_DBLCLKS; /* Catch double-clicks */
wincl.cbSize = sizeof (WNDCLASSEX);
/* Use default icon and mouse-pointer */
wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
wincl.lpszMenuName = NULL; /* No menu */
wincl.cbClsExtra = 0; /* No extra bytes after the window class */
wincl.cbWndExtra = 0; /* structure or the window instance */
/* Use Windows's default color as the background of the window */
wincl.hbrBackground = (HBRUSH)CreateSolidBrush(RGB(255,3,3));
//http://cboard.cprogramming.com/windows-programming/113200-window-background-color.html
/* Register the window class, and if it fails quit the program */
if (!RegisterClassEx (&wincl))
return 0;
/* The class is registered, let's create the program*/
hwnd = CreateWindowEx (
0, /* Extended possibilites for variation */
szClassName, /* Classname */
"Tony's Amazing Tic Tac Toe", /* Title Text */
WS_OVERLAPPEDWINDOW, /* default window */
CW_USEDEFAULT, /* Windows decides the position */
CW_USEDEFAULT, /* where the window ends up on the screen */
380, /* The programs width */
395, /* and height in pixels */
HWND_DESKTOP, /* The window is a child-window to desktop */
NULL, /* No menu */
hThisInstance, /* Program Instance handler */
NULL /* No Window Creation data */
);
CreateWindow("button", "1", WS_CHILD | WS_VISIBLE |BS_DEFPUSHBUTTON, 50, 10, 50, 50, hwnd, (HMENU)BUTTON1, GetModuleHandle (NULL), NULL);
CreateWindow("button", "2", WS_CHILD | WS_VISIBLE |BS_DEFPUSHBUTTON, 150, 10, 50, 50, hwnd, (HMENU)BUTTON2, GetModuleHandle (NULL), NULL);
CreateWindow("button", "3", WS_CHILD | WS_VISIBLE |BS_DEFPUSHBUTTON, 250, 10, 50, 50, hwnd, (HMENU)BUTTON3, GetModuleHandle (NULL), NULL);
CreateWindow("button", "4", WS_CHILD | WS_VISIBLE |BS_DEFPUSHBUTTON, 50, 110, 50, 50, hwnd, (HMENU)BUTTON4, GetModuleHandle (NULL), NULL);
CreateWindow("button", "5", WS_CHILD | WS_VISIBLE |BS_DEFPUSHBUTTON, 150, 110, 50, 50, hwnd, (HMENU)BUTTON5, GetModuleHandle (NULL), NULL);
CreateWindow("button", "6", WS_CHILD | WS_VISIBLE |BS_DEFPUSHBUTTON, 250, 110, 50, 50, hwnd, (HMENU)BUTTON6, GetModuleHandle (NULL), NULL);
CreateWindow("button", "7", WS_CHILD | WS_VISIBLE |BS_DEFPUSHBUTTON, 50, 210, 50, 50, hwnd, (HMENU)BUTTON7, GetModuleHandle (NULL), NULL);
CreateWindow("button", "8", WS_CHILD | WS_VISIBLE |BS_DEFPUSHBUTTON, 150, 210, 50, 50, hwnd, (HMENU)BUTTON8, GetModuleHandle (NULL), NULL);
CreateWindow("button", "9", WS_CHILD | WS_VISIBLE |BS_DEFPUSHBUTTON, 250, 210, 50, 50, hwnd, (HMENU)BUTTON9, GetModuleHandle (NULL), NULL);
CreateWindow("button","Start Game!", WS_CHILD | WS_VISIBLE |BS_DEFPUSHBUTTON, 130, 300, 100, 50, hwnd, (HMENU)BUTTON10, GetModuleHandle (NULL), NULL);
/* Make the window visible on the screen */
ShowWindow (hwnd, nFunsterStil);
disablebuttons(hwnd);
/* Run the message loop. It will run until GetMessage() returns 0 */
while (GetMessage (&messages, NULL, 0, 0))
{
/* Translate virtual-key messages into character messages */
TranslateMessage(&messages);
/* Send message to WindowProcedure */
DispatchMessage(&messages);
}
/* The program return-value is 0 - The value that PostQuitMessage() gave */
return messages.wParam;
}
/* This function is called by the Windows function DispatchMessage() */

LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message) /* handle the messages */
{
case WM_COMMAND:
switch(LOWORD(wParam)) {
case BUTTON1:{
b1 = tic;
t1 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON1), false);
SetDlgItemText(hwnd, BUTTON1, tic);
checkwin(hwnd);
changetic();
computerturn(hwnd);

}


}


switch(LOWORD(wParam)) {
case BUTTON2:{
b2 = tic;
t2 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON2), false);

SetDlgItemText(hwnd, BUTTON2, tic);
checkwin(hwnd);
changetic();
computerturn(hwnd);
}

}

switch(LOWORD(wParam)) {
case BUTTON3:{
b3 = tic;
t3 = "U";

EnableWindow(GetDlgItem(hwnd, BUTTON3), false);
SetDlgItemText(hwnd, BUTTON3, tic);
checkwin(hwnd);
changetic();
computerturn(hwnd);
}

}

switch(LOWORD(wParam)) {
case BUTTON4:{
b4 = tic;
t4 = "U";

EnableWindow(GetDlgItem(hwnd, BUTTON4), false);
SetDlgItemText(hwnd, BUTTON4, tic);
checkwin(hwnd);
changetic();
computerturn(hwnd);
}

}

switch(LOWORD(wParam)) {
case BUTTON5:{
b5 = tic;
t5 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON5), false);
SetDlgItemText(hwnd, BUTTON5, tic);
checkwin(hwnd);
changetic();
computerturn(hwnd);
}

}
switch(LOWORD(wParam)) {
case BUTTON6:{
b6 = tic;
t6 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON6), false);
SetDlgItemText(hwnd, BUTTON6, tic);
checkwin(hwnd);
changetic();
computerturn(hwnd);
}

}

switch(LOWORD(wParam)) {
case BUTTON7:{
b7 = tic;
t7 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON7), false);
SetDlgItemText(hwnd, BUTTON7, tic);
checkwin(hwnd);
changetic();
computerturn(hwnd);
}

}

switch(LOWORD(wParam)) {
case BUTTON8:{
b8 = tic;
t8 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON8), false);
SetDlgItemText(hwnd, BUTTON8, tic);
checkwin(hwnd);
changetic();
computerturn(hwnd);
}

}
switch(LOWORD(wParam)) {
case BUTTON9:{
b9 = tic;
t9 = "U";
EnableWindow(GetDlgItem(hwnd, BUTTON9), false);
SetDlgItemText(hwnd, BUTTON9, tic);
checkwin(hwnd);
changetic();
computerturn(hwnd);
}


}
switch(LOWORD(wParam)) {
case BUTTON10:{
srand (time(NULL));
/* generate secret number between 1 and 10: */
v1 = rand() % 10 + 1;
enablebuttons(hwnd);
if (v1 <= 4){
MessageBoxA(hwnd,"computer goes first!","TicTacToe",MB_OK|MB_ICONINFORMATION);
computerturn(hwnd);
}

if (v1 >= 5){
MessageBoxA(hwnd,"Person goes first!","TicTacToe",MB_OK|MB_ICONINFORMATION);}

}
}




break;

case WM_DESTROY:
PostQuitMessage (0); /* send a WM_QUIT to the message queue */
break;
default: /* for messages that we don't deal with */
return DefWindowProc (hwnd, message, wParam, lParam);
}
return 0;
}
[/CODE]

13 answers to this question

Recommended Posts

  • 0

Congrats man! I do not know of a better way.. but congrats on getting that far :)

Thanks Id like to change the windows api and see if I can change it around to run on linux or maybe try Haiku first (beos clone)

  • 0

A lot of this code is repetitive, so you could at least make functions that take the parts that vary as parameters.

A tic-tac-toe AI is basically a function that takes a game position as a parameter and returns the best move. One way to do this is pre-encode all possible positions along with their respective best moves in some kind of map structure. This is easy to do by hand for a 3x3 tic-tac-toe, but quickly becomes impractical if the board gets larger (the number of possible positions increases exponentially). Implementing the AI is then as easy as a look up in a table.

If you want to code a real AI that actually finds the best move dynamically, I suggest looking into the minimax algorithm. This is the basis of AI engines for chess, checkers, reverso and all those turn-based positional games.

  • Like 2
  • 0

A lot of this code is repetitive, so you could at least make functions that take the parts that vary as parameters.

A tic-tac-toe AI is basically a function that takes a game position as a parameter and returns the best move. One way to do this is pre-encode all possible positions along with their respective best moves in some kind of map structure. This is easy to do by hand for a 3x3 tic-tac-toe, but quickly becomes impractical if the board gets larger (the number of possible positions increases exponentially). Implementing the AI is then as easy as a look up in a table.

If you want to code a real AI that actually finds the best move dynamically, I suggest looking into the minimax algorithm. This is the basis of AI engines for chess, checkers, reverso and all those turn-based positional games.

Yes your right we learned about minimax but wasn't sure how to do in c++

  • 0

Before you attempt to optimize the AI algorithm, definitely clean the code up first. I think you can reduce the amount of code to maybe a third of what it is now by making helper functions to eliminate the repetition as suggested. Less code, less potential bugs.

And if you are up for a redesign, consider going the OOP approach as that is the main strength of C++ over C.

  • 0

wow what a mess :p anyways im sure you'll work on cleaning up your code as you mature as a programmer. just something i noticed right off the bat,i dont think you're using switches correctly.

from your code

switch (message) /* handle the messages */

{

case WM_COMMAND:

switch(LOWORD(wParam)) {

case BUTTON1:{

b1 = tic;

t1 = "U";

EnableWindow(GetDlgItem(hwnd, BUTTON1), false);

SetDlgItemText(hwnd, BUTTON1, tic);

checkwin(hwnd);

changetic();

computerturn(hwnd);

}

}

switch(LOWORD(wParam)) {

case BUTTON2:{

b2 = tic;

t2 = "U";

EnableWindow(GetDlgItem(hwnd, BUTTON2), false);

SetDlgItemText(hwnd, BUTTON2, tic);

checkwin(hwnd);

changetic();

computerturn(hwnd);

}

}

why do you keep using switch(LOWORD(wParam)) for every check of a button?

it should be

switch(LOWORD(wParam))

{

case BUTTON1:

yadda yadda

break;

case BUTTON2:

yadda yadda

break;

case BUTTON3:

break;

case BUTTON4:

break;

}

  • 0

Before you attempt to optimize the AI algorithm, definitely clean the code up first. I think you can reduce the amount of code to maybe a third of what it is now by making helper functions to eliminate the repetition as suggested. Less code, less potential bugs.

And if you are up for a redesign, consider going the OOP approach as that is the main strength of C++ over C.

Thank you I know oop but isn't this only useful if your program is about keeping data?

wow what a mess :p anyways im sure you'll work on cleaning up your code as you mature as a programmer. just something i noticed right off the bat,i dont think you're using switches correctly.

from your code

why do you keep using switch(LOWORD(wParam)) for every check of a button?

it should be

switch(LOWORD(wParam))

{

case BUTTON1:

yadda yadda

break;

case BUTTON2:

yadda yadda

break;

case BUTTON3:

break;

case BUTTON4:

break;

}

I thought I tried that and it didn't work.... I'll try it again later thou thanks

If you understand the algorithm then it's just a matter of learning the language. That's a much easier problem thankfully. :)

I think minmax will require alot more code?

I'd look at refactoring a lot of your code into function(s) as a first step - remove the repetition.

Thanks

  • 0
I think minmax will require alot more code?
If you know what you're doing it's not that much code... I get the feeling you're pretty new to programming with a general-purpose language, so perhaps coding a minimax-based AI (which is a lot more than just the algorithm itself) is outside of your grasp for now. Brush up on your data structures and algorithms and it should be fairly obvious how to do this.
  • 0

I actually wrote a (console based) Tic Tac Toe game in C++ two days ago. For my AI player implementation I wanted to avoid "Googling it" and implementing an algorithm, but as an experiment I just threw together whatever came to mind. Please note I am very much not an AI person (did a module on Machine Learning at Uni, it sucked the life out of me). My AI player doesn't try to block the human player because I couldn't be especially bothered to write that, but it wouldn't be hard to implement a test against the human players last move following the same ideas as the current code (i.e, checking which line the player's trying to fill and blocking it). If you're interested this was my code for the AI decision...

(Where char map[] is a 1D array of each square on the board left-to-right top-to-bottom, and int size is the width/height of the board (i.e, standard game of 3x3, 9 cells, size = 3))


int AIPlayer::YourMove(char map[], int size){
int move;
cout << "Computer player's move!" << endl;
if (lastMove == -1){
move = ((size*size)-1) / 2;
if (isFree(map,move)){
map[move] = _thischar;
}else{
if (isFree(map, 0)){
move = 0;
}else if (isFree(map, size-1)){
move = size-1;
}else if (isFree(map, size * (size-1))){
move = size * (size-1);
}else if (isFree(map, (size*size)-1)){
move = (size*size)-1;
}
}
}else{
int tmp = lastMove;
int iters = 0;
while(true){
move = testNeighbours(tmp, size, map);
if (move == -1 && iters < 30){
tmp = (rand() % (size*size));
iters++;
}else if (iters >= 30){
move = 0;
while (!isFree(map, move)) move = (rand() % (size*size));
break;
}else break;
}
}
map[move] = _thischar;
lastMove = move;
return move;
}
int AIPlayer::testNeighbours(int target, int size, char map[]){
/*
So... the way we're going to run this...
Take the target, scale it back to the start of it's horiz, vert, and diag lines (if rlvnt)
and run a test with testSequence which will check each element. If the whole path is clear
it's worth trying to fill up, so go for it.
Otherwise return a -1 and wait for a different target value.
*/
int chosen;
int vert = target;
while (vert >= size) vert -= size;
chosen = testSequence(vert, size, size, map);
if (chosen != -1) return chosen;
int horiz = target;
while (horiz % size != 0) horiz -= 1;
chosen = testSequence(horiz, 1, size, map);
if (chosen != -1) return chosen;
int diag = target;
if (target % (size+1) == 0){ //top-left to btm-right
while (diag != 0) diag -= size+1;
chosen = testSequence(diag, size+1, size, map);
if (chosen != -1) return chosen;
}
diag = target;
if (target % (size-1) == 0){ //top-right to btm-left
while (diag != (size-1)) diag -= size-1;
chosen = testSequence(diag, size-1, size, map);
if (chosen != -1) return chosen;
}
return -1;
}
int AIPlayer::testSequence(int start, int step, int size, char map[]){
int lfree;
for (int i=start;i<start+(size*step);i+=step){
if ( isFree(map, i) ) {lfree=i;continue;}
if ( map[i] != _thischar ) return -1;
}
return lfree;
}
[/CODE]

And to quote my own readme...

On it's first move it merely checks the "highly desirable" squares in the middle and corners, taking the first available. Subsequently, it uses it's previous move to decide it's next by checking the vertical, horizontal and diagonal (if applicable) paths which cross through the previous move. If it finds an opponents piece in one of these paths it is discounted as being "unwinnable", and it moves on to the next checking direction. If all directions are obstructed it picks a random cell and starts again from there. It is therefore trivial to beat the AI by forming your own line parallel to the one it's creating - it all just depends who makes the first move!

You can download my full code here: http://nerdshack.info/?p=730

  • 0

You are doing a lot of potentially dodgy string comparisons in your code.


// This is bad
char const * a = "a";
char const * b = "a";
bool eq1 = a == b;

// Slightly better
bool eq1 = strcmp(a, b) == 0;

// This is much better
std::string a = "a", b = "a";
bool eq2 = a == b;
[/CODE]

The C string comparisons will work if your compiler stores duplicate C strings in the same location in memory (which MSVC does do).

However, you cannot rely on this behaviour. So either use std::string to store the strings and make use of its equality operator,

or use strncmp on the two character arrays.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Onkyo Dolby Atmos AV receivers are really solid deals by Sayan Sen Recently we covered great deals on several soundbar models from the likes of Sony, JBL, Samsung and others for really good prices (the lowest in several months). Aside from that we also reported on the Edifier S3000MKII, a hi-fi two-way bookshelf monitor that's available for only $800. Today we bring a list of AV receivers from Onkyo that are available at great prices including the Onkyo NR7100, RZ30, and 8470 (purchase links under the specs table down below). The Onkyo TX-NR7100 and Onkyo TX-RZ30 are both 9.2-channel AV receivers designed for immersive home theater setups but they occupy slightly different tiers within Onkyo’s lineup with the RZ30 positioned as the more advanced model. The TX-NR7100 is a THX Certified 9.2-channel receiver offering up to 100 W per channel (8 ohms, 2 channels driven). It supports Dolby Atmos, DTS:X, and IMAX Enhanced formats, with flexible configurations such as 5.1.4 or 7.1.2 speaker layouts. A key highlight is its built-in Dirac Live Room Correction which should help optimize sound based on your room and its acoustics. In comparison, both models share several core capabilities though the RZ30 is geared toward enthusiasts seeking more precise calibration and system flexibility, while the NR7100 is positioned as a slightly more accessible, value-focused option with strong all-round performance. The technical specs of the RZ30 and NR7100 9.2 AVRs are given in the table below: Specification Onkyo TX-RZ30 Onkyo TX-NR7100 Power Output (FTC, 2ch driven) ~100 W/ch (8Ω, 20Hz–20kHz, 0.08% THD) 100 W/ch (8Ω, 20Hz–20kHz, 0.08% THD) Dynamic / Peak Power 9 × 170 W (6Ω, 1kHz, 1% THD, 1ch driven) 220 W/ch (6Ω, 1kHz, 10% THD, 1ch driven) Frequency Response 5 Hz – 100 kHz (+1/-3 dB) 10 Hz – 100 kHz (+1/-3 dB) THD 0.08% 0.08% Room Correction Dirac Live (full bandwidth) Dirac Live (with AccuReflex support) Immersive Audio Dolby Atmos, DTS:X, IMAX Enhanced Dolby Atmos, DTS:X, IMAX Enhanced Speaker Layout Support Up to 7.2.2 / 5.2.4 / 9.2 processing Up to 7.2.4 / 5.2.4 / 9.2 processing HDMI Inputs / Outputs 6 inputs / 2 outputs (eARC) 6 inputs / 2 outputs (Main + Sub/Zone 2) HDMI 2.1 Support 8K/60, 4K/120, VRR, ALLM, QFT, DSC, eARC 8K/60, 4K/120, VRR, ALLM, QFT, DSC, eARC Video Formats HDR10+, Dolby Vision, HDCP 2.3 HDR10+, Dolby Vision, HDCP 2.3 Streaming / Network Wi-Fi, AirPlay 2, Chromecast, Bluetooth, DTS Play-Fi Wi-Fi, AirPlay 2, Chromecast, Bluetooth, DTS Play-Fi Get them at the links below: Onkyo TX-RZ30 9.2-Channel AV Receiver: $797.00 (Sold and shipped by Electronic Expo) Onkyo TX-NR7100 9.2-Channel AV Receiver: $699.00 (Sold and shipped by Adorma) Onkyo TX-8470 2 Ch Stereo Receiver: $449.00 (Sold and Shipped by Adorma) Good to know This Amazon deal is U.S. specific, and not available in other regions unless specified. We only use first-party seller links or authorized dealer links (at the time of article publishing); ensure that you purchase from such links only. Check out Today's Deals on Amazon | or our recent tech deals. Become a Prime member (for Students or SNAP) via Neowin Get Prime Access - Prime for half price (for qualifying Medicaid, EBT, SNAP) Subscribe to Prime Video, Audible Plus, Music Unlimited or Kindle Unlimited via Neowin As an Amazon Associate, we earn from qualifying purchases.
    • A different thing with Russia. When you say is it better, depends on things. It is better that we don't have the E.U making rules and laws that have nothing to do with them. Is the trading part better? No, that is really mucked up, but then we knew that was going to happen and we would have make agreements, like we do with other parts of the world. Freedom of movement is certainly better, but could be improved, we still need more control over our borders. do you live in the U.K?
    • So what am I quoting from them? I never listened to what Farage or his cronies said. I wanted the U.K to leave the E.u years before the referendum and it had nothing to do with Farage and his cronies. So what country do you live in? Did we work much better together? We were always at logger heads with the E.U because we disagreed with them so much. Maggie was always on at them. I would have thought the E.U was glad to get rid of us as we stopped the integration or made it a two tier. Now without us they can integrate more. I would not have voted out if it was just a trading block and we can still work together on somethings.
    • MPC-BE 1.9.0 by Razvan Serea Media Player Classic - BE is a free and open source audio and video player for Windows. Media Player Classic - BE is based on the original "Media Player Classic" project (Gabest) and "Media Player Classic Home Cinema" project (Casimir666), contains additional features and bug fixes. The BE mod (Black Edition Mod) is a skinned version of Media Player Classic Home Cinema, much better looking than the plain old MPC. MPC-BE 1.9.0 changelog: Splitters Fixed crashes in some situations. AudioSplitter Added support for the RF64 format. Fixed reading of channel layout for some WavPack files. Added support for ID3 tags for Wave64 files. Unknown Wave64 chunks are now ignored. AviSplitter Added support for 'y408' video. Improved support for 'HEVC' video. FLVSplitter Added support for VVC video. MP4Splitter Improved handling of corrupted files. MatroskaSplitter Expanded support for V_UNCOMPRESSED video codecs. Fixed support for frame rotation (ProjectionPoseRoll). Improved support for "V_MS/VFW/FOURCC / HEVC". MpcDvdVideoDecoder Fixed conversion to YUY2. Fixed display of menus for some DVD-Videos. RoQVideoDecoder Output in NV12 and YV12 formats is allowed. Full range is used. MPC Video Decoder RGB32 format will be output as a top-down bitmap by default. Added support for the "IID_MediaSideDataDOVIMetadataV2" interface. Removed support for the deprecated "IID_MediaSideDataDOVIMetadata" interface. Fixed retrieving the name of the video adapter when using NVDEC. Fixed crashes in some situations. MPC Video Converter Added support for AYUV video format. MpcAudioRenderer Improved input format validation. Optimized retrieval of supported formats for exclusive mode. Added the "Keep audio device active when paused" setting. Fixed crashes and freezes in various situations. Subtitles Added the ability to open the properties of an external subtitle renderer in the "Subtitles" settings panel. Fixed external subtitle connections for VSFilter. Fixed a crash when rendering PGS/SUP subtitles when using AVX2. YouTube Improved support for yt-dlp. The built-in YouTube parser is no longer used. Player The HTTP read strategy has been changed. If the playlist contains one entry, more key combinations can be used to control the player (jump through chapters, adjust volume). Improved support for reading ASX playlists. The translation of the MediaInfo report for Chinese, Korean and Japanese has been removed. Added blocking of 32-bit filter "PICVideo Lossless JPEG Decompressor" (pvljpg20.dll), because it crashes. Added blocking of the system filter "AVI Decompressor", which will eliminate the crash of VFW codecs. Fixed a rare crash when using the "/slave" key. Fixed a crash when getting a list of fonts for OSD. Added the ability to load an external audio file using hotkeys. Fixed opening a network path starting with \?\UNC. The "Determine duration when adding" playlist setting now works for YouTube video URLs. The "Online media services" settings panel has been redesigned. Added a "Merge files using FFmpeg" option to the file saving dialog. This option is activated when playing multiple streams obtained using yt-dlp. Added loading of local .dpl playlists ("DAUMPLAYLIST"). Fixed a hang when the user closes the player during the URL opening process. Various interface fixes. Installer Updated MPC Video Renderer 0.10.5. Updated MPC Script Source 0.2.17. Added MPC Image Source 0.3.6. Translations Updated Japanese translation (by tsubasanouta). Updated Chinese (Traditional) and Dutch translation (by beter). Updated Romanian translation (by Andrei Miloiu). Updated Hungarian translation (by mickey). Updated Turkish translation (by cmhrky). Updated German translation (by Klaus1189). Updated Chinese (Simplified) translation (by wushantao). Updated Italian translation (by mapi68). Updated Korean translation (by Hackjjang). Updated Chinese (Traditional) (by udfbe). Updated libraries dav1d 1.5.3-6-g04b69f9; ffmpeg n8.2-dev-1857-g4653e68aab; libpng git-v1.6.55-9-g7d52a8087; Little-CMS git-lcms2.18-26-gf739cda; MediaInfo git-v26.05-38-g702c9b7fd; ZenLib git-v0.4.41-91-g073f297; zlib 1.3.2. Download: MPC-BE 64-bit | Portable MPC-BE 64-bit | ~20.0 MB (Open Source) Download: MPC-BE 32-bit | Portable MPC-BE 32-bit Link: Media Player Classic - BE Home Page Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Apple reportedly looks to blacklisted Chinese memory chips as RAM prices climb by Karthik Mudaliar Image via Apple Apple is reportedly trying to get a clearance from the Trump administration to buy memory from ChangXin Memory Technologies (CXMT) to get some relief from soaring DRAM prices. As per a report by the Financial Times, Apple approached the Commerce Department more than a month ago and also spoke to other officials and allies in Washington. For starters, CXMT is a company that's already been placed on the Pentagon's list of Chinese military companies. The Chinese company is the country's top DRAM maker. For Apple, the timing is certainly awkward but not surprising. Tim Cook had recently warned that Apple would have to raise prices because AI companies are buying up large amounts of memory for data centers, and just like that, Apple raised MacBook and iPad prices. Micron also recently revealed that customers have committed billions of dollars to secure memory supply years in advance, which shows us how aggressive securing infrastructure has become. This gives suppliers such as Samsung, SK Hynix, and Micron more leverage, while pushing hardware makers to look for alternatives. CXMT is one of those alternatives, but not the simplest one. Apple has spent many years trying to diversify parts of its supply chain away from China, especially for final assembly, while still depending heavily on Chinese manufacturing and suppliers. Even domestic brands from China are moving towards CXMT and YMTC instead of relying on Samsung, Micron, and SK Hynix. For Apple, though, it would invite more scrutiny than local Chinese companies. For now, this is more like a lobbying effort rather than a confirmed supply deal. There's no official statement from either of the parties. What is clearer, though, is the pressure behind such a request. AI demand has certainly made hardware a bottleneck, and companies are trying everything they can to bring things back to normal, even if that means making politically sensitive choices. Source: Financial Times
  • Recent Achievements

    • Week One Done
      flexorcist earned a badge
      Week One Done
    • One Month Later
      Woland13 earned a badge
      One Month Later
    • Week One Done
      Woland13 earned a badge
      Week One Done
    • One Year In
      bernmeister earned a badge
      One Year In
    • Week One Done
      Scoobystu earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      498
    2. 2
      +Edouard
      227
    3. 3
      PsYcHoKiLLa
      149
    4. 4
      Steven P.
      75
    5. 5
      FloatingFatMan
      70
  • Tell a friend

    Love Neowin? Tell a friend!