SlideShare a Scribd company logo
1 of 9
Download to read offline
#include<iostream>
#include<string>
#include<cstdio>
#include<map>
#include<algorithm>
#include<cmath>
#include<vector>
#include<sstream>
#include<stack>
#include<queue>
#include<cstring>
#include<fstream>
#include<climits>

#define pb push_back
#define LL long long
#define OUTPUT_TO_FILE 1
#define s(n)                                         scanf("%d",&n)
#define sl(n)                                        scanf("%lld",&n)
#define sf(n)                                        scanf("%lf",&n)
#define ss(n)                                        scanf("%s",n)
#define MAX_LEVEL 5

using namespace std;

class node
{
   public:
   int board[6][7];
};

typedef struct
{
int val,move;
}ret;
int team_no;
void print(node start){
   int i,j;
   for(i=0;i<6;i++){
            for(j=0;j<7;j++)
                      cout<<start.board[i][j]<<" ";
            cout<<endl;
   }
}
int weight(vector<int> v){
            if(v.size()<=3)
                      return 0;
            int i,j;
            int Weights[] = { 1, 5, 100, 10000,2, 6, 200, 15000 };
            int score = 0;
            for(i=0;i<v.size()-3;i++){
int c = 0;
         int p = 0;
         int dual = 0;
         for (j = 0; j < 4; j++){
             if (v[i + j] == team_no) c++; //TODO Make sure that it looks at it's own identity
            else if (v[i + j] ==3 - team_no) p++;
            else if (v[i + j] == 12) dual++;
         }
         if ((c > 0) && (p == 0))
         {
            c += dual;
            //Computer opportunity
             if (c == 4) return Weights[3]; //Win
            score += ((c/3)*Weights[2]) + ((c/2)*Weights[1]) + Weights[0];
         }
         else if ((c == 0) && (p > 0))
         {
             p += dual;
            //Player opportunity
             if (p == 4) return -1*Weights[7]; //Win
            score -= ((p / 3) * Weights[6]) + ((p / 2) * Weights[5]) + Weights[4];
         }
    }
    return score;

}


int evaluate(node start){
         int val = 0;
         int i,j,k;

        //rows
        vector<int> v;
        for(i=5;i>=0;i--){
                 v.clear();
                 for(j=0;j<=6;j++)
                           v.pb(start.board[i][j]);
                 val += weight(v);
        }
        //cout<<val<<" after rows"<<endl;
        //columns
        for(j=0;j<=6;j++){
                 v.clear();
                 for(i=0;i<=5;i++){
                           v.pb(start.board[i][j]);
                 }
                 val += weight(v);
        }
        //cout<<val<<" after columns"<<endl;
//daigonals
       for(k=0;k<=5;k++){
               i = k;
               j = 0;
               v.clear();
               while(i>=0){
                        v.pb(start.board[i][j]);
                        i--;j++;
               }
               val += weight(v);
       }

       for(k=1;k<=6;k++){
               i = 5;j = k;
               v.clear();
               while(j<=6){
                         v.pb(start.board[i][j]);
                         j++;i--;
               }
               val += weight(v);
       }
       //cout<<val<<" after diagonals"<<endl;

       //2nd set of diagonals
       for(k=5;k>=0;k--){
               i = k;
               j = 0;
               v.clear();
               while(i<=5){
                        v.pb(start.board[i][j]);
                        i++;j++;
               }
               val += weight(v);
       }
       for(k=1;k<=6;k++){
               j = k;
               i = 0;
               v.clear();
               while(j<=6){
                        v.pb(start.board[i][j]);
                        i++;j++;
               }
               val += weight(v);
       }

       return val;
}

