def main():
    road = Road(number_of_cars=30)
    number_of_runs = 100
    seconds_in_run = 60

    road.place_cars()
    speed_limit_list = []
    positions_list = []
    speeds_list = []
    mean_speeds = []
    st_devs = []

    for _ in range(number_of_runs):
        speeds, positions = road.simulate_n_seconds(seconds_in_run)

        mean = np.mean(speeds)
        stdv = np.std(speeds)
        speed_limit_list.append(mean + stdv)
        mean_speeds.append(mean)
        st_devs.append(stdv)

        if _ in {0, 9, 34, 74, 99}:
            positions_list.append(positions[:])
            speeds_list.append(speeds)

    return (int(np.mean(speed_limit_list)), positions_list, speeds_list,
            mean_speeds, st_devs)
 def setUp(self):
     """
     Compute following code before each test.
     """
     self.road = Road(road_length = 3.0,density_max = 120.0,free_v = 50.0,mean_time_gap =0.6,source=0.8)
     self.road.make_cells()
     self.cell = Cell(self.road)
def main():
    road = Road(number_of_cars=30)
    number_of_runs = 100
    seconds_in_run = 60

    road.place_cars()
    speed_limit_list = []
    positions_list = []
    speeds_list = []
    mean_speeds = []
    st_devs = []

    for _ in range(number_of_runs):
        speeds, positions = road.simulate_n_seconds(seconds_in_run)

        mean = np.mean(speeds)
        stdv = np.std(speeds)
        speed_limit_list.append(mean + stdv)
        mean_speeds.append(mean)
        st_devs.append(stdv)

        if _ in {0, 9, 34, 74, 99}:
            positions_list.append(positions[:])
            speeds_list.append(speeds)

    return (int(np.mean(speed_limit_list)), positions_list, speeds_list,
            mean_speeds, st_devs)
def run_simulation(VISUALIZE=True):
    road = Road(SPEED_LIMIT, TRAFFIC_DENSITY, LANE_SPEEDS, AMOUNT_OF_ROAD_VISIBLE)
    road.populate_traffic()
    ego_config = {
        'speed_limit': SPEED_LIMIT,
        'num_lanes': len(LANE_SPEEDS),
        'goal': GOAL,
        'max_acceleration': MAX_ACCEL
    }
    # ego car starts at lane 2, s=0, goal is s=300, lane 0
    road.add_ego(2, 0, ego_config)
    timestep = 0
    # only check if reached GOAL s, if reached check if reached GOAL lane
    # each iteration advance() on sec
    while road.get_ego().s <= GOAL[0]:
        timestep += 1
        if timestep > 150:
            if VISUALIZE:
                print("Taking too long to reach goal. Go faster!")
                break

        road.advance()
        if VISUALIZE:
            print(road)
            time.sleep(float(1.0) / FRAMES_PER_SECOND)
    ego = road.get_ego()
    if VISUALIZE:
        if ego.lane == GOAL[1]:
            print("You got to the goal in {} seconds!".format(timestep))
        else:
            print("You missed the goal. You are in lane {} instead of {}.".format(ego.lane, GOAL[1]))
    return timestep, ego.lane
Example #5
0
    def __init__(self):

        self._image_count = 0

        # Camera variables
        self._calibration_images_dir = '../camera_cal/calibration*.jpg'
        self._calibration_images_nx = 9
        self._calibration_images_ny = 6
        self._calibration_matrix = None
        self._initialize_calibration_matrix()

        # Thresholding variables
        self._sx_params = {"Active": True, "Orient": 'x', "Thresh": (20, 190)}
        self._sy_params = {"Active": True, "Orient": 'y', "Thresh": (20, 190)}
        self._sdir_params = {"Active": True, "Thresh": (0.8, 1.5), "Sobel_kernel": 15}
        self._mag_params = {"Active": True, "Thresh": (0, 255), "Sobel_kernel": 3}
        self._s_color_params = {"Active": True, "Thresh": (170, 255)}
        self._thresholder = None
        self._initialize_thresholder()

        # Masking
        self._masker = None
        self._initialize_masker()

        # Perspective transform
        self._perspective_transformer = None
        self._initialize_perspective_transformer()

        # WindowSearch
        self._window_searcher = None
        self._initialize_window_searcher()

        # Road
        self._road = Road()
Example #6
0
def main():
    # define display variables
    size = [WIN_SIZE_X, WIN_SIZE_Y]
    screen = pygame.display.set_mode(size)
    done = False
    clock = pygame.time.Clock()

    # define starting variables
    start_pos = np.array([20, size[1] / 2])
    start_dir = 10.0
    god = God(50, start_pos, start_dir)
    road = Road(size, width=50)

    # start a separate "god" evolutionary thread, different than the display update thread
    t = Thread(target=god.run, args=([road]))
    t.start()

    # main loop
    while not done:
        clock.tick(10)

        for event in pygame.event.get():  # User did something
            if event.type == pygame.QUIT:  # If user clicked close
                done = True  # Flag that we are done so we exit this loop

        screen.fill((255, 255, 255))

        road.draw(screen)
        god.draw(screen)

        pygame.display.flip()

    pygame.quit()
