作业:列出可能的动作

2024-06-02 08:43:52 发布

您现在位置: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

但是我不知道我需要对它做什么修改来计算新的可能移动列表。在


Tags: 函数board游戏列表棋盘颜色代表棋类
1条回答
网友
1楼 · 发布于 2024-06-02 08:43:52

首先,我们必须指出,前进或后退取决于作品的主人。在

我们将把移动的方向,玩家的代码,对手的代码和棋盘的代码作为参数。在

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

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)

现在我们有了一个发电机,它能产生棋盘上所有可能的动作。 我们可以用它来修改电路板以满足我们的需要。在

^{pr2}$

相关问题 更多 >