bool endgame(node start){
       int temp;
       temp = evaluate(start);
//cout<<temp<<endl;
        if(temp>=7000||temp<=-7000)
                return true;
        else
                return false;
}
bool possible(node start,int j){
       int i;
       for(i = 0;i <= 5;i++){
                 if(start.board[i][j]==0)
                           return true;
       }
       return false;
}
node makemove(node start,int j,int team,int disc){
       int i = 0,k;
       while(start.board[i][j]==0&&i<=5)
                 i++;
       i--;
       if(disc==5)
                 start.board[i][j] = team;
       else if(disc==4)
                 start.board[i][j] = 12;
       else if(disc==1){
                 for(j=0;j<=6;j++){
                           for(k=i-1;k>=0;k--){
                                    start.board[k+1][j] = start.board[k][j];
                           }
                           start.board[0][j] = 0;
                 }
       }
       else if(disc==2){
                 for(i=0;i<=5;i++)
                           start.board[i][j] = 0;
       }
       else if(disc==3){
                 start.board[i][j] = 0;
                 //clear all the neighbours
                 int t1[] = {0,0,-1,-1,-1,0,1,1,1};
                 int t2[] = {0,-1,-1,0,1,1,1,0,-1};
                 for(k=0;k<=8;k++){
                           int u1,v1;
                           u1 = t1[k] + i;
                           v1 = t2[k] + j;
                           if(u1>=0&&u1<=5&&v1>=0&&v1<=6){
                                    start.board[u1][v1] = 0;
                           }
                 }
                 vector<int> a;
                 if(j-1>=0){
                           k = i-2;
while(k>=0){
                                    if(start.board[k][j-1]!=0)
                                              a.pb(start.board[k][j-1]);
                                    start.board[k][j-1]=0;
                                    k--;
                          }
                          k = i;
                          if(i+1<=5)
                                    k = k+1;
                          int l = 0;
                          while(l<a.size()){
                                    start.board[k][j-1] = a[l];
                                    l++;k--;
                          }
                 }
                 a.clear();
                 if(j+1<=6){
                          k = i-2;
                          while(k>=0){
                                    if(start.board[k][j+1]!=0)
                                              a.pb(start.board[k][j+1]);
                                    start.board[k][j+1]=0;
                                    k--;
                          }
                          k = i;
                          if(i+1<=5)
                                    k = k+1;
                          int l = 0;
                          while(l<a.size()){
                                    start.board[k][j+1] = a[l];
                                    l++;k--;
                          }

                }
        }
        return start;
}
ret Min(node start,int level,int alpha,int beta,int disc);
ret Max(node start,int level,int alpha,int beta,int disc){
        //cout<<"Level ="<<level<<endl;
        //print(start);
        //system("pause");
        if(level == MAX_LEVEL||endgame(start)){
                  //cout<<"ho";
                  ret leaf;
                  leaf.val = evaluate(start);
                  leaf.move = -1;
                  //cout<<"Value = "<<leaf.val<<endl;
                  //system("pause");
                  return leaf;
        }
ret best;
        best.val = INT_MIN;
        for(int i = 0;i<7;i++){
                  if(possible(start,i)){
                           node newboard;
                           ret temp;
                           newboard = makemove(start,i,team_no,disc);
                           temp = Min(newboard,level+1,alpha,beta,5);
                           if(temp.val > best.val){
                                    best.val = temp.val;
                                    best.move = i;
                           }
                           alpha = max(alpha,temp.val);
                           if(alpha > beta)
                                    break;
                  }
        }
        return best;
}

ret Min(node start,int level,int alpha,int beta,int disc){
        //cout<<"Level ="<<level<<endl;
        //print(start);
        //system("pause");
        ret best;
        best.val = INT_MAX;
        for(int i = 0;i<7;i++){
                  if(possible(start,i)){
                           node newboard;
                           ret temp;
                           newboard = makemove(start,i,3 - team_no,5);
                           temp = Max(newboard,level+1,alpha,beta,5);
                           if(temp.val < best.val){
                                    best.val = temp.val;
                                    best.move = i;
                           }
                           beta = min(beta,temp.val);
                           if(alpha > beta)
                                    break;
                  }

        }
        return best;
}

