MCPcopy Index your code
hub / github.com/ndleah/python-mini-project / Board

Class Board

Othello-Reversi-Game/Board.py:3–213  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1import numpy as np
2
3class Board:
4 WHITE = -1
5 BLACK = 1
6 EMPTY = 0
7
8 def __init__(self) -> None:
9 '''Initiliaze the Othello game board with a 8x8 numpy matrix'''
10 self.board = np.array([0]*8, dtype = np.int8) # initiliasing 1D array with the first row of 8 zeroes
11 self.board = self.board[np.newaxis, : ] # expanding 1D array to 2D array
12 for _ in range(3): # increasing rows till 8
13 self.board = np.concatenate((self.board, self.board), axis = 0)
14
15 # initiliasing the centre squares
16 self.board[3, 3] = self.board[4,4] = Board.WHITE
17 self.board[3, 4] = self.board[4,3] = Board.BLACK
18
19 self.black_disc_count = 2
20 self.white_disc_count = 2
21
22 def all_legal_moves(self, PLAYER: int) -> set:
23 '''Return all legal moves for the player'''
24 OPPONENT = Board.WHITE if PLAYER == Board.BLACK else Board.BLACK
25
26 all_legal_moves = set()
27 for row in range(8):
28 for col in range(8):
29 if self.board[row, col] == PLAYER:
30 all_legal_moves.update(self.legal_moves(row, col))
31
32 return all_legal_moves
33
34 def legal_moves(self, row: int, col: int) -> list:
35 '''Return all legal moves for the cell at the given position'''
36 PLAYER = self.board[row, col]
37 OPPONENT = Board.WHITE if PLAYER == Board.BLACK else Board.BLACK
38 legal_moves = list()
39
40 # check for legal moves along the row of the cell
41 if col >= 2:
42 i = col - 1
43 while i >= 0 and self.board[row, i] == OPPONENT:
44 i -= 1
45 if (i != col - 1 and i >= 0) and self.board[row, i] == Board.EMPTY:
46 legal_moves.append((row, i))
47
48 if col <= 5:
49 i = col + 1
50 while i < 8 and self.board[row, i] == OPPONENT:
51 i += 1
52 if (i != col + 1 and i < 8) and self.board[row, i] == Board.EMPTY:
53 legal_moves.append((row, i))
54
55 # check for legal moves along the column of the cell
56 if row >= 2:
57 i = row - 1
58 while i >= 0 and self.board[i, col] == OPPONENT:
59 i -= 1
60 if (i != row - 1 and i >= 0) and self.board[i, col] == Board.EMPTY:

Callers 1

main.pyFile · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected