【问题标题】:Checkers multi-jump counting algorithm跳棋多跳计数算法
【发布时间】:2019-03-02 13:43:10
【问题描述】:

我正在 SFML - Checkers 中做我的第一个 C++ 项目。 不幸的是,我在发明一个递归函数时遇到了困难,它可以让我检查每一个可能的跳跃组合,并返回坐标。

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

编辑#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;

【问题讨论】:

  • 你已经有单跳的代码了吗?
  • @NicoSchertler 当然,它检查所选棋子的位置 + 1 块是否等于对手棋子,以及棋子的位置 +2 是否空闲(每个方向的代码相同)。 (我将编辑主帖子并将其粘贴在那里)
  • 一种方法是将棋盘状态作为参数添加到该函数。然后,根据你正在调查的跳跃修改状态(移除对手,改变自己棋子的位置)并从目标位置递归再次检查。

标签: c++ algorithm logic


【解决方案1】:

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

对于给定的棋盘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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    相关资源
    最近更新 更多