forked from UTSAVS26/PyVerse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
board.py
98 lines (76 loc) · 3.34 KB
/
board.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
from piece import Piece ,King ,Knight ,Queen ,Rook ,Bishop ,Pawn
class Board:
def __init__(self):
#print("Board class constructor called")
self.board = self.create_board()
self.setup_pieces()
def create_board(self):
""" have to create a 8x8 matrix for the representation of chess_board """
chess_board = []
for _ in range(8):
chess_board.append([None] * 8)
return chess_board
def setup_pieces(self):
"""
our board should look like :-
R KN B Q KI B KN R
P P P P P P P P
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
P P P P P P P P
R KN B Q KI B KN R
Where R = Rook
KN = Knight
B = Bishop
Q = Queen
KI = King
P = Pawn
"""
""" set up pawn """
for col in range(8):
self.board[1][col] = Pawn('white')
self.board[6][col] = Pawn('black')
piece_order = [Rook ,Knight ,Bishop ,Queen ,King ,Bishop ,Knight ,Rook]
""" setting up black piece """
for col ,piece in enumerate(piece_order):
self.board[0][col] = piece('white')
""" setting up white piece """
for col ,piece in enumerate(piece_order):
self.board[7][col] = piece('black')
def move_pieces(self ,start_position:tuple[int ,int] ,end_position:tuple[int ,int]) -> bool:
row_initial ,col_initial = start_position[0],start_position[1]
row_final ,col_final = end_position[0],end_position[1]
piece = self.board[row_initial][col_initial]
if piece is None:
print("No piece at the given position")
return False
if piece.is_valid_move(start_position ,end_position ,self.board):
target_piece = self.board[row_final][col_final]
if target_piece is not None:
if target_piece.color != piece.color:
print(f"Capturing {target_piece.symbol()} at {end_position}")
else:
print("Invalid move: Cannot capture your own piece")
return False
# Move the piece to the new location
self.board[row_final][col_final] = piece
self.board[row_initial][col_initial] = None
print(f"Moved {piece.symbol()} to {end_position}")
return True
else:
print("Invalid move")
return False
def print_board(self):
print(" ", end='') # Initial space before column labels
for col in range(8):
print(f" {col} ", end='')
print() # Newline after column labels
# Printing the board with row numbers
for row_idx, row in enumerate(self.board):
print(f"{row_idx} ", end='') # Print row numbers with space
for piece in row:
# Print the symbol for each piece or '.' if the spot is empty, each padded to 3 spaces
print(f"{piece.symbol() if piece else '.'} ", end='')
print() # Newline after each row