-
Notifications
You must be signed in to change notification settings - Fork 0
/
qt-pyfinder.py
761 lines (588 loc) · 20.9 KB
/
qt-pyfinder.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
import astar
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from enum import IntEnum, unique
import sys
@unique
class Colors(IntEnum):
"""List of colors used to render the map."""
BG_MAP = 1
BG_SURF = 2
CELL_GOAL = 3
CELL_NOPATH = 4
CELL_PATH = 5
CELL_START = 6
CELL_UNWALK = 7
CELL_WALK = 8
class QTilemap(QWidget):
"""A 2D map made of tiles using Qt for rendering and input handling."""
def __init__(self, parent = None):
super(QTilemap, self).__init__(parent)
"""
Parameters
----------
parent : QWidget
optional parent widget
"""
self.map = None
self.mapRows = 0
self.mapCols = 0
self.mapW = 0
self.mapH = 0
self.mapX0 = 0
self.mapY0 = 0
self.mapX1 = 0
self.mapY1 = 0
self.pf = astar.Pathfinder()
self.clear_path()
self.sizeCell = 30
self.sizeBorder = 1
self.sizeIncell = self.sizeCell - (self.sizeBorder * 2)
self.colors = { Colors.BG_MAP : QColor(33, 33, 33), \
Colors.BG_SURF : QColor(0, 0, 0), \
Colors.CELL_GOAL : QColor(0, 230, 118), \
Colors.CELL_NOPATH : QColor(239, 83, 80), \
Colors.CELL_PATH : QColor(255, 245, 157), \
Colors.CELL_START : QColor(41, 182, 246), \
Colors.CELL_UNWALK : QColor(99, 99, 99), \
Colors.CELL_WALK : QColor(230, 230, 230) }
self.surfW = 1280
self.surfH = 720
self.surf = QImage(self.surfW, self.surfH, QImage.Format_RGB32)
self.clear_surface()
self.setFixedSize(self.surfW , self.surfH)
self.animating = False
self.animPathIdx = 0
self.animFrameTime = 100
self.animTimer = QTimer(self)
self.animTimer.timeout.connect(self.next_anim_frame)
self.painter = QPainter()
def clear_surface(self):
"""Clears the rendering area."""
self.surf.fill(self.colors[Colors.BG_SURF])
def get_color(self, colorId):
"""Gets the RGB QColor associated to an ID.
Parameters
----------
colorId : Colors
unique ID for a specific color.
Returns
-------
QColor
A color from the map of available colors.
"""
if colorId in self.colors:
return self.colors[colorId]
else:
return QColor(255, 0, 255)
def set_color(self, colorId, color):
"""Sets the RGB QColor associated to an ID.
Parameters
----------
colorId : Colors
unique ID for a specific color.
color : QColor
color to associate to the ID.
"""
if colorId in self.colors:
self.colors[colorId] = color
def paintEvent(self, event):
"""Event emitted by Qt when rendering of the widget is needed.
Parameters
----------
event : QEvent
Event data.
"""
self.painter.begin(self)
self.painter.setPen(Qt.NoPen)
self.painter.setBrush(Qt.NoBrush)
self.painter.drawImage(0, 0, self.surf)
self.painter.end()
def next_anim_frame(self):
"""Handles a frame in the path animation."""
if self.animating:
if self.animPathIdx > 0 and self.animPathIdx < (len(self.path) - 1):
cell = self.path[self.animPathIdx]
self.draw_cell(cell, self.colors[Colors.CELL_PATH])
self.repaint()
self.animPathIdx += 1
else:
self.animating = False
self.animTimer.stop()
self.animPathIdx = 0
def set_anim_speed(self, speed):
"""Sets the speed of the path rendering animation.
Parameters
----------
speed : int
Value in the range [1, 10]. Higher value means faster animation.
"""
if speed > 0 and speed < 11:
self.animFrameTime = 500 / speed
def get_anim_speed(self):
"""Gets the animation speed. Higher value means faster animation.
Returns
-------
int
The animation speed as [1, 10] value.
"""
return 500 / self.animFrameTime
def clear_path(self):
"""Clears data used for handling the path."""
self.path = []
self.start = None
self.goal = None
def set_map(self, map):
"""Sets the current map to process.
Parameters
----------
map : list
Map made of 0 and 1 representing walkable and unwalkable cells.
"""
self.map = map
self.pf.set_map(map)
self.mapRows = len(map)
self.mapCols = len(map[0])
self.clear_path()
self.update_map_size()
def is_cell_walkable(self, cell):
"""Check if a cell is walkable.
Parameters
----------
cell : tuple
row, col that define a cell of the map
Returns
-------
bool
True if the cell is walkable, False otherwise
"""
if self.map == None:
return False
r, c = cell
return self.map[r][c] == 1
def draw_map(self):
""""Draws the map in the widget, including the background."""
# clear surface
self.surf.fill(self.colors[Colors.BG_SURF])
self.painter.begin(self.surf)
# draw background
self.painter.setPen(Qt.NoPen)
self.painter.setBrush(self.colors[Colors.BG_MAP])
self.painter.drawRect(self.mapX0, self.mapY0, self.mapW, self.mapH)
# draw cells
for r in range(self.mapRows):
cellY = self.mapY0 + (r * self.sizeCell) + self.sizeBorder
for c in range(self.mapCols):
cellX = self.mapX0 + (c * self.sizeCell) + self.sizeBorder
if(self.map[r][c] == 1):
self.painter.setBrush(self.colors[Colors.CELL_WALK])
elif(self.map[r][c] == 0):
self.painter.setBrush(self.colors[Colors.CELL_UNWALK])
else:
self.painter.setBrush(self.colors[Colors.BG_MAP])
self.painter.drawRect(cellX, cellY, self.sizeIncell, self.sizeIncell)
self.painter.end()
def draw_cell(self, cell, color):
"""Draws a single cell inside the map.
Parameters
----------
cell : tuple
row, col that define a cell of the map.
"""
r, c = cell
cellX = self.mapX0 + (c * self.sizeCell) + self.sizeBorder
cellY = self.mapY0 + (r * self.sizeCell) + self.sizeBorder
self.painter.begin(self.surf)
self.painter.setPen(Qt.NoPen)
self.painter.setBrush(color)
self.painter.drawRect(cellX, cellY, self.sizeIncell, self.sizeIncell)
self.painter.end()
def get_cell_size(self):
"""Gets the size of a cell of the map.
Returns
-------
int
Size in pixel.
"""
return self.sizeCell
def set_cell_size(self, size):
"""Sets the size of a cell of the map.
Parameters
-------
size : int
Size in pixel.
"""
self.sizeCell = size
self.sizeIncell = self.sizeCell - (self.sizeBorder * 2)
self.update_map_size()
def get_cell_from_point(self, point):
"""Return the cell corresponding to a point in the map.
Parameters
----------
point : QPoint
x, y coordinates
Returns
-------
tuple
row, col that define a cell of the map
"""
return (int((point.y() - self.mapY0) / self.sizeCell), int((point.x() - self.mapX0) / self.sizeCell))
def is_point_inside(self, point):
"""Check if a point is inside the map.
Parameters
----------
point : QPoint
x, y coordinates
Returns
-------
bool
True if the point is inside the map, False otherwise
"""
x, y = point.x(), point.y()
return x > self.mapX0 and x < self.mapX1 and y > self.mapY0 and y < self.mapY1
def has_map(self):
"""Checks if a map is assigned.
Returns
-------
bool
True if there's a map assigned, False otherwise.
"""
return self.map != None
def update_map_size(self):
"""Update the sizes in pixel of the map. Called after anything in the map is changed"""
self.mapW = self.mapCols * self.sizeCell
self.mapH = self.mapRows * self.sizeCell
self.mapX0 = int((self.surfW - self.mapW) / 2)
self.mapY0 = int((self.surfH - self.mapH) / 2)
self.mapX1 = self.mapX0 + self.mapW
self.mapY1 = self.mapY0 + self.mapH
def mouseReleaseEvent(self, event):
"""Event emitted by Qt when a mouse button is released.
Parameters
----------
event : QEvent
Event data.
"""
if (event.button() != Qt.LeftButton):
return
if not self.is_point_inside(event.pos()):
return
if self.animating:
return
# set start
if self.start == None:
self.start = self.get_cell_from_point(event.pos())
if self.is_cell_walkable(self.start):
self.draw_cell(self.start, self.colors[Colors.CELL_START])
self.repaint()
else:
self.start = None
# set goal
elif self.goal == None:
self.goal = self.get_cell_from_point(event.pos())
if self.is_cell_walkable(self.goal) and self.start != self.goal:
self.draw_cell(self.goal, self.colors[Colors.CELL_GOAL])
try:
self.path = self.pf.make_path(self.start, self.goal)
# path found -> start animation
if len(self.path) > 0:
self.animating = True
self.animPathIdx = 1
self.animTimer.start(self.animFrameTime)
# no path found
else:
self.draw_cell(self.start, self.colors[Colors.CELL_NOPATH])
self.draw_cell(self.goal, self.colors[Colors.CELL_NOPATH])
self.repaint()
except Exception as ex:
print("ERROR {}".format(ex))
self.repaint()
else:
self.goal = None
# clear everything
else:
if len(self.path) > 0:
for cell in self.path:
self.draw_cell(cell, self.colors[Colors.CELL_WALK])
else:
self.draw_cell(self.start, self.colors[Colors.CELL_WALK])
self.draw_cell(self.goal, self.colors[Colors.CELL_WALK])
self.start = None
self.goal = None
self.repaint()
class DialogOptions(QDialog):
"""Dialog that allows to set several options like cell size, animation speed and colors."""
def __init__(self, parent = None):
super(DialogOptions, self).__init__(parent)
"""
Parameters
----------
parent : QWidget
optional parent widget
"""
self.setWindowTitle("Options")
self.setMinimumSize(300, 179)
layout = QVBoxLayout()
self.setLayout(layout)
group = self.create_group_map()
layout.addWidget(group)
self.colors = dict()
group = self.create_group_colors()
layout.addWidget(group)
# spacer
spacer = QSpacerItem(1, 1, QSizePolicy.Expanding, QSizePolicy.Expanding)
layout.addItem(spacer)
# CANCEL, OK buttons
layoutRow = QHBoxLayout()
buttonCanc = QPushButton("CANCEL")
buttonCanc.setMaximumWidth(100)
buttonCanc.clicked.connect(self.reject)
layoutRow.addWidget(buttonCanc)
buttonOK = QPushButton("OK")
buttonOK.setDefault(True)
buttonOK.setMaximumWidth(100)
buttonOK.clicked.connect(self.accept)
layoutRow.addWidget(buttonOK)
layout.addLayout(layoutRow)
def create_group_map(self):
"""Creates the group box containing widgets to handle map options."""
group = QGroupBox("Map")
layout = QGridLayout()
layout.setColumnMinimumWidth(0, 200)
group.setLayout(layout)
# CELL SIZE
label = QLabel("Cell size (in px):")
layout.addWidget(label, 0, 0)
self.inputCell = QSpinBox()
self.inputCell.setRange(1, 100)
layout.addWidget(self.inputCell, 0, 1)
# ANIMATION SPEED
label = QLabel("Animation speed:")
layout.addWidget(label, 1, 0)
self.animSpeed = QSlider(Qt.Horizontal, self)
self.animSpeed.setMinimum(1)
self.animSpeed.setMaximum(10)
layout.addWidget(self.animSpeed, 1, 1)
return group
def create_group_colors(self):
"""Creates the group box containing widgets to handle color options."""
group = QGroupBox("Colors")
layout = QGridLayout()
layout.setColumnMinimumWidth(0, 200)
group.setLayout(layout)
strings = [ "MAP background:", "WINDOW background:", "GOAL cell:", "NO PATH cell:",\
"PATH cell:", "START cell:", "UNWALKABLE cell:", "WALKABLE cell:" ]
ids = list(Colors)
for row in range(len(Colors)):
self.create_color_row(strings[row], ids[row], layout, row)
return group
def create_color_row(self, text, colorId, layout, row):
"""Creates a row of widgets part of the group of map options."""
label = QLabel(text)
layout.addWidget(label, row, 0)
button = ButtonColor(colorId)
layout.addWidget(button, row, 1, 1, 1, Qt.AlignRight)
self.colors[colorId] = button
def get_color(self, colorId):
"""Gets the RGB QColor associated to an ID.
Parameters
----------
colorId : Colors
unique ID for a specific color.
Returns
-------
QColor
A color from the map of available colors.
"""
if colorId in self.colors:
return self.colors[colorId].color
else:
return QColor(255, 0, 255)
def set_color(self, colorId, color):
"""Sets the RGB QColor associated to an ID.
Parameters
----------
colorId : Colors
unique ID for a specific color.
color : QColor
color to associate to the ID.
"""
if colorId not in self.colors:
return
button = self.colors[colorId]
button.set_color(color)
def get_cell_size(self):
"""Gets the size of a cell of the map.
Returns
-------
int
Size in pixel.
"""
return self.inputCell.value()
def set_cell_size(self, size):
"""Sets the size of a cell of the map.
Parameters
-------
size : int
Size in pixel.
"""
self.inputCell.setValue(size)
def get_anim_speed(self):
"""Gets the animation speed. Higher value means faster animation.
Returns
-------
int
The animation speed as [1, 10] value.
"""
return self.animSpeed.value()
def set_anim_speed(self, speed):
"""Sets the speed of the path rendering animation.
Parameters
----------
speed : int
Value in the range [1, 10]. Higher value means faster animation.
"""
self.animSpeed.setValue(speed)
class ButtonColor(QPushButton):
"""A button that can be used to show and set a color."""
def __init__(self, colorId, color = QColor(), parent = None):
super(ButtonColor, self).__init__(parent)
"""
Parameters
----------
colorId : Colors
ID associated to a specific color.
color : QColor
RGB color.
parent : QWidget
Optional parent of the button.
"""
self.colorId = colorId
self.color = color
self.setFixedSize(32, 32)
self.clicked.connect(self.button_color_clicked)
def set_color(self, color):
"""Sets the RGB QColor associated to the button
Parameters
----------
color : QColor
color to associate.
"""
self.color = color
pal = self.palette()
pal.setColor(QPalette.Button, color)
self.setPalette(pal)
@Slot()
def button_color_clicked(self, checked):
"""Slot called when the button is clicked.
Parameters
----------
checked : bool
Unused.
"""
color = QColorDialog.getColor(self.color, self.parentWidget())
if color.isValid():
self.set_color(color)
class MainWindow(QMainWindow):
"""Main window of the application that contains the rendering surface and a menubar."""
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
"""
Parameters
----------
parent : QWidget
Optional parent of the window.
"""
self.setWindowTitle("qt-pyfinder")
# -- File menu --
self.menuFile = self.menuBar().addMenu("&File")
self.actOpen = QAction("&Open map", triggered = self.open_dialog_load)
self.menuFile.addAction(self.actOpen)
self.menuFile.addSeparator()
self.actOpt = QAction("O&ptions", triggered = self.open_dialog_options)
self.menuFile.addAction(self.actOpt)
self.menuFile.addSeparator()
self.actQuit = QAction("&Quit", triggered = self.close)
self.menuFile.addAction(self.actQuit)
# -- MainWidget --
self.widget = QTilemap()
self.setCentralWidget(self.widget)
layout = self.layout()
layout.setSizeConstraint(QLayout.SetFixedSize)
def open_dialog_load(self):
"""Creates and opens the file dialog to chose a map to load."""
fileName, fil = QFileDialog.getOpenFileName(self, "Open Map", "data/maps/", "Map files (*.map)")
# have a file to load
if len(fileName) > 0:
with open(fileName, 'r') as f:
fdata = f.readlines()
# convert map file to usable format
# 1 = walkable cell
# 0 = unwalkable cell
fRows = len(fdata)
if fRows == 0:
print("ERROR empty map")
return
# skip last column of '\n'
fCols = len(fdata[0]) - 1
map = []
for r in range(fRows):
map.append([1] * fCols)
for r in range(fRows):
for c in range(fCols):
if fdata[r][c] == '#':
map[r][c] = 0
self.widget.set_map(map)
self.widget.draw_map()
self.widget.repaint()
def open_dialog_options(self):
"""Creates and opens the options dialog."""
self.dialogOpt = DialogOptions(self)
self.dialogOpt.set_cell_size(self.widget.get_cell_size())
self.dialogOpt.set_anim_speed(self.widget.get_anim_speed())
for colorId in Colors:
self.dialogOpt.set_color(colorId, self.widget.get_color(colorId))
self.dialogOpt.finished.connect(self.dialog_opt_finished)
self.dialogOpt.open()
@Slot()
def dialog_opt_finished(self, result):
"""
Parameters
----------
result : QDialog.DialogCode
Flag that tells if the dialog has been accepted or rejected.
"""
if result != QDialog.Accepted:
return
changed = False
# update size cell
sizeCell = self.dialogOpt.get_cell_size()
if sizeCell != self.widget.get_cell_size():
changed = True
self.widget.set_cell_size(sizeCell)
# animation speed
animSpeed = self.dialogOpt.get_anim_speed()
if animSpeed != self.widget.get_anim_speed():
self.widget.set_anim_speed(animSpeed)
# colors
for colorId in Colors:
newColor = self.dialogOpt.get_color(colorId)
if self.widget.get_color(colorId) != newColor:
changed = True
self.widget.set_color(colorId, newColor)
# redraw
if changed:
# redraw everything
if self.widget.has_map():
self.widget.clear_path()
self.widget.draw_map()
# redraw window background only
else:
self.widget.clear_surface()
self.widget.repaint()
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit(app.exec_())