This repository was archived by the owner on Jun 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathvisualizer.py
334 lines (319 loc) · 14.8 KB
/
visualizer.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import argparse
import sys
from os import environ
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'
import pygame
from enum import Enum, auto
import solutions
# Game settings
SIZE = WIDTH, HEIGHT = 800, 800
TITLE = 'Visualizer'
ROWS = 20
COLS = 20
BORDER = 1
PADDING = 20
w = WIDTH / COLS
h = HEIGHT / ROWS
# Other constants
WHITE = pygame.Color(255, 255, 255)
GREY = pygame.Color(128, 128, 128)
BLACK = pygame.Color(0, 0, 0)
RED = pygame.Color(255, 0, 0)
BLUE = pygame.Color(0, 0, 255)
GREEN = pygame.Color(0, 255, 0)
PURPLE = pygame.Color(128, 0, 128)
GOLD = pygame.Color(255, 215, 0)
GOLDENROD = pygame.Color(218, 165, 32)
# All possible gamestates
class GameState(Enum):
INPUT = auto()
DEMO = auto()
TEST = auto()
END = auto()
# A single vertex in the graph
class Node:
# All possible node types
class NodeType(Enum):
UNBLOCKED = auto()
BLOCKED = auto()
START = auto()
GOAL = auto()
# Create a new node
def __init__(self, x, y) -> None:
# Position on screen
self.x = x
self.y = y
# Neighboring vertices
self.neighbors = []
# Type of node
self.type = self.NodeType.UNBLOCKED
# Draw the node on the screen
def draw(self, screen):
color = None
if self.type == self.NodeType.UNBLOCKED:
color = WHITE
elif self.type == self.NodeType.BLOCKED:
color = BLACK
elif self.type == self.NodeType.START:
color = RED
elif self.type == self.NodeType.GOAL:
color = BLUE
pygame.draw.rect(screen, color, (self.x * w + BORDER, self.y * h + BORDER, w - BORDER, h - BORDER))
pygame.display.update()
# Connect the node to each of its neighbors
def addNeighbors(self, graph):
x = self.x
y = self.y
if x < COLS-1 and graph[self.x + 1][y].type != Node.NodeType.BLOCKED:
self.neighbors.append(graph[self.x + 1][y])
if x > 0 and graph[self.x - 1][y].type != Node.NodeType.BLOCKED:
self.neighbors.append(graph[self.x - 1][y])
if y < ROWS-1 and graph[self.x][y + 1].type != Node.NodeType.BLOCKED:
self.neighbors.append(graph[self.x][y + 1])
if y > 0 and graph[self.x][y - 1].type != Node.NodeType.BLOCKED:
self.neighbors.append(graph[self.x][y - 1])
# Interact with selected node
def handleMouseClick(x, type, graph, screen):
t = x[0]
w = x[1]
g1 = t // (WIDTH // COLS)
g2 = w // (HEIGHT // ROWS)
node = graph[g1][g2]
if node.type != Node.NodeType.START and node.type != Node.NodeType.GOAL:
node.type = type
node.draw(screen)
# Write a message on the screen
def showMessage(text, font, screen):
message = font.render(text, True, BLACK)
message_rect = message.get_rect(center=(WIDTH / 2, HEIGHT / 2))
pygame.draw.rect(screen, WHITE, message_rect.inflate(PADDING, PADDING))
pygame.draw.rect(screen, GREY, message_rect.inflate(PADDING, PADDING), BORDER)
screen.blit(message, message_rect)
pygame.display.update()
# Depth-first search that recursively explores all reachable nodes
# Adapted from an online article by Educative, Inc.
# https://www.educative.io/edpresso/how-to-implement-depth-first-search-in-python
# Additional references taken from COS 226: Algorithms and Data Structures
# https://www.cs.princeton.edu/courses/archive/fall13/cos226/lectures/41UndirectedGraphs.pdf
def dfs_reference(node, explored, screen):
if pygame.event.get(pygame.QUIT):
pygame.quit()
sys.exit()
if node not in explored:
if node.type == Node.NodeType.UNBLOCKED:
pygame.draw.rect(screen, GOLD, (node.x * w + BORDER, node.y * h + BORDER, w - BORDER, h - BORDER))
pygame.display.update()
explored.append(node)
for neighbor in node.neighbors:
if neighbor.type == Node.NodeType.UNBLOCKED and neighbor not in explored:
pygame.draw.rect(screen, GOLDENROD, (neighbor.x * w + BORDER, neighbor.y * h + BORDER, w - BORDER, h - BORDER))
pygame.display.update()
explored = dfs_reference(neighbor, explored, screen)
return explored
# Breadth-first search to find the shortest path between two nodes
# Adapted from a blog post by Valerio Valardo on 03/18/2017
# https://pythoninwonderland.wordpress.com/2017/03/18/how-to-implement-breadth-first-search-in-python/
# Additional references taken from COS 226: Algorithms and Data Structures
# https://www.cs.princeton.edu/courses/archive/fall13/cos226/lectures/41UndirectedGraphs.pdf
def bfs_reference(start, goal, screen):
explored = []
queue = [[start]]
if start == goal:
raise RuntimeError('Start and Goal nodes cannot be the same!')
while queue:
if pygame.event.get(pygame.QUIT):
pygame.quit()
sys.exit()
path = queue.pop(0)
node = path[-1]
if node not in explored:
if node.type == Node.NodeType.UNBLOCKED:
pygame.draw.rect(screen, GOLD, (node.x * w + BORDER, node.y * h + BORDER, w - BORDER, h - BORDER))
pygame.display.update()
for neighbor in node.neighbors:
new_path = list(path)
new_path.append(neighbor)
queue.append(new_path)
if neighbor == goal:
return new_path
if neighbor.type == Node.NodeType.UNBLOCKED and neighbor not in explored:
pygame.draw.rect(screen, GOLDENROD, (neighbor.x * w + BORDER, neighbor.y * h + BORDER, w - BORDER, h - BORDER))
pygame.display.update()
explored.append(node)
raise RuntimeError('No path exists between start and goal nodes!')
def main():
# Set and parse argumennts
parser = argparse.ArgumentParser(description='Visualize graph traversal')
parser.add_argument('algorithm', help="the algorithm to use", choices=['bfs', 'dfs'])
parser.add_argument('-t', '--test', help='test the selected algorithm', default=False, action='store_true')
args = parser.parse_args()
# Initialize game
pygame.init()
screen = pygame.display.set_mode(SIZE)
pygame.display.set_caption(TITLE)
# Initialize font for messages
font = pygame.font.SysFont(['systemfont'], 36)
# Create graph
screen.fill(GREY)
graph = [[0 for c in range(COLS)] for r in range(ROWS)]
for i in range(COLS):
for j in range(ROWS):
graph[i][j] = Node(i, j)
graph[i][j].draw(screen)
# Set start and end nodes
start = graph[0][COLS - 1]
start.type = Node.NodeType.START
start.draw(screen)
goal = None
if args.algorithm == 'bfs':
goal = graph[ROWS - 1][0]
goal.type = Node.NodeType.GOAL
goal.draw(screen)
# Main game loop
reference_path = None
reference_explored = None
current_state = GameState.INPUT
while True:
events = pygame.event.get()
# Handle current game state
if current_state == GameState.INPUT: # Allow user input to edit playfield
for event in events:
# Check if user quits the game
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Set type of selected node
elif (pygame.mouse.get_pressed()[2] or (pygame.key.get_mods() &
pygame.KMOD_CTRL and pygame.mouse.get_pressed()[0])):
mousePosition = pygame.mouse.get_pos()
handleMouseClick(mousePosition, Node.NodeType.UNBLOCKED, graph, screen)
elif pygame.mouse.get_pressed()[0]:
mousePosition = pygame.mouse.get_pos()
handleMouseClick(mousePosition, Node.NodeType.BLOCKED, graph, screen)
# End user input period
elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
# Set neighbors of each node
for i in range(COLS):
for j in range(ROWS):
graph[i][j].addNeighbors(graph)
current_state = GameState.DEMO
elif current_state == GameState.DEMO: # Visualize graph traversal
for event in events:
# Check if user quits the game
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
else:
# Select reference algorithm to use
if (args.algorithm == 'dfs'):
reference_explored = dfs_reference(start, [], screen)
elif (args.algorithm == 'bfs'):
# Test if no path exists
try:
reference_path = bfs_reference(start, goal, screen)
except RuntimeError as e:
showMessage(str(e), font, screen)
current_state = GameState.END
continue
for node in reference_path:
if node.type == Node.NodeType.UNBLOCKED:
pygame.draw.rect(screen, GREEN, (node.x * w + BORDER, node.y * h + BORDER, w - BORDER, h - BORDER))
pygame.display.update()
if (args.test):
current_state = GameState.TEST
else:
current_state = GameState.END
elif current_state == GameState.TEST: # Test student solution
for event in events:
# Check if user quits the game
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
# Select student algorithm to use
if (args.algorithm == 'dfs'):
try:
solution_explored = solutions.dfs(start, [])
# Test for incorrect return type
if not all(isinstance(node, Node) for node in solution_explored):
raise TypeError
except AttributeError:
showMessage('Missing solution for ' + args.algorithm + '!', font, screen)
current_state = GameState.END
continue
except TypeError:
showMessage('Returned list type is incorrect!', font, screen)
current_state = GameState.END
continue
# Test student solution
try:
# Test for incorrect list length
if len(solution_explored) < len(reference_explored):
raise Exception('Student list shorter than expected!')
elif len(solution_explored) > len(reference_explored):
raise Exception('Student list longer than expected!')
# Test all unique reachable nodes found
if len(solution_explored) != len(set(solution_explored)):
raise Exception('Duplicate nodes found!')
for solution_node in solution_explored:
# Check if user quits the game
if pygame.event.get(pygame.QUIT):
pygame.quit()
sys.exit()
if solution_node.type == Node.NodeType.UNBLOCKED:
pygame.draw.rect(screen, PURPLE, (solution_node.x * w + BORDER, solution_node.y * h + BORDER, w - BORDER, h - BORDER))
pygame.display.update()
except Exception as e:
showMessage(str(e), font, screen)
else:
showMessage('All tests passed!', font, screen)
finally:
current_state = GameState.END
elif (args.algorithm == 'bfs'):
# Run student solution
try:
solution_path = solutions.bfs(start, goal)
# Test for incorrect return type
if not all(isinstance(node, Node) for node in solution_path):
raise TypeError
except AttributeError:
showMessage('Missing solution for ' + args.algorithm + '!', font, screen)
current_state = GameState.END
continue
except TypeError:
showMessage('Returned path type is incorrect!', font, screen)
current_state = GameState.END
continue
# Test student solution
try:
# Test for incorrect path length
if len(solution_path) < len(reference_path):
raise Exception('Student path shorter than expected!')
elif len(solution_path) > len(reference_path):
raise Exception('Student path longer than expected!')
for reference_node, solution_node in zip(reference_path, solution_path):
# Test for incorrect node in student path
if reference_node != solution_node:
raise Exception('Incorrect node in path!')
if solution_node.type == Node.NodeType.UNBLOCKED:
pygame.draw.rect(screen, PURPLE, (solution_node.x * w + BORDER, solution_node.y * h + BORDER, w - BORDER, h - BORDER))
pygame.display.update()
except Exception as e:
showMessage(str(e), font, screen)
else:
showMessage('All tests passed!', font, screen)
finally:
current_state = GameState.END
elif current_state == GameState.END: # End the game
for event in events:
# Check if user quits the game
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
pygame.quit()
sys.exit()
else:
pass
if __name__ == '__main__':
main()