Example #7
0
def run_simulation(VISUALIZE=True):
    road = Road(SPEED_LIMIT, TRAFFIC_DENSITY, LANE_SPEEDS,
                AMOUNT_OF_ROAD_VISIBLE)
    road.populate_traffic()
    ego_config = {
        'speed_limit': SPEED_LIMIT,
        'num_lanes': len(LANE_SPEEDS),
        'goal': GOAL,
        'max_acceleration': MAX_ACCEL,
    }
    # Ego begins travelling at lane #2.
    road.add_ego(2, 0, ego_config)
    timestep = 0
    while road.get_ego().s <= GOAL[0]:
        timestep += 1
        if timestep > 150:  # simulation time limit
            if VISUALIZE:
                print("Taking too long to reach goal. Go faster!")
            break

        road.advance()
        if VISUALIZE:
            print(road)
            time.sleep(float(1.0) / FRAMES_PER_SECOND)

    # Completed to the goal distance
    ego = road.get_ego()
    if VISUALIZE:
        if ego.lane == GOAL[1]:
            print("You got to the goal in %d seconds!" % timestep)
        else:
            print("You missed the goal. "
                  "You are in lane %d instead of %d." % (ego.lane, GOAL[1]))
    return timestep, ego.lane
Example #8
0
def basicRoad():
    r = Road()
    r.addSegment(Segment(100, theGear=Gear.DIRECT))
    r.addSegment(Segment(50, theGear=Gear.TURN))
    r.addSegment(Segment(100, theGear=Gear.DIRECT))
    r.addSegment(Segment(50, theGear=Gear.TURN))
    return r
Example #9
0
    def __init__(self, *args, **kwargs):
        super(Tester, self).__init__(*args, **kwargs)

        vehicles = []
        vehicles.append({})
        vehicles[0]['id'] = 'truck'
        vehicles[0]['vClass'] = 'truck'
        vehicles[0]['length'] = 15.0
        vehicles[0]['maxSpeed'] = 90.0
        vehicles[0]['accel'] = 1.0
        vehicles[0]['decel'] = 5.0
        vehicles[0]['sigma'] = 0.0
        vehicles.append({})
        vehicles[1]['id'] = 'car'
        vehicles[1]['vClass'] = 'passenger'
        vehicles[1]['length'] = 4.0
        vehicles[1]['maxSpeed'] = 120.0
        vehicles[1]['accel'] = 1.0
        vehicles[1]['decel'] = 5.0
        vehicles[1]['sigma'] = 0.0

        road_params = {}
        road_params['road_type'] = 'intersection'
        road_params['name'] = 'intersection_test'
        road_params['nb_lanes'] = 1
        road_params['nodes'] = np.array([[-200., 0.], [0., 0.], [200., 0.],
                                         [0., -200.], [0., 200.], [-1000, 0],
                                         [1000, 0], [0, -1000], [0, 1000]])
        road_params['priority'] = np.array([[0, 5, 0, 0, 0, 5, 0, 0, 0],
                                            [5, 0, 5, 3, 3, 0, 0, 0, 0],
                                            [0, 5, 0, 0, 0, 0, 5, 0, 0],
                                            [0, 3, 0, 0, 0, 0, 0, 3, 0],
                                            [0, 3, 0, 0, 0, 0, 0, 0, 3],
                                            [5, 0, 0, 0, 0, 0, 0, 0, 0],
                                            [0, 0, 5, 0, 0, 0, 0, 0, 0],
                                            [0, 0, 0, 3, 0, 0, 0, 0, 0],
                                            [0, 0, 0, 0, 3, 0, 0, 0, 0]])
        road_params['edges'] = np.array(road_params['priority'] > 0, dtype=int)
        road_params['routes'] = np.array([[0, 1, 2, 6], [0, 1, 3, 7],
                                          [2, 1, 0, 5], [2, 1, 4, 8],
                                          [3, 1, 4, 8]])
        road_params['vehicles'] = vehicles
        road_params['lane_change_duration'] = 4
        road_params['max_road_speed'] = 35
        road_params['overtake_right'] = True
        road_params['lane_width'] = 3.2
        road_params['emergency_decel_warn_threshold'] = 10

        road_params['collision_action'] = 'warn'
        road_params['no_display_step'] = 'true'

        road_params['view_position'] = np.array([200, 200])
        road_params['view_delay'] = 100
        road_params['zoom'] = 250

        self.road = Road(road_params)
Example #10
0
 def get_final_velocity(self):
     road = Road()
     car_list = road.populate_road()
     while self.time <= self.t_max:
         for index, car in enumerate(car_list):
             if index >= len(car_list) - 1:
                 car_list[index].update_car(car_list[0], road)
             else:
                 car_list[index].update_car(car_list[index+1], road)
         self.time += self.d_time
     return car_list