int main()
{
  int i,j;

  ///////////////////////////////////////////////////READING
INPUT////////////////////////////////////////////////////////////////////////////
/*SECTION I
  Reading Board Number and Team no from the file*/
  ifstream fin;
  ofstream fout;

  fin.open("team_no.txt");
  fin>>team_no;
  fin.close();

  fin.open("board.txt");
  node start;
  for(i=5;i>=0;i--){
     for(j=0;j<7;j++){
       int token;
       fin>>token;
       start.board[i][j] = token;
     }
  }
  fin.close();
  /*end*/

//////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////


 //////////////////////////////////////////////////////MAKING THE DUAL COLOR
MOVE//////////////////////////////////////////////////////////
 int moves,column,disc;          //This will hold the column and disc of my move
 int r,c,n,d;
 fin.open("moves.txt");
 fin>>moves>>r>>c>>n>>d;
 if(moves==0)
        disc = 4;
 else
        disc = 5;
 /*if(moves==5)
        disc = 4;
 else if(moves==6&&d!=1)
        disc = 4;
 else if(moves==7&&d!=1)
        disc = 4;
 else if(moves==8&&d!=1)
        disc = 4;
 else
        disc = 5;*/
 fin.close();

  ret ans = Max(start,1,INT_MIN,INT_MAX,disc);

  if(disc==4&&ans.val <= -10000&&moves!=8){
               disc = 5;
ans = Max(start,1,INT_MIN,INT_MAX,disc);
 }
 else if(!(disc==4&&moves==8))
 {
 ////////////////////////////////////////////////////MAKING THE CLEAR ROW,COL,NEIGHBOUR
MOVES/////////////////////////////////////////////
                 //now the dual disc is used
                 if(ans.val <= -10000){
                          ret temp;
                          if(r!=1){
                          temp = Max(start,1,INT_MIN,INT_MAX,1);
                          if(temp.val > ans.val){
                                    disc = 1;
                                    ans.val = temp.val;
                                    ans.move = temp.move;
                          }
                          }

                      if(c!=1){
                      temp = Max(start,1,INT_MIN,INT_MAX,2);
                      if(temp.val > ans.val){
                                disc = 2;
                                ans.val = temp.val;
                                ans.move = temp.move;
                      }
                      }

                      if(n!=1){
                      temp = Max(start,1,INT_MIN,INT_MAX,3);
                      if(temp.val > ans.val){
                               disc = 3;
                               ans.val = temp.val;
                               ans.move = temp.move;
                      }
                      }
              }
              else
              {
                      ret temp;
                      if(r!=1){
                      temp = Max(start,1,INT_MIN,INT_MAX,1);
                      if(temp.val > ans.val && temp.val > 8000){
                                disc = 1;
                                ans.val = temp.val;
                                ans.move = temp.move;
                      }
                      }

                      if(c!=1){
                      temp = Max(start,1,INT_MIN,INT_MAX,2);
                      if(temp.val > ans.val && temp.val > 8000){
disc = 2;
                                ans.val = temp.val;
                                ans.move = temp.move;
                        }
                        }

                        if(n!=1){
                        temp = Max(start,1,INT_MIN,INT_MAX,3);
                        if(temp.val > ans.val && temp.val > 8000){
                                 disc = 3;
                                 ans.val = temp.val;
                                 ans.move = temp.move;
                        }
                        }
                }
  }

  ////////////////////////////////////MAKING THE FINAL
MOVE////////////////////////////////////////////////////////////////////////////////
  column = ans.move + 1;
  cout<<ans.move<<endl;
  fout.open("output.txt");
  cout<<disc<<" "<<column<<" "<<ans.val<<endl;
  fout<<disc<<" "<<column;
}

More Related Content

What's hot

The Ring programming language version 1.4.1 book - Part 3 of 31
The Ring programming language version 1.4.1 book - Part 3 of 31The Ring programming language version 1.4.1 book - Part 3 of 31
The Ring programming language version 1.4.1 book - Part 3 of 31Mahmoud Samir Fayed
 
Reiterating JavaScript & Node.js iterators
Reiterating JavaScript & Node.js iteratorsReiterating JavaScript & Node.js iterators
Reiterating JavaScript & Node.js iteratorsLuciano Mammino
 
The Ring programming language version 1.10 book - Part 46 of 212
The Ring programming language version 1.10 book - Part 46 of 212The Ring programming language version 1.10 book - Part 46 of 212
The Ring programming language version 1.10 book - Part 46 of 212Mahmoud Samir Fayed
 
Racing To Win: Using Race Conditions to Build Correct and Concurrent Software
Racing To Win: Using Race Conditions to Build Correct and Concurrent SoftwareRacing To Win: Using Race Conditions to Build Correct and Concurrent Software
Racing To Win: Using Race Conditions to Build Correct and Concurrent SoftwareFastly
 
