foxycode
foxycode

Reputation: 3

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

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:

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.

Upvotes: 0

Views: 895

Answers (1)

Oswald
Oswald

Reputation: 31647

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. E.g. before finally deciding on a move, you have to test whether the king is in check.

Upvotes: 1

Related Questions