-
Notifications
You must be signed in to change notification settings - Fork 0
/
simulate.py
1376 lines (1006 loc) · 45.4 KB
/
simulate.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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/local/bin/python
#-*-coding:utf-8-*-
from Tkinter import *
import networkx as nx
DIRECTION_DELTA = {"E":(1,0),"W":(-1,0),"N":(0,-1),"S":(0,1)}
ROBOT_SIZE = 5
GAP = 2
COLOR_COVERED = "#FFDA89"
COLOR_CLEANED = "#FFFFFF"
COLOR_BOUNDARY = "#FEFFFF"
COLOR_DOOR = "#FDFFFF"
def calculateDistance(start,end):
return abs(start[0] - end[0])+abs(start[1] - end[1])
def getConverseDirection(direction):
if(direction == "E"):
return "W"
if(direction == "W"):
return "E"
if(direction == "N"):
return "S"
if(direction == "S"):
return "N"
def get1StepCleanedRegion(robotPosition,robotDirection, pixelNum = 1):
if(robotDirection == "W"):
edgeStartX = robotPosition[0] - int(ROBOT_SIZE/2) - pixelNum
edgeEndX = robotPosition[0] - int(ROBOT_SIZE/2) -1
edgeStartY = robotPosition[1] - int(ROBOT_SIZE/2)
edgeEndY = robotPosition[1] + int(ROBOT_SIZE/2)
if(robotDirection == "E"):
edgeStartX = robotPosition[0] + int(ROBOT_SIZE/2) +1
edgeEndX = robotPosition[0] + int(ROBOT_SIZE/2) +pixelNum
edgeStartY = robotPosition[1] - int(ROBOT_SIZE/2)
edgeEndY = robotPosition[1] + int(ROBOT_SIZE/2)
if(robotDirection == "S"):
edgeStartX = robotPosition[0] - int(ROBOT_SIZE/2)
edgeEndX = robotPosition[0] + int(ROBOT_SIZE/2)
edgeStartY = robotPosition[1] + int(ROBOT_SIZE/2) +1
edgeEndY = robotPosition[1] +int(ROBOT_SIZE/2) +pixelNum
if(robotDirection == "N"):
edgeStartX = robotPosition[0] - int(ROBOT_SIZE/2)
edgeEndX = robotPosition[0] + int(ROBOT_SIZE/2)
edgeStartY = robotPosition[1] - int(ROBOT_SIZE/2) -pixelNum
edgeEndY = robotPosition[1] - int(ROBOT_SIZE/2) -1
return (edgeStartX,edgeEndX,edgeStartY,edgeEndY)
class Map(nx.Graph,Canvas):
def __init__(self,parent, iniBackground):
nx.Graph.__init__(self)
Canvas.__init__(self,parent,bd=3,relief=RIDGE,width=500, height=300)
self.im = PhotoImage(file= iniBackground)
self.create_image(ROBOT_SIZE,ROBOT_SIZE,anchor=NW, image= self.im)
self.pack(side=RIGHT)
self.uncoveredReg =[]
self.uncoveredRoom = []
self.currentRoom = None
self.coveredReg =[]
self.currentReg = None
self.currentX = int(ROBOT_SIZE/2) +GAP # robot center coordinate because robot size is 5*5
self.currentY = int(ROBOT_SIZE/2) +GAP
self.index=0
self.NODE_TYPE_SHAPE_MAP = \
{'corner':self.__drawCornerNode, 'obstacle':self.__drawObstacleNode,'joint':self.__drawJointNode}
self.EDGE_TYPE_SHAPE_MAP = \
{'free':self.__drawFreeEdge, 'upObtacle':self.__drawUpObtacleEdge,'downObtacle':self.__drawDownObtacleEdge}
def moveUpdate(self,robotDirection):
(edgeStartX,edgeEndX,edgeStartY,edgeEndY) = get1StepCleanedRegion((self.currentX,self.currentY),robotDirection)
for i in range(edgeStartX, edgeEndX+1):
for j in range(edgeStartY, edgeEndY+1):
if(self.im.get(i,j)=="220 220 220"):
self.im.put(COLOR_CLEANED,(i,j))
self.currentX = self.currentX + DIRECTION_DELTA[robotDirection][0];
self.currentY = self.currentY + DIRECTION_DELTA[robotDirection][1]
def ifRoomFinished(self):
return not self.uncoveredReg
def ifFinished(self):
return not self.uncoveredRoom
def setCurrentPos(self,x,y):
self.currentX = x
self.currentY = y
edgeStartX = x - int(ROBOT_SIZE/2)
edgeEndX = x + int(ROBOT_SIZE/2)
edgeStartY = y - int(ROBOT_SIZE/2)
edgeEndY = y + int(ROBOT_SIZE/2)
for i in range(edgeStartX, edgeEndX+1):
for j in range(edgeStartY, edgeEndY+1):
self.im.put(COLOR_CLEANED,(i,j))
def ifBump(self,robotDirection):
robotPosition = (self.currentX,self.currentY)
(edgeStartX, edgeEndX, edgeStartY, edgeEndY) = get1StepCleanedRegion(robotPosition,robotDirection)
for i in range(edgeStartX, edgeEndX+1):
for j in range(edgeStartY, edgeEndY+1):
if(self.im.get(i,j)=="253 255 255"):
return True
return False
def buildVirtalWall(self,start, end,currentDirection):
if start[1] > end[1]:
upLimit = start[1]
downLimit = end[1]
else:
upLimit = end[1]
downLimit = start[1]
for i in range(start[0],end[0]+1):
for j in range(downLimit,upLimit+1):
self.im.put(COLOR_DOOR,(i,j))
self.currentRoom = {'pos':start, 'direction':getConverseDirection(currentDirection)}
self.uncoveredRoom.append({'pos':start, 'direction':currentDirection})
def ifCloseToVirtualWall(self,direction):
currentPos = (self.currentX, self.currentY)
(edgeStartX, edgeEndX, edgeStartY, edgeEndY) = get1StepCleanedRegion(currentPos, direction, pixelNum = ROBOT_SIZE)
for i in range(edgeStartX, edgeEndX+1):
for j in range(edgeStartY, edgeEndY+1):
if(self.im.get(i,j)=="253 255 255"):
return True
return False
def setCurrentRoom(self,room):
self.currentRoom = room
self.uncoveredRoom.remove(room)
def setCurrentRegion(self,region):
self.currentReg = region
self.__delUncoveredReg(region)
def getRouteToNextRoom(self):
currentPos = (self.currentX, self.currentY)
shortestDistance = 999
nextRoom = None
for item in self.uncoveredRoom:
distance= calculateDistance(currentPos, item['pos'])
if (distance < shortestDistance):
shortestDistance = distance
nextRoom = item
if shortestDistance==0:
break
path = self.__getPath(currentPos, nextRoom['pos'])
return {'path':path, 'targetRoom':nextRoom, 'targetRegion':{}}
# route = {path: [position, position], sweepDirection:"N"}
def getRouteToNextRegionBoundary(self):
currentPos = (self.currentX, self.currentY)
shortestDistance = 999
nextRegPoint = None
nextReg = None
for item in self.uncoveredReg:
if item['up']:
distance, point= self.__getDistanceFromPoint2Edge(currentPos, item['up'])
else:
distance,point = self.__getDistanceFromPoint2Edge(currentPos, item['down'])
if (distance < shortestDistance):
shortestDistance = distance
nextRegPoint = point
nextReg = item
if shortestDistance==0:
break
path = self.__getPath(currentPos, nextRegPoint)
return {'path':path, 'targetRegion':nextReg,'targetRoom':{}}
def addNode(self,position, type):
self.add_node(position,{'type':type})
self.NODE_TYPE_SHAPE_MAP[type](position)
return position
def addEdge(self,start, end,type):
self.add_edge(start,end,{'type':type})
self[start][end]['weight'] = calculateDistance(start,end)
self.EDGE_TYPE_SHAPE_MAP[type](start,end)
def updateRegion(self,nodeList):
upBoundary,downBoundary = self.__segmentRegionByBoundary(nodeList)
self.__updateUncoveredReg(upBoundary, downBoundary)
if not self.currentReg:
self.currentReg = self.uncoveredReg.pop()
return
self.combineCurrentBoundary()
def __getDistanceFromPoint2Edge(self,point, edge):
distance1 = calculateDistance(point, edge[0])
distance2 = calculateDistance(point, edge[1])
if distance1<distance2:
return distance1, edge[0]
else:
return distance2, edge[1]
def __getPath(self, start, end):
return self.__briefGetPath(start,end)
# return self.__aGetPath(start,end)
# return self.__dijkstraGetPath(start,end)
# a*算法
def __aGetPath(self, start, end):
opened = {}
closed = {}
closed[start] = {'parent':None, 'C':0, 'H': calculateDistance(start,end)}
point = start
while(point != end):
neighbourList = self.__getNeighbour(point)
for neighbourPoint in neighbourList:
if self.__ifBlock(neighbourPoint):
continue
if closed.has_key(neighbourPoint):
continue
c = closed[point]['C'] +1
h = calculateDistance(neighbourPoint, end)
if opened.has_key(neighbourPoint):
if (opened[neighbourPoint]['C'] + opened[neighbourPoint]['H']) > (c+h):
opened[neighbourPoint]['C'] = c
opened[neighbourPoint]['H'] = h
opened[neighbourPoint]['parent'] = point
else:
opened[neighbourPoint] = {}
opened[neighbourPoint]['C'] = c
opened[neighbourPoint]['H'] = h
opened[neighbourPoint]['parent'] = point
minF = 999
for item in opened:
F = opened[item]['C'] +opened[item]['H']
if minF >F:
minF = F
point = item
closed[point] ={}
closed[point] = opened[point]
del opened[point]
path =[]
point = end
while point:
path.insert(0,point)
point = closed[point]['parent']
return path
def __dijkstraGetPath(self,start,end):
closed = {}
opened ={}
opened[start] = {'parent':None}
while not (end in opened):
backupOpen ={}
for openitem in opened:
neighbourList = self.__getNeighbour(openitem)
for neighbourPoint in neighbourList:
if self.__ifBlock(neighbourPoint):
continue
if closed.has_key(neighbourPoint):
continue
if opened.has_key(neighbourPoint):
continue
backupOpen[neighbourPoint] = {'parent':openitem}
closed[openitem] = opened[openitem]
opened = backupOpen
path = [end]
point = opened[end]['parent']
while point:
path.insert(0,point)
point = closed[point]['parent']
return path
# 简洁算法
def __briefGetPath(self,start,end):
path = []
current = start
path.append(start)
while (current != end):
neighbourList = self.__getNeighbour(current)
F = 999
nextPoint = None
for neighbourPoint in neighbourList:
if self.__ifBlock(neighbourPoint):
continue
if neighbourPoint in path:
continue
weight = calculateDistance(neighbourPoint, end)
if( weight< F):
F = weight
nextPoint = neighbourPoint
current = nextPoint
path.append(current)
return path
def ifTouchBoundary(self,direction):
robotPosition = (self.currentX, self.currentY)
(edgeStartX, edgeEndX, edgeStartY, edgeEndY) = get1StepCleanedRegion(robotPosition,direction)
for i in range(edgeStartX, edgeEndX+1):
for j in range(edgeStartY, edgeEndY+1):
if(self.im.get(i,j)=="254 255 255"):
return True
return False
def __ifBlock(self,point):
edgeStartX = point[0] - int(ROBOT_SIZE/2)
edgeEndX = point[0] + int(ROBOT_SIZE/2)
edgeStartY = point[1] - int(ROBOT_SIZE/2)
edgeEndY = point[1] + int(ROBOT_SIZE/2)
# if ((edgeStartX <GAP) or (edgeEndX> Env.WIDTH-GAP) or (edgeStartY <GAP) or (edgeEndY>Env.HEIGHT-GAP)):
# return True
for i in range(edgeStartX, edgeEndX+1):
for j in range(edgeStartY, edgeEndY+1):
if(self.im.get(i,j)=="220 220 220"):
return True
return False
def __calculateF(self, point, start, end):
G = calculateDistance(point, start)
H = calculateDistance(point, end)
return H
def __getNeighbour(self,current):
neighbourList =[]
neighbourList.append((current[0]+1, current[1]))
neighbourList.append((current[0], current[1]-1))
neighbourList.append((current[0]-1, current[1]))
neighbourList.append((current[0], current[1]+1))
return neighbourList
def __updateUncoveredReg(self,upBoundary,downBoundary):
for item in upBoundary:
self.__addUncoveredReg({'up':item, 'down':()})
for item in downBoundary:
self.__addUncoveredReg({'up':(),'down':item})
def __addUncoveredReg(self, region):
self.__buildVirtualBoundary(region)
self.uncoveredReg.append(region)
def __delUncoveredReg(self, region):
self.__buildVirtualBoundary(region,color=COLOR_CLEANED)
self.uncoveredReg.remove(region)
def __buildVirtualBoundary(self,region,color=COLOR_BOUNDARY):
edge = None
if(region['up']):
edge = region['up']
edge = ((edge[0][0],edge[0][1]+2), (edge[1][0],edge[1][1]+2))
else:
edge = region['down']
edge = ((edge[0][0],edge[0][1]-2), (edge[1][0],edge[1][1]-2))
for i in range(edge[0][0], edge[1][0]+1):
for j in range(edge[0][1], edge[1][1]+1):
self.im.put(color,(i,j))
def combineCurrentBoundary(self):
if not self.currentReg:
return
if not self.currentReg['up']:
region = self.__findClosedRegion(self.currentReg['down'], 'up')
self.currentReg['up'] = region['up']
self.__delUncoveredReg(region)
elif not self.currentReg['down']:
region = self.__findClosedRegion(self.currentReg['up'], 'down')
self.currentReg['down'] = region['down']
self.__delUncoveredReg(region)
self.__drawFreeEdge(self.currentReg['up'][0], self.currentReg['down'][0])
self.__drawFreeEdge(self.currentReg['up'][1], self.currentReg['down'][1])
self.coveredReg.append(self.currentReg)
def __findClosedRegion(self,edge, direction):
anotherRegion = ()
for item in self.uncoveredReg:
if not item[direction]:
continue
if (direction == 'up') and (item[direction][0][1] >= edge[0][1]):
continue
if (direction == 'down') and (item[direction][0][1] <= edge[0][1]):
continue
if not anotherRegion:
anotherRegion = item
continue
if calculateDistance(edge[0],item[direction][0])< calculateDistance(edge[0],anotherRegion[direction][0]):
anotherRegion = item
return anotherRegion
def __drawCornerNode(self,position):
pos = self.__convertPos(position)
self.create_rectangle(pos[0]-1.5,pos[1]-1.5,pos[0]+1.5,pos[1]+1.5,\
fill="red",outline="red")
def __drawObstacleNode(self,position):
pos = self.__convertPos(position)
self.create_oval(pos[0]-1.5,pos[1]-1.5,pos[0]+1.5,pos[1]+1.5,\
outline="blue")
def __drawJointNode(self,position):
pos = self.__convertPos(position)
self.create_oval(pos[0]-1.5,pos[1]-1.5,pos[0]+1.5,pos[1]+1.5,\
fill="black")
def __drawFreeEdge(self,start,end):
newStart = self.__convertPos(start)
newEnd = self.__convertPos(end)
self.create_line(newStart[0], newStart[1],newEnd[0],newEnd[1])
def __drawUpObtacleEdge(self,start,end):
newStart = self.__convertPos(start)
newEnd = self.__convertPos(end)
self.create_line(newStart[0], newStart[1],newEnd[0],newEnd[1],dash=True, fill="red")
def __drawDownObtacleEdge(self,start,end):
newStart = self.__convertPos(start)
newEnd = self.__convertPos(end)
self.create_line(newStart[0], newStart[1],newEnd[0],newEnd[1],dash=True, fill="blue")
def __convertPos(self,position):
return (position[0]+5, position[1]+5)
def __segmentRegionByBoundary(self,nodeList):
upRegionBoundary = []
downRegionBoundary = []
up = ()
down=()
length = len(nodeList)
for i in range(length-1):
edge = self.get_edge_data(nodeList[i], nodeList[i+1])
if(edge['type'] == 'free') or (edge['type']=="upObtacle"):
if not up:
up = (nodeList[i], nodeList[i+1])
else:
if (up[1] == nodeList[i]):
up = (up[0], nodeList[i+1])
else:
upRegionBoundary.append(up)
up = (nodeList[i], nodeList[i+1])
if(edge['type'] == 'free') or (edge['type']=="downObtacle"):
if not down:
down = (nodeList[i], nodeList[i+1])
else:
if (down[1] == nodeList[i]):
down = (down[0], nodeList[i+1])
else:
downRegionBoundary.append(down)
down = (nodeList[i], nodeList[i+1])
if up:
upRegionBoundary.append(up)
if down:
downRegionBoundary.append(down)
return upRegionBoundary,downRegionBoundary
#控制行走策略, 通过在走每一步前, 安放检查点, 改变机器人的 行走方向,达到控制的目的
class MoveCtl():
def __init__(self, robot):
self.robot = robot
# return 是否真正移动
def decideNextMove(self):
return True
def endControl(self):
self.robot.checkProgress()
class FindCornerCtl(MoveCtl):
def __init__(self,robot,stepDirection):
MoveCtl.__init__(self, robot)
self.robot.currentDirection = stepDirection
self.stepNum =0
def decideNextMove(self):
if(self.stepNum < ROBOT_SIZE):
self.stepNum = self.stepNum +1
return True
else:
self.robot.currentDirection = 'N'
ifBump = self.robot.ifBump()
if(ifBump):
self.robot.moveCtl = ZigzagMoveCtl(self.robot,'S')
return False
return True
class ZigzagMoveCtl(MoveCtl):
global ROBOT_SIZE
global GAP
def __init__(self, robot, sweepDirection, ifAlterSliceAtFirst = False, firstSliceDirection="W"):
MoveCtl.__init__(self, robot)
self.alterDistance = 0
self.alterMaxDistance = ROBOT_SIZE
self.sweepDirection = sweepDirection
self.lastSliceDirection = firstSliceDirection
self.currentSlice = {}
self.ifSliceDeadHead = False
self.ifLastSlice = False
self.robot.stateText = "弓形清扫"
if (ifAlterSliceAtFirst):
self.robot.currentDirection = sweepDirection
self.__act = self.__processAlterSlice
else:
self.__act = self.__processSlice
self.robot.currentDirection = firstSliceDirection
self.ifSliceDeadHead = not self.__ifInCornerAtStart() #这个slice是否空驶
def __ifInCornerAtStart(self):
range = self.robot.getRangeData()
if(range[getConverseDirection(self.robot.currentDirection)]> GAP):
return False
else:
return True
def decideNextMove(self):
return self.__act()
def __processSlice(self):
ifBump = self.robot.ifBump()
if(ifBump):
if(self.ifLastSlice):
self.robot.map.combineCurrentBoundary()
assert(self.robot.ifCurrentRegionFinished())
self.endControl()
return False
if(self.ifSliceDeadHead):
self.robot.currentDirection = getConverseDirection(self.robot.currentDirection)
self.lastSliceDirection = self.robot.currentDirection
self.__act = self.__processSlice
self.__handleSliceBegin()
self.ifSliceDeadHead = False
else:
self.__handleSliceEnd()
self.__act = self.__processAlterSlice
range = self.__getRangeData()
if(range['head'] >(ROBOT_SIZE*3)):
self.alterMaxDistance = 3
else:
self.alterMaxDistance = ROBOT_SIZE
self.alterDistance = 0
self.lastSliceDirection = self.robot.currentDirection
self.robot.currentDirection = self.sweepDirection
return False
if(self.__ifLeftRightDoorFound()):
self.__buildVirtalWall()
self.__handleSliceEnd()
self.alterMaxDistance = ROBOT_SIZE
self.lastSliceDirection = self.robot.currentDirection
self.robot.currentDirection = getConverseDirection(self.lastSliceDirection)
self.__act = self.__processAlterSlice
return False
if(not self.ifSliceDeadHead):
self.__handleSliceInProgress()
return True
def __buildVirtalWall(self):
point = self.currentSlice['doorPoint'][-1]['pos']
start = point
if(self.sweepDirection == "S"):
end = (start[0], start[1] + ROBOT_SIZE*10)
else:
end = (start[0], start[1] - ROBOT_SIZE*10)
self.robot.map.buildVirtalWall(start,end,self.robot.currentDirection)
def __ifLeftRightDoorFound(self):
if (not self.currentSlice):
return False
if (not self.currentSlice['doorPoint']):
return False
if len(self.currentSlice['doorPoint'])<2:
return False
if(calculateDistance(self.currentSlice['doorPoint'][0]['pos'],self.currentSlice['start'])<ROBOT_SIZE):
self.currentSlice['doorPoint'] =[]
return False
corridorWidth = abs(self.currentSlice['doorPoint'][1]['pos'][0] - self.currentSlice['doorPoint'][0]['pos'][0])
if (corridorWidth<ROBOT_SIZE*3) and (corridorWidth>ROBOT_SIZE):
return True
self.currentSlice['doorPoint'] =[]
return False
def __processAlterSlice(self):
if(self.robot.ifTouchBoundary()):
self.ifLastSlice = True
self.robot.currentDirection = getConverseDirection(self.lastSliceDirection)
self.__act = self.__processSlice
self.ifSliceDeadHead = True
return False
ifBump = self.robot.ifBump()
if(ifBump):
if(self.alterDistance>0):
self.robot.currentDirection = getConverseDirection(self.lastSliceDirection)
self.__act = self.__processSlice
self.__handleSliceBegin()
else:
self.robot.currentDirection = getConverseDirection(self.lastSliceDirection)
self.backDistance = 0
self.__act = self.__processBackOneRobot
return False
if(self.alterDistance == self.alterMaxDistance):
self.robot.currentDirection = getConverseDirection(self.lastSliceDirection)
self.__act = self.__processSlice
if(self.__ifBackEmpty()):
self.ifSliceDeadHead = True
else:
self.__handleSliceBegin()
return False
self.alterDistance +=1
return True
def __ifBackEmpty(self):
range = self.robot.getRangeData()
backSpace = range[self.lastSliceDirection]
if (backSpace > ROBOT_SIZE*3):
if(self.robot.map.ifCloseToVirtualWall(self.lastSliceDirection)):
return False
return True
return False
def __processBackOneRobot(self):
ifBump = self.robot.ifBump()
if ifBump:
print "very very interesting"
self.robot.currentDirection = self.sweepDirection
self.__act = self.__processAlterSlice
return False
if(self.backDistance == ROBOT_SIZE):
self.robot.currentDirection = self.sweepDirection
self.__act = self.__processAlterSlice
return False
self.backDistance +=1
return True
def __handleSliceInProgress(self):
if(not self.currentSlice):
return None
self.__checkCriticality()
def __handleSliceBegin(self):
self.currentSlice["start"] = self.robot.getCurrentPos()
self.currentSlice["end"] = (999,999)
self.currentSlice['direction'] = self.robot.currentDirection
self.currentSlice['criticality'] = []
self.currentSlice['doorPoint'] = []
self.__checkCriticality()
def __handleSliceEnd(self):
self.currentSlice['end'] = self.robot.getCurrentPos()
self.__checkCriticality()
self.__filterEnd()
#普通slice, 没有临界点
if(len(self.currentSlice['criticality']) ==2) and \
(self.currentSlice['criticality'][0]['rangeStatus'] == (False,False)):
return
self.robot.buildBoundary(self.currentSlice['criticality'])
if(self.robot.ifCurrentRegionFinished()):
self.endControl()
#避免球形,斜边,凹形slice边界造成短距离的障碍物误判
def __filterEnd(self):
if (len(self.currentSlice['criticality']) > 2):
startNode = self.currentSlice['criticality'][0]
secondNode = self.currentSlice['criticality'][1]
startDistance = calculateDistance(startNode['pos'], secondNode['pos'])
if(startNode['rangeStatus'] != (False,False) and secondNode['rangeStatus'] != (False,False)):
self.currentSlice['criticality'][0]['rangeStatus'] = (False,False)
if (startDistance < (ROBOT_SIZE)):
startNode['rangeStatus'] = secondNode['rangeStatus']
self.currentSlice['criticality'].remove(secondNode)
if (len(self.currentSlice['criticality']) > 2):
endNode = self.currentSlice['criticality'][-1]
secondEndNode = self.currentSlice['criticality'][-2]
thirdEndNode = self.currentSlice['criticality'][-3]
endDistance = calculateDistance(endNode['pos'], secondEndNode['pos'])
if(thirdEndNode['rangeStatus'] != (False,False) and secondEndNode['rangeStatus'] != (False,False)):
self.currentSlice['criticality'][-1]['rangeStatus'] = (False,False)
self.currentSlice['criticality'][-2]['rangeStatus'] = (False,False)
if (endDistance < (ROBOT_SIZE)):
endNode['rangeStatus'] = secondEndNode['rangeStatus']
self.currentSlice['criticality'].remove(secondEndNode)
if (len(self.currentSlice['criticality']) == 2):
if(self.currentSlice['criticality'][0]['rangeStatus'] != self.currentSlice['criticality'][1]['rangeStatus']):
self.currentSlice['criticality'][0]['rangeStatus'] = (False,False)
self.currentSlice['criticality'][1]['rangeStatus'] = (False,False)
def __getLastPos(self,currentPos):
currentDirection = self.robot.currentDirection
if(currentDirection == "E"):
return(currentPos[0]-1, currentPos[1])
if(currentDirection == "W"):
return(currentPos[0]+1, currentPos[1])
if(currentDirection == "N"):
return(currentPos[0], currentPos[1]+1)
if(currentDirection == "S"):
return(currentPos[0], currentPos[1]-1)
def __checkCriticality(self):
currentPosition = self.robot.getCurrentPos()
range = self.__getRangeData()
ifUpClose = (range['up'] < ROBOT_SIZE+2)
ifBelowClose = (range['down'] < ROBOT_SIZE+2)
if(ifUpClose and ifBelowClose):
if(range['up']>range['down']):
ifUpClose = False
else:
ifBelowClose = False
# ifForwardClose = (range['head'] < ROBOT_SIZE+GAP+1)
upDownSpace = range['up'] + range['down']
ifUpDownClose = (upDownSpace<ROBOT_SIZE*10)
if(ifUpDownClose) and (not self.currentSlice['doorPoint']):
self.currentSlice['doorPoint'].append({'pos':currentPosition, 'upDownCloseStatus':ifUpDownClose})
if (self.currentSlice['doorPoint']) and (ifUpDownClose != self.currentSlice['doorPoint'][-1]['upDownCloseStatus']):
self.currentSlice['doorPoint'].append({'pos':currentPosition, 'upDownCloseStatus':ifUpDownClose})
if(self.currentSlice["start"] == currentPosition) and (not self.currentSlice['criticality']):
self.currentSlice['criticality'].append({'pos':currentPosition, 'rangeStatus':(ifUpClose,ifBelowClose)})
return
if(self.currentSlice['end'] == currentPosition):
self.currentSlice['criticality'].append({'pos':currentPosition, 'rangeStatus':(ifUpClose,ifBelowClose)})
return
if (self.currentSlice['criticality'][-1]['rangeStatus'] != (ifUpClose,ifBelowClose)):
self.currentSlice['criticality'].append({'pos':currentPosition, \
'rangeStatus':(ifUpClose,ifBelowClose)})
return
# return range of slice direction, sweep direction and anti-sweep direction
def __getRangeData(self):
range = self.robot.getRangeData()
head = range[self.robot.currentDirection]
up = range['N']
down = range['S']
return {'head':head,'up':up, 'down':down}
class NavMoveCtl(MoveCtl):
def __init__(self, robot, route):
MoveCtl.__init__(self, robot)
self.path = route['path']
self.targetRegion = route['targetRegion']
self.targetRoom = route['targetRoom']
self.pathIndex = 1
def decideNextMove(self):
if (self.pathIndex == len(self.path)):
if(self.targetRegion):
self.__startSweep()
elif(self.targetRoom):
self.__findCorner()
return False
currentPos = self.robot.getCurrentPos()
self.robot.currentDirection = self.__getMoveDirection(currentPos, self.path[self.pathIndex])
self.pathIndex+=1
return True
def __findCorner(self):
self.robot.setCurrentRoom(self.targetRoom)
self.robot.moveCtl = FindCornerCtl(self.robot, self.targetRoom['direction'])
def __startSweep(self):
self.robot.setCurrentRegion(self.targetRegion)
sweepDirection = "S"
targetEdge =None
firstSliceDirection = None
if self.targetRegion['down']:
sweepDirection ='N'
targetEdge = self.targetRegion['down']
else:
sweepDirection = 'S'
targetEdge = self.targetRegion['up']
currentPos = self.robot.getCurrentPos()
if currentPos == targetEdge[0]:
firstSliceDirection = "W"
else:
firstSliceDirection = "E"
self.robot.moveCtl = ZigzagMoveCtl(self.robot,sweepDirection, \
ifAlterSliceAtFirst = True, firstSliceDirection=firstSliceDirection)
def __getMoveDirection(self,start,end):
if start[0] < end[0]:
return 'E'
if start[0] > end[0]:
return 'W'
if start[1] < end[1]:
return 'S'
if start[1] > end[1]:
return 'N'
class Robot():
global DIRECTION_DELTA
global ROBOT_SIZE
global GAP
def __init__(self, env,map,statistic):
self.env = env
self.map = map
self.statistic = statistic
self.velocity = 0
self.state = "move"
self.map.setCurrentPos(int(ROBOT_SIZE/2) +GAP,int(ROBOT_SIZE/2) +GAP )
self.env.clearInitRobot(self.getCurrentPos())
self.appearance= env.create_rectangle(7,7,12,12, fill="red")
self.currentDirection = "E"
self.stateText = "弓形清扫"
self.moveCtl = ZigzagMoveCtl(self,"S")
self.move()
def checkProgress(self):
if not self.map.ifRoomFinished():
self.__navToNextRegion()
return
if not self.map.ifFinished():
self.__navToNextRoom()
return
self.stateText = "清扫结束"
self.stopMove()
return
def __navToNextRegion(self):
# route = {'path':path, 'targetRegion':edge}
route = self.map.getRouteToNextRegionBoundary()
self.stateText = "导航最近未清扫区域"
self.moveCtl = NavMoveCtl(self, route)
def __navToNextRoom(self):
# route = {'path':path, 'targetRegion':edge}
route = self.map.getRouteToNextRoom()
self.stateText = "导航最近房间"
self.moveCtl = NavMoveCtl(self, route)