尝试为游戏实施minimax,其中玩家可以交替添加一到两个,直到达到21次。玩家将总数增加到21胜。
我使用以下psueodocode:
01 function minimax(node, depth, maximizingPlayer)
02 if depth = 0 or node is a terminal node
03 return the heuristic value of node
04 if maximizingPlayer
05 bestValue := −∞
06 for each child of node
07 v := minimax(child, depth − 1, FALSE)
08 bestValue := max(bestValue, v)
09 return bestValue
10 else (* minimizing player *)
11 bestValue := +∞
12 for each child of node
13 v := minimax(child, depth − 1, TRUE)
14 bestValue := min(bestValue, v)
15 return bestValue
我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace minimax {
class Program {
static void Main(string[] args) {
int total = 0;
Console.WriteLine("the current total is " + total);
while (total < 21) {
Console.WriteLine("add 1 or 2?");
total += Convert.ToInt32(Console.ReadLine());
Console.WriteLine("you increased the total to " + total);
if (total == 21) {
Console.WriteLine("you win");
break;
}
int bestMove = 1;
int bestScore = 100;
for (int i = 1; (i <= 2) && (total + i <= 21); i++) {
if (minimax(total + i, -1) < bestScore) bestMove = i;
}
total += bestMove;
Console.WriteLine("computer increased the total to " + total);
if (total == 21) {
Console.WriteLine("computer wins");
break;
}
}
Console.ReadLine();
}
static int minimax(int total, int color) {
if (total == 21) {
return color * 100;
}
if (color == 1) {
int bestValue = -100;
int v = minimax(total + 1, -1);
bestValue = max(bestValue, v);
if (total < 20) {
v = minimax(total + 2, -1);
bestValue = max(bestValue, v);
}
return bestValue;
}
else {
int bestValue = 100;
int v = minimax(total + 1, 1);
bestValue = min(bestValue, v);
if (total < 20) {
v = minimax(total + 2, 1);
bestValue = min(bestValue, v);
}
return bestValue;
}
}
static int max(int a, int b) {
if (a > b) return a;
return b;
}
static int min(int a, int b) {
if (a < b) return a;
return b;
}
}
}
计算机对手没有做出正确的举动。当我浏览代码时,似乎来自伪代码的算法是错误的。
例如,如果我在开始时跳到17,AI应该将总数增加1.而是将它增加2,这是一个失败的举动。