-
Notifications
You must be signed in to change notification settings - Fork 0
/
colorflood.py
293 lines (219 loc) · 9.86 KB
/
colorflood.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
from tkinter import *
from tkinter import messagebox
from threading import Thread
import time
from random import randint
from collections import Counter
from copy import deepcopy
#utility functions
def get_runnable(func):
return lambda : Thread(target=func).start()
def set_button_color(button, color):
button.config(bg=color)
def get_button_color(button):
return button.cget('bg')
def flatten(lists):
return [item for sublist in lists for item in sublist]
def get_neighbors(i, j, grid):
neighbors = []
if i-1 >= 0:
neighbors.append((i-1, j))
if i+1 < len(grid):
neighbors.append((i+1, j))
if j-1 >= 0:
neighbors.append((i, j-1))
if j+1 < len(grid[0]):
neighbors.append((i, j+1))
return neighbors
def get_call_all(funcs):
def f():
return [func() for func in funcs]
return f
class ColorFlood:
colors = ['white', 'red', 'blue', 'yellow', 'green']
def __init__(self, num_rows, num_cols):
self.reset_game(num_rows, num_cols)
def reset_game(self, num_rows, num_cols, nodes=None):
self.num_rows = num_rows
self.num_cols = num_cols
self.nodes = nodes
if self.nodes is None:
self.nodes = [[self.getRandomColor() for i in range(num_cols)] for j in range(num_rows)]
self.nodes_init = deepcopy(self.nodes)
self.counts = Counter(flatten(self.nodes))
self.num_tiles = num_cols * num_rows
self.turns = 0
self.game_finished = False
def getRandomColor(self):
return ColorFlood.colors[randint(0,len(ColorFlood.colors)-1)]
def get_captured_nodes(self):
color = self.nodes[0][0]
def dfs(i, j, visited):
visited.add((i,j))
toRet = []
if self.nodes[i][j] == color:
toRet.append((i,j))
for row,col in get_neighbors(i,j,self.nodes):
if not (row, col) in visited:
toRet.extend(dfs(row, col, visited))
return toRet
return dfs(0, 0, set([]))
def get_new_state(self, color):
new_nodes = self.nodes[:]
new_counts = dict(self.counts)
captured_nodes = self.get_captured_nodes()
new_counts[color] += len(captured_nodes)
new_counts[self.nodes[0][0]] -= len(captured_nodes)
for i,j in captured_nodes:
new_nodes[i][j] = color
return (new_nodes, new_counts)
def apply_move(self, color):
self.turns += 1
self.nodes, self.counts = self.get_new_state(color)
if self.counts[color] == self.num_tiles:
self.game_finished = True
return self.game_finished
class GameView:
def __init__(self, cellSize, game, rootView):
screenWidth = root.winfo_screenwidth()
screenHeight = root.winfo_screenheight()
self.cellWidth = cellSize
self.cellHeight = round(self.cellWidth * screenHeight/screenWidth)
self.frame = Frame(rootView) #create a new frame, as a child of root
self.frame.pack() #make the frame visible
self.game = game
self.buttons = []
self.controls = []
self.players = None
self.all_buttons = []
self.draw_interface()
def addbutton(self, *args, **kwargs):
side = None
if 'side' in kwargs:
side = kwargs['side']
del kwargs['side']
b = Button(*args, **kwargs)
b.pack(side=side)
self.all_buttons.append(b)
return b
def draw_interface(self):
for i in range(self.game.num_rows):
f = Frame(self.frame)
f.pack()
self.buttons.append(list())
for j in range(self.game.num_cols):
button = Button(f, bg=game.nodes[i][j], width=self.cellWidth, height=self.cellHeight, state=DISABLED)
button.pack(side=LEFT)
self.buttons[i].append(button)
f = Frame(self.frame,pady=20)
f.pack()
for color in ColorFlood.colors:
self.addbutton(f, bg=color, width=self.cellWidth, height=self.cellHeight, activebackground=color, side=LEFT)
self.players = Frame(self.frame, padx=10, pady=10)
self.players.pack()
func = get_call_all([lambda : self.game.reset_game(self.game.num_rows, self.game.num_cols, self.game.nodes_init), self.refresh])
self.addbutton(self.frame, pady=10, text='Reset Game', command=func)
def refresh(self):
for i in range(game.num_rows):
for j in range(game.num_cols):
self.buttons[i][j].config(bg=game.nodes[i][j])
class GamePlayer:
def __init__(self, gameView, gameState):
self.gameView = gameView
self.gameState = gameState
def make_move(self, new_color):
game_finished = self.gameState.apply_move(new_color)
gameView.refresh()
if game_finished:
messagebox.showinfo('Congratulations', 'You won\nTurns taken = ' + str(game.turns))
class HumanPlayer(GamePlayer):
def __init__(self, gameView, gameState):
super(HumanPlayer, self).__init__(gameView, gameState)
for button in gameView.controls:
button.config(command=self.get_button_callback(button))
def get_button_callback(self, button):
return lambda : self.make_move(get_button_color(button))
class NonHumanPlayer(GamePlayer):
def __init__(self, gameView, gameState, string):
super(NonHumanPlayer, self).__init__(gameView, gameState)
gameView.addbutton(gameView.players, text=string, command=get_runnable(self.play), side=LEFT)
# rates colors according to the length of captured nodes. useful for various players
def get_color_score(self, color):
nodes, counts = deepcopy(self.gameState.nodes), deepcopy(self.gameState.counts) # copy old values
self.gameState.nodes, self.gameState.counts = self.gameState.get_new_state(color) # update
captured_nodes = self.gameState.get_captured_nodes()
self.gameState.nodes, self.gameState.counts = nodes, counts # reset old values
return len(captured_nodes)
def before_play(self):
for control in gameView.all_buttons:
control.config(state=DISABLED)
def after_play(self):
for control in gameView.all_buttons:
control.config(state=NORMAL)
def get_move(self):
pass
def play(self):
self.before_play()
while not self.gameState.game_finished:
self.make_move(self.get_move())
time.sleep(0.7)
self.after_play()
class GreedyPlayer(NonHumanPlayer):
def __init__(self, gameView, gameState):
super(GreedyPlayer, self).__init__(gameView, gameState, 'Try Greedy')
def get_moves(self):
moves = []
nodes, counts = deepcopy(self.gameState.nodes), deepcopy(self.gameState.counts)
while all(count < self.gameState.num_tiles for color,count in self.gameState.counts.items()):
color = self.get_move()
moves.append(color)
self.gameState.nodes, self.gameState.counts = self.gameState.get_new_state(color)
self.gameState.nodes, self.gameState.counts = nodes, counts
return moves[::-1]
def get_move(self):
score, color = max((self.get_color_score(color), color) for color in ColorFlood.colors)
return color
class OptimalPlayer(NonHumanPlayer):
def __init__(self, gameView, gameState, max_depth):
super(OptimalPlayer, self).__init__(gameView, gameState, 'Try Optimal Strategy')
self.moves = []
self.max_depth = max_depth
# performs dfs
def get_moves(self, num_moves, max_depth):
if any(count == self.gameState.num_tiles for color, count in self.gameState.counts.items()):
return (num_moves, [])
colors_on_board = len([color for color, count in self.gameState.counts.items() if count > 0])
if num_moves + colors_on_board > max_depth: # performed num_moves already and need atleast colors_on_board moves more
return (float('inf'), [])
else:
num_captured_ndoes = len(self.gameState.get_captured_nodes())
color_scores = ((self.get_color_score(color), color) for color in ColorFlood.colors)
nodes, counts = deepcopy(self.gameState.nodes), deepcopy(self.gameState.counts)
for score, color in sorted(color_scores, reverse=True):
if score > num_captured_ndoes: # otherwise we end up getting cycles
self.gameState.nodes, self.gameState.counts = self.gameState.get_new_state(color) # update state according to color
new_num_moves, moves = self.get_moves(num_moves + 1, max_depth) # recurse
self.gameState.nodes, self.gameState.counts = deepcopy(nodes), deepcopy(counts) # reset state
if new_num_moves < float('inf'): # found strategy
return (new_num_moves, moves + [color]) # moves stored in reverse order
return (float('inf'), []) # no strategy found
def get_move(self):
if not self.moves:
# perform iterative deepening
for i in range(1, self.max_depth + 1):
print('assuming there exists a strategy of ', i)
num_moves, self.moves = self.get_moves(0, i)
if self.moves:
break
else:
print('no such strategy exists:')
print('found optimal strategy')
return self.moves.pop()
root = Tk() #'root' gui element
game = ColorFlood(8, 8)
gameView = GameView(5, game, root)
player = HumanPlayer(gameView, game)
greedyPlayer = GreedyPlayer(gameView, game)
optimalPlayer = OptimalPlayer(gameView, game, len(greedyPlayer.get_moves()))
root.mainloop()
root.destroy()