473,386 Members | 1,860 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

minimax algorithm not working properly

hello i got frustrated after making several tries to make the minimax algorithm work in my console tic tac toe. the problem is the algorithm
doesn't play the game as it should.The thing is it just tries to play the move that it 'sees' to be the best for itself without caring that its opponet
is building an easy three to win the game.
For ex. it playing as second player as

ist player row=0;col=0;
minimax player row=2;col=1;
ist player row=0;col=1;
minimax row=2;col=0;(ignoring the fact the player will win in next move)
ist player row=0;col=2 and wins

so please help me finding the bug in this code.thank you.

Expand|Select|Wrap|Line Numbers
  1. //board.h file
  2.  
  3. #ifndef BOARD_H
  4. #define BOARD_H
  5.  
  6. #include<iostream>
  7. #include<cstdlib>
  8. using namespace std;
  9.  
  10.  
  11.  
  12. enum PosValue {O_WIN=-1,TIE,X_WIN,UNDEFINED};
  13. enum Piece {NAUGHT=-1,EMPTY,CROSS};
  14. enum Player {HUMAN=1,COMP};
  15.  
  16.  
  17.  
  18. class board
  19. {
  20. public:
  21.  
  22.     board();
  23.     ~board(){}
  24.     void initBoard(Player pl);
  25.     bool isAWin(Piece p);
  26.     bool isBoardFull();
  27.     bool isOver();
  28.     int evaluate();
  29.     bool makeMove(int r,int c,Piece p=EMPTY);
  30.     void undoMove(int r,int c);
  31.     void drawBoard();
  32.     Piece turnToPiece();
  33.     void alterTurn();
  34.     Player firstPlayer;
  35.     void playComp();
  36.     void playHuman();
  37.  
  38.     int chooseMove(Piece p,int &row,int &col);
  39.  
  40.  
  41. private:
  42.  
  43.     Piece hold[3][3];
  44.  
  45.     void placeMove(int r,int c,Piece p=EMPTY);
  46.     char pieceToChar(Piece p);
  47.     int turn;
  48.  
  49.  
  50. };
  51.  
  52. #endif
  53.  
  54. //board.cpp file
  55.  
  56. #include "board.h"
  57.  
  58. board::board()
  59. {
  60.  
  61. }
  62.  
  63. void board::initBoard(Player pl) //initialize the board, gets who is first playing
  64. {
  65.     firstPlayer=pl;
  66.     for(int i=0;i<3;i++)
  67.         for(int j=0;j<3;j++)
  68.             hold[i][j]=EMPTY;
  69.  
  70.     turn =1;
  71. }
  72.  
  73.  
  74.  
  75. bool board::isAWin(Piece p) //checks whether a Piece wins
  76. {
  77.     int row, column;
  78.  
  79.     //  check all rows
  80.     for( row = 0; row < 3; row++ )
  81.     {
  82.         for( column = 0; column < 3; column++ )
  83.             if( hold[ row ][ column ] != p )
  84.                 break;
  85.         if( column >= 3 )
  86.             return true;
  87.     }
  88.  
  89.       // check all column
  90.     for( column = 0; column < 3; column++ )
  91.     {
  92.         for( row = 0; row < 3; row++ )
  93.             if( hold[ row ][ column ] != p)
  94.                 break;
  95.         if( row >= 3 )
  96.             return true;
  97.     }
  98.  
  99.       // check diagonals
  100.     if( hold[ 1 ][ 1 ] == p && hold[ 2 ][ 2 ] == p
  101.                         && hold[ 0 ][ 0 ] == p )
  102.         return true;
  103.  
  104.     if( hold[ 0 ][ 2 ] == p && hold[ 1 ][ 1 ] == p
  105.             && hold[ 2 ][ 0 ] == p )
  106.         return true;
  107.  
  108.     return false;
  109.  
  110.  
  111. }
  112.  
  113. bool board::isBoardFull()
  114. {
  115.     for(int row=0;row<3;row++)
  116.     {
  117.         for(int col=0;col<3;col++)
  118.         {
  119.             if (hold[row][col]==EMPTY)
  120.                 return false;
  121.         }
  122.     }
  123.     return true;
  124. }
  125.  
  126. int board::evaluate()  //heuristic function used for minimax algo
  127. {
  128.     if (isAWin(CROSS))
  129.         return X_WIN;
  130.     else if (isAWin(NAUGHT))
  131.         return O_WIN;
  132.     else if (isBoardFull())
  133.         return TIE;
  134.     else
  135.         return UNDEFINED;
  136. }
  137.  
  138. bool board::makeMove(int r, int c, Piece p)  //makes a move on board, checking available
  139. {
  140.     if((r<0) || (r>2) || (c<0) || (c>2) || hold[r][c]!=EMPTY)
  141.         return false;
  142.  
  143.     placeMove(r, c, p);
  144.  
  145.     return true;
  146. }
  147.  
  148. void board::placeMove(int r, int c, Piece p )//makes a move on board,no checking available
  149. {                                                //(used by minimax)
  150.     hold[r][c]=p;
  151. }
  152.  
  153. void board::undoMove(int r, int c)           //undo a move(used by minimax)
  154. {
  155.     hold[r][c]=EMPTY;
  156. }
  157.  
  158. bool board::isOver()                       //if game is over
  159. {
  160.     if(evaluate()==UNDEFINED)
  161.         return false;
  162.     else
  163.         return true;
  164. }
  165.  
  166. char board::pieceToChar(Piece p)            //converts a piece to char( used by drawBoard)
  167. {
  168.     if(p==EMPTY)
  169.         return ' ';
  170.     else if(p==CROSS)
  171.         return 'X';
  172.     else
  173.         return 'O';
  174. }
  175.  
  176. void board::drawBoard()
  177. {
  178.     char print_board[3][3];
  179.  
  180.     for (int row=0; row<3; row++)
  181.         for(int col=0;col<3;col++)
  182.             print_board[row][col] = pieceToChar(hold[row][col]);
  183.  
  184.  
  185.     cout << print_board[0][0] << '|' << print_board[0][1] << '|' << print_board[0][2] << endl;
  186.     cout << print_board[1][0] << '|' << print_board[1][1] << '|' << print_board[1][2] << endl;
  187.     cout << print_board[2][0] << '|' << print_board[2][1] << '|' << print_board[2][2] << endl;
  188.     cout<<"\n\n";
  189. }
  190.  
  191.  
  192. Piece board::turnToPiece()  //converts current turn(1 for X, 0 for O) to piece
  193. {
  194.     if(turn>0)
  195.         return CROSS;
  196.     else
  197.         return NAUGHT;
  198. }
  199.  
  200. void board::alterTurn()  //alternates the turn
  201. {
  202.     turn*=-1;
  203. }
  204.  
  205. void board::playHuman()
  206. {
  207.     int r,c;
  208.     Piece p=turnToPiece();
  209.  
  210.     do
  211.     {
  212.         cout<<"Enter your move\n";
  213.         cin>>r>>c;
  214.     }while(makeMove(r,c,p)==false);
  215.     drawBoard();
  216.     alterTurn();
  217. }
  218.  
  219. void board::playComp()
  220. {
  221.     int r,c;
  222.     Piece p=turnToPiece();
  223.  
  224.     /*do
  225.     {
  226.         r=rand()%3;
  227.         c=rand()%3;
  228.     }while(makeMove(r,c,p)==false);*/
  229.     chooseMove(p,r,c);
  230.     cout<<makeMove(r,c,p)<<endl;
  231.     cout<<"r"<<r<<endl;
  232.     cout<<"c"<<c<<endl;
  233.     drawBoard();
  234.     alterTurn();
  235. }
  236.  
  237. int board::chooseMove(Piece p, int &row, int &col) //minimax algorithm
  238. {
  239.     int imVal;
  240.     int reply;
  241.     int bestVal;
  242.     int dr,dc;
  243.     Piece opp;
  244.  
  245.     if((imVal=evaluate())!=UNDEFINED)
  246.         return imVal;
  247.  
  248.     if(p==NAUGHT)
  249.     {
  250.         opp=CROSS;
  251.         bestVal=O_WIN;
  252.     }
  253.     else
  254.     {
  255.         opp=NAUGHT;
  256.         bestVal=X_WIN;
  257.     }
  258.  
  259.     for(int r=0;r<3;r++)
  260.     {
  261.         for(int c=0;c<3;c++)
  262.         {
  263.             if(hold[r][c]==EMPTY)
  264.             {
  265.                 placeMove(r,c,p);
  266.                 reply=chooseMove(opp,dr,dc);
  267.  
  268.                 placeMove(r,c,EMPTY);
  269.  
  270.                 if(((p==NAUGHT) && (reply>=bestVal)) || ((p==CROSS) && (reply<=bestVal)))
  271.                 {
  272.                     bestVal=reply;
  273.                     row=r;
  274.                     col=c;
  275.                 }
  276.             }
  277.         }
  278.     }
  279.     return bestVal;
  280. }
  281.  
  282.  
  283.  
Jan 27 '08 #1
1 2107
Banfa
9,065 Expert Mod 8TB
You best bet is to step through the code using a debugger so you can follow the logic of how your program is making it's decision. Then if there is an error you should be able to spot it.
Feb 13 '08 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

17
by: savesdeday | last post by:
In my beginnning computer science class we were asked to translate a simple interest problem. We are expected to write an algorithm that gets values for the starting account balance B, annual...
113
by: Bonj | last post by:
I was in need of an encryption algorithm to the following requirements: 1) Must be capable of encrypting strings to a byte array, and decyrpting back again to the same string 2) Must have the same...
4
by: Kinsley Turner | last post by:
Hey-ho, I'm getting a bit out of my depth porting the 'tiny encryption algorithm' from C to python. Ref: http://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm...
4
by: qbproger | last post by:
I'm developing a plugin for some software. The previous version of the software didn't require a start in directory to be set. This allowed me to leave the working directory to the default in the...
4
by: FBM | last post by:
Hi, I am working on a program that simulates one of the elements of ATM. The simulation stores events which occurs every some milliseconds for a certain amount of time. Every time that an event...
0
by: nimisha | last post by:
I have been trying to learn how to do a c++ tic tac toe game, with first implementing the game tree in a function and then having the AI in another function which uses minimax algorithm. I came...
51
by: Joerg Schoen | last post by:
Hi folks! Everyone knows how to sort arrays (e. g. quicksort, heapsort etc.) For linked lists, mergesort is the typical choice. While I was looking for a optimized implementation of mergesort...
4
prometheuzz
by: prometheuzz | last post by:
Hello (Java) enthusiasts, In this article I’d like to tell you a little bit about graphs and how you can search a graph using the BFS (breadth first search) algorithm. I’ll address, and...
1
by: j_depp_99 | last post by:
Hi I wrote a program for a two player game that involves the difference between 2 given numbers. The players take turns entering the differences between two numbers that start as random numbers...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.