Codigo
Codigo
import time
import threading
import pygame
import sys
import os
signals = []
Numero_signals = 4
Actual_green = 0 # Indicates which signal is green currently
Next_green = (Actual_green+1)%Numero_signals # Indicates which signal will
turn green next
Actual_yellow = 0 # Indicates whether yellow signal is on or off
velocity =
{'car1':2.25,'car2':2.25,'car3':2.25,'car4':2.25,'car5':2.25,'car6':2.25,
'bus1':1.8,
'truck1':1.8 ,
'bike1':2.5,'bike2':2.5,'bike3':2.5,'bike4':2.5,'bike5':2.5,'bike6':2.5
,
'ni1':1, 'ni2':1, 'ni3':1 } # average velocity of vehicles
# Coordinates of vehicles' start
x = {'right':[0,0,0], 'down':[853,791,730], 'left':[1400,1400,1400],
'up':[563,571,632]} ##NO CAMBIAR
y = {'right':[216,277,338], 'down':[0,0,0], 'left':[529,468,407],
'up':[800,800,800]} ###NO CAMBIAR
primer_stop_ni = {'right': 572, 'down': 280, 'left': 823, 'up': 530} ###no
cAMBIAR
segundo_stop_ni = {'right': 570, 'down': 278, 'left': 821, 'up': 527}##no cAMBIAR
tipos_vehicleList = []
vehicles_direc = {'right': {1:[], 2:[]}, 'down': {1:[], 2:[]}, 'left': {1:[],
2:[]}, 'up': {1:[], 2:[]}}
vehiclesNot_direc = {'right': {1:[], 2:[]}, 'down': {1:[], 2:[]}, 'left': {1:[],
2:[]}, 'up': {1:[], 2:[]}}
rotationAngle = 3
elapsed_time = 0
tiempito = 100
time_semaforo = (100,50)
pygame.init()
Sprite = pygame.sprite.Group()
car_group = pygame.sprite.RenderPlain()
heli_group = pygame.sprite.RenderPlain()
#Sprite_ni = pygame.sprite.Group()
class Semaforo:
def __init__(self, red, yellow, green):
self.red = red
self.yellow = yellow
self.green = green
self.signalText = ""
class Vehicle(pygame.sprite.Sprite):
def __init__(self, lane, clase_vehicle, direc_Num, direction, turno_rand):
pygame.sprite.Sprite.__init__(self)
self.lane = lane
self.clase_vehicle = clase_vehicle
self.speed = velocity[clase_vehicle]
self.direc_Num = direc_Num
self.direction = direction
self.x = x[direction][lane]
self.y = y[direction][lane]
self.crossed = 0
self.crossed_per = 0
self.willTurn = turno_rand
self.turned = 0
self.rotateAngle = 0
vehicles[direction][lane].append(self)
self.index = len(vehicles[direction][lane]) - 1
self.crossedIndex = 0
path = "images/" + direction + "/" + clase_vehicle + ".png"
self.originalImage = pygame.image.load(path)
self.image = pygame.image.load(path) ####OBJETO EN MOVIMIENTO
self.rect = self.image.get_rect()
if(len(vehicles[direction][lane])>1 and
vehicles[direction][lane][self.index-1].crossed==0):
#print(lane)
#print(len(vehicles[direction][lane]))
#print(vehicles[direction][lane][self.index-1].crossed)
if(direction=='right'):
self.stop = vehicles[direction][lane][self.index-1].stop -
vehicles[direction][lane][self.index-1].image.get_rect().width
- gap
elif(direction=='left'):
self.stop = vehicles[direction][lane][self.index-1].stop
+ vehicles[direction][lane][self.index-1].image.get_rect().width
+ gap
elif(direction=='down'):
self.stop = vehicles[direction][lane][self.index-1].stop
- vehicles[direction][lane][self.index-1].image.get_rect().height
- gap
elif(direction=='up'):
self.stop = vehicles[direction][lane][self.index-1].stop
+ vehicles[direction][lane][self.index-1].image.get_rect().height
+ gap
else:
self.stop = segundo_stop[direction]
elif(direction=='left'):
tmp = self.rect.width + gap
x[direction][lane] += tmp
elif(direction=='down'):
tmp = self.rect.height + gap
y[direction][lane] -= tmp
elif(direction=='up'):
tmp = self.rect.height + gap
y[direction][lane] += tmp
Sprite.add(self)
def move(self):
if(self.direction=='right'):
if(self.crossed==0 and
self.x+self.rect.width>primer_stop[self.direction]):
self.crossed = 1
vehicles[self.direction]['crossed'] += 1
if(self.willTurn==0):
vehiclesNot_direc[self.direction][self.lane].append(self)
self.crossedIndex =
len(vehiclesNot_direc[self.direction][self.lane]) - 1
if(self.willTurn==1):
if(self.lane == 1):
if((self.x+self.rect.width<=self.stop or self.crossed == 1 or
(Actual_green==0 and Actual_yellow==0))
and (self.index==0 or
self.x+self.rect.width<(vehicles[self.direction][self.lane][self.index-1].x -
moving_Gap))):
self.x -= self.speed
if(self.lane == 2):
if(self.crossed==0 or
self.x+self.rect.width<mid[self.direction]['x']):
if((self.x+self.rect.width<=self.stop or (Actual_green==0
and Actual_yellow==0) or self.crossed==1) and (self.index==0 or
self.x+self.rect.width<(vehicles[self.direction][self.lane][self.index-1].x -
moving_Gap) or vehicles[self.direction][self.lane][self.index-
1].turned==1)):
self.x += self.speed
else:
if(self.turned==0):
self.rotateAngle += rotationAngle
self.image =
pygame.transform.rotate(self.originalImage, -self.rotateAngle)
self.x += 2
self.y += 1.8
if(self.rotateAngle==90):
self.turned = 1
vehicles_direc[self.direction][self.lane].append(
self)
self.crossedIndex =
len(vehicles_direc[self.direction][self.lane]) - 1
else:
if(self.crossedIndex==0 or
((self.y+self.rect.height)<(vehicles_direc[self.direction][self.lane][self.crosse
dIndex-1].y - moving_Gap))):
self.y += self.speed
else:
if(self.crossed == 0):
if((self.x+self.rect.width<=self.stop or (Actual_green==0 and
Actual_yellow==0)) and (self.index==0 or
self.x+self.rect.width<(vehicles[self.direction][self.lane][self.index-1].x -
moving_Gap))):
self.x += self.speed
else:
if((self.crossedIndex==0) or
(self.x+self.rect.width<(vehiclesNot_direc[self.direction][self.lane][self.crosse
dIndex-1].x - moving_Gap))):
self.x += self.speed
elif(self.direction=='down'):
if(self.crossed==0 and
self.y+self.rect.height>primer_stop[self.direction]):
self.crossed = 1
vehicles[self.direction]['crossed'] += 1
if(self.willTurn==0):
vehiclesNot_direc[self.direction][self.lane].append(self)
self.crossedIndex =
len(vehiclesNot_direc[self.direction][self.lane]) - 1
if(self.willTurn==1):
if(self.lane == 1):
if((self.y+self.rect.height<=self.stop or (Actual_green==1
and Actual_yellow==0) or self.crossed==1)
and (self.index==0 or
self.y+self.rect.height<(vehicles[self.direction][self.lane][self.index-1].y -
moving_Gap) )):
self.y -= self.speed
elif(self.lane == 2):
if(self.crossed==0 or
self.y+self.rect.height<mid[self.direction]['y']):
if((self.y+self.rect.height<=self.stop or
(Actual_green==1 and Actual_yellow==0) or self.crossed==1) and (self.index==0 or
self.y+self.rect.height<(vehicles[self.direction][self.lane][self.index-1].y -
moving_Gap) or vehicles[self.direction][self.lane][self.index-
1].turned==1)):
self.y += self.speed
else:
if(self.turned==0):
self.rotateAngle += rotationAngle
self.image =
pygame.transform.rotate(self.originalImage, -self.rotateAngle)
self.x -= 2.5
self.y += 2
if(self.rotateAngle==90):
self.turned = 1
vehicles_direc[self.direction][self.lane].append(
self)
self.crossedIndex =
len(vehicles_direc[self.direction][self.lane]) - 1
else:
if(self.crossedIndex==0 or
(self.x>(vehicles_direc[self.direction][self.lane][self.crossedIndex-1].x +
vehicles_direc[self.direction][self.lane][self.crossedIndex-
1].image.get_rect().width + moving_Gap))):
self.x -= self.speed
else:
if(self.crossed == 0):
if((self.y+self.rect.height<=self.stop or (Actual_green==1
and Actual_yellow==0)) and (self.index==0 or
self.y+self.rect.height<(vehicles[self.direction][self.lane][self.index-1].y -
moving_Gap))):
self.y += self.speed
else:
if((self.crossedIndex==0) or
(self.y+self.rect.height<(vehiclesNot_direc[self.direction][self.lane][self.cross
edIndex-1].y - moving_Gap))):
self.y += self.speed
elif(self.direction=='left'):
if(self.crossed==0 and self.x<primer_stop[self.direction]):
self.crossed = 1
vehicles[self.direction]['crossed'] += 1
if(self.willTurn==0):
vehiclesNot_direc[self.direction][self.lane].append(self)
self.crossedIndex =
len(vehiclesNot_direc[self.direction][self.lane]) - 1
if(self.willTurn==1):
if(self.lane == 1):
if((self.x>=self.stop or self.crossed == 1 or
(Actual_green==2 and Actual_yellow==0))
and (self.index==0 or
self.x+self.rect.width>(vehicles[self.direction][self.lane][self.index-1].x +
vehicles[self.direction][self.lane][self.index-1].image.get_rect().width +
moving_Gap))):
self.x += self.speed
elif(self.lane == 2):
if(self.crossed==0 or self.x>mid[self.direction]['x']):
if((self.x>=self.stop or (Actual_green==2 and
Actual_yellow==0) or self.crossed==1) and (self.index==0 or
self.x>(vehicles[self.direction][self.lane][self.index-1].x +
vehicles[self.direction][self.lane][self.index-1].image.get_rect().width +
moving_Gap) or vehicles[self.direction][self.lane][self.index-
1].turned==1)):
self.x -= self.speed
else:
if(self.turned==0):
self.rotateAngle += rotationAngle
self.image =
pygame.transform.rotate(self.originalImage, -self.rotateAngle)
self.x -= 1.8
self.y -= 2.5
if(self.rotateAngle==90):
self.turned = 1
vehicles_direc[self.direction][self.lane].append(
self)
self.crossedIndex =
len(vehicles_direc[self.direction][self.lane]) - 1
else:
if(self.crossedIndex==0 or
(self.y>(vehicles_direc[self.direction][self.lane][self.crossedIndex-1].y +
vehicles_direc[self.direction][self.lane][self.crossedIndex-
1].image.get_rect().height + moving_Gap))):
self.y -= self.speed
else:
if(self.crossed == 0):
if((self.x>=self.stop or (Actual_green==2 and
Actual_yellow==0)) and (self.index==0 or
self.x>(vehicles[self.direction][self.lane][self.index-1].x +
vehicles[self.direction][self.lane][self.index-1].image.get_rect().width +
moving_Gap))):
self.x -= self.speed
else:
if((self.crossedIndex==0) or
(self.x>(vehiclesNot_direc[self.direction][self.lane][self.crossedIndex-1].x +
vehiclesNot_direc[self.direction][self.lane][self.crossedIndex-
1].image.get_rect().width + moving_Gap))):
self.x -= self.speed
elif(self.direction=='up'):
#if(self.crossed==0 and
self.y+self.rect.height<primer_stop[self.direction]):
if(self.crossed==0 and self.y<primer_stop[self.direction]):
self.crossed = 1
vehicles[self.direction]['crossed'] += 1
if(self.willTurn==0):
vehiclesNot_direc[self.direction][self.lane].append(self)
self.crossedIndex =
len(vehiclesNot_direc[self.direction][self.lane]) - 1
if(self.willTurn==1):
if(self.lane == 1):
if((self.y>=self.stop or self.crossed == 1 or
(Actual_green==3 and Actual_yellow==0))
and (self.index==0 or
self.y+self.rect.height>(vehicles[self.direction][self.lane][self.index-1].y +
vehicles[self.direction][self.lane][self.index-1].image.get_rect().height +
moving_Gap))):
self.y += self.speed
elif(self.lane == 2):
if(self.crossed==0 or self.y>mid[self.direction]['y']):
if((self.y>=self.stop or (Actual_green==3 and
Actual_yellow==0) or self.crossed == 1) and (self.index==0 or
self.y>(vehicles[self.direction][self.lane][self.index-1].y +
vehicles[self.direction][self.lane][self.index-1].image.get_rect().height
+ moving_Gap) or vehicles[self.direction][self.lane][self.index-1].turned==1)):
self.y -= self.speed
else:
if(self.turned==0):
self.rotateAngle += rotationAngle
self.image =
pygame.transform.rotate(self.originalImage, -self.rotateAngle)
self.x += 1
self.y -= 1
if(self.rotateAngle==90):
self.turned = 1
vehicles_direc[self.direction][self.lane].append(
self)
self.crossedIndex =
len(vehicles_direc[self.direction][self.lane]) - 1
else:
if(self.crossedIndex==0 or
(self.x<(vehicles_direc[self.direction][self.lane][self.crossedIndex-1].x -
vehicles_direc[self.direction][self.lane][self.crossedIndex-
1].image.get_rect().width - moving_Gap))):
self.x += self.speed
else:
if(self.crossed == 0):
if((self.y>=self.stop or (Actual_green==3 and
Actual_yellow==0)) and (self.index==0 or
self.y>(vehicles[self.direction][self.lane][self.index-1].y +
vehicles[self.direction][self.lane][self.index-1].image.get_rect().height +
moving_Gap))):
self.y -= self.speed
else:
if((self.crossedIndex==0) or
(self.y>(vehiclesNot_direc[self.direction][self.lane][self.crossedIndex-1].y +
vehiclesNot_direc[self.direction][self.lane][self.crossedIndex-
1].image.get_rect().height + moving_Gap))):
self.y -= self.speed
class Persona(pygame.sprite.Sprite):
def __init__(self, lane, persona_class, direc_Num, direction, turno_rand):
pygame.sprite.Sprite.__init__(self)
self.lane = lane
self.persona_class = persona_class
self.speed = velocity[persona_class]
self.direc_Num = direc_Num
self.direction = direction
self.x = x_ni[direction][lane]
self.y = y_ni[direction][lane]
self.crossed = 0
self.crossed_per = 0
self.willTurn = turno_rand
self.turned = 0
self.rotateAngle = 0
persona[direction][lane].append(self)
self.index = len(persona[direction][lane]) - 1
self.crossedIndex = 0
path_ni = "images/" + direction + "/" + persona_class + ".png"
self.originalImage = pygame.image.load(path_ni)
if(len(persona[direction][lane])>1 and
persona[direction][lane][self.index-1].crossed==0):
if(direction=='right'):
self.stop = persona[direction][lane][self.index-1].stop
- persona[direction][lane][self.index-1].image.get_rect().width
- gap_ni
#print("right",self.stop)
elif(direction=='left'):
self.stop = persona[direction][lane][self.index-1].stop
+ persona[direction][lane][self.index-1].image.get_rect().width
+ gap_ni
#print("left",self.stop)
elif(direction=='down'):
self.stop = persona[direction][lane][self.index-1].stop
- persona[direction][lane][self.index-1].image.get_rect().height
- gap_ni
#print("down",self.stop)
elif(direction=='up'):
self.stop = persona[direction][lane][self.index-1].stop
+ persona[direction][lane][self.index-1].image.get_rect().height
+ gap_ni
#print("up",self.stop)
else:
self.stop = segundo_stop_ni[direction]
# print("else",self.stop)
elif(direction=='left'):
tmp = self.rect.width + gap_ni
x[direction][lane] -= tmp
elif(direction=='down'):
tmp = self.rect.height + gap_ni
y[direction][lane] -= tmp
elif(direction=='up'):
tmp = self.rect.height + gap_ni
y[direction][lane] += tmp
Sprite.add(self)
def move(self):
if(self.direction=='right'):
if(self.crossed==0 and
self.x+self.rect.width>primer_stop_ni[self.direction]and (Actual_green==0 and
Actual_yellow==0)): # if the image has crossed stop line now
self.crossed = 1
if((self.x+self.rect.width<=self.stop or self.crossed == 1 or
(Actual_green==0 and Actual_yellow==0))
and (self.index==0 or
self.x+self.rect.width<(persona[self.direction][self.lane][self.index-1].x -
moving_Gap))):
# (if the image has not reached its stop coordinate or has crossed
stop line or has green signal)
# and (it is either the first vehicle in that lane or it is has
enough gap to the next vehicle in that lane)
self.x += self.speed # move the vehicle
elif(self.direction=='down'):
if(self.crossed==0 and
self.y+self.rect.height>primer_stop_ni[self.direction]and (Actual_green==1 and
Actual_yellow==0)):
self.crossed = 1
if((self.y+self.rect.height<=self.stop or self.crossed == 1 or
(Actual_green==1 and Actual_yellow==0))
and (self.index==0 or
self.y+self.rect.height<(persona[self.direction][self.lane][self.index-1].y -
moving_Gap))):
self.y += self.speed
elif(self.direction=='left'):
if(self.crossed==0 and self.x<primer_stop_ni[self.direction]and
(Actual_green==2 and Actual_yellow==0)):
self.crossed = 1
if((self.x>=self.stop or self.crossed == 1 or (Actual_green==2 and
Actual_yellow==0))
and (self.index==0 or
self.x>(persona[self.direction][self.lane][self.index-1].x +
persona[self.direction][self.lane][self.index-1].image.get_rect().width +
moving_Gap))):
self.x -= self.speed
elif(self.direction=='up'):
if(self.crossed==0 and self.y<primer_stop_ni[self.direction]and
(Actual_green==3 and Actual_yellow==0)):
self.crossed = 1
if((self.y>=self.stop or self.crossed == 1 or (Actual_green==3 and
Actual_yellow==0))
and (self.index==0 or
self.y>(persona[self.direction][self.lane][self.index-1].y +
persona[self.direction][self.lane][self.index-1].image.get_rect().height +
moving_Gap))):
self.y -= self.speed
def repeat():
global Actual_green, Actual_yellow, Next_green
for i in range(0,3):
for person in persona[directionNumbers[Actual_green]][i]:
person.stop = segundo_stop_ni[directionNumbers[Actual_green]]
if(tmp<dist[0]):
direc_Num = 0
elif(tmp<dist[1]):
direc_Num = 1
elif(tmp<dist[2]):
direc_Num = 2
elif(tmp<dist[3]):
direc_Num = 3
Vehicle(lane_number, vehicleTypes[vehicle_type], direc_Num,
directionNumbers[direc_Num], turno_rand)
#Persona(lane_number, personaTypes[persona_type], direc_Num,
directionNumbers[direc_Num], turno_rand)
time.sleep(1)
def generatePersona():
while(True):
persona_type = random.choice(tipos_personaList)
lane_number = random.randint(1,2)
turno_rand = 0
if(lane_number == 1):
tmp = random.randint(0,99)
if(tmp<40):
turno_rand = 1
elif(lane_number == 2):
tmp = random.randint(0,99)
if(tmp<40):
turno_rand = 1
tmp = random.randint(0,99)
direc_Num = 0
dist = [25,50,75,100]
if(tmp<dist[0]):
direc_Num = 0
elif(tmp<dist[1]):
direc_Num = 1
elif(tmp<dist[2]):
direc_Num = 2
elif(tmp<dist[3]):
direc_Num = 3
Persona(lane_number, personaTypes[persona_type], direc_Num,
directionNumbers[direc_Num], turno_rand)
time.sleep(1)
def showStats():
totalVehicles = 0
print('Direction-wise Vehicle Counts')
for i in range(0,4):
if(signals[i]!=None):
print('Direction',i+1,':',vehicles[directionNumbers[i]]['crossed'])
totalVehicles += vehicles[directionNumbers[i]]['crossed']
print('Total vehicles passed:',totalVehicles)
print('Total time:',elapsed_time)
def simTime():
global elapsed_time, tiempito
while(True):
elapsed_time += 1
time.sleep(1)
if(elapsed_time==tiempito):
showStats()
os._exit(1)
def collision(self):
# collision
coll_indices = []
for i in range(0,len(car_group)):
for j in range(0,len(car_group)):
if j != i and pygame.sprite.collide_rect(car_group.sprites()[j],
car_group.sprites()[i]):
coll_dict = {"index" : i, "angle" :
car_group.sprites()[i].angle, "x":car_group.sprites()[i].rect.x,
"y":car_group.sprites()[i].rect.y}
coll_indices.append(coll_dict)
break
return coll_indices
class Main:
global tipos_vehicleList
global tipos_personaList
i = 0
for vehicleType in tipos_vehicle:
if(tipos_vehicle[vehicleType]):
tipos_vehicleList.append(i)
i += 1
j = 0
for personaType in tipos_persona:
if(tipos_persona[personaType]):
tipos_personaList.append(j)
j += 1
operation1 = threading.Thread(name="initialization",target=initialize,
args=()) # initialization
operation1.daemon = True
operation1.start()
# Colours
black = (0, 0, 0)
white = (64, 255, 0)
# Screensize
fondoWidth = 1400
fondoHeight = 800
fondoSize = (fondoWidth, fondoHeight)
fondo = pygame.display.set_mode(fondoSize)
pygame.display.set_caption("Traffic system Sprite by Grace")
operation2 =
threading.Thread(name="generateVehicles",target=generateVehicles, args=()) #
Generating vehicles
operation2.daemon = True
operation2.start()
#### persona hilo
operation3 = threading.Thread(name="generatePersona",target=generatePersona,
args=()) # Generating vehicles
operation3.daemon = True
operation3.start()
###### persona hilo
operation4 = threading.Thread(name="simTime",target=simTime, args=())
operation4.daemon = True
operation4.start()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
showStats()
sys.exit()
le_groupe = pygame.sprite.Group()
for person in le_groupe:
fondo.blit(person.image, [person.x, person.y])
person.move()
pygame.display.update()
Main()