MCPcopy Create free account
hub / github.com/Mrinank-Bhowmick/python-beginner-projects / Board

Class Board

projects/Othello/src/utils/board.py:4–194  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

2
3
4class Board:
5 WHITE = -1
6 BLACK = 1
7 EMPTY = 0
8
9 DIRECTIONS = (
10 (1, 0), # right
11 (-1, 0), # left
12 (0, 1), # down
13 (-1, 1), # downwards left
14 (1, 1), # downwards right
15 (0, -1), # up
16 (-1, -1), # upwards left
17 (1, -1), # upwards right
18 )
19
20 def __init__(self) -> None:
21 """Initiliaze the Othello game board with a 8x8 numpy matrix"""
22 self.board = np.array(
23 [0] * 8, dtype=np.int8
24 ) # initiliasing 1D array with the first row of 8 zeroes
25 self.board = self.board[np.newaxis, :] # expanding 1D array to 2D array
26 for _ in range(3): # increasing rows till 8
27 self.board = np.concatenate((self.board, self.board), axis=0)
28
29 # initiliasing the centre squares
30 self.board[3, 3] = self.board[4, 4] = Board.WHITE
31 self.board[3, 4] = self.board[4, 3] = Board.BLACK
32
33 self.black_disc_count = 2
34 self.white_disc_count = 2
35
36 @staticmethod
37 def checkCoordRange(x: int, y: int) -> bool:
38 """Returns true if the given parameters represent an actual cell in a 8x8 matrix"""
39
40 return (x >= 0 and y >= 0) and (x < 8 and y < 8)
41
42 def all_legal_moves(self, PLAYER: int) -> set:
43 """Return all legal moves for the player"""
44
45 all_legal_moves = set()
46 for row in range(8):
47 for col in range(8):
48 if self.board[row, col] == PLAYER:
49 all_legal_moves.update(self.legal_moves(row, col))
50
51 return all_legal_moves
52
53 def legal_moves(self, r: int, c: int) -> list:
54 """Return all legal moves for the cell at the given position"""
55
56 PLAYER = self.board[r, c]
57 OPPONENT = PLAYER * -1
58
59 legal_moves = []
60 for dir in Board.DIRECTIONS:
61 rowDir, colDir = dir

Callers 1

__init__Method · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected