Negamax for simple addition game

I'm trying to implement negamax for a simple game where the players alternate adding one or two to a running sum. The player that increases the total to 21 wins.

I'm using the pseudocode here: https://en.wikipedia.org/wiki/Negamax#Negamax_base_algorithm

The human player moves first so the computer should easily win by adding the number that makes the total congruent to 0 mod 3.

I'm not doing any dynamic move generation. Just comparing the negamax score for adding 1 to the running sum to the negamax score for adding 2 to the running sum.

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;
    }
}

The negamax function:

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;
}

Max Method:

static int max(int a, int b) {
    if (a > b) return a;
    return b;
}

Not sure why the AI is just adding 2 every time.


The static evaluation function is incorrect.

https://en.wikipedia.org/wiki/Negamax#Negamax_base_algorithm The negamax node's return value is a heuristic score from the point of view of the node's current player.

if (total == 21), it's always a loss for the node's current player. So negamax return must be -100. There are other code errors too, such as when total is 22.


A player who cannot make a move obviously loses the game, right? If so, then

if (total == 21) {
    return color * 100;
}

looks wrong to me, because it inverts the rules. You are saying that the player who cannot make move wins! Try to rework these 3 lines.

链接地址: http://www.djcxy.com/p/56358.html

上一篇: 如何实现negamax的makemove功能

下一篇: Negamax为简单的补充游戏