0% found this document useful (0 votes)
23 views

Codigo

This document defines variables and classes for simulating vehicle traffic at an intersection with four signals. It initializes values like vehicle positions and speeds, signal timings, and defines classes for vehicles and signals. The vehicle class handles movement and rendering based on signal states. Complex logic manages vehicle order and turning.

Uploaded by

ksevillanocolina
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Codigo

This document defines variables and classes for simulating vehicle traffic at an intersection with four signals. It initializes values like vehicle positions and speeds, signal timings, and defines classes for vehicles and signals. The vehicle class handles movement and rendering based on signal states. Complex logic manages vehicle order and turning.

Uploaded by

ksevillanocolina
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

import random

import time
import threading
import pygame
import sys
import os

# Default values of signal timers


Green_default = {0:10, 1:10, 2:10, 3:10}
Red_default = 150
Yellow_default = 5

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

x_ni = {'right':[0,0,0], 'down':[885,860,835], 'left':[1400,1400,1400],


'up':[485,510,535]} ##NO CAMBIAR
y_ni = {'right':[190,215,240], 'down':[0,0,0], 'left':[513,538,563],
'up':[800,800,800]} ###NO CAMBIAR

vehicles = {'right': {0:[], 1:[], 2:[], 'crossed':0},


'down': {0:[], 1:[], 2:[], 'crossed':0},
'left': {0:[], 1:[], 2:[], 'crossed':0},
'up': {0:[], 1:[], 2:[], 'crossed':0}}

persona = {'right': {0:[], 1:[], 2:[], 'crossed':0},


'down': {0:[], 1:[], 2:[], 'crossed':0},
'left': {0:[], 1:[], 2:[], 'crossed':0},
'up': {0:[], 1:[], 2:[], 'crossed':0}}

personaTypes = { 0:'ni1', 1:'ni2', 2:'ni3'}


vehicleTypes = { 0:'car1'
,1:'car2',2:'car3',3:'car4',4:'car5',5:'car6'
,6:'bus1', 7:'truck1'
,8:'bike1',9:'bike2',10:'bike3',11:'bike4',12:'bike5',13:'bike6'}

directionNumbers = {0:'right', 1:'down', 2:'left', 3:'up'}

# Coordinates of signal image, timer, and vehicle count


ubi_semaforo = [(455,136),(903,136),(903,598),(455,598)]
signalTimerCoods = [(455,113),(905,113),(905,582),(455,583)]

# Coordinates of stop lines


primer_stop = {'right': 544, 'down': 248, 'left': 847, 'up': 552} ###no cAMBIAR
segundo_stop = {'right': 433, 'down': 137, 'left': 958, 'up': 663}##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

# Gap between vehicles


gap = 25 # stopping gap
moving_Gap = 25 # moving gap

# Gap between vehicles


gap_ni = 10 # stopping gap
moving_Gap_ni = 10 # moving gap

# set allowed vehicle types here


tipos_vehicle = { 'car1': True,'car2': True,'car3': True,'car4': True,'car5':
True,'car6': True
, 'bus1': True, 'truck1': True
,'bike1': True,'bike2': True,'bike3': True,'bike4':
True,'bike5': True,'bike6': True}

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:[]}}

tipos_persona = {'ni1': True, 'ni2': True, 'ni3': True}


tipos_personaList = []

rotationAngle = 3

mid = { 'right': {'x':711,'y':382},


'down': {'x':722,'y':422},
'left': {'x':705,'y':423},
'up': {'x':725,'y':382}}
# set random or default green signal time here
rd_green_time = True
# set random green signal time range here
rd_green_timeRange = [10,20]

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]

# Set new starting and stopping coordinate


if(direction=='right'):
tmp = self.rect.width + gap
x[direction][lane] -= tmp

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 render(self, fondo):


fondo.blit(self.image, (self.x, self.y))

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)

self.image = pygame.image.load(path_ni) ####OBJETO EN MOVIMIENTO


self.rect = self.image.get_rect()

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)

# Set new starting and stopping coordinate


if(direction=='right'):
tmp = self.rect.width + gap_ni
x[direction][lane] -= tmp

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 render(self, fondo):


fondo.blit(self.image, (self.x, self.y))

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

# Initialization of signals with default values


def initialize():
minTime = rd_green_timeRange[0]
maxTime = rd_green_timeRange[1]
if(rd_green_time):
ts1 = Semaforo(0, Yellow_default, random.randint(minTime,maxTime))
signals.append(ts1)
ts2 = Semaforo(ts1.red+ts1.yellow+ts1.green, Yellow_default,
random.randint(minTime,maxTime))
signals.append(ts2)
ts3 = Semaforo(Red_default, Yellow_default,
random.randint(minTime,maxTime))
signals.append(ts3)
ts4 = Semaforo(Red_default, Yellow_default,
random.randint(minTime,maxTime))
signals.append(ts4)
else:
ts1 = Semaforo(0, Yellow_default, Green_default[0])
signals.append(ts1)
ts2 = Semaforo(ts1.yellow+ts1.green, Yellow_default, Green_default[1])
signals.append(ts2)
ts3 = Semaforo(Red_default, Yellow_default, Green_default[2])
signals.append(ts3)
ts4 = Semaforo(Red_default, Yellow_default, Green_default[3])
signals.append(ts4)
repeat()

