-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGrid.py
121 lines (81 loc) · 2.89 KB
/
Grid.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
from copy import deepcopy
import numpy as np
class Grid():
def __init__(self, N = 7) -> None:
self.dim = N
self.map = np.zeros((N,N)) # empty board
def getAvailableCells(self):
"""
Returns all available cells in the grid in the form of [(x_0,y_0), ..., (x_n, y_n)]
"""
return [(x,y) for x,y in np.argwhere(self.map == 0)]
def getMap(self):
return self.map
def setCellValue(self, pos: tuple, val):
self.map[pos] = val
def getCellValue(self, pos: tuple):
return self.map[pos]
def clone(self):
"""
Makes a full copy of current grid
"""
grid_copy = Grid(self.dim)
grid_copy.map = deepcopy(self.map)
return grid_copy
def find(self, player_num : int):
"""Find a player given the player's number."""
assert(player_num in [1,2])
result = tuple(np.argwhere(self.map == player_num)[0])
return result
def get_neighbors(self, pos, only_available = False):
"""
Description
-----------
The function returns the neighboring cells of a certain cell in the board, given its x,y coordinates
Parameters
-----------
pos : position (x,y) whose neighbors are desired
only_available (bool) : if True, the function will return only available neighboring cells.
default = False
"""
x,y = pos
valid_range = lambda t: range(max(t-1, 0), min(t+2, self.dim))
# find all neighbors
neighbors = list({(a,b) for a in valid_range(x) for b in valid_range(y)} - {(x,y)})
# select only neighboring cells which aren't occupying by a player or trap
if only_available:
return [neighbor for neighbor in neighbors if self.map[neighbor] == 0]
return neighbors
def move(self, move, player):
"""
Description
-----------
Apply a move by specified player to the grid.
Parameters
-----------
move: coordinates of new position to which the player decides to move
player: the identifier of the player (1 for human, 2 for computer)
Returns
-------
the grid with the new configuration.
"""
old_pos = np.where(self.map == player)
self.map[old_pos] = 0
self.map[move] = player
return self
def trap(self, pos):
"""
Description
-----------
Apply a trap to specified loaction
Parameters
-----------
pos: a tuple (x,y) reprsenting the coordinates in which to place trap
Returns
-------
the grid with the new configuration.
"""
self.map[pos] = -1
return self
def print_grid(self):
print(self.map)