예제 #1
0
	def __init__(self):
		self.car = Car(self.TRACK_LENGHT)
		self.road = Road()
		self.ambient = self.init_ambient() #lista de objetos que nao colidem com o carro
		self.obstacles = self.init_obstacles()
		self.angle = 50
		self.game_over = False
예제 #2
0
 def main(self, startT, endT):
     FEL = []
     #Generate Queue at enters
     Q0 = self.genQueue(startT, endT, True)
     Q1 = self.genQueue(startT, endT, False)
     Q2 = self.genQueue(startT, endT, False)
     Q3 = self.genQueue(startT, endT, False)
     #Generate four roads with its length and number of sections and IDs
     Road0 = Road.Road(0.2, 2, 2, 0)
     Road1 = Road.Road(0.8, 8, 2, 1)
     Road2 = Road.Road(0.8, 8, 2, 2)
     Road3 = Road.Road(0.4, 4, 2, 3)
     self.roadDic[0] = Road0
     self.roadDic[1] = Road1
     self.roadDic[2] = Road2
     self.roadDic[3] = Road3
     #Put the queue at enters into the Future Event List(FEL)
     for car in Q0:
         j = int(random() // (1 / 2))
         heapq.heappush(FEL, [car.T, "enter0", car.ID, j])
     for car in Q1:
         heapq.heappush(FEL, [car.T, "enter1", car.ID, 0])
     for car in Q2:
         heapq.heappush(FEL, [car.T, "enter2", car.ID, 0])
     for car in Q3:
         heapq.heappush(FEL, [car.T, "enter3", car.ID, 0])
     #Use carHistory to record information of event with the index of Car's ID
     self.carHistory = [[] for _ in range(self.ID + 1)]
     #record wait time at entry due to conflict
     Waittime_sofar = [0] * 3
     Lastvehicle_outtime = [0] * 3
     #Start FEL
     while FEL:
         event = heapq.heappop(FEL)
         curtime = event[0]
         event_list = [event]
         while FEL and FEL[0][0] == curtime:
             event_list.append(heapq.heappop(FEL))
         for event in event_list:
             ID = event[-2]
             self.carHistory[ID].append(event)
         self.conflict(event_list, Waittime_sofar, Lastvehicle_outtime, FEL)
         for event in event_list:
             ID = event[-2]
             car = self.carDic[event[2]]
             if event[0] > endT: break
             if event[1] in {"enter0", "enter1", "enter2", "enter3"}:
                 road = self.roadDic[int(event[1][-1])]
                 self.enter(car, FEL, road, event[-1])
             elif event[1] in {"exit0", "exit1", "exit2", "exit3"}:
                 road = self.roadDic[int(event[1][-1])]
                 self.exit(car, FEL, road, event[-1])
             else:
                 Road_n = int(event[1][-3])
                 intersection_n = [int(event[1][-1]), event[-1]]
                 self.proceed(car, FEL, Road_n, intersection_n)
예제 #3
0
def main():

    r = []
    r.append(Road(40, 1, 1000, "Hostetter"))  #r[0]

    r.append(Road(40, 1, 1000, "Berryessa"))  #r[1]
    r.append(Road(40, 1, 1000, "Penitencia"))  #r[2]
    r.append(Road(40, 1, 1000, "Piedmont"))  #r[3]

    r.append(Road(40, 1, 1000, "Piedmont"))  #r[4]
    r.append(Road(40, 1, 1000, "Piedmont"))  #r[5]

    r.append(Road(40, 1, 1000, "Capitol"))  #r[6]
    r.append(Road(40, 1, 1000, "Capitol"))  #r[7]
    r.append(Road(40, 1, 1000, "Capitol"))  #r[8]

    r[0].getEndIntersection().setSouthmostRoad(r[6])
    r[0].getEndIntersection().setEastmostRoad(r[1])
    # Theres got to be a better wat to do this

    #    r0.end_intersection.setEastmostRoad(r1)

    print(r[0])
    print(r[1])
    print(r[0].getEndIntersection().getTravelOptions())
    print(r[0].getEndIntersection().intersection_name)
예제 #4
0
    def deadendSetup(self):

        count = 0
        print(len(self.roads))
        self.deadendsMax = floor(len(self.roads) / 100 * self.deFrequency)

        print(self.deadendsMax)

        selectedList = []

        for roadIdx in range(0, len(self.roads) - 2):
            selectedList.append(self.roads[roadIdx])

        while (count < self.deadendsMax):

            target = choice(selectedList)
            targetID = target.getRoadID()

            startID = target.getFromID()
            endID = target.getToID()
            keysList = target.getMid()
            limit = target.getLimit()
            #def __init__(self, map, start, end, roadID,startingRoomID,destinationID,*randomRoad):
            deadend = Road(self.dMap, keysList[0], keysList[1],
                           (targetID + len(self.roads) * 2), startID, endID,
                           limit)

            self.deadends.append(deadend)
            selectedList.remove(target)
            count += 1

        return self.deadends
예제 #5
0
    def roadGen(self):
        self.roadcontainer.clear_widgets()
        Localdefs.roadlist = list()

        for pathnum in range(0, len(self.movelists)):
            x = 0
            for square in self.pathrectlists[pathnum]:
                localized = (self.background.to_local(square[0], square[1]))
                localized = (localized[0], localized[1], square[2], square[3])
                if pathnum > 0:
                    if self.checkDupRoad(localized):
                        break
                Road.Road(localized, square, x, pathnum)
                x += 1

        if not self.baseimg:
            self.baseimg = Image(source=os.path.join('backgroundimgs',
                                                     'Base.png'),
                                 allow_stretch=True,
                                 size=(__main__.app.root.squsize * 3 - 3,
                                       __main__.app.root.squsize * 3 - 3),
                                 id='Base')
            pos = (self.basepoint[0] * __main__.app.root.squsize,
                   self.basepoint[1] * __main__.app.root.squsize -
                   (self.baseimg.size[1] / 3))
            pos = self.background.to_local(*pos)
            self.baseimg.pos = pos
            self.baseimg.type = 'Base'
            self.towercontainer.add_widget(self.baseimg)

        else:
            self.baseimg.pos = self.background.to_local(
                self.basepoint[0] * __main__.app.root.squsize,
                self.basepoint[1] * __main__.app.root.squsize -
                (self.baseimg.size[1] / 3))
예제 #6
0
    def __init__(self, dt=0.25, trafficWeight=1):
        """ The default constructor for the Model """

        # self.test_agent = Agent.Agent()
        self.trafficWeight = trafficWeight

        self.gate = Gate.Gate()

        self.campus_way_road = Road.Road(2, 2, 3)

        self.south_garage = Garage.Garage("South Garage",
                                          num_spot=771,
                                          num_carpool_spot=23,
                                          num_handicapped_spot=20,
                                          num_bike_spot=12,
                                          garage_width=31)

        self.school = School.School()

        self.num_days = 30
        self.dt = 0.15

        self.plot_figure = None
        self.plot_axis = None
        self.plot_image = None

        #Tracks utilization per time step.
        self.utilization = []
예제 #7
0
 def __init__(self, user_info={}):
     self.user_info = user_info
     self.enemyInfo = dict()
     self.enemy_num = 0
     self.zombie_num = 0
     self.ack_que = Queue.Queue(32)
     self.req_que = Queue.Queue(32)
     self.road = Road.Road()
예제 #8
0
	def setupObjects(self):
		"""Get all the road tiles ready."""

		for y in range(self.height):
			for x in range(self.width):
				tempType = self.getSquare(x, y)
				if tempType <= 11:
					xCoord = float(x)
					yCoord = float(y)
					tempObject = Road.Road(tempType)
					tempObject.setPosition(xCoord * 12.0, (float(self.height) - yCoord) * 12.0, 0.0)
					self.mapObjects.append(tempObject)
예제 #9
0
    def entranceCreating(self):

        directionList = [(1, 1), (0, 1)]
        direction = choice(directionList)
        reversedDirection = (direction[0], direction[1] * -1)

        endNode = self.mapping[0][0].get('doors').get(reversedDirection)[0]
        roomID = self.mapping[0][0].get('room')

        ##def __init__(self, map, start, end, roadID,startingRoomID,destinationID):
        entrance = Road(self.dMap, (0, 0), endNode, -1, -1, roomID)

        return entrance
예제 #10
0
    def roadCreating(self):

        for field in self.mapping[0]:

            startCandidates = field.get('neightborDirection')
            startNeightbor = field.get('neightbor')

            if field.get('room') != 0:

                while len(startNeightbor) != 0:

                    startFieldID = field.get('fieldID')
                    endFieldID = field.get('neightbor')[0]

                    startDirection = startCandidates[0]
                    start = field.get('doors').get(startDirection)[0]

                    endFieldSelected = self.mapping[0][endFieldID]
                    endDirection = (startCandidates[0][0],
                                    startCandidates[0][1] * -1)
                    endRoom = endFieldSelected.get('room')

                    if endRoom == 0:

                        startNeightbor.remove(endFieldID)
                        startCandidates.remove(startDirection)
                        endFieldSelected.get('neightbor').remove(startFieldID)
                        endFieldSelected.get('neightborDirection').remove(
                            endDirection)

                    else:

                        end = endFieldSelected.get('doors').get(
                            endDirection)[0]
                        startNeightbor.remove(endFieldID)
                        startCandidates.remove(startDirection)

                        endFieldSelected.get('neightbor').remove(startFieldID)
                        endFieldSelected.get('neightborDirection').remove(
                            endDirection)
                        #def __init__(self, map, start, end, roadID,startingRoomID,destinationID):
                        tempRoad = Road(self.dMap, start, end, 1, startFieldID,
                                        endFieldID)
                        self.roads.append(tempRoad)

        self.roads.append(self.entranceCreating())
        self.roads.append(self.exitCreating())
        self.deadends.extend(self.deadendSetup())

        self.printRoad()
예제 #11
0
 def set_road(self,spotname_1,spotname_2,dist,cost):
     try:
         i = self.spots.index(spotname_1)
         j = self.spots.index(spotname_2)
         r = Road(dist,cost)
         if i != j:
             self.data[j][i] = r
             self.data[i][j] = r
         else:
             print('请勿输入同一个景点。')
     except:
         print('请输入合法的景点名称。')
     self.set_costshortest()
     self.set_timeshortest()
     self.set_transhortest()
예제 #12
0
def main():
    """The main program."""

    # Initialize Pygame

    pygame.init()

    # First we set some stuff up.

    prefs = Preferences.Preferences()
    prefs.loadPreferences()
    video = Video.Video(prefs)
    video.prepareVideo()

    carObject = Car.Car()
    groundObject = Road.Road(1)

    carDir = 0.0

    while 1:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        carDir += 1.0
        if (carDir >= 360.0):
            carDir -= 360.0
        carObject.setAngle(carDir)

        video.prepareNewFrame()
        video.setupCamera()
        video.setupLights()

        # Drawing happens here

        glLoadIdentity()

        #		drawReference(0.0, 0.0, 0.0, 1.0)

        groundObject.draw()
        carObject.draw()

        video.finishNewFrame()

        pygame.time.wait(33)
    def create_hubs(self, num_hubs, speed):
        for hub in ['hub{}'.format(x) for x in range(num_hubs)]:
            self.world['hubs'][hub] = Hub.Hub(hub)
            self.world['hubs'][hub].x = random.random()
            self.world['hubs'][hub].y = random.random()

        for hubA in self.world['hubs']:
            dist = []
            for hubB in self.world['hubs']:
                distance = self.distance(self.world['hubs'][hubA].x,
                                         self.world['hubs'][hubA].y,
                                         self.world['hubs'][hubB].x,
                                         self.world['hubs'][hubB].y)
                if distance != 0 and hubB not in self.world['hubs'][
                        hubA].connections:
                    dist.append([distance, hubB])

            connections = []
            number_connections = random.randint(1, 2)
            passes = 1
            while passes <= number_connections and dist != []:
                min = []
                for element in dist:
                    if min == [] or min[0] > element[0]:
                        min = [element[0], element[1], dist.index(element)]
                dist.pop(min[2])
                connections.append(min[1])
                self.world['hubs'][min[1]].connections.append(hubA)
                passes += 1

            for node in connections:
                self.world['hubs'][hubA].connections.append(node)

        for hubA in self.world['hubs']:
            for hubB in self.world['hubs'][hubA].connections:
                x1 = self.world['hubs'][hubA].x
                y1 = self.world['hubs'][hubA].y
                x2 = self.world['hubs'][hubB].x
                y2 = self.world['hubs'][hubB].y

                self.world['hubs'][hubA].roads[hubB] = Road.Road(
                    '{}:{}'.format(hubA, hubB), x1, y1, x2, y2, speed)
                self.world['hubs'][hubA].park['Trailer{}:{}'.format(
                    hubA, hubB)] = Trailer.Trailer(self.world['hubs'][hubA],
                                                   self.world['hubs'][hubB])
예제 #14
0
    def __init__(self, budget, patches, numDumpTrucks, numOilTrucks):

        self.simClock = 0
        self.totalSimTime = 0
        self.budget = budget
        self.timePoints = []

        ###### Cubic Feet, Gallons, int Location ######
        self.stockpile = Stockpile.Stockpile(1000, 11600, 0)

        self.road = Road.Road(patches)

        self.chipper = Chipper.Chipper(30, 40, 'Chipper')

        self.flaggerOne = Pickup.Pickup(5, 8, 'Pickup')
        self.flaggerTwo = Pickup.Pickup(5, 8, 'Pickup')
        self.pilotCar = Pickup.Pickup(5, 8, 'Pickup')

        self.numDumpTrucks = []
        for i in range(numDumpTrucks):
            self.numDumpTrucks.append(
                Dumptruck.Dumptruck(10, 20, 'Dumptruck ' + str(i + 1),
                                    self.stockpile, self.chipper))

        self.numOilTrucks = []
        for i in range(numOilTrucks):
            self.numOilTrucks.append(
                Oiltruck.Oiltruck(30, 40, 'Distributor ' + str(i + 1),
                                  self.stockpile))

        self.pickup = Pickup.Pickup(5, 8, 'Pickup')
        self.ironwolf = Ironwolf.Ironwolf(10, 30, 'Ironwolf')
        self.grader = Grader.Grader(40, 80, 'Grader')

        self.rtr = RubberTireRoller.RubberTireRoller(15, 30, 'RTR')

        self.oilArrivalTime = 0
        self.day = 1

        self.oilDeliveryTime = 0
        self.d1DeliveryTime = 0

        self.costPerDayList = []
예제 #15
0
    def exitCreating(self):

        directionList = [(1, 1), (0, 1)]
        direction = choice(directionList)
        print(direction)

        for f in range(len(self.mapping[0]) - 1, -1, -1):
            room = self.mapping[0][f].get('room')
            if room != 0:
                startNode = self.mapping[0][f].get('doors').get(direction)[0]
                roomID = self.mapping[0][f].get('room')

                endNode = [self.shape[0] - 1, self.shape[1] - 1]

                #def __init__(self, map, start, end, roadID,startingRoomID,destinationID):
                exit = Road(self.dMap, startNode, endNode, -1, -1, roomID)

                break

        return exit
예제 #16
0
 def build_item(self, object_to_build_on):
     """
     The Game_Engine uses this method in order to instantiate the object that the build() method has determined as
     the valid object to instantiate after previous checks, check_location() and player_inventory() methods, have
     returned a True boolean value.
     Args:
         object_to_build_on (object): An object argument that is passed to this method to determine which object that
         the build() method, that invoked this method, is attempting to instantiate.
     Returns:
          None
     """
     if object_to_build_on is None:
         self.game_state.current_player.inventory.add_dev_card(Development_Card.Development_Card())
         return True
     elif type(object_to_build_on) is Vertex.Vertex and object_to_build_on.settlement is None:
         if object_to_build_on.city is None:
             self.game_state.add_invalid_vertices_to_build(object_to_build_on)
             object_to_build_on.settlement = Settlement.Settlement(object_to_build_on)
             object_to_build_on.settlement.owner = self.game_state.current_player
             self.game_state.current_player.inventory.add_settlement(object_to_build_on.settlement)
             return True
         else:
             return False
     elif type(object_to_build_on) is Vertex.Vertex and object_to_build_on.settlement.owner ==\
             self.game_state.current_player:
         object_to_build_on.settlement = None
         object_to_build_on.city = City.City(object_to_build_on)
         object_to_build_on.city.owner = self.game_state.current_player
         self.game_state.current_player.inventory.add_city(object_to_build_on.city)
         # TODO: uniformize this output
         return 'city'
     elif type(object_to_build_on) is Edge.Edge and self.game_state.not_on_opp_sett(object_to_build_on):
         object_to_build_on.road = Road.Road(object_to_build_on)
         object_to_build_on.road.owner = self.game_state.current_player
         self.game_state.current_player.inventory.add_road(object_to_build_on.road)
         return True
예제 #17
0
파일: drive.py 프로젝트: pidipidi/PyCar
from Startup import*
from Car import*
from Road import*
import pickle, os
import numpy as np
import random

vehicle  = Car(250, random.choice([height/2+40, height/2-20]))
road     = Road()
vehicle1 = Car(width/2+100, height/2+40)


def display_all(main_surface, display_list, text_list):
    main_surface.fill((0, 100, 100))
    for element in display_list:
        element.display(main_surface)
    for element_val in range(0, len(text_list)):
        main_surface.blit(font.render(str(text_list[element_val]), True, (0, 255, 0)), (10, 10 + (10 * element_val)))


def update_all(update_list):
    for element in update_list:
        element.update()


# make a plan
traj = np.array([np.random.normal(1,1.0,550),
                 np.random.normal(0,1.0,550)])
## traj = np.array([np.linspace(1.0, 1.0, 550),
##                  np.linspace(0, 0, 550)])
예제 #18
0
'''
Test to make sure everything builds.
'''

# test board structures
edge = Edge.Edge()
vertex = Vertex.Vertex()
tile = Tile.Tile()
print('board structures built')

# test Board
board = Board.Board()
print('board builds')

# test Structures
road = Road.Road(edge)
settlement = Settlement.Settlement(vertex)
city = City.City(vertex)
print('structures build')

# test players
player1 = Player.Player(None, 'red', 'red')
player2 = Player.Player(None, 'blue', 'blue')
player1.inventory.brick += 10000
player1.inventory.grain += 10000
player1.inventory.lumber += 10000
player1.inventory.ore += 10000
player1.inventory.wool += 10000
players = [player1, player2]
print('players build')
예제 #19
0
import pygame
from Road import *
from Map import *

model = Road()
model.run()







예제 #20
0
if (os.path.isfile(sys.argv[1])):
    config = json.loads(open(sys.argv[1]).read())
else:
    print("The config file your provided doesn't exist !")
    exit()

pygame.init()

screen = pygame.display.set_mode((1200, 1000), 0, 32)
clock = pygame.time.Clock()
pygame.display.set_caption('Racing game')

font_20 = pygame.font.SysFont("monospace", 20)

road = Road(config['map'], screen)
cars = []

for car in config['players']:
    for car2 in cars:
        if (car2.name == car['name']):
            print("Two players can't have the same name")
            exit()
        if (car2.playable and car['playable']):
            print("Only one car can be playable")
            exit()
    cars.append(Car(car["folder"], car['name'], road, car["playable"], car["debug"], screen))

def draw():
    clock.tick(60)
    screen.fill( (50, 50, 70) )
예제 #21
0
 def createRoad(self, xl, yl, xt, yt, xr, yr, xb, yb, C):
     self.rLeft = Road(xl, yl, C)
     self.rRight = Road(xt, yt, C)
     self.rTop = Road(xr, yr, C)
     self.rBottom = Road(xb, yb, C)
예제 #22
0
class Scene:
	TRACK_HEIGHT = 50
	TRACK_LENGHT = 7
	GRASS_LENGHT = TRACK_LENGHT * 20

	def __init__(self):
		self.car = Car(self.TRACK_LENGHT)
		self.road = Road()
		self.ambient = self.init_ambient() #lista de objetos que nao colidem com o carro
		self.obstacles = self.init_obstacles()
		self.angle = 50
		self.game_over = False
	
	def init_ambient(self):
		ambient = []

		ambient.append(Tree(self.TRACK_LENGHT - 30, -20, 30, -20))
		ambient.append(Tree(self.TRACK_LENGHT - 30, -5, 30, -20))
		ambient.append(Tree(self.TRACK_LENGHT - 30, 15, 30, -20))
		ambient.append(Tree(self.TRACK_LENGHT + 15, -20, 30, -20))
		ambient.append(Tree(self.TRACK_LENGHT + 15, -5, 30, -20))
		ambient.append(Tree(self.TRACK_LENGHT + 15, 15, 30, -20))
		return ambient

	def init_obstacles(self):
		obstacles = []
		# obstacles.append(Box(self.TRACK_LENGHT, -30, 30, -60))
		obstacles.append(Box(self.TRACK_LENGHT, -30, 30, -30))
		return obstacles

	def render_ground(self):
		pass
		glColor3f(0.0, 0.8, 1.0)
		gluSphere(gluNewQuadric(),250,200,200)
		# RIGHT GRASS
				

		glBegin(GL_QUADS)
		glColor3f(0.0, 1.0, 0.0)
		glVertex3f(self.GRASS_LENGHT, -5, -self.TRACK_HEIGHT - 15)
		glVertex3f(-self.GRASS_LENGHT - 20, -5, -self.TRACK_HEIGHT - 15)
		glVertex3f(-self.GRASS_LENGHT -20, -5, self.TRACK_HEIGHT)
		glVertex3f(self.GRASS_LENGHT + 20, -5, self.TRACK_HEIGHT)
		glEnd()

		# TRACK
		# glBegin(GL_QUADS)
		# glColor3f(1.0, 1.0, 1.0)
		# glVertex3f(self.TRACK_LENGHT, 0, -self.TRACK_HEIGHT)
		# glVertex3f(-self.TRACK_LENGHT, 0, -self.TRACK_HEIGHT)
		# glVertex3f(-self.TRACK_LENGHT, 0, self.TRACK_HEIGHT)
		# glVertex3f(self.TRACK_LENGHT, 0, self.TRACK_HEIGHT)
		# glEnd()

	def render_scene(self):

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
		glMatrixMode(GL_MODELVIEW)
		glLoadIdentity()

		gluLookAt(0, 5, 20, 0, 1.2, 0, 0, 1, 0) # PER
		# gluLookAt(0, 15, 5, 0, -90, 0, 0, 1, 0) # TOP

		self.car.render_car()
		self.road.render()
		self.render_obstacles()
		self.render_ground()
		self.render_ambient()

	def render_ambient(self):
		for obj in self.ambient:
			obj.render()


	def render_obstacles(self):
		for obj in self.obstacles:
			obj.render()

	def update(self,SPEED_RATE):
		self.road.update()
		for obj in self.ambient:
			obj.update(SPEED_RATE)
		for obj in self.obstacles:
			obj.update(SPEED_RATE)
			self.game_over = self.car.check_collision(obj)
 def get_init_network(self,roadname_list,signal_plan, roaddata,demand_data,stime,etime):
     Network= []
     car_len=self.car_len
     self.Demand = demand_data
     for i in range(len(roadname_list)): #for each road of the network
         res = self.get_one_roaddata(roadname_list[i],roaddata)
         widen_S=0  #the number of lanes with Stretching-segment Design
         for j in range(len(res)):
             if res[j][5]!=-1 and res[j][3]=='直':
                 widen_S+=1
                 widen_S_len=res[j][5]
         road_len = int(res[0][4])
         lane_num=2   #The number of lanes in the road,the default is 2
         #Initilize a road
         one_road=Road.Road(roadname_list[i],road_len,lane_num,40,10.8,1,1,car_len,stime,etime,widen_S)  #初始化路段对象
         ssa = []    #The green light interval corresponding to each turn
         ssa_right = ''  #Judge whether there is right turn signal control
         for j in range(len(signal_plan)):
             #print(roadname_list[i],signal_plan[j].roadname)
             if roadname_list[i] == signal_plan[j].roadname:
                 temp = []
                 temp.append(signal_plan[j].CDZ)  # 转向
                 temp.append(signal_plan[j].green)  # 绿灯区间
                 ssa.append(temp)
         for j in range(len(ssa)):
             ssa_right += ssa[j][0]
         o_lane = []
         road_right = ''  #Judge whether there is a right turn lane in the road information
         for j in range(len(res)):
             road_right += res[j][3]
             o_lane.append(res[j][3])
         if '右' in road_right and '右' not in ssa_right:  #Has right turn lane but no right turn signal control
             for j in range(len(o_lane)):
                 if '右' in o_lane[j] and len(o_lane[j]) == 1:
                     o_lane[j] = '右转nosig'   #Supplement the right turn lane without signal control
         elif '右' not in road_right:
             if '右' in ssa_right:
                 o_lane.append('右')   #Supplement the right turn lane
             else:
                 o_lane.append('右转nosig')   #Supplement the right turn lane without signal control
         #print(o_lane)
         lane = ['直' for x in range(len(o_lane))]
         for j in range(len(o_lane)):  #Change to standard turn order( left->straight->right )
             if '左' in o_lane[j]:
                 lane[0] = o_lane[j]
                 o_lane[j]=''
             if '左' in lane and '左' in o_lane[j]:
                 lane[1] = o_lane[j]
             if '右' in o_lane[j]:
                 lane[-1] = o_lane[j]
         Road_widen=[0 for x in range(len(lane))]  #Stretching-segment lane distribution
         #print(lane)
         for j in range(len(lane)): # for each lane of this road
             lane_ID=roadname_list[i]+'-'+str(j)
             direction=lane[j]
             if 'nosig' in lane[j]:
                 signalornot=1   #No signal control lane is always 1
             else:
                 signalornot=0
             ht=2        #Saturation headway,default is 2 second
             wideornot=0
             if 'nosig' in lane[j]:
                 SSA=[[stime, etime]]
             else:
                 SSA =self.get_green(ssa, lane[j])  #Obtain the green traffic time corresponding to each lane
             lane_len = road_len
             widen_len=-1
             for k in range(len(res)):
                 if res[k][5]!=-1:
                     if '左' in res[k][3] and '左' in direction and j==0:
                         widen_len=res[k][5]
                         Road_widen[j]='L'
                     if '右' in res[k][3] and '右' in direction and j==len(lane)-1:
                         widen_len = res[k][5]
                         Road_widen[j] = 'R'
             if widen_S>0:
                 if direction=='直' and len(lane)-1-widen_S<=j:
                     widen_len=widen_S_len
                     Road_widen[j] = 'S'
             # initilize a lane of this road
             one_lane = Lane.Lane(lane_ID, direction, lane_len, signalornot, ht, wideornot, car_len, SSA,widen_len,stime,etime)
             one_road.Lanes.append(one_lane)
         one_road.widen=Road_widen
         for j in range(len(self.Demand)):
             if self.Demand[j].road_path[0]==roadname_list[i] and stime<=self.Demand[j].entrytime<=etime:
                 time_index=(self.Demand[j].entrytime-stime).seconds
                 one_road.demand_time[time_index]+=1
                 one_road.demand[time_index].append(self.Demand[j])
         for j in range(len(one_road.Lanes)):
             if one_road.widen[j]!=0:
                 one_road.capcaity+=int(one_road.Lanes[j].widen_len/car_len)
             else:
                 one_road.capcaity += int(one_road.Lanes[j].lane_length/car_len)
         Network.append(one_road)
     self.Network=Network
     #self.Demand=demand_data
     return 0
예제 #24
0
파일: Space.py 프로젝트: BolotinPetr/4-sem
 def __init__(self):
     self.size = self.width, self.height = 1000, 800
     self.screen = pygame.display.set_mode(self.size, pygame.HWSURFACE)
     pygame.display.set_caption('Model')
     self.bg = Surface((self.width, self.height))
     self.objects = pygame.sprite.Group()  # need to draw all objects.
     self.branchBlocks = pygame.sprite.Group(
     )  # need for easy linking with drivers.
     self.leaders = pygame.sprite.Group()  # we need to find leader.
     self.drivers = pygame.sprite.Group()
     self.finishPoints = pygame.sprite.Group()
     x = y = 0
     for row in level:
         for col in row:
             if col == '.':
                 road = Road.RoadBlock(x, y)
                 self.objects.add(road)
             if col == 'l':
                 light = Road.Light(x, y, (0, 1), "WHITE")
                 self.objects.add(light)
                 self.branchBlocks.add(light)
                 self.leaders.add(light)
             if col == 'k':
                 light = Road.Light(x, y, (0, 1), "RED")
                 self.objects.add(light)
                 self.branchBlocks.add(light)
                 self.leaders.add(light)
             """if col == 's':
                 driver = Driver.Driver(0, 0.1, (0, 1), x, y, self.branchBlocks, self.leaders, self.drivers)
                 self.drivers.add(driver)
                 self.leaders.add(driver)"""
             if col == 'f':
                 finish = Road.FinishPoint(x, y)
                 self.objects.add(finish)
                 self.branchBlocks.add(finish)
                 self.leaders.add(finish)
                 self.finishPoints.add(finish)
             if col == '1':
                 branches = ((0, -1), (1, 0))
             if col == '2':
                 branches = ((0, -1), (-1, 0))
             if col == '3':
                 branches = ((-1, 0), (0, 1))
             if col == '4':
                 branches = ((1, 0), (0, 1))
             if (col == '1') or (col == '2') or (col == '3') or (col
                                                                 == '4'):
                 light = Road.BranchPoint(x, y, branches)
                 self.leaders.add(light)
                 self.branchBlocks.add(light)
                 self.objects.add(light)
             if col == 'W':
                 branches = ((1, 0), (1, 0))
             if col == 'E':
                 branches = ((-1, 0), (-1, 0))
             if col == 'N':
                 branches = ((0, -1), (0, -1))
             if col == 'S':
                 branches = ((0, 1), (0, 1))
             if (col == 'W') or (col == 'E') or (col == 'N') or (col
                                                                 == 'S'):
                 branch = Road.BranchPoint(x, y, branches)
                 self.leaders.add(branch)
                 self.branchBlocks.add(branch)
                 self.objects.add(branch)
             x += ROAD_WIDTH
         y += ROAD_HEIGHT
         x = 0
예제 #25
0
 def driveForward(self, road: Road, distance_traveled: int = 0):
     pass
     road.endIntersection()
예제 #26
0
 def __init__(self, root):
     self.description = modulDescription.Description(root)
     self.road = modulRoad.Road(root)
     self.calculation = modulCalculation.Calculation(root)
예제 #27
0
파일: Loop.py 프로젝트: pidipidi/PyCar
from Startup import *
from Car import *
from Road import *
import pickle, os
import numpy as np
import random

vehicle = Car(250, random.choice([height / 2 + 40, height / 2 - 20]))
road = Road()
vehicle1 = Car(width / 2 + 100, height / 2 + 40)
#obstacle2 = Car(width/2-100, height/2-20)


def display_all(main_surface, display_list, text_list):
    main_surface.fill((0, 100, 100))
    for element in display_list:
        element.display(main_surface)
    for element_val in range(0, len(text_list)):
        main_surface.blit(
            font.render(str(text_list[element_val]), True, (0, 255, 0)),
            (10, 10 + (10 * element_val)))


def update_all(update_list):
    for element in update_list:
        element.update()


data = {
    'u': [],
    'x': [],