-
Notifications
You must be signed in to change notification settings - Fork 0
/
FourWay.py
77 lines (62 loc) · 2.3 KB
/
FourWay.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
#
# FourWay.py
# Taco --- SPH Innovation Challenge
#
# Created by Mat, Kon and Len on 2017-03-11.
# Copyright 2016 Researchnix. All rights reserved.
#
import Car
import Street
import TrafficLight
import collections
class FourWay:
ID = ""
xPos = 0
yPos = 0
incoming = []
outgoing = []
waitingCars = {}
queueSize = 5 # Number of cars that can wait in each queue
trali = None
def __init__ (self, ID, x, y):
self.ID = ID
self.xPos = x
self.yPos = y
self.incoming = list([])
self.outgoing = list([])
self.waitingCars = dict([])
# Initialize this traffic light only after all streets are attached to this intersection
def initializeTrafficLight(self):
self.trali = TrafficLight.TrafficLight(self.incoming, self.outgoing)
# Attach a new street as incoming
def addIncoming(self, s):
self.incoming.append(s)
for a in self.waitingCars.values():
a[s.ID] = collections.deque([])
# Attach a new street as outgoing
def addOutgoing(self, s):
self.outgoing.append(s)
self.waitingCars[s.ID] = {}
for u in self.incoming:
self.waitingCars[s.ID][u.ID] = collections.deque([])
# Do a time step, which means:
# Update traffic lights
# Try to queue cars in streets
# Ask streets to dequeue cars
def update(self):
self.trali.update(0) # Only a dummy for now
# Try to queue cars in streets
# It depends on the traffic light state
for o in self.outgoing:
for i in self.incoming:
if self.trali.pathAllowed(i.ID, o.ID) and len(self.waitingCars[o.ID][i.ID]) != 0:
car = self.waitingCars[o.ID][i.ID].pop()
if not o.queueCar(car):
self.waitingCars[o.ID][i.ID].appendleft(car)
# Ask streets to dequeue a car, if there is space in the specific queue
# for this incoming street
for s in self.incoming:
if max([len(x[s.ID]) for x in self.waitingCars.values()]) <= self.queueSize:
newCar = s.dequeueCar()
if newCar != None:
self.waitingCars[newCar.dequeueNextSt(), s.ID].append(newCar)