Example #11
0
def baseRoad(request):
    _ = Road()
    print('\n')
    try:
        lengths = request.param
    except AttributeError:
        lengths = []
    for length in lengths:
        _.addSegment(Segment(length))
        print('adding segment with length {}'.format(length))
    print('road created')
    return _
 def __init__(self, _num_of_roads, size_of_road, size_of_bridge):
     if _num_of_roads < 4:
         self.num_of_roads = 4
     if _num_of_roads % 2 == 1:
         self.num_of_roads += 1
     else:
         self.num_of_roads = _num_of_roads
     self.roads = [None] * self.num_of_roads
     # self.roads = [Road(size_of_road)] * self.num_of_roads
     for i in range(self.num_of_roads):
         self.roads[i] = Road(size_of_road)
     self.bridge = Road(size_of_bridge)
     self.state = []
Example #13
0
	def __init__(self, pos, nodes, G,direction=None, machine=None, main=False, radius=None):
		Road.__init__(self, pos, nodes, G, direction,radius=radius)
		self.m=machine
		self.trees=[]
		self.harvestTrees=0 #used to take care of the overlapping problem..
		tL=G.terrain.GetTrees(self.pos, self.radius+1) #+1 to be sure...
		for tree in tL:
			if col.pointInPolygon(tree.pos, self.getNodes()): #tree inside road,
				#check if tree already belongs to a road:
				if not self._checkIfTaken(tree):
					self.harvestTrees+=1
				self.trees.append(tree)
		self.startPoint=None #the startpoint of a corridor is where it intersects the mainRoad.This is where the crane is supposed to begin.
		self.main=main
Example #14
0
    def create_objects(self):
        background = pyglet.graphics.OrderedGroup(0)
        foreground = pyglet.graphics.OrderedGroup(1)

        self.road = Road(x=0, y=0, batch=self.batch, group=background)
        self.player = Player(x=PLAYER_POS_X,
                             y=PLAYER_POS_Y,
                             batch=self.batch,
                             group=foreground)

        self.lines = []
        for coords in lines_coordinates:
            x0, y0, x1, y1 = coords
            self.lines.append(pyglet.shapes.Line(x0, y0, x1, y1))
class GameScene(Scene):
    grass = (0, 80, 0)

    def __init__(self, width, height, scene_stack, difficulty):
        super(GameScene, self).__init__(width, height, scene_stack)
        self.difficulty = difficulty
        self.counter = 0
        self.road = Road(width, height)

    def update(self):
        self.road.update(10)

    def draw(self, surface):
        self.road.draw(surface)
Example #16
0
class Game(pyglet.window.Window):
    def __init__(self, *args, **kwargs):
        super(Game, self).__init__(fullscreen=True, *args, **kwargs)

        # Set batch and entities
        self.batch = pyglet.graphics.Batch()

        self.create_objects()

        # Set handlers
        self.push_handlers(self.player.key_handler)

        # Set frequence
        pyglet.clock.schedule_interval(self.update, 1 / 60.0)

    def create_objects(self):
        background = pyglet.graphics.OrderedGroup(0)
        foreground = pyglet.graphics.OrderedGroup(1)

        self.road = Road(x=0, y=0, batch=self.batch, group=background)
        self.player = Player(x=PLAYER_POS_X,
                             y=PLAYER_POS_Y,
                             batch=self.batch,
                             group=foreground)

        self.lines = []
        for coords in lines_coordinates:
            x0, y0, x1, y1 = coords
            self.lines.append(pyglet.shapes.Line(x0, y0, x1, y1))
            ## Uncomment for printing control lines
            # self.lines.append(pyglet.shapes.Line(
            #     x0, y0, x1, y1, color=LINE_RGB_COLOR, batch=self.batch, group=foreground))

    def update(self, dt):
        if not self.player.crashed:
            self.player.update(dt)
            self.player.check_collision()
            self.player.check_on_line(self.lines)
        else:
            self.player.reset()

        self.road.update(dt)

    def on_mouse_press(self, x, y, button, modifiers):
        print(x, y)

    def on_draw(self):
        self.clear()
        self.batch.draw()
Example #17
0
class Game(object):
    def __init__(self, tps, res):

        # Config
        self.tps = tps
        self.res = res

        # Init
        pygame.init()
        self.screen = pygame.display.set_mode(self.res)
        self.tps_clock = pygame.time.Clock()
        self.tps_delta = 0.0
        self.cars = []
        self.road = Road(self)
        self.map = Map(self)
        print(self.map.board)
        self.spawn_car(self.road.position_s2_line)

        while True:

            # Handle events
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit(0)
                elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    sys.exit(0)

            # Ticking
            self.tps_delta += self.tps_clock.tick() / 1000.0
            while self.tps_delta > 1 / self.tps:
                self.tick()
                self.tps_delta -= 1 / self.tps

# Drawing
            self.screen.fill((0, 0, 0))
            self.draw()
            pygame.display.flip()

    def tick(self):
        list(map(lambda x: x.tick(), self.cars))

    def draw(self):
        self.road.draw()
        list(map(lambda x: x.draw(), self.cars))

    def spawn_car(self, position):
        car = Car(self, position)
        self.cars.append(car)
