首页 > 解决方案 > 需要一个有效的算法来根据规格移动游戏块(游戏:Janggi)

问题描述

我正在用 Python 为一个名为 Janggi 的韩国象棋游戏构建后端。

以下是一些基本规则:https ://en.wikipedia.org/wiki/Janggi

我发现有几件制作起来有点挑战性……即马和象件。

他们有同样的问题,所以我只关注马片。

本质上,马块先正交移动一步,然后对角向外移动一步,没有跳跃。如果可以移动,我is_legal_move()设置方法的方式应该返回 True 或 False。(此方法是特定于棋子的。其他类中的其他方法确保遵守一般合法动作)。

但是,我目前不考虑“不跳跃”规则。我基本上只有一个合法转置坐标的列表。但是如果在 to 和 from 坐标之间有一块,它不会检测到这个问题。

试图思考我如何才能解释马必须“走”在 from 坐标和 to 坐标之间的空间......

这是我当前的迭代。

class Horse(GamePiece):
    """
    Represents Horse game piece, inherits from Game Piece class
    """

    def __init__(self, _player_piece_color):
        """

        """
        super().__init__(_player_piece_color)
        self._moves = [(-1, -2), (-1, 2), (-2, -1),
                    (-2, 1), (0, 0), (1, -2), 
                    (1, 2), (2, -1), (2, 1)]
    
    def is_legal_move(self, x_from, y_from, x_to, y_to):
        """
        checks that Horse piece can make attempted move
        returns True if legal, False otherwise
        """
        
        diff = (x_to - x_from, y_to - y_from)
        return diff in self._moves

标签: pythonalgorithmclassoop

解决方案


您需要创建一个以 a作为键并返回中间位置的self._jumps字典,该位置没有任何内容。diff

您还需要为is_legal_move板添加一个参数,以便您可以检查条件。

是的,您需要将该参数添加到其他部分的相同方法中。但他们可以忽略它。


推荐阅读