Dzanan_Bajgoric_C2CUDA_MscThesis_Present
Dzanan_Bajgoric_C2CUDA_MscThesis_PresentDzanan_Bajgoric_C2CUDA_MscThesis_Present
Dzanan_Bajgoric_C2CUDA_MscThesis_PresentDžanan Bajgorić
 
Introduction to CNN with Application to Object Recognition
Introduction to CNN with Application to Object RecognitionIntroduction to CNN with Application to Object Recognition
Introduction to CNN with Application to Object RecognitionArtifacia
 
Legacy projects: how to win the race
Legacy projects: how to win the raceLegacy projects: how to win the race
Legacy projects: how to win the raceVictor_Cr
 
Bowling Game Kata by Robert C. Martin
Bowling Game Kata by Robert C. MartinBowling Game Kata by Robert C. Martin
Bowling Game Kata by Robert C. MartinLalit Kale
 
The Ring programming language version 1.5.1 book - Part 51 of 180
The Ring programming language version 1.5.1 book - Part 51 of 180The Ring programming language version 1.5.1 book - Part 51 of 180
The Ring programming language version 1.5.1 book - Part 51 of 180Mahmoud Samir Fayed
 
Bowling Game Kata in C# Adapted
Bowling Game Kata in C# AdaptedBowling Game Kata in C# Adapted
Bowling Game Kata in C# AdaptedMike Clement
 
Bowling Game Kata C#
Bowling Game Kata C#Bowling Game Kata C#
Bowling Game Kata C#Dan Stewart
 
Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Leonardo Borges
 
The Ring programming language version 1.4.1 book - Part 17 of 31
The Ring programming language version 1.4.1 book - Part 17 of 31The Ring programming language version 1.4.1 book - Part 17 of 31
The Ring programming language version 1.4.1 book - Part 17 of 31Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 59 of 202
The Ring programming language version 1.8 book - Part 59 of 202The Ring programming language version 1.8 book - Part 59 of 202
The Ring programming language version 1.8 book - Part 59 of 202Mahmoud Samir Fayed
 
Bowling Game Kata
Bowling Game KataBowling Game Kata
Bowling Game Kataguest958d7
 
Model Based Fault Detection, Identification and Accommodation in Antilock Bra...
Model Based Fault Detection, Identification and Accommodation in Antilock Bra...Model Based Fault Detection, Identification and Accommodation in Antilock Bra...
Model Based Fault Detection, Identification and Accommodation in Antilock Bra...Behzad Samadi
 
Monadologie
MonadologieMonadologie
Monadologieleague
 
Java Puzzle
Java PuzzleJava Puzzle
Java PuzzleSFilipp
 

What's hot (19)

The Ring programming language version 1.4.1 book - Part 3 of 31
The Ring programming language version 1.4.1 book - Part 3 of 31The Ring programming language version 1.4.1 book - Part 3 of 31
The Ring programming language version 1.4.1 book - Part 3 of 31
 
Reiterating JavaScript & Node.js iterators
Reiterating JavaScript & Node.js iteratorsReiterating JavaScript & Node.js iterators
Reiterating JavaScript & Node.js iterators
 
The Ring programming language version 1.10 book - Part 46 of 212
The Ring programming language version 1.10 book - Part 46 of 212The Ring programming language version 1.10 book - Part 46 of 212
The Ring programming language version 1.10 book - Part 46 of 212
 
Racing To Win: Using Race Conditions to Build Correct and Concurrent Software
Racing To Win: Using Race Conditions to Build Correct and Concurrent SoftwareRacing To Win: Using Race Conditions to Build Correct and Concurrent Software
Racing To Win: Using Race Conditions to Build Correct and Concurrent Software
 
Dzanan_Bajgoric_C2CUDA_MscThesis_Present
Dzanan_Bajgoric_C2CUDA_MscThesis_PresentDzanan_Bajgoric_C2CUDA_MscThesis_Present
Dzanan_Bajgoric_C2CUDA_MscThesis_Present
 
