Finding all legal moves in a simple board game

时间:2015-06-20 09:36:27

标签: python numpy

I have an 8x8 board represented by a numpy.ndarray:

array([[0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0]])

#    0 = free space
#    1 = player1's figure     

A figure can either move forward and left, forward and right or just forward (forward means down the board in this case).

Right now I am using nested for loops in order to look through the board indexes. When I find a figure I append the board states that can be achieved by making moves with that figure to a list and then keep searching for figures.

For this example the output of my function looks like this:

[array([[[0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0]],

       [[0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 1, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0]],

       [[0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 1, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0]]])]

Is there a faster way in which I can find all the possible moves for a given board state?

1 个答案:

答案 0 :(得分:0)

对于内存和性能而言,不是更容易,而不是将complete board保留在内存中,保持玩家数字在内存中的位置。让我们举个例子,玩家人物的位置是 -

player1 =(1,4)

我们假设,球员位置由(x,y)表示。然后你可以在运行时计算该玩家的动作(不需要留在内存中),可能的动作是 -

  1. (X + 1,y)的
  2. (X + 1,Y + 1)
  3. (X + 1,Y-1)
  4. 如果玩家的数字可以在棋盘中回圈,那就是如果他位于棋盘的最底部位置,那么接下来的动作将是最顶行,如果是这样的话,那么移动将被确定将modulo与行数和列数相对应(假设nr - number of rowsnc - number of columns)。例如,对于(x,y),下一步行动将是 -

    1. ((x + 1)%nr,y%nc)
    2. ((x + 1)%nr,(y + 1)%nc)
    3. ((x + 1)%nr,(y-1)%nc)