# Print the signal timers on cmd


def printStatus():
for i in range(0, 4):
if(signals[i] != None):
if(i==Actual_green):
if(Actual_yellow==0):
print(" GREEN TS",i+1,"-> r:",signals[i].red,"
y:",signals[i].yellow," g:",signals[i].green)
else:
print("YELLOW TS",i+1,"-> r:",signals[i].red,"
y:",signals[i].yellow," g:",signals[i].green)
else:
print(" RED TS",i+1,"-> r:",signals[i].red,"
y:",signals[i].yellow," g:",signals[i].green)
print()

def repeat():
global Actual_green, Actual_yellow, Next_green

while(signals[Actual_green].green>0): # while the timer of current green


signal is not zero
printStatus()
updateValues()
time.sleep(1)
Actual_yellow = 1 # set yellow signal on
# reset stop coordinates of lanes and vehicles
for i in range(0,3):
for vehicle in vehicles[directionNumbers[Actual_green]][i]:
vehicle.stop = segundo_stop[directionNumbers[Actual_green]]

for i in range(0,3):
for person in persona[directionNumbers[Actual_green]][i]:
person.stop = segundo_stop_ni[directionNumbers[Actual_green]]

while(signals[Actual_green].yellow>0): # while the timer of current yellow


signal is not zero
printStatus()
updateValues()
time.sleep(1)
Actual_yellow = 0 # set yellow signal off

# reset all signal times of current signal to default/random times


if(rd_green_time):
signals[Actual_green].green =
random.randint(rd_green_timeRange[0],rd_green_timeRange[1])
else:
signals[Actual_green].green = Green_default[Actual_green]
signals[Actual_green].yellow = Yellow_default
signals[Actual_green].red = Red_default

Actual_green = Next_green # set next signal as green signal


Next_green = (Actual_green+1)%Numero_signals # set next green signal
signals[Next_green].red =
signals[Actual_green].yellow+signals[Actual_green].green # set the red time of
next to next signal as (yellow time + green time) of next signal
repeat()

# Update values of the signal timers after every second


def updateValues():
for i in range(0, Numero_signals):
if(i==Actual_green):
if(Actual_yellow==0):
signals[i].green -=1
else:
signals[i].yellow -=1
else:
signals[i].red-=1

# Generating vehicles in the Sprite


def generateVehicles():
while(True):
vehicle_type = random.choice(tipos_vehicleList)
lane_number = random.randint(1,2)
turno_rand = 0
if(lane_number == 1):
tmp = random.randint(0,99)
if(tmp<35):
turno_rand = 1
elif(lane_number == 2):
tmp = random.randint(0,99)
if(tmp<35):
turno_rand = 1
tmp = random.randint(0,99)
direc_Num = 0
dist = [25, 50, 75, 105]

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)

# Setting background image i.e. image of intersection


background = pygame.image.load('images/intersection3.png')

fondo = pygame.display.set_mode(fondoSize)
pygame.display.set_caption("Traffic system Sprite by Grace")

# Loading signal images and font


redSignal = pygame.image.load('images/signals/red1.png')
yellowSignal = pygame.image.load('images/signals/yellow1.png')
greenSignal = pygame.image.load('images/signals/green1.png')
font = pygame.font.Font(None, 30)

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()

fondo.blit(background,(0,0)) # display background in Sprite


for i in range(0,Numero_signals): # display signal and set timer
according to current status: green, yello, or red
if(i==Actual_green):
if(Actual_yellow==1):
signals[i].signalText = signals[i].yellow
fondo.blit(yellowSignal, ubi_semaforo[i])
else:
signals[i].signalText = signals[i].green
fondo.blit(greenSignal, ubi_semaforo[i])
else:
if(signals[i].red<=10):
signals[i].signalText = signals[i].red
else:
signals[i].signalText = "---"
fondo.blit(redSignal, ubi_semaforo[i])
signalTexts = ["","","",""]

# display signal timer


for i in range(0,Numero_signals):
signalTexts[i] = font.render(str(signals[i].signalText), True, white,
black)
fondo.blit(signalTexts[i],signalTimerCoods[i])

# display time elapsed


elapsed_timeText = font.render(("Time Elapsed: "+str(elapsed_time)),
True, black, white)
fondo.blit(elapsed_timeText,time_semaforo)
# display the vehicles
for veh in Sprite:
fondo.blit(veh.image, [veh.x, veh.y])
veh.move()

for person in Sprite:


fondo.blit(person.image, [person.x, person.y])
person.move()

le_groupe = pygame.sprite.Group()
for person in le_groupe:
fondo.blit(person.image, [person.x, person.y])
person.move()

pygame.display.update()

Main()

You might also like