家庭作业:生成可能移动的列表

时间:2016-05-31 00:43:15

标签: python

我正在尝试为类似跳棋的游戏生成一系列可能的动作。例如,在游戏开始时,棋盘看起来像[[1,1,1],[0,0,0],[2,2,2]]。我的功能将采用颜色(一个用于白色,或两个用于黑色)并将这些部件向前移动一个空格或一个空间对角线以捕获另一个部分。因此,首先出现白色的第一个可能的移动列表是[[[0,1,1],[1,0,0],[2,2,2]],[[1,0,1],[0 ,1,0,[2,2,2]],[[1,1,1],[0,0,1,[2,2,2]]]

到目前为止,我有:

def generateMoves(color, board):

    newboard = []
    subboard = []
    board = [[1, 1, 1], [0, 0, 0], [2, 2, 2]]
    x = 0

    for i in board:
        while x < len(board):
            subboard.append(board[x])
            newboard.append(subboard)
            x += 1
    return newboard

但我无法弄清楚我需要做些什么修改才能计算出新的可能行动清单。

1 个答案:

答案 0 :(得分:0)

首先,我们必须注意向前或向后移动取决于作品的拥有者。

我们将运动的方向,运动员的代码,对手的代码和棋盘作为参数。

现在,我将定义一个生成可能移动的函数。格式为(原件行,原件列,新件行,新件列)

def generate_moves(player, direction, board, opponent)
 for y, row in enumerate(board):
  for x, piece in enumerate(row):
   # Check if the piece belongs to the player
   if piece == player:
    new_row = y + direction
    # Check we don't go out of bounds
    if new_row >= 0 and new_row < len(board);
     # Check that the new square is not occupied by the same player
     if board[new_row][x] != player:
      # Produce the "advance" move
      yield (y,x ,new_row,x)
     # Now check if you can "eat" an opponent piece
     for side_offset in (+1, -1):
      # +1: check diagonal right, -1: check diagonal left
      new_column = x + side_offset
      if new_column >= 0  and new_column < len(row) and board[new_row][new_column] == opponent:
       yield (y, x, new_row, new_column)

现在我们有一台发电机可以在电路板上产生所有可能的动作。 我们可以用它来根据我们的需要修改电路板。

board = [....]
for player, direction, opponent in ((1,-1,2),(2,+1,1)):
 # Player 1 goes down (-1), player 2 goes up (+1)
 for move in generate_moves(player, direction, board, opponent):
  # REMEMBER: do not modify the board, as the object is shared inside the generator
  new_board = deepcopy(board) # You need to implement the deep copy
  col, row, new_col, new_row = move
  # The piece is no longer in the old position
  new_board[col][row] = 0
  # But in the new position instead!
  new_board[new_col, new_row] = player

  # Do something with the new_board