Un simple juego tres en raya implementado con el algoritmo minimax
#include <windows.h>
#include <iostream>
using namespace std;
int t[9];
int check( int turno ){
int G = 0;
int r[8][3] = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},
{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
for( int f = 0; f < 8; f++ )
if( (t[ r[f][0] ] + t[ r[f][1] ] + t[ r[f][2] ] ) == (turno*3) )
G = turno;
return G;
}
int minimax( int p ,int tr ){
int minimax_val = 0;
bool empate = false;
t[p] = tr;
if( check( tr ) == tr )
return tr;
else
for( int f = 0; f < 9; f++){
if( t[f] != 0 ) continue;
int next = minimax( f, -tr);
if( next == -tr ){
t[f] = 0;
return -tr;
}
else if( next == 0){
minimax_val = 0;
empate = true;
}
else if( next == tr )
if( !empate )
minimax_val = tr;
t[f] = 0;
}
return minimax_val;
}
void Graficar(){
system("cls");
cout << "\n\n Se juega con:\n 1 2 3\n 4 5 6\n 7 8 9\n La computadora juega con O\n\n";
for(int f = 0; f < 9;f++){
if( t[f] == 1 ) cout <<" O ";
else if( t[f] == -1 ) cout << " X ";
else cout << " - ";
if( (f +1 )%3 == 0 ) cout << "\n";
}
}
int main(){
memset(t,0,sizeof(t));
bool Jugando = true;
int tr = 1; /*Si es 1 empieza la computadora, si es -1 Empieza la persona*/
int c = 0;
int g = 0;
while(Jugando){
Graficar();
if(tr == 1){
int mejor_movimiento = -1;
int anext = -1;
for(int f = 0; f < 9;f++){
if( t[f] != 0) continue;
int next = minimax( f, 1);
if( next > anext ){
anext = next;
mejor_movimiento = f;
}
t[f] = 0;
}
t[mejor_movimiento] = 1;
}
else{
int m = -1;
while( !(m > -1 and m < 10) )
cin >> m;
t[m-1] = -1;
}
g = check(tr);
if( g == 1 or g == -1 )
Jugando = false;
else if( c == 8 ){
g = 0;
Jugando = false;
}
tr = -tr;
c++;
}
Graficar();
switch(g){
case 1: cout << "HA GANADO LA COMPUTADORA!!\n"; break;
case -1: cout << "HAS GANADO FELICIDADES!!\n"; break;
case 0: cout <<"ES EMPATE, BUEN LOGRO!!\n"; break;
}
getchar();
return 0;
}
Si juegas empatas o pierdes