Example #18
0
    def load_sections(self, road_network):
        self.cursor.execute('SELECT * FROM get_section();')
        for (id, name, number_lanes, speed_limit, capacity, from_node_id,
             to_node_id, length) in self.cursor.fetchall():

            if id in road_network.sections:
                raise Error("section id=%d already exists" % id)
            if from_node_id not in road_network.nodes:
                raise Error("section id=%d unknown from-node=%d" %
                            (id, from_node_id))
            if to_node_id not in road_network.nodes:
                raise Error("section id=%d unknown to-node=%d" %
                            (id, to_node_id))

            road_name = name.title()
            if road_name not in road_network.roads:
                road_network.roads[road_name] = Road(road_name)
            road = road_network.roads[road_name]

            from_node = road_network.nodes[from_node_id]
            to_node = road_network.nodes[to_node_id]
            section = Section(id, road, number_lanes, speed_limit, capacity,
                              from_node, to_node, length)
            from_node.add_from_section(section)
            to_node.add_to_section(section)
            road_network.sections[id] = section
            road.sections.append(section)
Example #19
0
def initialize_2():
    global time, lightAgents, envir, cars

    time = 0
    road_1 = Road(0, 10, 10)
    car_1 = Car(0, 0)
    cars = []
    def set_roads(self, G, node_dict):
        
        """
        Method: set_roads

        Method Arguments:
        * G - The graph of a real section of the world that will be produced
              from using the osmnx package and the lat and lon provided by the
              user input.

        * node_dict - The node dictionary that will be used to show which roads
                        are connected to each other.

        Output:
        * A dictionary of the edges created will be returned, where each edge id
          is their key.
        """ 
        
        edge_dict = {}
        id = 0
        for e in G.edges(data=True):
            start = node_dict[e[0]]
            destination = node_dict[e[1]]
            length = int(e[2]['length']) 
            #name = e[2]['name']
            edge_to_insert = Road(id, start, destination, length)
            if id in edge_dict: 
                print("duplicate edge")
            edge_dict[id] = edge_to_insert
            id+=1
        #removed bad edge
        return edge_dict
Example #21
0
	def parse(self):
		data = open(u'graph%d' % self.game, u'r').read()
		for line in data.split(u'\n'):
			line = line.strip()
			if not line:
				continue
			line = line.split(u' ')

			self.parsed[int(line[0])][int(line[1])] = True
			self.parsed[int(line[1])][int(line[0])] = True
			try:
				self.connections[int(line[1])][int(line[0])].append(int(line[2]))
				self.connections[int(line[0])][int(line[1])].append(int(line[2]))

			except:
				pass

		data = open(u'roads%d' % self.game, u'r').read()
		for line in data.split(u'\n'):
			line = line.strip()
			if not line:
				continue
			line = line.split(u' ')

			self.roads[int(line[0])] = Road(
				int(line[0]),
				int(line[1]),
				int(line[2]),
				float(line[3]),
				float(line[4]),
				float(line[5]),
			)
Example #22
0
def readRoads(e, nodes):
    roads = []

    # Desired road types
    driveable = [
        "motorway", "trunk", "primary", "secondary", "tertiary", "residential",
        "service", "living_street", "track", "road", "unclassified"
    ]
    for r in driveable.copy():
        driveable.append(r + "_link")

    # Read all roads/ways into an array
    for road in e.findall('way'):
        r = Road(road.get("id"))

        supported = False

        # Read all information about each road
        for tag in road.findall('tag'):
            setattr(r, tag.get("k").replace(":", "_"), tag.get("v"))

            # Filter out unwanted roads
            if tag.get('k') == "highway":
                if tag.get('v') in driveable:
                    supported = True
        if not supported:
            continue

        # Connect to the nodes
        for nd in road.findall('nd'):
            r.nodes.append(nodes[nd.get("ref")])

        roads.append(r)

    return roads
Example #23
0
 def get_string(self):
     self.new_string = input("Type the string to validate: ")
     # self.create_error_character()
     self.reviewed = []
     current_state = self.initial_state
     self.roads = [Road([current_state], True)]
     self.make_epsilon_transitions()
     for symbol in self.new_string:
         # self.make_epsilon_transitions()
         self.change_road_status()
         for road in self.roads:
             if road.check_now == True:
                 aux_state = []
                 for transition in self.transitions_objects:
                     aux_state.append(transition.get_next_state(road.way[-1], symbol))
                 aux_state = [state for state in aux_state if state != "error"]
                 if len(aux_state) > 0:
                     if ( len(aux_state) > 1 ):
                         self.create_new_roads(road, aux_state)
                         road.add_to_road(aux_state[0])
                     else:
                         road.add_to_road(aux_state[0])
                 else:
                     road.add_error(road.way[-1], symbol)
         self.make_epsilon_transitions()
Example #24
0
def build_map(map_arg):
    new_map = [[]]
    map_file = open(map_arg, "r")
    map_file_contents = map_file.read()
    x_index = 0
    y_index = 0
    for c in map_file_contents:
        if c == 'N' or c == 'M' or c == 'B' or c == 'R':
            node = Node(x_index, y_index, c)
            new_map[y_index].append(node)
            x_index += 1
        elif c == '+':
            road = Road(x_index, y_index)
            new_map[y_index].append(road)
            x_index += 1
        elif c == '\n':
            x_index = 0
            y_index += 1
            new_map.append([])
        else:
            new_map[y_index].append(None)
            x_index += 1
    for y, row in enumerate(new_map):
        for x, location in enumerate(row):
            if location:
                if x < len(row) - 1:
                    east_loc = new_map[y][x + 1]
                    if east_loc:
                        location.add_neighbor(Direction.EAST, east_loc)
                if y < len(new_map) - 1 and new_map[y + 1]:
                    south_loc = new_map[y + 1][x]
                    if south_loc:
                        location.add_neighbor(Direction.SOUTH, south_loc)
    return new_map
