Get enemy's possible moves in chess to a 2D array

I have three arrays,

chess = [["c","d","e","f","g","e","d","c"],
         ["b","b","b","b","b","b","b","b"],
         ["a","a","a","a","a","a","a","a"],
         ["a","a","a","a","a","a","a","a"],
         ["a","a","a","a","a","a","a","a"],
         ["a","a","a","a","a","a","a","a"],
         ["h","h","h","h","h","h","h","h"],
         ["i","j","k","l","m","k","j","i"]]

that stores the positions of the pieces, ('a' is empty, 'b' is a black pawn etc.) and two other 8x8 arrays filled with False named whiteMoves and blackMoves. What I want is a function

def getEnemyMoves():
    global chess, whiteMoves, blackMoves
    doSomethingToWhiteMoves()
    doSomethingToBlackMoves()

that does for example these:

  • If there is an enemy piece in chess[5][0] (or a3), whiteMoves[5][0] should turn True because the pawn in chess[7][1] (b2) can eat it.
  • If a black queen would be in chess[7][0] (a1) and the king in chess[7][1] (b1), blackMoves[7][1] should turn True.
  • whiteMoves[0][0] should be True if there is a black piece in danger in chess[0][0] (a8).
  • I have tried many different ways to do this, but they were very complex and none of them worked fully. This is the only thing to do before my chess game is finished.


    Iterate over the pieces on the board. For each piece, narrow down the destination squares according to the move rules for that piece:

  • King can move to the adjacent 8 squares or two squares to each side
  • Pawns can move one or two squares ahead or one diagonally ahead.
  • etc.
  • For each such candidate move, test whether additional constraints prevent that candidate move:

  • King can only move two squares to a side, if it castles.
  • Pawns can only move diagonally ahead, if it captures an opponents piece (possibly en passant).
  • Rook cannot jump over other pieces
  • etc.
  • If you combine these two passes into a single one, you save some CPU cycles:

  • If a rook on a1 cannot move to a3, because of a blocking piece, it can certainly not move to a4, a5, a6, a7 and a8.
  • These things are complex. Eg before finally deciding on a move, you have to test whether the king is in check.

    链接地址: http://www.djcxy.com/p/84668.html

    上一篇: 国际象棋决赛:国王和白嘴鸦vs国王在蟒蛇

    下一篇: 在国际象棋中获得敌人可能的移动到2D阵列