Checkers多跳计数算法

时间:2019-03-02 13:43:11

标签: c++ algorithm logic

我正在用SFML做我的第一个C ++项目-Checkers。 不幸的是,我被困在发明一个递归函数上,该函数允许我检查所有可能的跳跃组合,并返回坐标。

我该怎么做?我搜索了很多网页,没有找到答案, 所以我认为它比我想象的要容易。

EDIT#1:

if (player2.isSelected(pos_x + blockSize, pos_y + blockSize))
    if (isBoardBlockEmpty(pos_x + 2 * blockSize, pos_y + 2 * blockSize))
        return true;
if (player2.isSelected(pos_x - blockSize, pos_y + blockSize))
    if (isBoardBlockEmpty(pos_x - 2 * blockSize, pos_y + 2 * blockSize))
        return true;
if (player2.isSelected(pos_x + blockSize, pos_y - blockSize))
    if (isBoardBlockEmpty(pos_x + 2 * blockSize, pos_y - 2 * blockSize))
        return true;
if (player2.isSelected(pos_x - blockSize, pos_y - blockSize))
    if (isBoardBlockEmpty(pos_x - 2 * blockSize, pos_y - 2 * blockSize))
        return true;

1 个答案:

答案 0 :(得分:0)

这是一个树木搜索问题的实例,其中节点是木板,它们之间的边缘是一次执行一次跳跃的特定棋子。

对于给定的木板board和棋子在位置pos,您可以确定它可以进行哪些跳跃:

  • 如果没有可能的跳转,则多次跳转序列结束。如果当前的跳转列表不为空,请按顺序报告。
  • 如果可能存在跳跃,则通过进行跳跃(从板上移除被跳过的棋子)并查看是否可以从该位置进行更多跳跃来递归地探索每个跳跃。

在伪C ++中,这类似于以下内容。请注意,这是出于教育目的而编写的,不考虑性能。

// Assuming types pos and board were defined earlier.
using jump_list = std::vector<pos>;

// List of moves from a given starting position and board
std::vector<pos> possible_jumps(pos start, const board& board);

// Apply a move (remove the pawn from the board, move the jumping pawn)
board apply_move(const board& board, pos start, pos move);

// I'm bundling the multi-jump calculation in a struct to easily store
// the resulting jump list.
struct multi_jump {
    std::vector<jump_list> jumps;
    multi_jump(pos start, board board) {
        explore({}, start, board);
    }

    void explore(jump_list so_far, pos start, board board) {
        auto moves = possible_jumps(start, board);
        if (moves.empty()) {
            if (!so_far.empty()) {
                jumps.push_back(so_far);
            }
        } else {
            for (const auto move : moves) {
                board new_board = apply_move(board, start, move);
                jump_list new_so_far = so_far;
                new_so_far.push_back(move);
                explore(new_so_far, move, new_board);
            }
        }
    }
};

最后,您可以按照以下步骤从起始位置和板上检索跳跃列表:

jump_list jumps = multi_jump(start, board).jumps;