initial load of http://downloads.sourceforge.net/project/cmancala/mancala-gui/mancala...
[mancala] / src / ai-recurse.c
diff --git a/src/ai-recurse.c b/src/ai-recurse.c
new file mode 100644 (file)
index 0000000..cb53fa8
--- /dev/null
@@ -0,0 +1,88 @@
+/*  
+ *  Recursive AI Algorithm -- ai-recurse.c
+ *  Kevin Riggle
+ *  http://cmancala.sourceforge.net
+ *  $Source: /cvsroot/cmancala/mancala/src/Attic/ai-recurse.c,v $
+ *  $Revision: 1.22.2.1 $
+ *  $Date: 2003/12/29 05:49:52 $
+ *
+ */
+
+#include <stdlib.h>
+#include <stdio.h>
+#include "mancala.h"
+#include "ai.h"
+#include "ai-init.h"
+
+/* How far should I go? */
+#define MAX_DEPTH 20
+
+/* keep the actual mechanics of the recursive algorithm internal */
+static int aiRecurse (int *aiBoard, int *humanBoard, int depth, FILE *log);
+
+/* new stub api function using init routine */
+
+int aiMove(int *aiBoard, int *humanBoard) {
+
+       return aiInit(aiBoard, humanBoard, "recurse.log", aiRecurse);
+
+}
+
+/* actual recursive function, accept no imitations */
+int aiRecurse (int *aiBoard, int *humanBoard, int depth, FILE *log) { 
+
+       int aiBoardTemp[BOARD_MAX+1], humanBoardTemp[BOARD_MAX+1];
+       int i, j, bestmove, pts, endpos;
+
+       bestmove = pts = endpos = 0;
+
+       /*printf("AI at depth %d\n", depth);*/
+       fprintf(log, "AI at depth %d\n", depth);
+
+       /* Keep us from recursing infinitely */ 
+       if (depth > MAX_DEPTH) 
+               return bestmove; 
+
+       /* iterate through each board position */
+       for (i=1; i<=BOARD_MAX; i++) {
+
+               /* copy boards to temp. location */
+               for(j=0; j<=BOARD_MAX; j++) {
+                       aiBoardTemp[j] = aiBoard[j];
+                       humanBoardTemp[j] = humanBoard[j];
+               }
+
+               /* test the current move */ 
+               endpos = move(aiBoardTemp, humanBoardTemp, i);
+
+               /* if we get another turn, recurse */
+               if (endpos == 0)
+                       aiRecurse(aiBoardTemp, humanBoardTemp, 
+                               (depth+1), log);
+
+               /* log it */
+               fprintf(log, "Moving from %d at depth %d\n", i, depth);
+               fprintf(log, "Ends at %d and nets %d points.\n", endpos,
+                       (aiBoardTemp[0] - aiBoard[0]));
+
+               /* if this move is better, record it */ 
+               if ((aiBoardTemp[0] - aiBoard[0]) > pts) {
+                       pts = (aiBoardTemp[0] - aiBoard[0]);
+                       bestmove = i;
+               }
+       }
+
+       /* if no move is best and some still exist, pick one at random */  
+       if ((bestmove == 0) && (!gameWon(aiBoard, humanBoard)))
+               while (aiBoard[(bestmove 
+                       = rand_btw(1,BOARD_MAX+1))] == 0)
+                       ;
+
+       /* make the final move and return */
+       move(aiBoard, humanBoard, bestmove);
+
+       return bestmove;
+
+}
+
+/*  End ai-recurse.c  */