我正在为C ++中的Tic-Tac-Toe创建一些基本的AI。它涉及创建一个由“板”类组成的二叉树。每个节点随机放置一个X或O,然后再创建两个子节点,直到有人赢了或者已经绘制了游戏。为了跟踪每个节点的值,我使用一个整数:-1表示O获胜,0表示抽奖,1表示X获胜,2表示游戏仍在进行中。 Here is an example of what a game could look like.
填充完树后,我需要查看根节点的左侧和右侧,并总结所有叶子。具有较高金额的一方将是最初两个孩子更理想的选择。
我有一些非常粗略的代码用于扩展看似有效的树,但是,当我尝试在扩展后总结我的树时,我似乎已经失去了每个节点包含的值。这是节点
的.cppBTNode.cpp
#include <iostream>
#include <string>
#include "BTNode.h"
#include <ctime>
#include <cstdlib>
#include <iostream>
using namespace std;
BTNode::BTNode(board gameboard, string setplayer)
{
value = 2; //assume the game is continuing
cout << "Beginning a new node\n";
nodeboard = gameboard;
player = setplayer;
expand();
}
void BTNode::expand()
{
//place a piece
cout << "Expanding";
placerandom(player);
//check to see if a leaf
value = nodeboard.checkwinner(); //returns -1 for O win, 0 for draw, 1 for X win and 2 for game still in progress
cout << "Value of this node: " << value << "\n";
if (value == 2)
{
if (player == "X")
{
BTNode right(nodeboard, "O");
BTNode left(nodeboard, "O");
}
else
{
BTNode left(nodeboard, "X");
BTNode right(nodeboard, "X");
}
}
else
{
cout << "A game had ended";
}
}
int BTNode::getvalue(int side)
{
//in case this node is the root, i will only want to check 1 side of the tree
//-1 is left side, 0 is both, 1 is right
int toreturn=0;
if (value ==2)
{
if (side == -1)
{
toreturn = left ->getvalue(0);
}
if (side == 0)
{
toreturn = right->getvalue(0) + left->getvalue(0);
}
if (side == 1)
{
toreturn = right->getvalue(0);
}
}
else
{
cout << "\nThis is a leaf, returning: " << value;
toreturn = value;
}
return toreturn;
}
void BTNode::placerandom(string player)
{
srand(time(NULL)); //make a new seed based off time
int randx = rand()%3;
int randy = rand()%3;
while (not nodeboard.place(randx,randy,player))
{
randx = rand()%3;
randy = rand()%3;
}
nodeboard.printboard();
}
BTNode.h
#include <string>
#include "board.h"
using namespace std;
class BTNode
{
public:
BTNode(board gameboard, string setplayer);
void placerandom(string player);
int getvalue(int side);
void expand();
private:
board nodeboard;
string player;
BTNode *left;
BTNode *right;
int value;
};
理论上,我应该能够从树中调用“root - &gt; getvalue(-1)”,这将返回从树左侧开始的所有节点的总和。但是,尝试在扩展函数之后从任何节点获取“值”返回“-1131609994”。
我创建了错误的树吗?在我试图总结之前,这似乎很有希望。