Introduction to CNN with Application to Object Recognition
Introduction to CNN with Application to Object RecognitionIntroduction to CNN with Application to Object Recognition
Introduction to CNN with Application to Object Recognition
 
Legacy projects: how to win the race
Legacy projects: how to win the raceLegacy projects: how to win the race
Legacy projects: how to win the race
 
Bowling Game Kata by Robert C. Martin
Bowling Game Kata by Robert C. MartinBowling Game Kata by Robert C. Martin
Bowling Game Kata by Robert C. Martin
 
The Ring programming language version 1.5.1 book - Part 51 of 180
The Ring programming language version 1.5.1 book - Part 51 of 180The Ring programming language version 1.5.1 book - Part 51 of 180
The Ring programming language version 1.5.1 book - Part 51 of 180
 
Bowling Game Kata in C# Adapted
Bowling Game Kata in C# AdaptedBowling Game Kata in C# Adapted
Bowling Game Kata in C# Adapted
 
Bowling Game Kata C#
Bowling Game Kata C#Bowling Game Kata C#
Bowling Game Kata C#
 
Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012
 
The Ring programming language version 1.4.1 book - Part 17 of 31
The Ring programming language version 1.4.1 book - Part 17 of 31The Ring programming language version 1.4.1 book - Part 17 of 31
The Ring programming language version 1.4.1 book - Part 17 of 31
 
Aa
AaAa
Aa
 
The Ring programming language version 1.8 book - Part 59 of 202
The Ring programming language version 1.8 book - Part 59 of 202The Ring programming language version 1.8 book - Part 59 of 202
The Ring programming language version 1.8 book - Part 59 of 202
 
Bowling Game Kata
Bowling Game KataBowling Game Kata
Bowling Game Kata
 
Model Based Fault Detection, Identification and Accommodation in Antilock Bra...
Model Based Fault Detection, Identification and Accommodation in Antilock Bra...Model Based Fault Detection, Identification and Accommodation in Antilock Bra...
Model Based Fault Detection, Identification and Accommodation in Antilock Bra...
 
Monadologie
MonadologieMonadologie
Monadologie
 
Java Puzzle
Java PuzzleJava Puzzle
Java Puzzle
 

Similar to C++ Connect Four AI using MiniMax algorithm

Dynamic programming
Dynamic programmingDynamic programming
Dynamic programmingShakil Ahmed
 
The following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdfThe following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdffonecomp
 
i have a code that runs, but it only lets the player to guess where .pdf
i have a code that runs, but it only lets the player to guess where .pdfi have a code that runs, but it only lets the player to guess where .pdf
i have a code that runs, but it only lets the player to guess where .pdfpoblettesedanoree498
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語ikdysfm
 
Microsoft Word Hw#1
Microsoft Word   Hw#1Microsoft Word   Hw#1
Microsoft Word Hw#1kkkseld
 
This is the Java code i have for a Battleship project i am working o.pdf
This is the Java code i have for a Battleship project i am working o.pdfThis is the Java code i have for a Battleship project i am working o.pdf
This is the Java code i have for a Battleship project i am working o.pdfcalderoncasto9163
 
C Code and the Art of Obfuscation
C Code and the Art of ObfuscationC Code and the Art of Obfuscation
C Code and the Art of Obfuscationguest9006ab
 
Snake report ROHIT MALAV
Snake report ROHIT MALAVSnake report ROHIT MALAV
Snake report ROHIT MALAVRohit malav
 
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docxPiersRCoThomsonw
 
include ltiostreamgt include ltstringgt include .pdf
include ltiostreamgt include ltstringgt include .pdfinclude ltiostreamgt include ltstringgt include .pdf
include ltiostreamgt include ltstringgt include .pdfcontact32
 
Project_Euler_No_104_Pandigital_Fibonacci_ends
Project_Euler_No_104_Pandigital_Fibonacci_endsProject_Euler_No_104_Pandigital_Fibonacci_ends
Project_Euler_No_104_Pandigital_Fibonacci_ends? ?
 
Artificial intelligence
Artificial intelligenceArtificial intelligence
Artificial intelligenceAditya Sharma
 
Please implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdfPlease implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdffms12345
 
