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. -
//board.h file
-
-
#ifndef BOARD_H
-
#define BOARD_H
-
-
#include<iostream>
-
#include<cstdlib>
-
using namespace std;
-
-
-
-
enum PosValue {O_WIN=-1,TIE,X_WIN,UNDEFINED};
-
enum Piece {NAUGHT=-1,EMPTY,CROSS};
-
enum Player {HUMAN=1,COMP};
-
-
-
-
class board
-
{
-
public:
-
-
board();
-
~board(){}
-
void initBoard(Player pl);
-
bool isAWin(Piece p);
-
bool isBoardFull();
-
bool isOver();
-
int evaluate();
-
bool makeMove(int r,int c,Piece p=EMPTY);
-
void undoMove(int r,int c);
-
void drawBoard();
-
Piece turnToPiece();
-
void alterTurn();
-
Player firstPlayer;
-
void playComp();
-
void playHuman();
-
-
int chooseMove(Piece p,int &row,int &col);
-
-
-
private:
-
-
Piece hold[3][3];
-
-
void placeMove(int r,int c,Piece p=EMPTY);
-
char pieceToChar(Piece p);
-
int turn;
-
-
-
};
-
-
#endif
-
-
//board.cpp file
-
-
#include "board.h"
-
-
board::board()
-
{
-
-
}
-
-
void board::initBoard(Player pl) //initialize the board, gets who is first playing
-
{
-
firstPlayer=pl;
-
for(int i=0;i<3;i++)
-
for(int j=0;j<3;j++)
-
hold[i][j]=EMPTY;
-
-
turn =1;
-
}
-
-
-
-
bool board::isAWin(Piece p) //checks whether a Piece wins
-
{
-
int row, column;
-
-
// check all rows
-
for( row = 0; row < 3; row++ )
-
{
-
for( column = 0; column < 3; column++ )
-
if( hold[ row ][ column ] != p )
-
break;
-
if( column >= 3 )
-
return true;
-
}
-
-
// check all column
-
for( column = 0; column < 3; column++ )
-
{
-
for( row = 0; row < 3; row++ )
-
if( hold[ row ][ column ] != p)
-
break;
-
if( row >= 3 )
-
return true;
-
}
-
-
// check diagonals
-
if( hold[ 1 ][ 1 ] == p && hold[ 2 ][ 2 ] == p
-
&& hold[ 0 ][ 0 ] == p )
-
return true;
-
-
if( hold[ 0 ][ 2 ] == p && hold[ 1 ][ 1 ] == p
-
&& hold[ 2 ][ 0 ] == p )
-
return true;
-
-
return false;
-
-
-
}
-
-
bool board::isBoardFull()
-
{
-
for(int row=0;row<3;row++)
-
{
-
for(int col=0;col<3;col++)
-
{
-
if (hold[row][col]==EMPTY)
-
return false;
-
}
-
}
-
return true;
-
}
-
-
int board::evaluate() //heuristic function used for minimax algo
-
{
-
if (isAWin(CROSS))
-
return X_WIN;
-
else if (isAWin(NAUGHT))
-
return O_WIN;
-
else if (isBoardFull())
-
return TIE;
-
else
-
return UNDEFINED;
-
}
-
-
bool board::makeMove(int r, int c, Piece p) //makes a move on board, checking available
-
{
-
if((r<0) || (r>2) || (c<0) || (c>2) || hold[r][c]!=EMPTY)
-
return false;
-
-
placeMove(r, c, p);
-
-
return true;
-
}
-
-
void board::placeMove(int r, int c, Piece p )//makes a move on board,no checking available
-
{ //(used by minimax)
-
hold[r][c]=p;
-
}
-
-
void board::undoMove(int r, int c) //undo a move(used by minimax)
-
{
-
hold[r][c]=EMPTY;
-
}
-
-
bool board::isOver() //if game is over
-
{
-
if(evaluate()==UNDEFINED)
-
return false;
-
else
-
return true;
-
}
-
-
char board::pieceToChar(Piece p) //converts a piece to char( used by drawBoard)
-
{
-
if(p==EMPTY)
-
return ' ';
-
else if(p==CROSS)
-
return 'X';
-
else
-
return 'O';
-
}
-
-
void board::drawBoard()
-
{
-
char print_board[3][3];
-
-
for (int row=0; row<3; row++)
-
for(int col=0;col<3;col++)
-
print_board[row][col] = pieceToChar(hold[row][col]);
-
-
-
cout << print_board[0][0] << '|' << print_board[0][1] << '|' << print_board[0][2] << endl;
-
cout << print_board[1][0] << '|' << print_board[1][1] << '|' << print_board[1][2] << endl;
-
cout << print_board[2][0] << '|' << print_board[2][1] << '|' << print_board[2][2] << endl;
-
cout<<"\n\n";
-
}
-
-
-
Piece board::turnToPiece() //converts current turn(1 for X, 0 for O) to piece
-
{
-
if(turn>0)
-
return CROSS;
-
else
-
return NAUGHT;
-
}
-
-
void board::alterTurn() //alternates the turn
-
{
-
turn*=-1;
-
}
-
-
void board::playHuman()
-
{
-
int r,c;
-
Piece p=turnToPiece();
-
-
do
-
{
-
cout<<"Enter your move\n";
-
cin>>r>>c;
-
}while(makeMove(r,c,p)==false);
-
drawBoard();
-
alterTurn();
-
}
-
-
void board::playComp()
-
{
-
int r,c;
-
Piece p=turnToPiece();
-
-
/*do
-
{
-
r=rand()%3;
-
c=rand()%3;
-
}while(makeMove(r,c,p)==false);*/
-
chooseMove(p,r,c);
-
cout<<makeMove(r,c,p)<<endl;
-
cout<<"r"<<r<<endl;
-
cout<<"c"<<c<<endl;
-
drawBoard();
-
alterTurn();
-
}
-
-
int board::chooseMove(Piece p, int &row, int &col) //minimax algorithm
-
{
-
int imVal;
-
int reply;
-
int bestVal;
-
int dr,dc;
-
Piece opp;
-
-
if((imVal=evaluate())!=UNDEFINED)
-
return imVal;
-
-
if(p==NAUGHT)
-
{
-
opp=CROSS;
-
bestVal=O_WIN;
-
}
-
else
-
{
-
opp=NAUGHT;
-
bestVal=X_WIN;
-
}
-
-
for(int r=0;r<3;r++)
-
{
-
for(int c=0;c<3;c++)
-
{
-
if(hold[r][c]==EMPTY)
-
{
-
placeMove(r,c,p);
-
reply=chooseMove(opp,dr,dc);
-
-
placeMove(r,c,EMPTY);
-
-
if(((p==NAUGHT) && (reply>=bestVal)) || ((p==CROSS) && (reply<=bestVal)))
-
{
-
bestVal=reply;
-
row=r;
-
col=c;
-
}
-
}
-
}
-
}
-
return bestVal;
-
}
-
-
-
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.
Sign in to post your reply or Sign up for a free account.
Similar topics |
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...
|
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...
|
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
|
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...
|
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...
| |
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...
|
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?
|
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?
|
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...
|
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...
|
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,...
| |
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...
|
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,...
|
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...
|
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...
|
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...
|
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();...
| |
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...
| |