forked from AC-Unicorn/Traffic-Flow-Optimization
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimulate.py
More file actions
79 lines (67 loc) · 2.43 KB
/
simulate.py
File metadata and controls
79 lines (67 loc) · 2.43 KB
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
# simulate.py
from time import sleep
from car import CarMap
class Car(object):
"""
A car in simulation.
"""
def __init__(self, idd, dirs):
self.stepLeft = dirs[0]
self.dirs = dirs[1]
self.timeStamp = 0
def isArrived(self):
return self.stepLeft == 0
def nextRoad(self):
if self.dirs[0][1] == 1 and len(self.dirs) != 1:
return self.dirs[1][0] # id of next new road
return -1 # no need to change road
def move(self):
self.stepLeft -= 1
if self.dirs[0][1] == 1:
del self.dirs[0]
else:
self.dirs[0] = (self.dirs[0][0], self.dirs[0][1] - 1)
class Simulation(object):
def __init__(self, startEndList, carMap):
self.carN = len(startEndList)
self.cm = carMap
self.cm.initialCars([startEndList[i][0] for i in range(self.carN)])
self.cars = []
for i in range(self.carN):
self.cars.append(Car(i, self.cm.getDirection(startEndList[i][0], startEndList[i][1])))
self.carCnt = self.carN
self.tick = 0
def run(self, delay, limit, sec=0.1):
while self.carCnt:
if self.tick > limit: return (-1, -1)
if delay: sleep(sec)
self.tick += 1
self.cm.updateTrafficLights(self.tick)
for i in range(self.carN):
self.moveCarRecursively(i)
self.cm.clearAllCars()
total = 0
for i in range(self.carN):
total += self.cars[i].timeStamp
# print "Car", i, "takes", self.cars[i].timeStamp, "ticks."
return (total, float(total) / self.carN)
def makeAMove(self, i, nextRoad):
if nextRoad == -1:
return self.cm.move(i)
return self.cm.moveTo(i, nextRoad, self.tick)
def moveCarRecursively(self, i):
if self.cars[i].isArrived() or self.cars[i].timeStamp == self.tick:
return
self.cars[i].timeStamp = self.tick
nextRoad = self.cars[i].nextRoad()
state = self.makeAMove(i, nextRoad)
if state[0] == CarMap.BLOCKED_BY_OTHER_CAR:
self.moveCarRecursively(state[1])
state = self.makeAMove(i, nextRoad)
if state[0] == CarMap.SUCCESS:
self.cars[i].move()
if self.cars[i].isArrived():
self.cm.remove(i)
self.carCnt -= 1
if __name__ == '__main__':
Simulation([((7, 4), (10, 4))], CarMap('face')).run()