Psimd open64 workshop_2012-new
Psimd open64 workshop_2012-newPsimd open64 workshop_2012-new
Psimd open64 workshop_2012-newdibyendu_das0708
 
PostgreSQL10の新機能 ~ロジカルレプリケーションを中心に~
PostgreSQL10の新機能 ~ロジカルレプリケーションを中心に~PostgreSQL10の新機能 ~ロジカルレプリケーションを中心に~
PostgreSQL10の新機能 ~ロジカルレプリケーションを中心に~Atsushi Torikoshi
 

Similar to C++ Connect Four AI using MiniMax algorithm (20)

Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Include
IncludeInclude
Include
 
The following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdfThe following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdf
 
i have a code that runs, but it only lets the player to guess where .pdf
i have a code that runs, but it only lets the player to guess where .pdfi have a code that runs, but it only lets the player to guess where .pdf
i have a code that runs, but it only lets the player to guess where .pdf
 
week-18x
week-18xweek-18x
week-18x
 
week-17x
week-17xweek-17x
week-17x
 
Proga 0622
Proga 0622Proga 0622
Proga 0622
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
 
Microsoft Word Hw#1
Microsoft Word   Hw#1Microsoft Word   Hw#1
Microsoft Word Hw#1
 
This is the Java code i have for a Battleship project i am working o.pdf
This is the Java code i have for a Battleship project i am working o.pdfThis is the Java code i have for a Battleship project i am working o.pdf
This is the Java code i have for a Battleship project i am working o.pdf
 
C Code and the Art of Obfuscation
C Code and the Art of ObfuscationC Code and the Art of Obfuscation
C Code and the Art of Obfuscation
 
C# Assignmet Help
C# Assignmet HelpC# Assignmet Help
C# Assignmet Help
 
Snake report ROHIT MALAV
Snake report ROHIT MALAVSnake report ROHIT MALAV
Snake report ROHIT MALAV
 
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
 
include ltiostreamgt include ltstringgt include .pdf
include ltiostreamgt include ltstringgt include .pdfinclude ltiostreamgt include ltstringgt include .pdf
include ltiostreamgt include ltstringgt include .pdf
 
Project_Euler_No_104_Pandigital_Fibonacci_ends
Project_Euler_No_104_Pandigital_Fibonacci_endsProject_Euler_No_104_Pandigital_Fibonacci_ends
Project_Euler_No_104_Pandigital_Fibonacci_ends
 
Artificial intelligence
Artificial intelligenceArtificial intelligence
Artificial intelligence
 
Please implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdfPlease implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdf
 
Psimd open64 workshop_2012-new
Psimd open64 workshop_2012-newPsimd open64 workshop_2012-new
Psimd open64 workshop_2012-new
 
PostgreSQL10の新機能 ~ロジカルレプリケーションを中心に~
PostgreSQL10の新機能 ~ロジカルレプリケーションを中心に~PostgreSQL10の新機能 ~ロジカルレプリケーションを中心に~
PostgreSQL10の新機能 ~ロジカルレプリケーションを中心に~
 

Recently uploaded

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 

Recently uploaded (20)

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 

