A while ago, I was working on a chess project with a couple other people. In the end, I wrote all but a couple of the lines of code, including these:
class Piece(list):
def IsValidMovePattern(self, FromCoord, ToCoord):
print(self, "Validation not done")
return False
class King(Piece):
def IsValidMovePattern(self, FromCoord, ToCoord):
move = [abs(ToCoord[0] - FromCoord[0]), abs(ToCoord[1] - FromCoord[1])]
# One square in any direction
if move[0] <= 1 and move[1] <= 1:
return True
# Castling - AND has higher priority than OR
if move[0] == 0 and move[1] == 2:
if self[1] == Player(1) and FromCoord == (0, 4) or self[1] == Player(2) and FromCoord == (7, 4):
return True
return False
class Queen(Piece):
def IsValidMovePattern(self, FromCoord, ToCoord):
move = [abs(ToCoord[0] - FromCoord[0]), abs(ToCoord[1] - FromCoord[1])]
# Diagonal and straight moves
if move[0] == move[1] or move[0] == 0 or move[1] == 0:
return True
return False
class Rook(Piece):
HasMoved = False
def IsValidMovePattern(self, FromCoord, ToCoord):
move = [ToCoord[0] - FromCoord[0], ToCoord[1] - FromCoord[1]]
if move[0] == 0 or move[1] == 0:
return True
return False
class Knight(Piece):
def IsValidMovePattern(self, FromCoord, ToCoord):
move = [abs(ToCoord[0] - FromCoord[0]), abs(ToCoord[1] - FromCoord[1])]
# L-shaped moves
if move[0] == 1 and move[1] == 2 or move[0] == 2 and move[1] == 1:
return True
return False
class Bishop(Piece):
def IsValidMovePattern(self, FromCoord, ToCoord):
move = [abs(ToCoord[0] - FromCoord[0]), abs(ToCoord[1] - FromCoord[1])]
# Can only move diagonal
if move[0] == move[1]:
return True
return False
class Pawn(Piece):
# Set to True when a pawn moves two squares past
# Pawn must be on square 3 for PlayerOne or square 4 for PlayerTwo
EnPassant = False
def IsValidMovePattern(self, FromCoord, ToCoord):
move = [ToCoord[0] - FromCoord[0], ToCoord[1] - FromCoord[1]]
# Player(1) capture
if self[1] == Player(1) and abs(move[1]) == move[0] == 1:
return True
# Player(2) capture
if self[1] == Player(2) and abs(move[1]) == 1 and move[0] == -1:
return True
# Player(1) first move
if self[1] == Player(1) and FromCoord[0] == 1 and move[1] == 0 and move[0] == 2:
return True
# Player(2) first move
if self[1] == Player(2) and FromCoord[0] == 6 and move[1] == 0 and move[0] == -2:
return True
# Player(1) move
if self[1] == Player(1) and move[1] == 0 and move[0] == 1:
return True
# Player(2) move
if self[1] == Player(2) and move[1] == 0 and move[0] == -1:
return True
return False
This is called like this (where self
is similar to this
in C#; it is being called from the Board class):
if not self.data[FromCoord[0]][FromCoord[1]].IsValidMovePattern(FromCoord, ToCoord):
FromCoord
and ToCoord
are tuples (similar to immutable arrays) like (FromX, FromY)
.
Is this a good implementation? Would this be a slow implementation, or is it reasonable? The rest of the code (with Checkmate and the AI incomplete) can be found at Github.