473,836 Members | 2,138 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

minimax algorithm not working properly

1 New Member
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;(ig noring 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 2142
Banfa
9,065 Recognized Expert Moderator Expert
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
6532
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 interest rate I, and annual service charge S. Your algorithm would then compute and print out the total amount of interest earned during the year and the final account balance at the end of the year (assuming that interest is compounded monthly, and...
113
12363
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 algorithm work with strings that may or may not be unicode 3) Number of bytes back must either be <= number of _TCHARs in * sizeof(_TCHAR), or the relation between output size and input size can be calculated simply. Has to take into account the...
4
3713
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 http://www.simonshepherd.supanet.com/source.htm#new_ansi Specifically I don;t know how to handle a C-long block and perform the
4
2123
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 project. Now I have to get my plugin working with the newer version of the software. When I start the debugger with it aimed at that program and my program installed, the program doesn't run properly unless I have the Working Directory set to...
4
4289
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 is stored in a double linked list, the whole list is sorted for the next round. My problem appears when subjecting the program to heavy load, that is, when I run the simulation for more than 10,000 miliseconds (every event occurs in...
0
6354
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 across the following code in my search for sources that would help me get a better understanding: /** evaluate board state from player's point of view */ int evaluate(Node node, int player) { /* using NEGMAX version of MINIMAX */ int value...
51
8666
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 for linked lists, I couldn't find one. I read something about Mcilroy's "Optimistic Merge Sort" and studied some implementation, but they were for arrays. Does anybody know if Mcilroys optimization is applicable to truly linked lists at all?
4
32090
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 hopefully answer, the following questions: • what is a graph? • how can a graph be represented as an ADT? • how can we search/walk through a graph using the BFS algorithm?
1
2439
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 and then the board includes all differences entered so far. I found the possible solutions by implementing euclids algorithm. The game sort of works but I now need to implement it using minimax with alpha beta pruning. I dont understand how to...
0
9810
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9656
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10527
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10571
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10241
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9358
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7773
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6973
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5642
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...

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.