def parse_map(filename):
    # initialize location dictionary {ID -> Location} and road dictionary {ID -> list[Road]}
    locationDict = {}
    roadDict = {}

    # parse file
    with open(filename, "r") as file:
        for line in file:
            # remove \n and split line by delimiter
            line = line.rstrip()
            splitLine = line.split("|")

            # create new Location instances for "location" lines and add them to locationDict
            if splitLine[0] == "location":
                newLocation = Location(splitLine[1], splitLine[2],
                                       splitLine[3])
                locationDict[splitLine[1]] = newLocation

            # create new Road instances for "road" lines and add them to roadDict
            elif splitLine[0] == "road":
                newRoad = Road(splitLine[4], splitLine[3], splitLine[1],
                               splitLine[2])

                if splitLine[1] in roadDict.keys():
                    roadDict[splitLine[1]] += [newRoad]
                else:
                    roadDict[splitLine[1]] = [newRoad]

                if splitLine[2] in roadDict.keys():
                    roadDict[splitLine[2]] += [newRoad]
                else:
                    roadDict[splitLine[2]] = [newRoad]

        file.close()
    return locationDict, roadDict
Example #26
0
    def __init__(self, asurface):

        self.crashed = False

        self.hud = HUD(asurface)

        self.status = GameStatus.PLAYING
        self.road = Road(asurface)

        self.surface = asurface
        self.surface_width = surface.get_width()
        self.surface_height = surface.get_height()

        self.car = Car(surface)
        self.obstacles = []
        self.adding_obstacle = False
Example #27
0
def test_init():
    try:
        Road(1, 2, -30, [])
        assert False
    except ValueExpectedException as ex:
        print()
        print(ex.message)
        assert True
def random_wind_smoothing(road: Road, maxh: int):
    """
    Global max/wind smoothing function similar to wind_smoothing.
    The difference is that the grains are randomly distributed over all lowest positions with the lowest height
    and not to the first position in the road with the lowest height.
    :param road: Road class instance
    :param maxh: positive integer, threshold value, above this value all grains are removed
    :return:
    """
    while max(road) > maxh:
        for i in range(road.size):
            if road[i] > maxh:
                temp_minimum = min(road)
                temp_minimum_indices = np.where(road.piles == temp_minimum)
                chosen_index = np.random.choice(temp_minimum_indices[0])
                road.remove_grain(i)
                road.add_grain(chosen_index)
Example #29
0
    def setup_road(self, start, end, image):
        ''' Sets up a single, 1-D road. '''
        r = Road(start, end, height=self.img_size)

        x_len = int(r.length)  # - self.img_size
        y_len = self.img_size * 2

        s = Sprite(image, (x_len, y_len))

        x = start.x
        y = self.height - start.y

        angle = r.angle

        # force angle between [0, 360)
        while angle < 0:
            angle += 360
        while angle >= 360.0:
            angle -= 360

        # This is the logic for the direction the bmp should face.
        # It's messy because of the way pygame handles PNG's (position is
        #   top left corner of the bmp)
        image_flipped = False
        # DONT ASK
        if 90.0 <= angle < 270.0:
            image_flipped = True
            x = end.x
            y = self.height - end.y

        if angle == 0.0:
            x += self.img_size

        elif angle == 90.0:
            if image_flipped:
                y += self.img_size
            else:
                y -= self.img_size

        elif angle == 180.0:
            if image_flipped:
                x += self.img_size
            else:
                x -= self.img_size

        elif angle == 270.0:
            y += self.img_size

        if angle == 0.0 or angle == 180.0:
            y -= self.img_size / 2
        else:
            x -= self.img_size / 2

        s.move_to(x=x, y=y)
        s.set_angle(angle)

        self.window.add_sprite(s)
        return r
Example #30
0
    def create_scenario(self):
        """
        Create the scenrario here, some of this could be moved to an __init__
        """
        road_data = Road.generate_random_road_data()
        self.road = Road(**road_data)
        # determine number of signals to create
        num_signals = int(self.road.length / 4)

        self.signals = []

        for x in range(1, num_signals):
            data = Signal.generate_random_signal_data(x, self.road.length)
            signal = Signal(**data)
            self.signals.append(signal)

        vehicle_data = Vehicle.generate_random_vehicle_data()
        self.vehicle = Vehicle(**vehicle_data)
