def __init__(self, lanes, roadLength, new_cars, density): self.lanes = lanes self.roadLength = roadLength self.new_cars = new_cars self.cars = [] self.count = 0 self.times = [] self.num = 0 self.numcount = 0 #Create a world full of empty cars of size lanes x roadlength self.world = np.full((lanes, roadLength), car.Car(0, self.EMPTY, 0, 0, 0, 0), dtype=car.Car) for i in range(0, self.lanes): for j in range(0, self.roadLength): if random.randint(0, 100) <= density: new_car = car.Car(0, self.FILLED, i, j, self.roadLength, 0) self.world[i][j] = new_car self.cars.append(new_car) #crate an empty array of cars in the system self.points = {} self.time = 0 self.blocked_cars = [] self.traffic = [(37, 20, 0), (72, 10, 0), (128, 0, 0)]
class Testcase(unittest.TestCase): """ Submodule for unittests, derives from unittest.TestCase """ bmw = car.Car("BMW", 100000) volvo = car.Car("Volvo", 150000) # Name the function test_ to allow verbose information. def test_if_objects_are_same(self): """ Returns True if instances are not same """ self.assertIsNot(self.bmw, self.volvo) def test_attribute(self): """ Returns True attribute matches expected """ self.assertIs(self.bmw.model, "BMW") self.assertIs(self.volvo.model, "Volvo") def test_sum_instances(self): """ Returns True if __add__ is correct """ self.assertEqual(self.volvo + self.bmw, 250000) def test_equipment(self): """ Returns True if Airbag exists in equipment """ self.bmw.addEquipment("Bluetooth") self.bmw.addEquipment("Airbag") self.bmw.addEquipment("AC") self.assertIn("Airbag", self.bmw.equipment)
def test_car_wheels(self): man = car.Car('MAN', 'Truck', 'trailer') koenigsegg = car.Car('Koenigsegg', 'Agera R') self.assertEqual( [8, 4], [man.num_of_wheels, koenigsegg.num_of_wheels], msg= 'The car shoud have four (4) wheels except its a type of trailer')
def make_cars_appear(lanes, sources, traffic_lights, time, delta_time): new_cars = [] for source, light in zip(sources['car'], traffic_lights): for direction in ('NORTH', 'SOUTH'): src = source[direction] if not light.is_green(time): if src.chances_to_appear(delta_time): new_car = car_module.Car( light.position + car_module.Car.length + DISTANCE_MARGIN, 0, 0, 0, 0) targets = filter(lambda x: not x.exclusive, lanes) targets = filter( lambda x: not get_next_car(new_car, x) or rear( get_next_car(new_car, x), 0) > new_car.position + DISTANCE_MARGIN, targets) if targets: new_cars.append(new_car) random.choice(targets).add_car(new_car) src.reset() for index, lane in enumerate(lanes): src = sources['lanes'][index] if not lane.exclusive and src.chances_to_appear(delta_time): new_car = car_module.Car(0, 0, 0, 0, 0) next_car = get_next_car(new_car, lane) if not next_car or (rear(next_car, 0) > new_car.position + DISTANCE_MARGIN): lane.add_car(new_car) new_cars.append(new_car) src.reset() return new_cars
def __init__(self, client, name, drive_func): self.client = client self.drive_func = drive_func self.name = name self.track = track.Track() self.players = {} self.cars = [car.Car(1), car.Car(2), car.Car(3), car.Car(4)] self.world = world.generate_world(self)
def generate_car(self, score): #generate cars as more frequent as level grows if score > 10: c = car.Car(320, generate_ypos()) self.cars.append(c) elif random.randint(0, 11 - score) == 1: c = car.Car(320, generate_ypos()) self.cars.append(c)
def __init__(self, num_of_cars, lanes, length, speed_limit, init_pos, init_lane, ego_speed_init, dt, r_seed, x_range=10): self.n_lanes = lanes self.n_cars = num_of_cars self.x_range = x_range self.length = length self.speed_limit = speed_limit / 3.6 self.T = 1.5 self.s0 = self.T * self.speed_limit self.delta = 4 self.road_width = 4 self.lane_init = (init_lane - 1) * self.road_width + self.road_width * 0.5 self.dt = dt random.seed(r_seed) self.vehicle_list = [] # Ego Car v_init = random.random() * (ego_speed_init / 3.6) self.x_base = 0 self.vehicle_list.append( car.Car(init_pos, self.lane_init, v_init, 0, speed_limit, self.dt)) self.dist_to_front = -1 self.non_ego_limit = self.speed_limit * 0.4 ### RL Params self.done = False self.success = False self.reward = 0 self.timestep = 0 self.lane = self.lane_init self.lane_prev = self.lane_init self.x_goal = 3 self.steering = 0 self.lateral_controller = lateral_agent.lateral_control(dt) s = set() while len(s) < num_of_cars: s.add(np.random.choice(np.arange(0.3, 1, 0.05)) * self.length) alist = list(s) for n in range(0, self.n_cars): y_random = random.randint( 0, self.n_lanes - 2) * self.road_width + self.road_width * 0.5 x_random = alist[n] v_random = random.random() * self.non_ego_limit self.vehicle_list.append( car.Car(x_random, y_random, v_random, 0, speed_limit, self.dt))
def test_car_doors(self): opel = car.Car('Opel', 'Omega 3') porshe = car.Car('Porshe', '911 Turbo') self.assertListEqual( [ opel.num_of_doors, porshe.num_of_doors, car.Car('Koenigsegg', 'Agera R').num_of_doors ], [4, 2, 2], msg= 'The car shoud have four (4) doors except its a Porshe or Koenigsegg' )
def world_features(num=0): dyn = dynamics.CarDynamics(0.1) world = World() clane = lane.StraightLane([0., -1.], [0., 1.], 0.13) world.lanes += [clane, clane.shifted(1), clane.shifted(-1)] world.roads += [clane] world.fences += [clane.shifted(2), clane.shifted(-2)] world.cars.append(car.UserControlledCar(dyn, [-0.13, 0., math.pi/2., 0.3], color='red')) world.cars.append(car.Car(dyn, [0., 0.1, math.pi/2.+math.pi/5, 0.], color='yellow')) world.cars.append(car.Car(dyn, [-0.13, 0.2, math.pi/2.-math.pi/5, 0.], color='yellow')) world.cars.append(car.Car(dyn, [0.13, -0.2, math.pi/2., 0.], color='yellow')) #world.cars.append(car.NestedOptimizerCar(dyn, [0.0, 0.5, math.pi/2., 0.3], color='yellow')) return world
def main(): car_one = car.Car('black', 4) car_two = car.Car('black', 4) car_three = car.Car('blue', 4) car_four = car.Car('brown', 2) lst_of_cars = [car_one, car_two, car_three, car_four] for vehicle in lst_of_cars: print(vehicle.color) print(vehicle.number_of_doors) print(vehicle.number_of_wheels) vehicle.honk() print('-'* 46)
def __init__(self): pygame.init() pygame.display.set_caption("Running Car") self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) self.clock = pygame.time.Clock() self.ticks = 60 self.exit = False self.alive = True self.status = "RUNNING" # car, track image load self.track_image = pygame.image.load(TRACK_IMAGE_PATH) self.car_image = pygame.image.load(IMAGE_PATH) # create car self.car = car.Car(4, 8) # create a mask for each of them. self.track_mask = pygame.mask.from_surface(self.track_image, 50) self.car_mask = pygame.mask.from_surface(self.car_image, 50) mask = pygame.mask.from_surface(self.track_image) mask_fx = pygame.mask.from_surface( pygame.transform.flip(self.track_image, True, False)) mask_fy = pygame.mask.from_surface( pygame.transform.flip(self.track_image, False, True)) mask_fx_fy = pygame.mask.from_surface( pygame.transform.flip(self.track_image, True, True)) self.flipped_masks = [[mask, mask_fy], [mask_fx, mask_fx_fy]] self.beam_surface = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
def main(): #create instance of car my_car = car.Car(2003, 'Chevrolet') #speed it up and slow it down using class methods speed_up(my_car, 5) slow_down(my_car, 5)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.keysDown = [] self.label = pyglet.text.Label("test", font_name='Times New Roman', font_size=36, x=self.width // 2, y=self.height // 2, anchor_x='center', anchor_y='center') self.space = pymunk.Space() self.options = DrawOptions() self.score = 0 self.playerCar = car.Car(self.space) self.course = walls.Walls(self.space) self.coins = coins.Coins(self.space) self.fps = FPSDisplay(self) self.nearestCoinPos = self.coins.usedCoinPos[0] handler = self.space.add_collision_handler(1, 2) handler.begin = self.hitWall coinHandler = self.space.add_collision_handler(1, 3) coinHandler.begin = self.collectCoin
def _get_cars(self): competitors = [] for competitor in self._competitors: this_car = car.Car(competitor) competitors.append(this_car) self._notification_manager.subscribe(this_car) return (competitors)
def parser( tracefile, max_vehicles ): # Read the tracefile and fills nodecontainer with vehicles objects global nodecontainer # Structure: {'vehicle_id':object} node_id = int() # Var used to attribute a new id for each vehicle with open(tracefile, 'rb') as csvfile: fp = csv.DictReader(csvfile) for row in fp: # if row['vehicle_type'] == 'Vehicle': # Just cars if row['vehicle_id'] not in used_ids: if not nodecontainer.has_key(row['vehicle_id']) and ( node_id < max_vehicles): # how many nodes? Can I add one more? m_car = car.Car(n_id=node_id) nodecontainer[row['vehicle_id']] = m_car node_id += 1 # Increments node_id for another Vehicle add_ids.write(row['vehicle_id'] + '\n') time = row['timestep_time'] posX = row['vehicle_x'] posY = row['vehicle_y'] speed = row['vehicle_speed'] try: m_car = nodecontainer[ row['vehicle_id']] # temporary object m_car.setPositionAt(time, 'X_', posX) m_car.setPositionAt(time, 'Y_', posY) m_car.setVelocityAt(time, speed) except: pass add_ids.close()
def create_player(playerName, width, length): startingPosition = random_starting_location() playerScores[playerName] = 0 playerNames.append(playerName) playerColors[playerName] = random_color() return car.Car(playerColors[playerName], playerName, [startingPosition[0], startingPosition[1]], width, length)
def test_one(): ''' Simple test case with little movement. ''' # Create a 2D world of 0's height = 4 width = 6 world = np.zeros((height, width)) # Define the initial car state initial_position = [0, 0] # [y, x] (top-left corner) velocity = [0, 1] # [vy, vx] (moving to the right) # Create a car with initial params carla = car.Car(initial_position, velocity, world) carla.move() carla.move() carla.turn_right() carla.move() if carla.state == [[1, 2], [1, 0]]: return True else: return False
def test_three(): ''' Check when using a different initial position, velocity and world. ''' # Create a 2D world of 0's height = 6 width = 8 world = np.zeros((height, width)) # Define the initial car state initial_position = [4, 5] # [y, x] velocity = [1, 0] # [vy, vx] # Create a car with initial params carla = car.Car(initial_position, velocity, world) carla.turn_right() carla.move() carla.move() carla.turn_right() for i in range(10): carla.move() if carla.state == [[0, 3], [-1, 0]]: return True else: return False
def show(self): # get engine filename = self.getParamcomboBox.currentText() engine = rbfn.RBFN() engine.loadParams(filename) # set car self.c = car.Car() self.c.setEngine(engine) self.c.run() # self.c.saveResult() self.thread1 = threading.Thread(target=self.updateShow) self.thread1.start() self.resetFigure() ims = [] for i in range(len(self.c.x_rec)): move = list( zip([self.c.x_rec[i], self.c.y_rec[i]], [self.c.x_rec[i], self.c.y_rec[i]])) im = plt.plot(move[0], move[1], marker='o', markersize=20, color='b') ims.append(im) self.ani = animation.ArtistAnimation(self.fig, ims, interval=20, repeat=False) self.lay.setGeometry(QtCore.QRect(25, 101, 431, 341)) self.lay.setContentsMargins(100, 100, 100, 10) # left, up, right, down self.lay.update()
def test_two(): ''' More advanced case going off of the map. ''' # Create a 2D world of 0's height = 4 width = 6 world = np.zeros((height, width)) # Define the initial car state initial_position = [0, 0] # [y, x] (top-left corner) velocity = [0, 1] # [vy, vx] (moving to the right) # Create a car with initial params carla = car.Car(initial_position, velocity, world) carla.move() carla.move() carla.turn_right() carla.move() carla.move() carla.turn_left() for i in range(4): carla.move() if carla.state == [[2, 0], [0, 1]]: return True else: return False
def __init__(self, fig=None): # O = 31.5 # I = 28.5 # outer = geom.Figure([(-O, -O), # (-O, O), # (O, O), # (O, -O)], # close=True, fig=fig) # inner = geom.Figure([(-I, -I), # (-I, I), # (I, I), # (I, -I)], # close=True, fig=fig) # self.walls = geom.CompoundFigure([outer, inner]) P = 30.0 ps = [[-P, -P], [-P, P], [P, P], [P, -P]] #self.walls = track.make_track(ps, 3.0, fig=fig) self.walls = track.clover(2.0, scale=10.0, fig=fig) #1.5 self.walls.draw() self.car = car.Car((-110.0, 0), (0.0, 1.0), nrays=36, fig=fig, walls=self.walls) self._state = self._calc_state() self.draw() self.ema = 0.0 self.ema_a = 0.1
def car_init(): """Initialize the car to control it moving. Returns: A initialized car object. """ # Creates 4 wheels with GPIO and PWM configurations to make up the car. front_left_wheel = car.Wheel(pwm_pin=33, dir_pin_1=35, dir_pin_2=37, pwm_freq=1500) front_right_wheel = car.Wheel(pwm_pin=32, dir_pin_1=31, dir_pin_2=29, pwm_freq=1500) rear_left_wheel = car.Wheel(pwm_pin=40, dir_pin_1=38, dir_pin_2=36, pwm_freq=1500) rear_right_wheel = car.Wheel(pwm_pin=15, dir_pin_1=13, dir_pin_2=11, pwm_freq=1500) # Make up the car with the wheels. my_car = car.Car(front_left_wheel, front_right_wheel, rear_left_wheel, rear_right_wheel) return my_car
def initialization(self): # radioButton self.wheel.setChecked(True) # getTraincomboBox comboList = os.listdir(parent + '/data/') self.getTraincomboBox.addItems(comboList) self.getTraincomboBox.setEditable(True) self.getTraincomboBox.lineEdit().setReadOnly(True) self.getTraincomboBox.lineEdit().setAlignment(QtCore.Qt.AlignCenter) for i in range(self.getTraincomboBox.count()): self.getTraincomboBox.setItemData(i, QtCore.Qt.AlignCenter, QtCore.Qt.TextAlignmentRole) # getTraincomboBox comboList = os.listdir(parent + '/weights/') self.getParamcomboBox.addItems(comboList) self.getParamcomboBox.setEditable(True) self.getParamcomboBox.lineEdit().setReadOnly(True) self.getParamcomboBox.lineEdit().setAlignment(QtCore.Qt.AlignCenter) for i in range(self.getParamcomboBox.count()): self.getParamcomboBox.setItemData(i, QtCore.Qt.AlignCenter, QtCore.Qt.TextAlignmentRole) # buttons self.Go.clicked.connect(self.go) self.Save.clicked.connect(self.save) self.showPushButton.clicked.connect(self.show) # graph self.c = car.Car() self.fig = self.c.draw() self.resetFigure() # self.plotWidget = FigureCanvas(self.fig) self.lay = QtWidgets.QVBoxLayout(self.frame) self.lay.setGeometry(QtCore.QRect(25, 101, 431, 341)) self.lay.setContentsMargins(100, 100, 100, 10) # left, up, right, down self.lay.addWidget(self.plotWidget)
def setUp(self) -> None: """ Create three cars for testing The first car has a fuel efficiency of 20 miles/gallon, initial mileage of 1000 miles and 9 gallons of fuel in the tank. The second car has a fuel efficiency of 30 miles/gallon, initial mileage of 5000 miles and 2 gallons of fuel in the tank The third car has a fuel efficiency of 24 miles/gallon, initial mileage of 0 miles and an empty gas tank. """ # save the 3 car objects as instance variables # so we can access them in the test methods self.first_car = car.Car('Porsche', '911', 20, 1000, 9) self.second_car = car.Car('Honda', 'Civic', 30, 2000, 2) self.third_car = car.Car('Honda', 'Pilot', 24)
def main(): import base64, json global the_car tornado.options.parse_command_line() app = Application() app.listen(options.port) # initialize the car if options.replay: folder = options.replay print("replaying from %s" % options.replay) else: folder = "records/" + strftime("record_%a_%d_%b_%Y-%H_%M_%S", gmtime()) print("recording to %s" % folder) os.mkdir(folder) the_car = car.Car() print("recoding images with interval %f" % float(options.image_interval)) the_car.camera.start(folder, float(options.image_interval)) def _send_image(): image = the_car.camera.get_last_image() if image: img_base64 = base64.b64encode(image) CarSocketHandler.send_updates( json.dumps({ 'cmd': 'camera_sensor', 'value': img_base64 })) tornado.ioloop.PeriodicCallback(_send_image, 100).start() try: tornado.ioloop.IOLoop.current().start() except KeyboardInterrupt as e: the_car.camera.stop()
def __init__(self): super().__init__() self.controller = inputs.devices.gamepads[0] self.cur_track_segment = 0 track_f = open("track.json") track_data = json.load(track_f) track_f.close() self.track = track.Track(track_data, world) self.car = car.Car(base, world, self.track) dlight = DirectionalLight('dlight') dlnp = render.attachNewNode(dlight) dlnp.setHpr(0, -80, 0) render.setLight(dlnp) alight = AmbientLight('alight') alight.setColor(Vec4(0.2, 0.2, 0.2, 1)) alnp = render.attachNewNode(alight) render.setLight(alnp) myFog = Fog("Fog") myFog.setColor(0.2, 0.2, 0.2) myFog.setExpDensity(0.005) render.setFog(myFog) taskMgr.add(self.update, 'update') self.controller_t = threading.Thread(target=self.controller_tf, daemon=True) self.controller_t.start()
def test_default_car_name(self): gm = car.Car() self.assertEqual( 'General', gm.name, msg= 'The car should be called `General` if no name was passed as an argument' )
def playground(): dyn = dynamics.CarDynamics(0.1) world = World() clane = lane.StraightLane([0., -100.], [0., 100.], 0.17) world.lanes += [clane, clane.shifted(1), clane.shifted(-1)] #world.roads += [clane] #world.fences += [clane.shifted(2), clane.shifted(-2)] #world.cars.append(car.UserControlledCar(dyn, [0., 0., math.pi/2., 0.], color='orange')) world.auto_cars.append(car.Car([-0.17, -0.10, -math.pi/2., 0.], color='white',trained=0, car_no=0)) world.auto_cars.append(car.Car([-0.17, 0.1, -math.pi/2., 0.], color='white',trained=0,car_no=1)) world.auto_cars.append(car.Car([-0.17, -0.3, -math.pi/2., 255.], color='white',trained=0,car_no=2)) world.human_cars.append(car.Car([0, 0.30, -math.pi / 2., 0], color='blue',car_no=10)) for i in range(13): world.objects.append(car.Obj([0.35, 0.9-i*0.15])) world.objects.append(car.Obj([-0.35, 0.9 - i * 0.15])) return world
def generate_cars(self, solution_list): """Generate cars from the list of solutions(neural networks) to be evaluated""" cars = [] for solution in solution_list: cars.append( car.Car(solution, self.carStartPos[0], self.carStartPos[1])) return cars
def test_default_car_model(self): gm = car.Car() self.assertEqual( 'GM', gm.model, msg= "The car's model should be called `GM` if no model was passed as an argument" )