首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Tac Tac Toe negamax实现。

Tac Tac Toe negamax实现。
EN

Stack Overflow用户
提问于 2015-05-13 06:31:33
回答 1查看 1.6K关注 0票数 2

我正在尝试为tic-tac-toe应用程序实现negamax搜索功能,但它并没有返回最佳值,相反,它似乎是半随机猜测的。以下是我的代码的相关部分:

代码语言:javascript
复制
public int negamax(Result result, Token token) {
    if (result == Result.WIN) {
        return 1;
    } else if (result == Result.DRAW) {
        return 0;
    }

    int best = -1;

    for (Coordinate move : Board.getAvailableMoves()) {
        Token other = token.getOther();
        Result r = Board.makeMove(move, other);
        int eval = -negamax(r, other);
        Board.unmakeMove(move);

        if (eval > best) {
            best = eval;
        }
    }

    return best;
}

public Coordinate getNegamaxMove(Token token) {
    int score = -1;
    Coordinate bestMove = null;

    for (Coordinate move : Board.getAvailableMoves()) {
        Result result = Board.makeMove(move, token);
        int newScore = negamax(result, token);
        Board.unmakeMove(move);

        if (newScore >= score) {
            score = newScore;
            bestMove = move;
        }
    }

    return bestMove;
}

重要的是要注意,我不是将棋盘作为参数传递,而是将移动的结果作为参数传递,可以是WIN,be,VALID或either (最后两个与当前讨论无关),这些都是不言而喻的。Coordinate类只保存移动的行值和列值。

非常感谢:)

EN

回答 1

Stack Overflow用户

发布于 2015-05-17 20:29:01

我已经设法让它工作了,负极最大方法有两个问题。首先,应该在循环遍历所有可用移动之前更改令牌,而不是在循环内部。其次,由于我在getNegamaxMove方法中检查最佳走法,在negamax方法中,我必须跟踪最差的走法而不是最好的走法。下面是使用注释掉的旧部分的工作实现,以供比较:

代码语言:javascript
复制
public int negamax(Result result, Token token) {
    if (result == Result.WIN) {
        return 1;
    } else if (result == Result.DRAW) {
        return 0;
    }

    int worst = 1;
    // int best = -1

    Token other = token.getOther();
    for (Coordinate move : Board.getAvailableMoves()) {
        // Token other = token.getOther();
        Result r = Board.makeMove(move, other);
        int eval = -negamax(r, other);
        Board.unmakeMove(move);

        // if (eval > best) {
        //     best = eval;
        // }

        if (eval < worst) {
            worst = eval;
        }
    }

    // return best
    return worst;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30202563

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档