def wind_smoothing(road: Road, maxh: int):
    """
    Global max/wind smoothing function.
    Takes all the grains above a threshold maxh and puts them to the lowest heights (globally).
    This methods puts the grains to the first position with the lowest height.
    :param road: Road class instance
    :param maxh: positive integer, threshold value, above this value all grains are removed
    :return:
    """
    while max(road) > maxh:
        for i in range(road.size):
            if road[i] > maxh:
                temp_minimum = min(road)
                for j in range(road.size):
                    if road[j] == temp_minimum:
                        road.remove_grain(i)
                        road.add_grain(j)
                        break
Example #32
0
    def parseROAD(self, data):
        data = data.split(u' ')
        id = int(data[0])
        destination = int(data[1])
        speed = float(data[2])
        cost = float(data[3])
        length = float(data[4])

        return Road(id, None, destination, speed, cost, length)
Example #33
0
    def __init__(self,
                 dimensions,
                 path,
                 background_images,
                 asphalt_textures,
                 templates_collection,
                 seed=0,
                 set_seed=True):
        self.w, self.h = dimensions
        self.path = path  # Where the image will be saved
        self.road = Road(self.w, self.h)

        # Defining the dictionaries containing random images
        self.templates_collection = templates_collection
        self.backgrounds = background_images
        self.grounds = asphalt_textures

        if set_seed:
            random.seed(seed)
Example #34
0
def test_hard_road_slowing_factor():
    road = Road(length=7000, slowing_factor=1, hard_road=True)
    assert road.slow_factor(position=0, car_slowing_chance=0.1) == 0.1
    assert road.slow_factor(position=500, car_slowing_chance=0.1) == 0.1
    assert road.slow_factor(position=1000, car_slowing_chance=0.1) == 0.1 * 1.4
    assert road.slow_factor(position=1500, car_slowing_chance=0.1) == 0.1 * 1.4
    assert road.slow_factor(position=2000, car_slowing_chance=0.1) == 0.1
    assert road.slow_factor(position=3500, car_slowing_chance=0.1) == 0.1 * 2.0
    assert road.slow_factor(position=5500, car_slowing_chance=0.1) == 0.1 * 1.2
    assert road.slow_factor(position=6500, car_slowing_chance=0.1) == 0.1
Example #35
0
def test_validate_position():
    road = Road(length=1000, slowing_factor=2)
    assert road.validate(0) == 0
    assert road.validate(1) == 1
    assert road.validate(1000) == 0
    assert road.validate(1001) == 1
    assert road.validate(2000) == 0
    assert road.validate(2001) == 1

    assert road.validate(-1) == 999

    assert road.validate(-1000) == 0
    assert road.validate(-1005) == 995
    assert road.validate(-2005) == 995
Example #36
0
def test_road_curve():
    test_road = Road(2)
    test_car = Car()
    test_car.speed = 8
    test_car_two = Car(20)
    td = test_road.set_tail_distance(test_car, test_car_two)
    test_car.set_new_speed(test_car_two, td)
    test_car.change_position()
    test_road.check_end_of_lap(test_car)
    test_car.check_position(test_car_two)
    test_road.check_end_of_lap(test_car)
    assert test_car.speed == 10
Example #37
0
def test_choose_speed_stop_please():
    test_road = Road(2)
    test_car = Car(75)
    test_car.speed = 12
    test_car_two = Car(80)
    test_car_two.speed = 2
    td = test_road.set_tail_distance(test_car, test_car_two)
    test_car.set_new_speed(test_car_two, td)
    test_car.change_position()
    test_road.check_end_of_lap(test_car)
    test_car.check_position(test_car_two)
    test_road.check_end_of_lap(test_car)
    assert test_car.speed == 0
Example #38
0
def test_choose_speed_steady_fast():
    test_road = Road(2)
    test_car = Car()
    test_car.speed = 10
    test_car_two = Car(14)
    test_car_two.speed = 12
    td = test_road.set_tail_distance(test_car, test_car_two)
    test_car.set_new_speed(test_car_two, td)
    test_car.change_position()
    test_road.check_end_of_lap(test_car)
    test_car.check_position(test_car_two)
    test_road.check_end_of_lap(test_car)
    assert test_car.speed == 12
Example #39
0
File: level.py Project: ikn/latof
 def init (self):
     self._changed = set()
     self._changed_rects = []
     self.overlays = []
     self.ui = {}
     self.dirty = True
     if self.ident != self._last_ident:
         self.game.clear_caches()
     data = conf.LEVELS[self.ident]
     sx, sy = LEVEL_SIZE
     self.objs = objs = [[[] for j in xrange(sx)] for i in xrange(sy)]
     self.road = Road(self)
     self.frog = Frog(self, data['frog pos'], data.get('frog dirn', 1))
     for pos, os in data['objs'].iteritems():
         if isinstance(os, basestring):
             os = (os,)
         objs[pos[0]][pos[1]] = [getattr(obj_module, obj)(self, pos)
                                 for obj in os]
     self.update_held()
Example #40
0
from grid import Grid
from road import Road, Junction, StopSign, TrafficLight, Roundabout, NullJunction

g = Grid(94, 46)
r = Road("Iodine Road", [ [4, 5], [4, 6], [4, 7], [4, 8] ])
r.classification = 3
r.numLanes = 6
r.speed = 50
r.toll = 1
g.roads.append(r)

