From 6b58ec2d0c4e6735a04070c67717f02864487e44 Mon Sep 17 00:00:00 2001 From: Juan Santelices <86135408+jdsantelicesl@users.noreply.github.com> Date: Sat, 6 Apr 2024 17:50:05 -0700 Subject: [PATCH] finished tree func 'createChildren' --- ai.cpp | 26 ++++++++++++++++++++++---- game.cpp | 12 ++++++++++-- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/ai.cpp b/ai.cpp index a501c56..f0fd14d 100644 --- a/ai.cpp +++ b/ai.cpp @@ -80,17 +80,35 @@ float minimax(int board[]){ } /* - Process: Creates children for a node based on actions + Process: Creates children for a node based on actions. Then calls upon itself recursively until tree has been built. Input: actions: vector containing possible actions. head: The node to be expanded. + player: player's turn Output: No output. Creates node children. */ -void createChildren(vector actions, Node *head, bool player) { +void createChildren(vector possibleActions, Node *head, bool player) { - for(int i = 0; i < static_cast(actions.size()); i++) { - int *arr = result(head->board, actions[i], player); + for(int i = 0; i < static_cast(possibleActions.size()); i++) { + int *arr = result(head->board, possibleActions[i], player); head->addChild(new Node(arr)); + char state = winner(head->children[i]->board); + + if (!state) { + createChildren(actions(head->children[i]->board), head->children[i], getPlayer(player)); + } + else { + if(state == 'X') { + head->children[i]->setValue(1); + } + else if(state == 'O') { + head->children[i]->setValue(-1); + } + else if(state == 'D') { + head->children[i]->setValue(0); + } + } + } } diff --git a/game.cpp b/game.cpp index 952065a..530fb53 100644 --- a/game.cpp +++ b/game.cpp @@ -42,6 +42,9 @@ Input : 1 dimensional board array Output : returns X or O depending on winner */ char winner(int board[]) { + + char retVal = 'D'; // Need it for draw check + // Define winning patterns indexes int winning_patterns[8][3] = { {0, 1, 2}, // Row 1 @@ -55,7 +58,7 @@ char winner(int board[]) { }; // Check each winning pattern - for (int i = 0; i < 8; ++i) { + for (int i = 0; i < 8; ++i) { int a = winning_patterns[i][0]; int b = winning_patterns[i][1]; int c = winning_patterns[i][2]; @@ -69,8 +72,13 @@ char winner(int board[]) { } } + // Need to check if draw for creating tree + if(board[i] == 0 || board[8] == 0) { + retVal = '\0'; + } + } - return '\0'; // Return null character to indicate no winner yet + return retVal; // Return null character to indicate no winner }