java tictactoe,Java中用于TicTacToe AI的最简单的MiniMax算法

I was trying to get a grasp of MiniMax algorithm, and have read up on it. My initial approach was to implement a simple MiniMax algorithm, and then to add alpha-beta pruning. However this is my current code:

public int miniMax(char[] node, int playerNum)

{

int victor = checkWin(node); // returns 0 if game is ongoing, 1 for p1, 2 for p2, 3 for tie.

if(victor != 0) //game over .

return score(victor);

if(playerNum == 2) //AI

{

int bestVal = Integer.MIN_VALUE;

int bestSpot = 0;

for(int i = 0; i < node.length; i++)

{

if(node[i] != '-')

continue;

node[i] = getSymbol(playerNum);

int value = miniMax(node, 1);

if(value > bestVal)

{

bestVal = value;

bestSpot = i;

}

node[i] = '-';

}

return bestSpot;

}

else

{

int bestVal = Integer.MAX_VALUE;

int bestSpot = 0;

for(int i = 0; i < node.length; i++)

{

if(node[i] != '-')

continue;

node[i] = getSymbol(playerNum);

int value = miniMax(node, 2);

if(value < bestVal)

{

bestVal = value;

bestSpot = i;

}

node[i] = '-';

}

return bestSpot;

}

}

And my score function

private int Score(int gameState)

{

if(gameState ==2) //O wins.

return 10;

else if(gameState==1) //X wins

return -10;

return 0;

}

Now, I have a working AI that tries to block my move and win, however sometimes it is making non-intelligent choices for instance this is the output I get if my input read from console is 6,7,8 in that order. It does not attempt to block my win. But in other cases it does.

| O | O | |

| | | |

| X | X | X |

In my second attempt I tried 4,3 and it blocked my winning move.

| | O | |

| X | X | O |

| | | |

I was wondering anyone could point out what is wrong with my implementation?

解决方案

The behavior of the code for the shown examples is correct!

So why is the threat in the following position not blocked? Why does the program play move 1 instead of 6?

O . . O 1 2

. . . numbering available moves: 3 4 5

X X . X X 6

It is because if the game is lost on perfect play the program just plays the first available move.

The algorithm only cares about win or loss and not in how many moves.

See what happens if the threat is blocked:

O . . O . .

. . . . X . and X wins on his next move

X X O X X O

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值