C++ Connect Four AI using MiniMax algorithm

  • 1. #include<iostream> #include<string> #include<cstdio> #include<map> #include<algorithm> #include<cmath> #include<vector> #include<sstream> #include<stack> #include<queue> #include<cstring> #include<fstream> #include<climits> #define pb push_back #define LL long long #define OUTPUT_TO_FILE 1 #define s(n) scanf("%d",&n) #define sl(n) scanf("%lld",&n) #define sf(n) scanf("%lf",&n) #define ss(n) scanf("%s",n) #define MAX_LEVEL 5 using namespace std; class node { public: int board[6][7]; }; typedef struct { int val,move; }ret; int team_no; void print(node start){ int i,j; for(i=0;i<6;i++){ for(j=0;j<7;j++) cout<<start.board[i][j]<<" "; cout<<endl; } } int weight(vector<int> v){ if(v.size()<=3) return 0; int i,j; int Weights[] = { 1, 5, 100, 10000,2, 6, 200, 15000 }; int score = 0; for(i=0;i<v.size()-3;i++){
  • 2. int c = 0; int p = 0; int dual = 0; for (j = 0; j < 4; j++){ if (v[i + j] == team_no) c++; //TODO Make sure that it looks at it's own identity else if (v[i + j] ==3 - team_no) p++; else if (v[i + j] == 12) dual++; } if ((c > 0) && (p == 0)) { c += dual; //Computer opportunity if (c == 4) return Weights[3]; //Win score += ((c/3)*Weights[2]) + ((c/2)*Weights[1]) + Weights[0]; } else if ((c == 0) && (p > 0)) { p += dual; //Player opportunity if (p == 4) return -1*Weights[7]; //Win score -= ((p / 3) * Weights[6]) + ((p / 2) * Weights[5]) + Weights[4]; } } return score; } int evaluate(node start){ int val = 0; int i,j,k; //rows vector<int> v; for(i=5;i>=0;i--){ v.clear(); for(j=0;j<=6;j++) v.pb(start.board[i][j]); val += weight(v); } //cout<<val<<" after rows"<<endl; //columns for(j=0;j<=6;j++){ v.clear(); for(i=0;i<=5;i++){ v.pb(start.board[i][j]); } val += weight(v); } //cout<<val<<" after columns"<<endl;
  • 3. //daigonals for(k=0;k<=5;k++){ i = k; j = 0; v.clear(); while(i>=0){ v.pb(start.board[i][j]); i--;j++; } val += weight(v); } for(k=1;k<=6;k++){ i = 5;j = k; v.clear(); while(j<=6){ v.pb(start.board[i][j]); j++;i--; } val += weight(v); } //cout<<val<<" after diagonals"<<endl; //2nd set of diagonals for(k=5;k>=0;k--){ i = k; j = 0; v.clear(); while(i<=5){ v.pb(start.board[i][j]); i++;j++; } val += weight(v); } for(k=1;k<=6;k++){ j = k; i = 0; v.clear(); while(j<=6){ v.pb(start.board[i][j]); i++;j++; } val += weight(v); } return val; } bool endgame(node start){ int temp; temp = evaluate(start);
  • 4. //cout<<temp<<endl; if(temp>=7000||temp<=-7000) return true; else return false; } bool possible(node start,int j){ int i; for(i = 0;i <= 5;i++){ if(start.board[i][j]==0) return true; } return false; } node makemove(node start,int j,int team,int disc){ int i = 0,k; while(start.board[i][j]==0&&i<=5) i++; i--; if(disc==5) start.board[i][j] = team; else if(disc==4) start.board[i][j] = 12; else if(disc==1){ for(j=0;j<=6;j++){ for(k=i-1;k>=0;k--){ start.board[k+1][j] = start.board[k][j]; } start.board[0][j] = 0; } } else if(disc==2){ for(i=0;i<=5;i++) start.board[i][j] = 0; } else if(disc==3){ start.board[i][j] = 0; //clear all the neighbours int t1[] = {0,0,-1,-1,-1,0,1,1,1}; int t2[] = {0,-1,-1,0,1,1,1,0,-1}; for(k=0;k<=8;k++){ int u1,v1; u1 = t1[k] + i; v1 = t2[k] + j; if(u1>=0&&u1<=5&&v1>=0&&v1<=6){ start.board[u1][v1] = 0; } } vector<int> a; if(j-1>=0){ k = i-2;
  • 5. while(k>=0){ if(start.board[k][j-1]!=0) a.pb(start.board[k][j-1]); start.board[k][j-1]=0; k--; } k = i; if(i+1<=5) k = k+1; int l = 0; while(l<a.size()){ start.board[k][j-1] = a[l]; l++;k--; } } a.clear(); if(j+1<=6){ k = i-2; while(k>=0){ if(start.board[k][j+1]!=0) a.pb(start.board[k][j+1]); start.board[k][j+1]=0; k--; } k = i; if(i+1<=5) k = k+1; int l = 0; while(l<a.size()){ start.board[k][j+1] = a[l]; l++;k--; } } } return start; } ret Min(node start,int level,int alpha,int beta,int disc); ret Max(node start,int level,int alpha,int beta,int disc){ //cout<<"Level ="<<level<<endl; //print(start); //system("pause"); if(level == MAX_LEVEL||endgame(start)){ //cout<<"ho"; ret leaf; leaf.val = evaluate(start); leaf.move = -1; //cout<<"Value = "<<leaf.val<<endl; //system("pause"); return leaf; }
  • 6. ret best; best.val = INT_MIN; for(int i = 0;i<7;i++){ if(possible(start,i)){ node newboard; ret temp; newboard = makemove(start,i,team_no,disc); temp = Min(newboard,level+1,alpha,beta,5); if(temp.val > best.val){ best.val = temp.val; best.move = i; } alpha = max(alpha,temp.val); if(alpha > beta) break; } } return best; } ret Min(node start,int level,int alpha,int beta,int disc){ //cout<<"Level ="<<level<<endl; //print(start); //system("pause"); ret best; best.val = INT_MAX; for(int i = 0;i<7;i++){ if(possible(start,i)){ node newboard; ret temp; newboard = makemove(start,i,3 - team_no,5); temp = Max(newboard,level+1,alpha,beta,5); if(temp.val < best.val){ best.val = temp.val; best.move = i; } beta = min(beta,temp.val); if(alpha > beta) break; } } return best; } int main() { int i,j; ///////////////////////////////////////////////////READING INPUT////////////////////////////////////////////////////////////////////////////
  • 7. /*SECTION I Reading Board Number and Team no from the file*/ ifstream fin; ofstream fout; fin.open("team_no.txt"); fin>>team_no; fin.close(); fin.open("board.txt"); node start; for(i=5;i>=0;i--){ for(j=0;j<7;j++){ int token; fin>>token; start.board[i][j] = token; } } fin.close(); /*end*/ ////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////// //////////////////////////////////////////////////////MAKING THE DUAL COLOR MOVE////////////////////////////////////////////////////////// int moves,column,disc; //This will hold the column and disc of my move int r,c,n,d; fin.open("moves.txt"); fin>>moves>>r>>c>>n>>d; if(moves==0) disc = 4; else disc = 5; /*if(moves==5) disc = 4; else if(moves==6&&d!=1) disc = 4; else if(moves==7&&d!=1) disc = 4; else if(moves==8&&d!=1) disc = 4; else disc = 5;*/ fin.close(); ret ans = Max(start,1,INT_MIN,INT_MAX,disc); if(disc==4&&ans.val <= -10000&&moves!=8){ disc = 5;
  • 8. ans = Max(start,1,INT_MIN,INT_MAX,disc); } else if(!(disc==4&&moves==8)) { ////////////////////////////////////////////////////MAKING THE CLEAR ROW,COL,NEIGHBOUR MOVES///////////////////////////////////////////// //now the dual disc is used if(ans.val <= -10000){ ret temp; if(r!=1){ temp = Max(start,1,INT_MIN,INT_MAX,1); if(temp.val > ans.val){ disc = 1; ans.val = temp.val; ans.move = temp.move; } } if(c!=1){ temp = Max(start,1,INT_MIN,INT_MAX,2); if(temp.val > ans.val){ disc = 2; ans.val = temp.val; ans.move = temp.move; } } if(n!=1){ temp = Max(start,1,INT_MIN,INT_MAX,3); if(temp.val > ans.val){ disc = 3; ans.val = temp.val; ans.move = temp.move; } } } else { ret temp; if(r!=1){ temp = Max(start,1,INT_MIN,INT_MAX,1); if(temp.val > ans.val && temp.val > 8000){ disc = 1; ans.val = temp.val; ans.move = temp.move; } } if(c!=1){ temp = Max(start,1,INT_MIN,INT_MAX,2); if(temp.val > ans.val && temp.val > 8000){
  • 9. disc = 2; ans.val = temp.val; ans.move = temp.move; } } if(n!=1){ temp = Max(start,1,INT_MIN,INT_MAX,3); if(temp.val > ans.val && temp.val > 8000){ disc = 3; ans.val = temp.val; ans.move = temp.move; } } } } ////////////////////////////////////MAKING THE FINAL MOVE//////////////////////////////////////////////////////////////////////////////// column = ans.move + 1; cout<<ans.move<<endl; fout.open("output.txt"); cout<<disc<<" "<<column<<" "<<ans.val<<endl; fout<<disc<<" "<<column; }