def testCanGetDistanceToPreviousCar(self): car = Car(radius=100, alpha=0) anotherCar = Car(radius=100, alpha=math.pi / 2) car.previous_car = anotherCar self.assertAlmostEqual(100 * math.sqrt(2), car.distance_to_previous_car)
class Slot: def __init__(self, number): self.number = number self.empty = True self.car = None def make_it_empty(self): self.empty = True del self.car self.car = None print "Slot number " + str(self.number) + " is free" def put_car(self, registration_number, color): self.car = Car(registration_number, color) self.empty = False print "Allocated slot number: " + str(self.get_slot_number()) def get_car_parked(self): if self.empty: return None, None return self.car.get_registration_number(), self.car.get_color() def is_empty(self): return self.empty def get_slot_number(self): return self.number
def testCanMoveCarTwice(self): car = Car(alpha=0, speed=1) car.move() car.move() self.assertEqual(0 + 1 + 1, car.alpha)
def testCanGetMovedCarCoordinates(self): car = Car(radius=100, alpha=0, speed=math.pi / 6) car.move() self.assertAlmostEqual(100 * math.sqrt(3) / 2, car.x, 5) self.assertAlmostEqual(100 * 1 / 2, car.y, 5)
def setup_window(self): width = 800 height = 650 x = (self.window.winfo_screenwidth() / 2) - (width / 2) y = (self.window.winfo_screenheight() / 2) - (height / 2) if self.window.winfo_screenwidth() == 1920: self.window.geometry('%dx%d+%d+%d' % (width, height, x + 500, y)) else: self.window.geometry('%dx%d+%d+%d' % (width, height, x - 500, y)) self.window.title('Race Circuit') self.canvas = Canvas(self.window, bg='#202827', height=height - 40, width=width) self.canvas.bind("<Button-1>", self.start_line) self.canvas.bind("<B1-Motion>", self.drawing_line) self.canvas.bind("<ButtonRelease-1>", self.draw_line) self.car = Car(self.canvas) # Car Control self.window.bind("<KeyPress-Up>", self.car.up) self.window.bind("<KeyPress-Down>", self.car.down) self.window.bind("<KeyPress-Left>", self.car.turn_left) self.window.bind("<KeyPress-Right>", self.car.turn_right) self.window.bind("<space>", self.car.stop) self.canvas.pack(side=BOTTOM)
def testStopWhenCrash(self): car = Car(radius=100, alpha=0, speed=1) anotherCar = Car(radius=100, alpha=0.01, speed=1) car.previous_car = anotherCar car.move() self.assertAlmostEqual(0, car.speed)
def testAccelerateWhenDistanceToPreviousCarIsBig(self): car = Car(radius=100, alpha=0, speed=1, speed_limit=2) anotherCar = Car(radius=100, alpha=math.pi, speed=1) car.previous_car = anotherCar car.move() self.assertAlmostEqual(1.2, car.speed)
def testDecelerateWhenDistanceToPreviousCarIsSmall(self): car = Car(radius=100, alpha=0, speed=0.1) anotherCar = Car(radius=100, alpha=0.5, speed=0.1) car.previous_car = anotherCar car.move() self.assertAlmostEqual(0.08, car.speed)
def testCarHas2LapsAfterCrossing0Twice(self): car = Car(alpha=0.01, speed=math.pi, speed_limit=10) car.move() car.move() car.move() car.move() self.assertEqual(2, car.laps)
def test_engine_turned_off_when_car_is(mocker): # Set up mock / given engine = mocker.Mock() car = Car(engine) # when car.turn_off() # then assert the function was called once engine.turn_off.assert_called_once()
class TestCar(unittest.TestCase): def setUp(self): self.car = Car("123", "Red") def test_color(self): self.assertEqual(self.car.get_color(), 'Red') def test_reg_number(self): self.assertEqual(self.car.get_registration_number(), '123')
def test_car_on_when_engine_on(mocker): # Set up mock / given engine = mocker.Mock() engine.on = True car = Car(engine) # Get result / when actual = car.is_on() # Assert / then assert actual == True
def __init__(self, circuit, render=False): self.circuit = circuit self.car = Car(self.circuit, num_sensors=self.NUM_SENSORS) # To render the environment self.render = render if render: self.ui = Interface(self.circuit, self.car) self.ui.show(block=False) # Build the possible actions of the environment self.actions = [] for turn_step in range(-2, 3, 1): for speed_step in range(-1, 2, 1): self.actions.append((speed_step, turn_step)) self.count = 0
class CarTest(unittest.TestCase): def setUp(self): self.initialSpeed = 3 self.testObject = Car(self.initialSpeed) def test_ctor_speed(self): """ctor should initialize speed field""" testObject = Car(9) assert testObject.getSpeed() == 9 def test_brake_stop(self): """brake should stop the car""" self.testObject.speed = 30 self.testObject.brake() assert self.testObject.speed == 0
def select_new_gen(self): if time.time() - self.start > self.max_ai_loop_time: for ai in self.AIs: ai.die() if self.groups['AIs']: return self.best_AIs = sorted(self.AIs, key=lambda ai: ai.fitness, reverse=True)[:6] best_AI = self.best_AIs[0] if best_AI.fitness > self.all_time_best[0]: self.all_time_best = [best_AI.fitness, best_AI] mating_pool = [(ai, ai.fitness) for ai in self.best_AIs] # if self.all_time_best[1]: # mating_pool.append((self.all_time_best[1], self.all_time_best[0])) random.shuffle(mating_pool) new_gen = [] for _ in range(len(self.AIs)): partner_1 = self.select_random_cumulative(mating_pool) partner_2 = self.select_random_cumulative(mating_pool) child = Car.cross_over(self, partner_1, partner_2) new_gen.append(child) self.AIs = new_gen self.groups['AIs'].add(*new_gen) self.groups['cars'].add(*new_gen) self.start = time.time()
def _init(self): self._running = True pygame.init() pygame.font.init() self.font = pygame.font.SysFont('Ubuntu', 15) self.bg = pygame.image.load('track2.png') self._display_surf = pygame.display.set_mode( self.size, pygame.HWSURFACE | pygame.DOUBLEBUF) self._display_surf.blit(self.bg, (0, 0)) self.player = Car(self, None) self.AIs = [Car(self, AI([4, 4])) for _ in range(20)] #[Car() for _ in range(100)] [] self.groups['players'] = pygame.sprite.Group([self.player]) self.groups['cars'] = pygame.sprite.Group([self.player, *self.AIs]) self.groups['AIs'] = pygame.sprite.Group(self.AIs) self.groups['text'] = pygame.sprite.Group()
def test_change_list_of_strings_to_list_of_cars(): file_location = '/Users/jacob.scheuer/Development/python/AutoXAPI/data/carClasses.pdf' list_of_rows = extract_pdf_rows_into_list_of_strings(file_location) list_of_cars = change_list_of_strings_to_list_of_cars(list_of_rows) actual = list_of_cars[0] expected = Car(make="Acura", model="CL", car_class="H Street") assert actual == expected assert len(list_of_cars) == 901
def matrix_to_solution(self, matrix: List[List[bool]]) -> Solution: """ transforms a two-dimensional binary list into a chromosome """ cars: List[Car] = [ Car(self.dataset.bonus) for _ in range(self.dataset.ncars) ] solution: Solution = Solution(cars, self.dataset.rides.copy()) solution.matrix_allocation(matrix) return solution
def add_car(self, pos=None, vel=1, idx=-1): if pos is None: if np.sum(self.intensities) > 1: self.intensities = np.divide(self.intensities, np.sum(self.intensities)) pos = choice2(self.starting_point, p=self.intensities) else: assert (0 <= pos.x < self.cellmap.shape[0] and 0 <= pos.y < self.cellmap.shape[1]), "Invalid position" assert self.cellmap[pos.x, pos.y].kind == "road", "Position is not a road" assert 0 < vel < 5, "Invalid velocity" if self.cellmap[pos.x, pos.y].car is None: car = Car(position=pos, velocity=choice([1, 2, 3, 4]), idx=idx) # car = Car(position=pos, velocity=1, idx=idx) self.cellmap[pos.x, pos.y].car = car self.cars.append(car)
def __init__(self, origin, destination, stations_list, **kwargs): # Optional parameters initialisation self.battery_lowest = kwargs.get('battery_lowest', 15) self.station_max_distance = kwargs.get('station_max_distance', 20000) self.car = kwargs.get('car', Car('default', 50, 35)) # Primary data: origin and destination locations, and charging station list self.origin = origin self.destination = destination self.stations_list = stations_list self.distance = 0 self.duration = 0 self.steps = [] # Become an array if the travel need to stop at some charging station. self.waypoints = None self.stations = [] self.get_direct_road() self.find_empty_battery_location()
def create_random_population(self): """ creates random population with size equal to max_population_size """ start = tm.time() progress = tqdm(total=self.max_population_size, desc='Creating first random population') while len(self.population) < self.max_population_size: cars: List[Car] = [ Car(self.dataset.bonus) for _ in range(self.dataset.ncars) ] random_solution: Solution = Solution(cars, self.dataset.rides.copy()) random_solution.randomize_allocation() self.population.append(random_solution) progress.update(1) progress.set_postfix_str( 'Generated Chromosomes = {}, Time Elapsed = {:.2f} seconds'. format(len(self.population), tm.time() - start)) progress.close() progress.clear()
def test_acceleration(): car = Car(2, 0, 1) car.accelerate(17) assert car.get_speed() == 17
class Game: FRAMERATE = 60 def __init__(self): self._running = True self._display_surf = None self._bg = None self.size = self.width, self.height = 840, 600 self.clock = pygame.time.Clock() self.start = time.time() self.max_ai_loop_time = 10 self.groups = {} self.font = None self.starting_line = [(360, 80), (360, 160)] self.finish_line = [(350, 80), (350, 160)] self.all_time_best = [0, None] self.best_AIs = [] self.goals = { 'start': { 'coords': [(360, 80), (360, 160)], 'points': 10 }, 'finish': { 'coords': [(350, 80), (350, 160)], 'points': 60 }, 'checkpoints': { 0: { 'coords': [(540, 230), (630, 230)], 'points': 50 }, 1: { 'coords': [(600, 450), (650, 523)], 'points': 10 }, 2: { 'coords': [(175, 300), (250, 260)], 'points': 50 }, 3: { 'coords': [(450, 330), (450, 415)], 'points': 120 }, 4: { 'coords': [(263, 500), (263, 580)], 'points': 20, 'special': 'speed' } } } def _init(self): self._running = True pygame.init() pygame.font.init() self.font = pygame.font.SysFont('Ubuntu', 15) self.bg = pygame.image.load('track2.png') self._display_surf = pygame.display.set_mode( self.size, pygame.HWSURFACE | pygame.DOUBLEBUF) self._display_surf.blit(self.bg, (0, 0)) self.player = Car(self, None) self.AIs = [Car(self, AI([4, 4])) for _ in range(20)] #[Car() for _ in range(100)] [] self.groups['players'] = pygame.sprite.Group([self.player]) self.groups['cars'] = pygame.sprite.Group([self.player, *self.AIs]) self.groups['AIs'] = pygame.sprite.Group(self.AIs) self.groups['text'] = pygame.sprite.Group() def on_event(self, event): # print(event) if event.type == pygame.QUIT: self._running = False def on_loop(self): keystate = pygame.key.get_pressed() if keystate[pygame.K_UP]: self.player.accelerate(1) if keystate[pygame.K_DOWN]: self.player.accelerate(-1) if keystate[pygame.K_RIGHT]: self.player.steer(-1) if keystate[pygame.K_LEFT]: self.player.steer(1) if keystate[pygame.K_SPACE]: for ai in self.AIs: ai.die() self.groups['cars'].update() self.groups['cars'].clear(self._display_surf, self.bg) self.groups['cars'].draw(self._display_surf) self.draw_goals() self.select_new_gen() self.draw_stats() def on_cleanup(self): pygame.quit() def run(self): self._init() while self._running: for event in pygame.event.get(): self.on_event(event) self.on_loop() pygame.display.update() self.clock.tick(Game.FRAMERATE) self.on_cleanup() def sensor_check_on_track(self, pos, facing, stop=100): facing = facing.normalize() left_looking = facing.rotate(-45) right_looking = facing.rotate(45) to_go = {"f": facing, "l": left_looking, "r": right_looking} dist = {"f": stop, "l": stop, "r": stop} for d in range(stop): for i in to_go: if not to_go[i]: continue landed = pos + to_go[i] * d landed_rounded = round(landed[0]), round(landed[1]) try: pixel = self._display_surf.get_at(landed_rounded) if pixel == (255, 255, 255, 255): to_go[i] = False dist[i] = d except IndexError: continue return dist def draw_stats(self): self._display_surf.fill((255, 255, 255), pygame.Rect(700, 30, 100, 100)) self._display_surf.fill((255, 255, 255), pygame.Rect(10, 30, 100, 100)) self._display_surf.blit( self.font.render('Top 5 best cars', True, (0, 0, 0)), (700, 30)) self._display_surf.blit( self.font.render('All time best', True, (0, 0, 0)), (10, 30)) self._display_surf.blit( self.font.render( f'{self.all_time_best[0]}', True, self.all_time_best[1].color.rgb if self.all_time_best[1] else (0, 0, 0)), (10, 50)) for i in range(min(len(self.best_AIs), 5)): text = self.font.render(f'{i+1}. {self.best_AIs[i].fitness}', True, self.best_AIs[i].color.rgb) self._display_surf.blit(text, (700, 30 + (i + 1) * 15)) def draw_goals(self): goals = [ self.goals['start'], self.goals['finish'], *self.goals['checkpoints'].values() ] for goal in goals: coords = goal['coords'] pygame.draw.line(self._display_surf, 200, coords[0], coords[1]) def select_new_gen(self): if time.time() - self.start > self.max_ai_loop_time: for ai in self.AIs: ai.die() if self.groups['AIs']: return self.best_AIs = sorted(self.AIs, key=lambda ai: ai.fitness, reverse=True)[:6] best_AI = self.best_AIs[0] if best_AI.fitness > self.all_time_best[0]: self.all_time_best = [best_AI.fitness, best_AI] mating_pool = [(ai, ai.fitness) for ai in self.best_AIs] # if self.all_time_best[1]: # mating_pool.append((self.all_time_best[1], self.all_time_best[0])) random.shuffle(mating_pool) new_gen = [] for _ in range(len(self.AIs)): partner_1 = self.select_random_cumulative(mating_pool) partner_2 = self.select_random_cumulative(mating_pool) child = Car.cross_over(self, partner_1, partner_2) new_gen.append(child) self.AIs = new_gen self.groups['AIs'].add(*new_gen) self.groups['cars'].add(*new_gen) self.start = time.time() def select_random_cumulative(self, pool): max_val = sum(i[1] for i in pool) selected = random.random() * max_val c = 0 for cand, val in pool: c += val if c >= selected: return cand
def predict4(self, img, frame_index, cars, name): print("-" * 50) start_detect_vehicle = time.time() cars_img, Lcars = self.detect_vehicle.detect(img, name, pixel_threshold=50000) print("Predict vehicle cost: ", time.time() - start_detect_vehicle) Llp_shapes = [] Llp_str = [] for i, (car, loc) in enumerate(zip(cars_img, Lcars)): print() print("Processing car {}".format(i + 1)) cur_car = Car(frame_index, loc.tl(), loc.br()) need_check = True car_name = "car_{}".format(len(cars) + 1) for key, value in cars.items(): if value.in_list(cur_car): if value.license_plate is not None: # cur_car.license_plate = value.license_plate need_check = False car_name = key if need_check: start_detect_lp = time.time() lp_img, shape = self.license_plate_detection.predict( car, "{}_car{}".format(name, i)) print("Predict lp cost: ", time.time() - start_detect_lp) print("\t\tCar image shape:\t", car.shape) print("\t\tCar image location:\t", loc) Llp_shapes.append(shape) if lp_img is not None: start_ocr = time.time() lp_str = self.ocr.predict(lp_img) print("Predict ocr cost: ", time.time() - start_ocr) Llp_str.append(lp_str) cur_car.license_plate = lp_str print("\t\tLP image shape: ", lp_img.shape) print("\t\tResult: ", lp_str) else: Llp_str.append(None) else: Llp_shapes.append(None) Llp_str.append(None) if car_name not in cars: cars[car_name] = ListCars([], None) print("New car_name {}: ".format(car_name), cars[car_name].cars) cars[car_name].add(cur_car) print("cur car license_plate: ", cur_car.license_plate) start_gen_output = time.time() img = self.gen_output.draw(img, Lcars, Llp_shapes, Llp_str) print("Gen output cost: ", time.time() - start_gen_output) print("TOTAL TIME: ", time.time() - start_detect_vehicle) return img, Llp_str, len(cars_img)
def testCanMoveCar(self): car = Car(alpha=0, speed=math.pi / 2, speed_limit=10) car.move() self.assertEqual(math.pi / 2, car.alpha)
def testCarHas1LapsAfterCrossing0(self): car = Car(alpha=2 * math.pi - 1, speed=2, speed_limit=2) car.move() self.assertEqual(1, car.laps)
def greedy_solve(self) -> Solution: def manhattan_distance(v1, v2): return abs(v1[0] - v2[0]) + abs(v1[1] - v2[1]) solution = Solution([Car(self.bonus) for _ in range(self.ncars)], self.rides.copy()) step = 0 progress = tqdm(total=self.steps, desc='Building initial solution') while step < self.steps: for car in solution.cars: if car.step > step: continue ride_priority = [ sys.maxsize for _ in solution.unallocated_rides ] rides_available: bool = False for ride_id, ride in enumerate(solution.unallocated_rides): distance_to_car = manhattan_distance( car.position, ride.orig) if step + distance_to_car > self.steps: continue if step + distance_to_car + ride.distance > ride.latest_finish: continue earliest_start = ride.earliest_start - step ride_priority[ride_id] = abs(distance_to_car - earliest_start) rides_available = True if not rides_available: continue ride_id = None priority = sys.maxsize for ri, rp in enumerate(ride_priority): if rp < priority: ride_id = ri priority = rp ride = solution.unallocated_rides[int(ride_id)] distance_to_car = manhattan_distance(car.position, ride.orig) ride_start = max([step + distance_to_car, ride.earliest_start]) car.step = ride_start + ride.distance car.allocate_ride(ride) car.position = ride.dest solution.unallocated_rides.remove(ride) step += 1 progress.update(1) progress.close() return solution
def empty_solution(self) -> Solution: return Solution([Car(self.bonus) for _ in range(self.ncars)], self.rides.copy())
def test_split_string_into_key_value_ineligible(): test_string = "Acura CL ineligible" expected = Car("Acura", "CL", "ineligible") actual = Car.car_from_string(test_string) assert actual == expected
class App: """Application principale""" def __init__(self): self.window = Tk() self.canvas = None self.forms = [] self.setup_window() self.setup_window_components() self.is_drawing_mode = False self.is_drawing_line = False self.line_start_x = None self.line_start_y = None def setup_window(self): width = 800 height = 650 x = (self.window.winfo_screenwidth() / 2) - (width / 2) y = (self.window.winfo_screenheight() / 2) - (height / 2) if self.window.winfo_screenwidth() == 1920: self.window.geometry('%dx%d+%d+%d' % (width, height, x + 500, y)) else: self.window.geometry('%dx%d+%d+%d' % (width, height, x - 500, y)) self.window.title('Race Circuit') self.canvas = Canvas(self.window, bg='#202827', height=height - 40, width=width) self.canvas.bind("<Button-1>", self.start_line) self.canvas.bind("<B1-Motion>", self.drawing_line) self.canvas.bind("<ButtonRelease-1>", self.draw_line) self.car = Car(self.canvas) # Car Control self.window.bind("<KeyPress-Up>", self.car.up) self.window.bind("<KeyPress-Down>", self.car.down) self.window.bind("<KeyPress-Left>", self.car.turn_left) self.window.bind("<KeyPress-Right>", self.car.turn_right) self.window.bind("<space>", self.car.stop) self.canvas.pack(side=BOTTOM) def setup_window_components(self): self.draw_line_btn = Button(self.window) self.draw_line_img = PhotoImage(file=ROOT_DIR + "/assets/draw_line.png") self.draw_line_btn.config(image=self.draw_line_img, command=self.active_drawing_mode) self.draw_line_btn.pack(side=LEFT) self.open_btn = Button(self.window) self.open_img = PhotoImage(file=ROOT_DIR + "/assets/open.png") self.open_btn.config(image=self.open_img, command=self.choose_and_draw_from_file) self.open_btn.pack(side=LEFT) self.save_btn = Button(self.window) self.save_img = PhotoImage(file=ROOT_DIR + "/assets/save.png") self.save_btn.config(image=self.save_img, command=self.save_positions) self.save_btn.pack(side=LEFT) self.erase_btn = Button(self.window) self.erase_img = PhotoImage(file=ROOT_DIR + "/assets/erase.png") self.erase_btn.config(image=self.erase_img, command=self.erase) self.erase_btn.pack(side=LEFT) self.reset_btn = Button(self.window) self.reset_img = PhotoImage(file=ROOT_DIR + "/assets/reset.png") self.reset_btn.config(image=self.reset_img, command=self.reset) self.reset_btn.pack(side=LEFT) def reset(self): self.car.reset() def run(self, creative_mode=False): if creative_mode is False: circuit01_path = ROOT_DIR + "/saves/circuit01.txt" if os.path.exists(circuit01_path): self.draw_from_file(circuit01_path) self.car.draw() self.car.move() self.window.mainloop() def active_drawing_mode(self): """ Fonction de callback appelée lorsque l'on appuie sur le bouton de dessin """ self.is_drawing_mode = not self.is_drawing_mode if self.is_drawing_mode is True: self.draw_line_btn.config(bg='#aaa') else: self.draw_line_btn.config(bg='#d9d9d9') def start_line(self, event): """ Fonction de callback appelée lorsque l'on clique dans le canvas a pour effet d'activer une variable de controle qui va dire que l'on est en train de dessiner ainsi que d'enregistrer la position x;y de départ de la ligne """ # active une seconde variable qui servira de condition quant à l'écoute de l'event B1-Motion if self.is_drawing_mode: self.is_drawing_line = True self.line_start_x = event.x self.line_start_y = event.y def drawing_line(self, event): """ Fonction de callback appelée lorsque l'on maintient le click enfoncé pour dessiner la ligne Si jamais on est en mode dessin et que l'on a bien cliquer pour commencer à dessiner, alors on supprime tous les dessins avec le tag 'temporary', et on crée une ligne avec la position de départ et la position courante de la souris """ if self.is_drawing_mode and self.is_drawing_line: self.canvas.delete("temporary") line = self.canvas.create_line(self.line_start_x, self.line_start_y, event.x, event.y, width=3, fill="#A9ACAB") self.canvas.itemconfig(line, tags="temporary") def draw_line(self, event): """ Lorsque l'on relache la souris, les lignes temporaires sont supprimées, et une ligne "définitive" est crée et ajoutée à une liste """ if self.is_drawing_mode and self.is_drawing_line: self.canvas.delete("temporary") self.is_drawing_line = False line_coord = self.line_start_x, self.line_start_y, event.x, event.y line = self.canvas.create_line(*line_coord, width=3, fill="#A9ACAB") self.canvas.itemconfig(line, tags="track_segment") self.forms.append(line) def draw_point(self, point): self.canvas.create_oval(point[0] - 3, point[1] - 3, point[0], point[1], outline='red', fill='red') def save_positions(self): if len(self.forms) == 0: print("Il n'y a rien à sauvegarder") else: positions = "" for form in self.forms: positions += str(self.canvas.coords(form)).replace( "[", "").replace("]", "") + "\n" save_text_in_file(positions, saves_dir, "save_" + now.strftime("%Y%d%m-%H%M%S")) def choose_and_draw_from_file(self): self.erase() file_path = choose_file(saves_dir) self.draw_from_file(file_path) def draw_from_file(self, file_path): with open(file_path, 'r') as file: for line in file: coords = line.replace(" ", "").rstrip().split(",") line_form = self.canvas.create_line(coords[0], coords[1], coords[2], coords[3], width=3, fill="#A9ACAB") self.canvas.itemconfig(line_form, tags="track_segment") self.forms.append(line_form) def erase(self): self.canvas.delete("track_segment") self.forms = []
class Environment(object): NUM_SENSORS = 5 def __init__(self, circuit, render=False): self.circuit = circuit self.car = Car(self.circuit, num_sensors=self.NUM_SENSORS) # To render the environment self.render = render if render: self.ui = Interface(self.circuit, self.car) self.ui.show(block=False) # Build the possible actions of the environment self.actions = [] for turn_step in range(-2, 3, 1): for speed_step in range(-1, 2, 1): self.actions.append((speed_step, turn_step)) self.count = 0 def reward(self) -> float: """Computes the reward at the present moment""" # This should return a float""" if not (self.isEnd()): reward = self.car.speed * (min(self.car.distances())) else: reward = -1 return reward def isEnd(self) -> bool: """Is the episode over ?""" if (not (self.car.in_circuit())): return True return False def reset(self): self.count = 0 self.car.reset() self.circuit.reset() return self.current_state @property def current_state(self): result = self.car.distances() result.append(self.car.speed) return result def step(self, i: int, greedy): """Takes action i and returns the new state, the reward and if we have reached the end""" self.count += 1 self.car.action(*self.actions[i]) state = self.current_state isEnd = self.isEnd() reward = self.reward() completed = self.circuit.laps * 100 + self.circuit.progression * 100 if self.render: self.ui.update() return state, reward, isEnd, completed def mayAddTitle(self, title): if self.render: self.ui.setTitle(title)
def test_string_to_car(): test_string = "Acura CL H Street HS" expected = Car("Acura", "CL", "H Street") actual = Car.car_from_string(test_string) assert actual == expected