Compare commits
36 Commits
Author | SHA1 | Date | |
---|---|---|---|
e6fafc8081 | |||
1be71bf203 | |||
e862ab6b0b | |||
6c0819428e | |||
496207861e | |||
87e8e75c04 | |||
13e3675665 | |||
2e27e7b703 | |||
d7863e0d81 | |||
a3b7df4e4c | |||
806a4a7f65 | |||
052f815ee1 | |||
c14a8c83b3 | |||
ac85f3e6d3 | |||
ddfb95176b | |||
bb0a3266c7 | |||
aabbaa83a8 | |||
96b9b3db86 | |||
6b0a134230 | |||
e95caa0015 | |||
bb0b8cdd27 | |||
55ba824b13 | |||
16d107e5ea | |||
baa09135ee | |||
eae87f353b | |||
362b0e157d | |||
c900ebcfa0 | |||
c3e46017eb | |||
324484aa31 | |||
eca7a6ae0c | |||
ffe76b161a | |||
06f78487d9 | |||
51648a5960 | |||
331c475c2a | |||
28ef132944 | |||
f7c0dcbd4b |
1
.github/workflows/automatic-prerelease.yml
vendored
@ -17,3 +17,4 @@ jobs:
|
||||
repo_token: "${{ secrets.GITHUB_TOKEN }}"
|
||||
prerelease: true
|
||||
automatic_release_tag: "latest"
|
||||
title: "Development Build"
|
||||
|
BIN
res/black-bishop.png
Normal file
After Width: | Height: | Size: 1.4 KiB |
BIN
res/black-king.png
Normal file
After Width: | Height: | Size: 3.5 KiB |
BIN
res/black-knight.png
Normal file
After Width: | Height: | Size: 1.8 KiB |
BIN
res/black-pawn.png
Normal file
After Width: | Height: | Size: 734 B |
BIN
res/black-queen.png
Normal file
After Width: | Height: | Size: 2.7 KiB |
BIN
res/black-rook.png
Normal file
After Width: | Height: | Size: 1014 B |
BIN
res/trimmed.png
Normal file
After Width: | Height: | Size: 4.2 KiB |
BIN
res/white-bishop.png
Normal file
After Width: | Height: | Size: 2.5 KiB |
BIN
res/white-king.png
Normal file
After Width: | Height: | Size: 3.0 KiB |
BIN
res/white-knight.png
Normal file
After Width: | Height: | Size: 2.2 KiB |
BIN
res/white-pawn.png
Normal file
After Width: | Height: | Size: 1.4 KiB |
BIN
res/white-queen.png
Normal file
After Width: | Height: | Size: 3.8 KiB |
BIN
res/white-rook.png
Normal file
After Width: | Height: | Size: 1.3 KiB |
63
src/controller/controller.py
Normal file
@ -0,0 +1,63 @@
|
||||
from logic.board import Board
|
||||
from logic.move import Move
|
||||
from logic.pieces.piece import Piece
|
||||
from logic.position import Position
|
||||
from view.view import View
|
||||
|
||||
|
||||
class Controller:
|
||||
def __init__(self, board: Board, view: View) -> None:
|
||||
self._board = board
|
||||
self._view = view
|
||||
|
||||
self._view.set_controller(self)
|
||||
self._reset_selection()
|
||||
|
||||
self._selected_piece: Piece = None
|
||||
self._legal_moves: list[Move] = []
|
||||
|
||||
def _reset_selection(self):
|
||||
self._selected_piece = None
|
||||
self._legal_moves = []
|
||||
self._view.update_board(self._board, self._selected_piece, self._legal_moves)
|
||||
|
||||
|
||||
def _show_legal_moves(self, pos: Position):
|
||||
piece = self._board.piece_at(pos.x, pos.y)
|
||||
|
||||
if piece:
|
||||
if piece.colour != self._board._turn:
|
||||
return
|
||||
self._selected_piece = piece
|
||||
self._legal_moves = piece.legal_moves(self._board)
|
||||
self._view.update_board(self._board, self._selected_piece, self._legal_moves)
|
||||
else:
|
||||
self._reset_selection()
|
||||
|
||||
def _make_move(self, move: Move) -> None:
|
||||
self._board = self._board.make_move(move)
|
||||
self._reset_selection()
|
||||
|
||||
def on_tile_selected(self, x: int, y: int) -> None:
|
||||
pos = Position(x, y)
|
||||
|
||||
piece = self._board.piece_at(x, y)
|
||||
|
||||
if self._selected_piece is None \
|
||||
or (piece is not None and piece != self._selected_piece and piece.colour == self._selected_piece.colour):
|
||||
self._show_legal_moves(pos)
|
||||
else:
|
||||
legal_moves_positions = [move for move in self._legal_moves if move.pos == pos]
|
||||
assert len(legal_moves_positions) <= 1, f"Apparently we can make multiple moves towards {pos.to_algebraic()} with {type(self._selected_piece)}, which doesn't make sense..."
|
||||
|
||||
if len(legal_moves_positions) == 0: # click on a square outside of the possible moves
|
||||
self._reset_selection()
|
||||
else:
|
||||
move = legal_moves_positions[0]
|
||||
self._make_move(move)
|
||||
|
||||
if self._board.is_checkmate_for(self._board._turn):
|
||||
self._view.notify_checkmate(self._board._turn)
|
||||
|
||||
if self._board.is_stalemate_for(self._board._turn):
|
||||
self._view.notify_stalemate(self._board._turn)
|
@ -1,41 +1,106 @@
|
||||
from logic.move import CastleSide, Move
|
||||
from logic.pieces.bishop import Bishop
|
||||
from logic.pieces.king import King
|
||||
from logic.pieces.knight import Knight
|
||||
from logic.pieces.queen import Queen
|
||||
from logic.pieces.rook import Rook
|
||||
from logic.pieces.pawn import Pawn
|
||||
from logic.pieces.piece import Piece
|
||||
from logic.pieces.piece import Colour, Piece
|
||||
from logic.position import Position
|
||||
|
||||
from typing import Type
|
||||
|
||||
class Board:
|
||||
def __init__(self) -> None:
|
||||
self._white: dict[Position, Piece] = {}
|
||||
self._black: dict[Position, Piece] = {}
|
||||
self._turn = None
|
||||
self._white_castling_rights = set()
|
||||
self._black_castling_rights = set()
|
||||
self._en_passant_target = None
|
||||
|
||||
for x in range(8):
|
||||
pos_w_pawn = Position(x, 1)
|
||||
pos_b_pawn = Position(x, 6)
|
||||
@staticmethod
|
||||
def _piece_class_from_char(c: str) -> Type[Piece]:
|
||||
assert len(c) == 1, f"The piece {c} isn't denoted by 1 character"
|
||||
c = c.lower()
|
||||
if c == "p":
|
||||
return Pawn
|
||||
if c == "r":
|
||||
return Rook
|
||||
if c == "n":
|
||||
return Knight
|
||||
if c == "b":
|
||||
return Bishop
|
||||
if c == "q":
|
||||
return Queen
|
||||
if c == "k":
|
||||
return King
|
||||
raise ValueError(f"Unknown piece '{c}'")
|
||||
|
||||
self._white[pos_w_pawn] = Pawn(pos_w_pawn, Piece.WHITE)
|
||||
self._black[pos_b_pawn] = Pawn(pos_b_pawn, Piece.BLACK)
|
||||
@staticmethod
|
||||
def setup_FEN_position(position: str) -> "Board":
|
||||
ret = Board()
|
||||
index = 0
|
||||
|
||||
pos_w_piece = Position(x, 0)
|
||||
pos_b_piece = Position(x, 7)
|
||||
# -- Pieces
|
||||
pieces = "prnbqk" # possible pieces
|
||||
numbers = "12345678" # possible number of empty squares
|
||||
|
||||
piece = None
|
||||
if x == 0 or x == 7:
|
||||
piece = Rook
|
||||
elif x == 1 or x == 6:
|
||||
piece = Knight
|
||||
elif x == 2 or x == 5:
|
||||
piece = Bishop
|
||||
elif x == 3:
|
||||
piece = Queen
|
||||
elif x == 4:
|
||||
piece = King
|
||||
assert piece != None, f"Didn't know which piece to assign for {x = }"
|
||||
self._white[pos_w_piece] = piece(pos_w_piece, Piece.WHITE)
|
||||
self._black[pos_b_piece] = piece(pos_b_piece, Piece.BLACK)
|
||||
x = 0
|
||||
y = 7 # FEN starts from the top left, so 8th rank
|
||||
for c in position:
|
||||
index += 1
|
||||
if c == " ":
|
||||
break
|
||||
if c in pieces or c in pieces.upper():
|
||||
pos = Position(x, y)
|
||||
piece = Board._piece_class_from_char(c)
|
||||
if c.isupper():
|
||||
ret._white[pos] = piece(pos, Colour.WHITE)
|
||||
else:
|
||||
ret._black[pos] = piece(pos, Colour.BLACK)
|
||||
|
||||
x += 1
|
||||
continue
|
||||
if c in numbers:
|
||||
x += int(c)
|
||||
if c == '/':
|
||||
x = 0
|
||||
y -= 1
|
||||
|
||||
|
||||
# -- Active colour
|
||||
if position[index] == "w":
|
||||
ret._turn = Colour.WHITE
|
||||
elif position[index] == "b":
|
||||
ret._turn = Colour.BLACK
|
||||
else:
|
||||
raise ValueError(f"The FEN position is malformed, the active colour should be either 'w' or 'b', but is '{position[index]}'")
|
||||
index += 2
|
||||
|
||||
|
||||
# -- Castling Rights
|
||||
for c in position[index:]:
|
||||
index += 1
|
||||
if c == "-" or c == " ":
|
||||
break
|
||||
|
||||
sides = "kq"
|
||||
assert c in sides or c in sides.upper(), f"The FEN position is malformed, the castling rights should be either k or q (both either lower- or upper-case), instead is '{c}'"
|
||||
if c == "K":
|
||||
ret._white_castling_rights.add(CastleSide.King)
|
||||
if c == "Q":
|
||||
ret._white_castling_rights.add(CastleSide.Queen)
|
||||
if c == "k":
|
||||
ret._black_castling_rights.add(CastleSide.King)
|
||||
if c == "q":
|
||||
ret._black_castling_rights.add(CastleSide.Queen)
|
||||
|
||||
# -- En passant target
|
||||
if position[index] != "-":
|
||||
ret._en_passant_target = position[index:index+2]
|
||||
|
||||
return ret
|
||||
|
||||
def piece_at(self, x: int, y: int) -> Piece | None:
|
||||
pos = Position(x, y)
|
||||
@ -48,5 +113,117 @@ class Board:
|
||||
return white_piece
|
||||
return black_piece
|
||||
|
||||
def create_board():
|
||||
return Board()
|
||||
def is_check_for(self, colour: Colour) -> bool:
|
||||
""" Is it check for the defending colour passed as parameter """
|
||||
defending_pieces, attacking_pieces = (self._white, self._black) if colour == Colour.WHITE else (self._black, self._white)
|
||||
|
||||
kings = [piece for piece in defending_pieces.values() if type(piece) == King]
|
||||
assert len(kings) == 1, f"We have more than one king for {colour}, that is no buono..."
|
||||
king = kings[0]
|
||||
|
||||
for piece in attacking_pieces.values():
|
||||
possible_pos = []
|
||||
if type(piece) == King:
|
||||
# special case for the king, because it creates infinite recursion (since he looks if he's walking into a check)
|
||||
for dx in [-1, 0, 1]:
|
||||
for dy in [-1, 0, 1]:
|
||||
x, y = piece.pos.x + dx, piece.pos.y + dy
|
||||
if Position.is_within_bounds(x, y):
|
||||
possible_pos.append(Position(x, y))
|
||||
else:
|
||||
possible_pos += [move.pos for move in piece.legal_moves(self, looking_for_check=True)]
|
||||
if king.pos in possible_pos:
|
||||
return True
|
||||
return False
|
||||
|
||||
def is_checkmate_for(self, colour: Colour) -> bool:
|
||||
""" Is it checkmate for the defending colour passed as parameter """
|
||||
return self.is_check_for(colour) and self._no_legal_moves_for(colour)
|
||||
|
||||
def is_stalemate_for(self, colour: Colour) -> bool:
|
||||
""" Is it stalemate for the defending colour passed as parameter """
|
||||
return not self.is_check_for(colour) and self._no_legal_moves_for(colour)
|
||||
|
||||
def _no_legal_moves_for(self, colour: Colour) -> bool:
|
||||
""" Return true if there are indeed no legal moves for the given colour (for checkmate or stalemate)"""
|
||||
pieces = self._white if colour == Colour.WHITE else self._black
|
||||
for piece in pieces.values():
|
||||
if len(piece.legal_moves(self)) > 0:
|
||||
return False
|
||||
return True
|
||||
|
||||
def castling_rights_for(self, colour: Colour) -> set[CastleSide]:
|
||||
return self._white_castling_rights if colour == Colour.WHITE else self._black_castling_rights
|
||||
|
||||
def make_move(self, move: Move) -> "Board":
|
||||
dest_piece = self.piece_at(move.pos.x, move.pos.y)
|
||||
|
||||
if dest_piece:
|
||||
assert dest_piece.colour != move.piece.colour, "A piece cannot cannot eat another piece of the same colour"
|
||||
|
||||
# -- Copy current state
|
||||
ret = Board()
|
||||
ret._white = self._white.copy()
|
||||
ret._black = self._black.copy()
|
||||
ret._turn = Colour.WHITE if self._turn == Colour.BLACK else Colour.BLACK
|
||||
ret._white_castling_rights = self._white_castling_rights.copy()
|
||||
ret._black_castling_rights = self._black_castling_rights.copy()
|
||||
|
||||
|
||||
piece = move.piece
|
||||
|
||||
# -- Actually make the move
|
||||
pieces_moving, other_pieces = (ret._white, ret._black) if piece.colour == Colour.WHITE else (ret._black, ret._white)
|
||||
|
||||
del pieces_moving[piece.pos]
|
||||
pieces_moving[move.pos] = piece.move_to(move.pos)
|
||||
if move.pos in other_pieces:
|
||||
del other_pieces[move.pos]
|
||||
|
||||
if move.en_passant:
|
||||
pos_to_remove = Position(move.pos.x, move.pos.y + (1 if self._turn == Colour.BLACK else -1))
|
||||
del other_pieces[pos_to_remove]
|
||||
|
||||
# -- Set en passant target if needed
|
||||
if move.becomes_en_passant_target:
|
||||
ret._en_passant_target = pieces_moving[move.pos]
|
||||
else:
|
||||
ret._en_passant_target = None
|
||||
|
||||
# -- Handle castling (just move the rook over)
|
||||
if move.castle_side == CastleSide.King:
|
||||
rook_pos = Position(7, piece.pos.y)
|
||||
assert rook_pos in pieces_moving and type(pieces_moving[rook_pos]) == Rook, "Either rook is absent from the king side or you are trying to castle with something else than a rook..."
|
||||
del pieces_moving[rook_pos]
|
||||
new_rook_pos = Position(5, piece.pos.y)
|
||||
pieces_moving[new_rook_pos] = Rook(new_rook_pos, piece.colour)
|
||||
|
||||
elif move.castle_side == CastleSide.Queen:
|
||||
rook_pos = Position(0, piece.pos.y)
|
||||
assert rook_pos in pieces_moving and type(pieces_moving[rook_pos]) == Rook, "Either rook is absent from the queen side or you are trying to castle with something else than a rook..."
|
||||
del pieces_moving[rook_pos]
|
||||
new_rook_pos = Position(3, piece.pos.y)
|
||||
pieces_moving[new_rook_pos] = Rook(new_rook_pos, piece.colour)
|
||||
|
||||
# -- Check for castling rights
|
||||
if piece.colour == Colour.WHITE:
|
||||
if type(piece) == King:
|
||||
ret._white_castling_rights = set()
|
||||
|
||||
if type(piece) == Rook:
|
||||
if piece.pos.x == 0 and CastleSide.Queen in ret._white_castling_rights:
|
||||
ret._white_castling_rights.remove(CastleSide.Queen)
|
||||
elif piece.pos.x == 7 and CastleSide.King in ret._white_castling_rights:
|
||||
ret._white_castling_rights.remove(CastleSide.King)
|
||||
else:
|
||||
if type(piece) == King:
|
||||
ret._black_castling_rights = set()
|
||||
|
||||
if type(piece) == Rook:
|
||||
if piece.pos.x == 0 and CastleSide.Queen in ret._black_castling_rights:
|
||||
ret._black_castling_rights.remove(CastleSide.Queen)
|
||||
elif piece.pos.x == 7 and CastleSide.King in ret._black_castling_rights:
|
||||
ret._black_castling_rights.remove(CastleSide.King)
|
||||
|
||||
|
||||
return ret
|
||||
|
40
src/logic/move.py
Normal file
@ -0,0 +1,40 @@
|
||||
# from logic.pieces.piece import Piece
|
||||
from logic.position import Position
|
||||
from enum import Enum
|
||||
|
||||
class CastleSide(Enum):
|
||||
Neither = ""
|
||||
King = "O-O"
|
||||
Queen = "O-O-O"
|
||||
|
||||
class Move:
|
||||
def __init__(self, piece: "Piece", pos: Position,/, is_capturing: bool = False, castle_side: CastleSide = CastleSide.Neither, en_passant: bool = False, becomes_en_passant_target: bool = False) -> None:
|
||||
self.piece = piece
|
||||
self.pos = pos
|
||||
self.is_capturing = is_capturing
|
||||
self.castle_side = castle_side
|
||||
self.becomes_en_passant_target = becomes_en_passant_target
|
||||
self.en_passant = en_passant
|
||||
|
||||
def to_algebraic(self) -> str:
|
||||
raise NotImplementedError("The move can't be translated to algbraic notation, as it was not implemented")
|
||||
|
||||
@staticmethod
|
||||
def from_algebraic(move: str) -> "Move":
|
||||
raise NotImplementedError("The move can't be translated from algbraic notation, as it was not implemented")
|
||||
|
||||
def __str__(self) -> str:
|
||||
if self.castle_side == CastleSide.King:
|
||||
return "O-O"
|
||||
if self.castle_side == CastleSide.Queen:
|
||||
return "O-O-O"
|
||||
|
||||
ret = ""
|
||||
if type(self.piece).__name__ != "Pawn":
|
||||
ret += self.piece.letter().upper()
|
||||
|
||||
ret += str(self.pos)
|
||||
return ret
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return str(self)
|
@ -1,4 +1,24 @@
|
||||
from logic.move import Move
|
||||
from .piece import Piece
|
||||
|
||||
class Bishop(Piece):
|
||||
pass
|
||||
def legal_moves(self, board: "Board", / , looking_for_check = False) -> list[Move]:
|
||||
ret = []
|
||||
|
||||
# looking north east
|
||||
ret.extend(self._look_direction(board, 1, 1))
|
||||
|
||||
# looking south east
|
||||
ret.extend(self._look_direction(board, 1, -1))
|
||||
|
||||
# looking south west
|
||||
ret.extend(self._look_direction(board, -1, -1))
|
||||
|
||||
# looking north west
|
||||
ret.extend(self._look_direction(board, -1, 1))
|
||||
|
||||
if not looking_for_check and board.is_check_for(self.colour):
|
||||
return self.keep_only_blocking(ret, board)
|
||||
|
||||
return ret
|
||||
|
||||
|
@ -1,5 +1,69 @@
|
||||
from logic.move import CastleSide, Move
|
||||
from logic.position import Position
|
||||
from .piece import Piece
|
||||
|
||||
class King(Piece):
|
||||
pass
|
||||
def legal_moves(self, board: "Board") -> list[Move]:
|
||||
ret = []
|
||||
|
||||
# -- Regular moves
|
||||
for dx in [-1, 0, 1]:
|
||||
for dy in [-1, 0, 1]:
|
||||
if dx == 0 and dy == 0: # skip current position
|
||||
continue
|
||||
x = self.pos.x + dx
|
||||
y = self.pos.y + dy
|
||||
move = self._move_for_position(board, x, y)
|
||||
if move:
|
||||
board_after_move = board.make_move(move)
|
||||
if not board_after_move.is_check_for(self.colour):
|
||||
ret.append(move)
|
||||
|
||||
if board.is_check_for(self.colour):
|
||||
return self.keep_only_blocking(ret, board)
|
||||
|
||||
# -- Castles
|
||||
castling_rights = board.castling_rights_for(self.colour)
|
||||
if len(castling_rights) == 0:
|
||||
return ret
|
||||
|
||||
if CastleSide.King in castling_rights:
|
||||
clear = True
|
||||
for dx in range(1, 3):
|
||||
x = self.pos.x + dx
|
||||
y = self.pos.y
|
||||
if board.piece_at(x, y) is not None:
|
||||
clear = False
|
||||
break
|
||||
|
||||
move = self._move_for_position(board, x, y)
|
||||
board_after_move = board.make_move(move)
|
||||
if board_after_move.is_check_for(self.colour):
|
||||
clear = False
|
||||
break
|
||||
|
||||
if clear:
|
||||
ret.append(Move(self, Position(6, self.pos.y), castle_side=CastleSide.King))
|
||||
|
||||
if CastleSide.Queen in castling_rights:
|
||||
clear = True
|
||||
for dx in range(1, 3):
|
||||
x = self.pos.x - dx
|
||||
y = self.pos.y
|
||||
|
||||
if board.piece_at(x, y) is not None:
|
||||
clear = False
|
||||
break
|
||||
|
||||
move = self._move_for_position(board, x, y)
|
||||
board_after_move = board.make_move(move)
|
||||
if board_after_move.is_check_for(self.colour):
|
||||
clear = False
|
||||
break
|
||||
|
||||
if clear:
|
||||
ret.append(Move(self, Position(2, self.pos.y), castle_side=CastleSide.Queen))
|
||||
|
||||
return ret
|
||||
|
||||
|
||||
|
@ -1,5 +1,23 @@
|
||||
from .piece import Piece
|
||||
|
||||
class Knight(Piece):
|
||||
pass
|
||||
def letter(self):
|
||||
return "n"
|
||||
|
||||
def legal_moves(self, board: "Board", / , looking_for_check = False) -> list["Move"]:
|
||||
ret = []
|
||||
for dx, dy in [
|
||||
(+2, +1), (+1, +2), # north east
|
||||
(+2, -1), (+1, -2), # south east
|
||||
(-2, -1), (-1, -2), # south west
|
||||
(-2, +1), (-1, +2), # north west
|
||||
]:
|
||||
move = self._move_for_position(board, self.pos.x + dx, self.pos.y + dy)
|
||||
if move is not None:
|
||||
ret.append(move)
|
||||
|
||||
if not looking_for_check and board.is_check_for(self.colour):
|
||||
return self.keep_only_blocking(ret, board)
|
||||
|
||||
return ret
|
||||
|
||||
|
@ -1,31 +1,55 @@
|
||||
from logic.move import Move
|
||||
from logic.pieces.piece import Colour, Piece
|
||||
from logic.position import Position
|
||||
from logic.pieces.piece import Piece
|
||||
|
||||
class Pawn(Piece):
|
||||
def legal_moves(self, board) -> list[Position]:
|
||||
def legal_moves(self, board, / , looking_for_check = False) -> list[Move]:
|
||||
ret = []
|
||||
|
||||
# can we capture to the left?
|
||||
if self.pos.x > 0 and (
|
||||
(self.colour == self.WHITE and (capturable_piece := board.piece_at(self.pos.x - 1, self.pos.y + 1)))
|
||||
(self.colour == Colour.WHITE and (capturable_piece := board.piece_at(self.pos.x - 1, self.pos.y + 1)))
|
||||
or
|
||||
(self.colour == self.BLACK and (capturable_piece := board.piece_at(self.pos.x - 1, self.pos.y - 1)))
|
||||
(self.colour == Colour.BLACK and (capturable_piece := board.piece_at(self.pos.x - 1, self.pos.y - 1)))
|
||||
):
|
||||
if capturable_piece.colour != self.colour:
|
||||
ret.append(capturable_piece.pos)
|
||||
ret.append(Move(self, capturable_piece.pos, is_capturing = True))
|
||||
|
||||
# can we capture to the right?
|
||||
if self.pos.x < 7 and (
|
||||
(self.colour == self.WHITE and (capturable_piece := board.piece_at(self.pos.x + 1, self.pos.y + 1)))
|
||||
(self.colour == Colour.WHITE and (capturable_piece := board.piece_at(self.pos.x + 1, self.pos.y + 1)))
|
||||
or
|
||||
(self.colour == self.BLACK and (capturable_piece := board.piece_at(self.pos.x + 1, self.pos.y - 1)))
|
||||
(self.colour == Colour.BLACK and (capturable_piece := board.piece_at(self.pos.x + 1, self.pos.y - 1)))
|
||||
):
|
||||
if capturable_piece.colour != self.colour:
|
||||
ret.append(capturable_piece.pos)
|
||||
ret.append(Move(self, capturable_piece.pos, is_capturing = True))
|
||||
|
||||
# -- Can we capture en passant?
|
||||
if board._en_passant_target is not None and \
|
||||
board._en_passant_target.pos.y == self.pos.y and (
|
||||
board._en_passant_target.pos.x == self.pos.x - 1
|
||||
or board._en_passant_target.pos.x == self.pos.x + 1
|
||||
):
|
||||
if board._en_passant_target.colour != self.colour:
|
||||
old_pos = board._en_passant_target.pos
|
||||
new_pos = Position(old_pos.x, old_pos.y + (1 if self.colour == Colour.WHITE else -1))
|
||||
ret.append(Move(self, new_pos, is_capturing = True, en_passant = True))
|
||||
|
||||
# -- Normal moves
|
||||
if self.colour == Colour.WHITE:
|
||||
for dy in range(1, 3 if self.pos.y == 1 else 2):
|
||||
if self.pos.y + dy > 7 or board.piece_at(self.pos.x, self.pos.y + dy):
|
||||
break
|
||||
ret.append(Position(self.pos.x, self.pos.y + dy))
|
||||
pos = Position(self.pos.x, self.pos.y + dy)
|
||||
ret.append(Move(self, pos, becomes_en_passant_target=dy==2))
|
||||
else:
|
||||
for dy in range(1, 3 if self.pos.y == 6 else 2):
|
||||
if self.pos.y - dy < 0 or board.piece_at(self.pos.x, self.pos.y - dy):
|
||||
break
|
||||
pos = Position(self.pos.x, self.pos.y - dy)
|
||||
ret.append(Move(self, pos, becomes_en_passant_target=dy==2))
|
||||
|
||||
if not looking_for_check and board.is_check_for(self.colour):
|
||||
return self.keep_only_blocking(ret, board)
|
||||
|
||||
return ret
|
||||
|
@ -1,17 +1,65 @@
|
||||
from logic.move import Move
|
||||
from logic.position import Position
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class Colour(Enum):
|
||||
WHITE = "white"
|
||||
BLACK = "black"
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.value
|
||||
|
||||
class Piece:
|
||||
WHITE = 0
|
||||
BLACK = 1
|
||||
|
||||
def __init__(self, pos, colour) -> None:
|
||||
def __init__(self, pos: Position, colour: Colour) -> None:
|
||||
self.pos = pos
|
||||
assert colour == self.WHITE or colour == self.BLACK, "The colour of the piece must be either Piece.WHITE or Piece.BLACK"
|
||||
assert colour == Colour.WHITE or colour == Colour.BLACK, "The colour of the piece must be either Piece.WHITE or Piece.BLACK"
|
||||
self.colour = colour
|
||||
|
||||
def letter(self):
|
||||
return type(self).__name__[0].lower()
|
||||
|
||||
def keep_only_blocking(self, candidates: list[Move], board: "Board") -> list[Move]:
|
||||
ret = []
|
||||
for move in candidates:
|
||||
board_after_move = board.make_move(move)
|
||||
if not board_after_move.is_check_for(self.colour):
|
||||
ret.append(move)
|
||||
return ret
|
||||
|
||||
def _look_direction(self, board: "Board", mult_dx: int, mult_dy: int):
|
||||
ret = []
|
||||
for d in range(1, 8):
|
||||
dx = mult_dx * d
|
||||
dy = mult_dy * d
|
||||
|
||||
move = self._move_for_position(board, self.pos.x + dx, self.pos.y + dy)
|
||||
if move is None:
|
||||
break
|
||||
ret.append(move)
|
||||
if move.is_capturing:
|
||||
break
|
||||
|
||||
return ret
|
||||
|
||||
def _move_for_position(self, board: "Board", x: int, y: int) -> Move | None:
|
||||
if not Position.is_within_bounds(x, y):
|
||||
return None
|
||||
piece = board.piece_at(x, y)
|
||||
|
||||
if piece is None:
|
||||
return Move(self, Position(x, y))
|
||||
|
||||
if piece.colour != self.colour:
|
||||
return Move(self, Position(x, y), is_capturing=True)
|
||||
return None
|
||||
|
||||
def position(self) -> Position:
|
||||
return self.pos
|
||||
|
||||
def legal_moves(self, board) -> list[Position]:
|
||||
def move_to(self, pos: Position) -> "Piece":
|
||||
ret = type(self)(pos, self.colour)
|
||||
return ret
|
||||
|
||||
def legal_moves(self, board: "Board", / , looking_for_check = False) -> list["Move"]:
|
||||
raise NotImplementedError(f"Can't say what the legal moves are for {type(self).__name__}, the method hasn't been implemented yet")
|
||||
|
@ -1,5 +1,35 @@
|
||||
from logic.move import Move
|
||||
from .piece import Piece
|
||||
|
||||
class Queen(Piece):
|
||||
pass
|
||||
def legal_moves(self, board: "Board", / , looking_for_check = False) -> list[Move]:
|
||||
ret = []
|
||||
|
||||
# looking north east
|
||||
ret.extend(self._look_direction(board, 1, 1))
|
||||
|
||||
# looking south east
|
||||
ret.extend(self._look_direction(board, 1, -1))
|
||||
|
||||
# looking south west
|
||||
ret.extend(self._look_direction(board, -1, -1))
|
||||
|
||||
# looking north west
|
||||
ret.extend(self._look_direction(board, -1, 1))
|
||||
|
||||
# looking east
|
||||
ret.extend(self._look_direction(board, 1, 0))
|
||||
|
||||
# looking south
|
||||
ret.extend(self._look_direction(board, 0, -1))
|
||||
|
||||
# looking west
|
||||
ret.extend(self._look_direction(board, -1, 0))
|
||||
|
||||
# looking north
|
||||
ret.extend(self._look_direction(board, 0, 1))
|
||||
|
||||
if not looking_for_check and board.is_check_for(self.colour):
|
||||
return self.keep_only_blocking(ret, board)
|
||||
|
||||
return ret
|
||||
|
@ -1,5 +1,23 @@
|
||||
from logic.move import Move
|
||||
from .piece import Piece
|
||||
|
||||
class Rook(Piece):
|
||||
pass
|
||||
def legal_moves(self, board: "Board", / , looking_for_check = False) -> list[Move]:
|
||||
ret = []
|
||||
|
||||
# looking east
|
||||
ret.extend(self._look_direction(board, 1, 0))
|
||||
|
||||
# looking south
|
||||
ret.extend(self._look_direction(board, 0, -1))
|
||||
|
||||
# looking west
|
||||
ret.extend(self._look_direction(board, -1, 0))
|
||||
|
||||
# looking north
|
||||
ret.extend(self._look_direction(board, 0, 1))
|
||||
|
||||
if not looking_for_check and board.is_check_for(self.colour):
|
||||
return self.keep_only_blocking(ret, board)
|
||||
|
||||
return ret
|
||||
|
@ -1,4 +1,7 @@
|
||||
class Position:
|
||||
_RANKS = range(1, 9)
|
||||
_FILES = "abcdefgh"
|
||||
|
||||
_MIN_POS = 0
|
||||
_MAX_POS = 7
|
||||
|
||||
@ -9,6 +12,14 @@ class Position:
|
||||
self.x = x
|
||||
self.y = y
|
||||
|
||||
@staticmethod
|
||||
def is_within_bounds(x: int, y: int) -> bool:
|
||||
return x >= Position._MIN_POS and x <= Position._MAX_POS \
|
||||
and y >= Position._MIN_POS and y <= Position._MAX_POS
|
||||
|
||||
def to_algebraic(self) -> str:
|
||||
return f"{Position._FILES[self.x]}{Position._RANKS[self.y]}"
|
||||
|
||||
def __eq__(self, value: object, /) -> bool:
|
||||
if type(value) != type(self):
|
||||
return False
|
||||
@ -18,8 +29,7 @@ class Position:
|
||||
return hash((self.x, self.y))
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.x, self.y}"
|
||||
return f"{Position._FILES[self.x]}{Position._RANKS[self.y]}"
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return str(self)
|
||||
|
||||
|
11
src/main.py
@ -1,9 +1,14 @@
|
||||
from logic.board import create_board
|
||||
from controller.controller import Controller
|
||||
from logic.board import Board
|
||||
from view.gui import GUI
|
||||
from view.tui import TUI
|
||||
|
||||
if __name__ == "__main__":
|
||||
board = create_board()
|
||||
initial_board_position = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
|
||||
board = Board.setup_FEN_position(initial_board_position)
|
||||
|
||||
view = TUI(board)
|
||||
view = GUI()
|
||||
|
||||
controller = Controller(board, view)
|
||||
|
||||
view.show()
|
||||
|
155
src/view/gui.py
Normal file
@ -0,0 +1,155 @@
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox
|
||||
from typing import Type
|
||||
from PIL import ImageTk, Image
|
||||
import os
|
||||
|
||||
from logic.board import Board
|
||||
from logic.move import Move
|
||||
from logic.pieces.bishop import Bishop
|
||||
from logic.pieces.king import King
|
||||
from logic.pieces.knight import Knight
|
||||
from logic.pieces.pawn import Pawn
|
||||
from logic.pieces.piece import Colour, Piece
|
||||
from logic.pieces.queen import Queen
|
||||
from logic.pieces.rook import Rook
|
||||
from logic.position import Position
|
||||
from view.view import View
|
||||
|
||||
class GUI(View):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
|
||||
self.root = tk.Tk()
|
||||
self.root.title("Chess Board")
|
||||
|
||||
self.tile_size = 80
|
||||
board_size = self.tile_size * 8
|
||||
|
||||
self.canvas = tk.Canvas(self.root, width=board_size, height=board_size)
|
||||
self.canvas.pack()
|
||||
|
||||
self.canvas.bind("<Button-1>", self._on_canvas_click)
|
||||
|
||||
self._piece_images = self._load_piece_images("res/")
|
||||
|
||||
def _piece_svg(self, root: str, piece: Type[Piece], colour: Colour) -> ImageTk.PhotoImage:
|
||||
piece_name = piece.__name__.lower()
|
||||
|
||||
path = os.path.join(root, f"{"white" if colour == Colour.WHITE else "black"}-{piece_name}.png")
|
||||
img = Image.open(path)
|
||||
|
||||
if img.mode == "LA":
|
||||
img = img.convert(mode="RGBA")
|
||||
img.save(path)
|
||||
|
||||
return ImageTk.PhotoImage(img)
|
||||
|
||||
def _load_piece_images(self, root: str) -> dict[Type[Piece], dict[Colour, ImageTk.PhotoImage]]:
|
||||
ret = {}
|
||||
for piece in [Pawn, Rook, Knight, Bishop, Queen, King]:
|
||||
if piece not in ret:
|
||||
ret[piece] = {}
|
||||
ret[piece][Colour.WHITE] = self._piece_svg(root, piece, Colour.WHITE)
|
||||
ret[piece][Colour.BLACK] = self._piece_svg(root, piece, Colour.BLACK)
|
||||
|
||||
return ret
|
||||
|
||||
def _on_canvas_click(self, event):
|
||||
x, y = event.x // self.tile_size, event.y // self.tile_size
|
||||
y = 7 - y
|
||||
|
||||
self._controller.on_tile_selected(x, y)
|
||||
|
||||
def notify_checkmate(self, colour: Colour) -> None:
|
||||
messagebox.showinfo("Checkmate", f"{colour} is currently checkmated")
|
||||
|
||||
def notify_stalemate(self, colour: Colour) -> None:
|
||||
messagebox.showinfo("Stalemate", f"{colour} is currently stalemated")
|
||||
|
||||
|
||||
def update_board(self, board: Board, selected_piece: Piece, legal_moves: list[Move]) -> None:
|
||||
self.canvas.delete("all")
|
||||
self._draw_chess_board(board, selected_piece, legal_moves)
|
||||
|
||||
|
||||
def _draw_chess_board(self, board: Board, selected_piece = None, legal_moves = []):
|
||||
colours = ["#EDD6B0", "#B88762"] # Light and dark squares
|
||||
alt_colours = ["#F6EB72", "#DCC34B"] # Light and dark squares, when selected
|
||||
circle_colours = ["#CCB897", "#9E7454"] # circles to show legal moves
|
||||
|
||||
for y in range(8):
|
||||
for x in range(8):
|
||||
colour = colours[(x + y) % 2]
|
||||
pos = Position(x, 7-y)
|
||||
if selected_piece is not None and pos == selected_piece.pos:
|
||||
colour = alt_colours[(x + y) % 2]
|
||||
|
||||
self.canvas.create_rectangle(
|
||||
x * self.tile_size,
|
||||
y * self.tile_size,
|
||||
(x + 1) * self.tile_size,
|
||||
(y + 1) * self.tile_size,
|
||||
fill=colour,
|
||||
outline=colour,
|
||||
)
|
||||
|
||||
if selected_piece is not None:
|
||||
possible_positions = [move.pos for move in legal_moves]
|
||||
if pos in possible_positions:
|
||||
colour = circle_colours[(x + y) % 2]
|
||||
move = [move for move in legal_moves if move.pos == pos][0]
|
||||
if move.is_capturing:
|
||||
radius = .40 * self.tile_size
|
||||
self.canvas.create_oval(
|
||||
(x + .5) * self.tile_size - radius,
|
||||
(y + .5) * self.tile_size - radius,
|
||||
(x + .5) * self.tile_size + radius,
|
||||
(y + .5) * self.tile_size + radius,
|
||||
fill="",
|
||||
outline=colour,
|
||||
width=.075 * self.tile_size,
|
||||
)
|
||||
else:
|
||||
radius = .15 * self.tile_size
|
||||
self.canvas.create_oval(
|
||||
(x + .5) * self.tile_size - radius,
|
||||
(y + .5) * self.tile_size - radius,
|
||||
(x + .5) * self.tile_size + radius,
|
||||
(y + .5) * self.tile_size + radius,
|
||||
fill=colour,
|
||||
outline=colour,
|
||||
)
|
||||
|
||||
piece = board.piece_at(x, 7-y)
|
||||
|
||||
if piece:
|
||||
self.canvas.create_image(
|
||||
(x + 0.5) * self.tile_size,
|
||||
(y + 0.9) * self.tile_size,
|
||||
image=self._piece_images[type(piece)][piece.colour],
|
||||
anchor=tk.S,
|
||||
)
|
||||
|
||||
# Cell annotations
|
||||
text_colour = colours[(x + y + 1) % 2] # the other colour
|
||||
|
||||
if x == 0: # numbers in the top left of the first column
|
||||
self.canvas.create_text(
|
||||
(x + .15) * self.tile_size,
|
||||
(y + .15) * self.tile_size,
|
||||
text=8-y,
|
||||
fill=text_colour,
|
||||
font=("Arial", 12, "bold")
|
||||
)
|
||||
if y == 7: # numbers in the top left of the first column
|
||||
self.canvas.create_text(
|
||||
(x + .85) * self.tile_size,
|
||||
(y + .85) * self.tile_size,
|
||||
text="abcdefgh"[x],
|
||||
fill=text_colour,
|
||||
font=("Arial", 12, "bold")
|
||||
)
|
||||
|
||||
def show(self) -> None:
|
||||
self.root.mainloop()
|
@ -1,10 +1,24 @@
|
||||
from logic.board import Board
|
||||
from logic.move import Move
|
||||
from logic.pieces.piece import Colour, Piece
|
||||
|
||||
|
||||
class View:
|
||||
def __init__(self, board: Board) -> None:
|
||||
self.board: Board = board
|
||||
def __init__(self) -> None:
|
||||
self._controller: "Controller" = None
|
||||
|
||||
def show(self) -> None:
|
||||
raise NotImplementedError(f"Can't show the board, the show() method of {type(self)} is not implemented")
|
||||
|
||||
def update_board(self, board: Board, selected_piece: Piece, legal_moves: list[Move]) -> None:
|
||||
raise NotImplementedError(f"Can't update the board, the update_board() method of {type(self)} is not implemented")
|
||||
|
||||
def notify_checkmate(self, colour: Colour) -> None:
|
||||
raise NotImplementedError(f"Can't notify of the checkmate, the notify_checkmate() method of {type(self)} is not implemented")
|
||||
|
||||
def notify_stalemate(self, colour: Colour) -> None:
|
||||
raise NotImplementedError(f"Can't notify of the stalemate, the notify_stalemate() method of {type(self)} is not implemented")
|
||||
|
||||
def set_controller(self, controller: "Controller") -> None:
|
||||
self._controller = controller
|
||||
|
||||
|