Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Is this code correct?

This code was adapted from this alphabeta pseudocode. AlphaBeta search is often mentioned but getting the code 100% correct is tricky.

IGame is an interface with two methods:
getScore() - evaluates the current game state from the viewpoint of the AI
generateMoves() - creates possible moves from the current game state.

class Search
{
    Move bestMove;

    Move findBestMove(int ply, IGame g)
    {
        bestMove = null;
        alpha_beta(ply, g, Integer.MINIMUM, Integer.MAXIMUM);
        return bestMove;
    }

    int alpha_beta(int depth, IGame g, int alpha, int beta)
    {
        if (depth == 0 || g.isGameFinished()) return g.getScore();

        Move[] gameMove = g.generateMoves();

        for (int i = 0; i < gameMove.length; i++)
        {
            g.execute(gameMove[i]);
            int score = -alpha_beta(depth - 1, -beta, -alpha);
            g.undo(gameMove[i]);

            if (alpha < score)
            {
                alpha = score;
                bestMove = gameMove[i];
            }
            if (beta <= alpha) return alpha;
        }
        return alpha;
    } 
}
share|improve this question
2  
Even if the algorithm is know as "alphabeta", "minimax", etc, you should find better variable names that "alpha" and "beta". – Sulthan Mar 14 at 15:56
2  
By the way, what is the question? – Sulthan Mar 14 at 15:57
@Sulthan, firstly, the question explicitly states the question: "is this correct." Secondly, this is Code Review. Every question is a code review, and we don't need to explicitly state a question. – Winston Ewert Mar 16 at 5:40
@WinstonEwert firstly, the "is this correct" question was added some time after my comment. Secondly, per Code Review FAQ, only working code should be here. It seems to me that the OP doesn't even know if the code is working. – Sulthan Mar 16 at 10:41
@Sulthan, actually the faq says: "To the best of my knowledge, does the code work?" As long as the poster is unaware of the flaws, asking for help in spotting them is on-topic. – Winston Ewert Mar 16 at 19:56

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.