s = Road("Bromine Road", [ [20, 8], [19, 8], [18, 8], [17, 8], [16, 7], [15, 7], [14, 8], [13, 8], [12, 8], [11, 8], [10, 8], [9, 8], [8, 8], [7, 8], [6, 8], [5, 8], [4, 8] ])
s.classification = 3
s.numLanes = 6
s.speed = 50
s.toll = 1
g.roads.append(s)

junctionRS = TrafficLight([r, s], [])
junctionRS.loc = [4, 8]
r.replaceJunction(junctionRS)
s.replaceJunction(junctionRS)


g.save("./data/roadNetwork.db")

#h = Grid(10, 10)
#h.reconstruct("./data/roadNetwork.db")
#for rd in h.roads:
#	print(rd.name + " " + str(rd.path) + " " + str(rd.junctions) + " " + str(rd.numLanes) + " " + str(rd.classification) + " " + str(rd.speed) + " " + str(rd.toll) + " " + str(rd.ID))
Example #41
0
File: level.py Project: ikn/latof
class Level (object):
    def __init__ (self, game, event_handler, ident = 0):
        self.game = game
        event_handler.add_event_handlers({
            pg.MOUSEBUTTONDOWN: self._click,
            pg.MOUSEMOTION: self._move_mouse
        })
        event_handler.add_key_handlers([
            (conf.KEYS_BACK, self.end, eh.MODE_ONDOWN)
        ])
        self._held_sfc = pg.Surface(TILE_SIZE).convert_alpha()
        self._held_sfc.fill(conf.UI_BG)
        self._last_ident = self.ident = ident
        self._locked = False
        self.drop_input()
        self.game.linear_fade(*conf.INIT_FADE)
        self.init()

    def init (self):
        self._changed = set()
        self._changed_rects = []
        self.overlays = []
        self.ui = {}
        self.dirty = True
        if self.ident != self._last_ident:
            self.game.clear_caches()
        data = conf.LEVELS[self.ident]
        sx, sy = LEVEL_SIZE
        self.objs = objs = [[[] for j in xrange(sx)] for i in xrange(sy)]
        self.road = Road(self)
        self.frog = Frog(self, data['frog pos'], data.get('frog dirn', 1))
        for pos, os in data['objs'].iteritems():
            if isinstance(os, basestring):
                os = (os,)
            objs[pos[0]][pos[1]] = [getattr(obj_module, obj)(self, pos)
                                    for obj in os]
        self.update_held()

    def restart (self):
        self.cutscene(self.init, *conf.RESTART)

    def end (self, *args):
        self.cutscene(self.game.quit_backend, *conf.END, persist = True)

    def _progress (self):
        if hasattr(self, '_cleanup'):
            self._cleanup()
        self.game.switch_backend(level_backends[self.ident], self.ident)

    def progress (self):
        self.ident += 1
        if self.ident >= len(conf.LEVELS):
            self.end()
        else:
            self.cutscene(self._progress, *conf.PROGRESS)

    def _end_cutscene (self):
        self._locked = False

    def cutscene (self, evt_f, evt_t, fade, ctrl_t = None, persist = False):
        self._locked = True
        self.frog.stop()
        self.game.linear_fade(*fade, persist = persist)
        self.game.scheduler.add_timeout(evt_f, seconds = evt_t)
        if ctrl_t is None:
            ctrl_t = evt_t
        self.game.scheduler.add_timeout(self._end_cutscene, seconds = ctrl_t)

    def _click (self, evt):
        if self._locked:
            return
        if self._grab_click(evt) and evt.button in conf.ACTION_SETS:
            self._rm_ui('msg')
            pos = tuple(x / s for x, s in zip(evt.pos, TILE_SIZE))
            self.frog.action(conf.ACTION_SETS[evt.button],
                             self.objs[pos[0]][pos[1]], pos)

    def _move_mouse (self, evt):
        if self._grab_move(evt):
            orig_x, orig_y = evt.pos
            x = orig_x / TILE_SIZE[0]
            y = orig_y / TILE_SIZE[1]
            obj = self.top_obj(self.objs[x][y])
            if obj is None:
                self._rm_ui('label')
                return
            label = obj_module.name(obj)
            sfc = self.game.render_text(
                'label', label, conf.FONT_COLOUR, bg = conf.UI_BG,
                pad = conf.LABEL_PADDING, cache = ('label', label)
            )[0]
            o = conf.LABEL_OFFSET
            ws, hs = sfc.get_size()
            x, y = orig_x + o[0], orig_y - hs + o[1]
            w, h = conf.RES
            x = min(max(x, 0), w - ws)
            y = min(max(y, 0), h - hs)
            self._add_ui('label', sfc, (x, y))

    def _native_click (self, evt):
        return True

    def _native_move (self, evt):
        return True

    def grab_input (self, click, move):
        self._grab_click = click
        self._grab_move = move

    def drop_input (self):
        self._grab_click = self._native_click
        self._grab_move = self._native_move

    def change_tile (self, tile):
        self._changed.add(tuple(tile))

    def rect_tiles (self, rect):
        sx, sy = TILE_SIZE
        x, y, w, h = rect
        x0 = int(x / sx)
        y0 = int(y / sy)
        x1 = int(ceil(float(x + w) / sx))
        y1 = int(ceil(float(y + h) / sy))
        w, h = LEVEL_SIZE
        tiles = []
        for i in xrange(x0, x1):
            if 0 <= i < w:
                for j in xrange(y0, y1):
                    if 0 <= j < h:
                        tiles.append((i, j))
        return tiles

    def change_rect (self, rect, tiles = None):
        if tiles is None:
            tiles = self.rect_tiles(rect)
        self._changed.update(tiles)
        self._changed_rects.append(rect)
        return tiles

    def add_obj (self, obj, pos):
        self.objs[pos[0]][pos[1]].append(obj)
        if isinstance(obj, obj_module.OneTileObj):
            self.change_tile(pos)
        road = self.road
        if road.tile_rect.collidepoint(pos) and hasattr(obj, 'on_crash') and \
           road.lane_moving(pos[1]):
            obj.on_crash(self.frog, road)
            assert not (obj.holdable and obj.solid)

    def rm_obj (self, obj, pos = None):
        if pos is None:
            pos = obj.pos
        self.objs[pos[0]][pos[1]].remove(obj)
        if isinstance(obj, obj_module.OneTileObj):
            self.change_tile(pos)
        if self.road.tile_rect.collidepoint(pos) and \
           hasattr(obj, 'on_uncrash'):
            obj.on_uncrash(self.frog, self.road)

    def top_obj (self, objs):
        # select uppermost (last) obj
        return objs[-1] if objs else None

    def solid_objs (self, *ignore):
        # return set of tiles of containing solid objects
        objs = set()
        for x, col in enumerate(self.objs):
            for y, os in enumerate(col):
                for o in os:
                    if o.solid and o not in ignore:
                        objs.add((x, y))
                        break
        return objs

    def _add_ui (self, ident, sfc, pos = None):
        if pos is None:
            pos = conf.UI_POS[ident]
        ui = self.ui
        if ident in ui:
            ui[ident].hide()
        ui[ident] = Overlay(self, sfc, pos).show()

    def _rm_ui (self, ident):
        ui = self.ui
        if ident in ui:
            overlay = ui[ident]
            del ui[ident]
            overlay.hide()

    def update_held (self):
        sfc = self._held_sfc
        if self.frog.item is not None:
            sfc = sfc.copy()
            self.frog.item.draw(sfc, (0, 0))
        self._add_ui('held', sfc)

    def say (self, msg):
        sfc = self.game.render_text(
            'msg', msg, conf.FONT_COLOUR, width = conf.MSG_WIDTH,
            bg = conf.UI_BG, pad = conf.MSG_PADDING, cache = ('msg', msg)
        )[0]
        self._add_ui('msg', sfc)

    def update (self):
        self.frog.update()
        self.road.update()
        self._changed.update(self.road.tiles)

    def _draw_objs (self, screen, objs):
        last = None
        # draw non-solid
        for o in objs:
            if isinstance(o, obj_module.OneTileObj):
                if o.solid:
                    last = o
                else:
                    o.draw(screen)
        # draw solid
        if last is not None:
            last.draw(screen)

    def _draw_cars (self, screen):
        for dirn, cars in self.road.cars:
            for car in cars:
                car.draw(screen)

    def draw (self, screen):
        bg = self.game.img('bg.png')
        draw_objs = self._draw_objs
        overlays = self.overlays
        road = self.road
        if self.dirty:
            self.dirty = False
            # background
            screen.blit(bg, (0, 0))
            # objects
            for col in self.objs:
                for objs in col:
                    if objs:
                        draw_objs(screen, objs)
            # moving cars
            self._draw_cars(screen)
            # overlays
            for overlay in overlays:
                overlay.draw(screen)
            rtn = True
        else:
            # draw changed tiles
            rects = self._changed_rects
            in_road_rect = road.tile_rect.collidepoint
            objs = self.objs
            sx, sy = TILE_SIZE
            todo_os = set()
            # draw bg and objs
            screen.blit(bg, road.rect, road.rect)
            for x, y in road.tiles:
                draw_objs(screen, objs[x][y])
                for overlay in overlays:
                    if (x, y) in overlay.tiles:
                        todo_os.add(overlay)
            for tile in self._changed:
                if in_road_rect(tile):
                    continue
                x, y = tile
                this_objs = objs[x][y]
                x *= sx
                y *= sy
                r = (x, y, sx, sy)
                screen.blit(bg, (x, y), r)
                draw_objs(screen, this_objs)
                # add to changed rects
                rects.append(r)
                # add overlays
                for overlay in overlays:
                    if tile in overlay.tiles:
                        todo_os.add(overlay)
            self._draw_cars(screen)
            rects.append(road.rect)
            # draw overlays
            for overlay in todo_os:
                overlay.draw(screen)
            rtn = rects
        self._changed = set()
        self._changed_rects = []
        return rtn
Example #42
0
def test_tail_distance():
    test_road = Road(2)
    test_car = Car()
    test_car_two = Car(10)
    assert test_road.set_tail_distance(test_car, test_car_two) == 6