简体   繁体   中英

Python Chess Validation move

I am new to programming and I am trying to implement a small chess game.

I am currently struggling with the validations move for each piece.

Each piece is an object inheriting from a higher class "ChessPiece". The board is a dict of 64 elements ('board array'): top left is element 0 (ie A8 is the black rook on the black sloth) while the bottom right element 64 is (ie H1 is the white rook on the black sloth).

The user inputs the coordinate, example a1, and through a dictionary the program retrive the index in the 'board array'.

The dictionary is:

board_array= {
    "a8": 0, "a7": 8, "a6": 16, "a5": 24, "a4": 32, "a3": 40, "a2": 48, "a1": 56,
    "b8": 1, "b7": 9, "b6": 17, "b5": 25, "b4": 33, "b3": 41, "b2": 49, "b1": 57,
    "c8": 2, "c7": 10, "c6": 18, "c5": 26, "c4": 34, "c3": 42, "c2": 50, "c1": 58,
    "d8": 3, "d7": 11, "d6": 19, "d5": 27, "d4": 35, "d3": 43, "d2": 51, "d1": 59,
    "e8": 4, "e7": 12, "e6": 20, "e5": 28, "e4": 36, "e3": 44, "e2": 52, "e1": 60,
    "f8": 5, "f7": 13, "f6": 21, "f5": 29, "f4": 37, "f3": 45, "f2": 53, "f1": 61,
    "g8": 6, "g7": 14, "g6": 22, "g5": 30, "g4": 38, "g3": 46, "g2": 54, "g1": 62,
    "h8": 7, "h7": 15, "h6": 23, "h5": 31, "h4": 39, "h3": 47, "h2": 55, "h1": 63,
}

I have created a function in each subclass (Pawn, Rook, Queen...) that should validate the move. The syntax is something like:

def isvalid(self, final_position):
   #Check if the final_position is valid. If it is valid, return True and thus the program che update the instance position. Otherwise, return False and re-ask the user to input a valid final_position

Currently I can move any white piece in any white sloth or sloth with a black piece on it (but I cannot eat myself) and vice versa.

The issue is that I do not know how to start to validate.

I guess the fact that I am using a dict for the board and not a list of lists makes thing harder. I am really lost. It would be amazing if you could help me by showing a validation, maybe for an easier piece such as the Rook.

For rook:

 def invalid(pos, target):

       d0 = 1 if pos[0]>target[0] else -1
       d1 = 1 if pos[1]>target[1] else -1
       return any(board_array[i + j ] for i, j in zip(range(target[0], pos[0], d0 ), range(target[1], pos[1], d1 ))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM