プレーヤーが実行中の合計に 1 つまたは 2 つ追加する単純なゲームにネガマックスを実装しようとしています。合計を21に増やしたプレーヤーが勝ちです。
ここで疑似コードを使用しています: https://en.wikipedia.org/wiki/Negamax#Negamax_base_algorithm
人間のプレイヤーが最初に動くので、合計が 0 mod 3 に一致する数を追加することで、コンピューターが簡単に勝つはずです。
私は動的な動きの生成を行っていません。現在の合計に 1 を追加する場合の negamax スコアと、現在の合計に 2 を追加する場合の negamax スコアを比較するだけです。
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;
}
if (negamax(total + 1, 1) > negamax(total + 2, 1)) total++;
else total += 2;
Console.WriteLine("computer increased the total to " + total);
if (total == 21) {
Console.WriteLine("computer wins");
break;
}
}
ネガマックス関数:
static int negamax(int total, int color) {
if (total == 21) {
return color * 100;
}
int bestValue = -100;
for (int i = 1; i <= 2; i++) {
if (total + i <= 21) {
int v = -1 * negamax(total + i, -1 * color);
bestValue = max(bestValue, v);
}
}
return bestValue;
}
最大方法:
static int max(int a, int b) {
if (a > b) return a;
return b;
}
AI が毎回 2 を追加する理由がわかりません。