【发布时间】:2016-08-16 00:38:48
【问题描述】:
我正在尝试为连续四个(或 connect4 或连接四个)游戏实现 MinMax 算法。
我想我明白了,它应该建立一个可能的板子树直到一定深度,评估它们并返回它们的分数,然后我们只取这些分数的最大值。
因此,aiChooseCol() 通过调用 MinMax() 检查每个可能列的分数,并返回具有最高分数的列。
现在我不确定,这是拨打MinMax() 的正确方式吗?
检查temp = Math.Max(temp, 1000);是否正确?
我还没有制作启发式函数,但这至少应该识别一个获胜的列并选择它,但目前它只是选择左边的第一个空闲列......我不知道我在做什么错了。
private int AiChooseCol()
{
int best = -1000;
int col=0;
for (int i = 0; i < m_Board.Cols; i++)
{
if (m_Board.CheckIfColHasRoom(i))
{
m_Board.FillSignInBoardAccordingToCol(i, m_Sign);
int t = MinMax(5, m_Board, board.GetOtherPlayerSign(m_Sign));
if (t > best)
{
best = t;
col = i;
}
m_Board.RemoveTopCoinFromCol(i);
}
}
return col;
}
private int MinMax(int Depth, board Board, char PlayerSign)
{
int temp=0;
if (Depth <= 0)
{
// return from heurisitic function
return temp;
}
char otherPlayerSign = board.GetOtherPlayerSign(PlayerSign);
char checkBoard = Board.CheckBoardForWin();
if (checkBoard == PlayerSign)
{
return 1000;
}
else if (checkBoard == otherPlayerSign)
{
return -1000;
}
else if (!Board.CheckIfBoardIsNotFull())
{
return 0; // tie
}
if (PlayerSign == m_Sign) // maximizing Player is myself
{
temp = -1000;
for (int i = 0; i < Board.Cols; i++)
{
if (Board.FillSignInBoardAccordingToCol(i, PlayerSign)) // so we don't open another branch in a full column
{
var v = MinMax(Depth - 1, Board, otherPlayerSign);
temp = Math.Max(temp, v);
Board.RemoveTopCoinFromCol(i);
}
}
}
else
{
temp = 1000;
for (int i = 0; i < Board.Cols; i++)
{
if (Board.FillSignInBoardAccordingToCol(i, PlayerSign)) // so we don't open another branch in a full column
{
var v = MinMax(Depth - 1, Board, otherPlayerSign);
temp = Math.Min(temp, v);
Board.RemoveTopCoinFromCol(i);
}
}
}
return temp;
}
一些注意事项:
FillSignInBoardAccordingToCol() 如果成功则返回一个布尔值。
board 类型有一个 char[,] 数组,其中包含实际的棋盘和玩家的标志。
此代码在 AI Player 类中。
【问题讨论】:
-
在
AiChooseCol中,您没有将i列传递给MinMax,那么它如何知道您要求它评估哪一列? -
哦,对了,也许我应该在调用
MinMax()之前在i列中放置一个硬币? @juharr -
是的,我知道它可以重构。它仍然无法修复
AiChooseCol。 @juharr -
您应该在
else分支中使用Min值,而不是Max。因为这是唯一的区别,所以你应该把if-else放在周围。 -
@juharr 仍然无法正常工作,我也尝试在
1000和-1000之间切换。
标签: c# artificial-intelligence minmax game-ai