In this program we play tic tac toe against AI whith minimax algorithm. This code isn't mine. Im just trying to understand why it doesn't work. Please explain why it shows mistake in function void cmp.
#include<stdio.h>
#include<iostream>
using namespace std;
char brd[]= {49,50,51,52,53,54,55,56,57};
int mv=0;
void board() {
cout << "|_" << brd[0] << "_|_" << brd[1] << "_|_" << brd[2] << "_|\n";
cout << "|_" << brd[3] << "_|_" << brd[4] << "_|_" << brd[5] << "_|\n";
cout << "|_" << brd[6] << "_|_" << brd[7] << "_|_" << brd[8] << "_|\n\n";
}
int iswin(char le,char ar[]) {
int cr,h,v;
cr= ar[0]==le && ar[4]==le && ar[8]==le || ar[2]==le && ar[4]==le && ar[6]==le;
h= ar[0]==le && ar[1]==le && ar[2]==le || ar[3]==le && ar[4]==le && ar[5]==le || ar[6]==le && ar[7]==le && ar[8]==le ;
v= ar[0]==le && ar[3]==le && ar[6]==le || ar[1]==le && ar[4]==le && ar[7]==le || ar[2]==le && ar[5]==le && ar[8]==le ;
return (cr||h||v); }
Here is the mistake
void cmp() {
int bestscore=-1000,score,move,k,i;
for(i=0; i<=8; i++) {
if(brd[i]!='X'&& brd[i]!='O') {
k=brd[i];
brd[i]='O';
score=minimax(brd,0);
brd[i]=k;
if(score>bestscore) {
move=i;
bestscore=score;
} } }
brd[move]='O'; }
This is function that causes mistake. It goes right after void cmp.
int minimax(char cb[],int max) {
int i,bestscore,score,k;
if(iswin('O',cb))
return 100;
if(iswin('X',cb))
return -100;
if(draw())
return 0;
if(max) {
bestscore=-1000;
for(i=0; i<=8; i++) {
if(cb[i]!='X'&& cb[i]!='O') {
k=cb[i];
cb[i]='O';
score=minimax(cb,0);
cb[i]=k;
if(score>bestscore)
bestscore=score;
} }
return bestscore; }
else {
bestscore=800;
for(i=0; i<=8; i++) {
if(brd[i]!='X'&& brd[i]!='O') {
k=cb[i];
cb[i]='X';
score=minimax(cb,1);
cb[i]=k;
if(score<bestscore)
bestscore=score;
} }
return bestscore;
} }