def test_straight_bets(): bin_builder = BinBuilder() wheel = Wheel() bin_builder.gen_straight_bets(wheel) assert wheel.get_bin(0).outcomes == frozenset([Outcome("0", 35)]) assert wheel.get_bin(37).outcomes == frozenset([Outcome("00", 35)]) assert wheel.get_bin(3).outcomes == frozenset([Outcome("3", 35)])
def test_streets_bets(): bin_builder = BinBuilder() wheel = Wheel() bin_builder.gen_streets_bets(wheel) assert wheel.get_bin(1).outcomes == frozenset([Outcome("1, 2, 3", 17)]) assert wheel.get_bin(2).outcomes == frozenset([Outcome("1, 2, 3", 17)]) assert wheel.get_bin(3).outcomes == frozenset([Outcome("1, 2, 3", 17)])
def test_column_bets(): bin_builder = BinBuilder() wheel = Wheel() bin_builder.gen_column_bets(wheel) assert wheel.get_bin(1).outcomes == frozenset([Outcome("Column 1", 2)]) assert wheel.get_bin(28).outcomes == frozenset([Outcome("Column 1", 2)]) assert wheel.get_bin(27).outcomes == frozenset([Outcome("Column 3", 2)])
def __init__(self, args): '''Constructor''' self.parser = msgParser.MsgParser() self.state = carState.CarState() self.control = carControl.CarControl() self.state_size = 20 self.action_size = 3 self.model = LinearModel(args.replay_size, self.state_size, self.action_size) self.enable_training = args.enable_training self.enable_exploration = args.enable_exploration self.show_sensors = args.show_sensors self.exploration_decay_steps = args.exploration_decay_steps self.exploration_rate_start = args.exploration_rate_start self.exploration_rate_end = args.exploration_rate_end from wheel import Wheel self.wheel = Wheel(args.joystick_nr, args.autocenter, args.gain, args.min_level, args.max_level, args.min_force) self.steer_lock = 0.785398 self.max_speed = 100 #from plotlinear import PlotLinear #self.plot = PlotLinear(self.model, ['Speed', 'Angle', 'TrackPos'], ['Steer', 'Accel', 'Brake']) if self.show_sensors: from sensorstats import Stats self.stats = Stats(inevery=8) self.reset()
def test_streetbet_builder(): wheel = Wheel() builder = BinBuilder() street1_2_3 = Outcome("Street 1-2-3", RouletteGame.StreetBet) builder._buildStreetBets(wheel) assert street1_2_3 in wheel.get(1)
class Game(): def __init__(self, gru_file=None): self.compiler = Compiler() if gru_file: self.stream = self.compiler.decompile(gru_file) else: self.stream = self.compiler.compile(None) self.metadata = self.stream.metadata self.flags = Flags(self.stream) self.wheel = Wheel(config) self.title = Title(config) self.inventory = Inventory(self.stream, self.flags, config) self.combiner = Combiner(self.stream, self.flags, self.inventory) self.page = Page(config, self.flags, self.combiner, self.inventory) self.state = State(self.stream, self.flags, self.inventory, self.wheel, self.combiner, self.title, self.page) if self.metadata.has_key("start"): start = self.metadata["start"] self.state.update(start) else: self.state.update("start") def draw(self, tick): self.inventory.draw() self.wheel.draw() self.title.draw() self.page.draw(tick)
def test_dozen_bets(): bin_builder = BinBuilder() wheel = Wheel() bin_builder.gen_dozen_bets(wheel) assert wheel.get_bin(1).outcomes == frozenset([Outcome("Dozen 1", 2)]) assert wheel.get_bin(13).outcomes == frozenset([Outcome("Dozen 2", 2)]) assert wheel.get_bin(36).outcomes == frozenset([Outcome("Dozen 3", 2)])
def get_outcome(self, outcome_name): """Query a constructed wheel for getting outcome.""" # create Whell wheel = Wheel() return wheel.get_outcome(outcome_name)
def test_linebet_builder(): wheel = Wheel() builder = BinBuilder() line1 = Outcome("Line 1-2-3-4-5-6", RouletteGame.LineBet) builder._buildLineBets(wheel) assert line1 in wheel.get(1)
def testFlat(self): testPressure = Wheel.BURST_PRESSURE / 2.0 wheel = Wheel() wheel.pressure = testPressure self.assertEqual(wheel.pressure, testPressure) self.assertEqual(wheel.flat, False) wheel.pressure = 0.0 self.assertEqual(wheel.flat, True)
def test_buildBins(): wheel = Wheel() builder = BinBuilder() assert wheel == builder.buildBins(wheel) number1 = Outcome("Number 1", RouletteGame.StraightBet) assert number1 in wheel.get(1) assert Outcome("Number 0", RouletteGame.StraightBet) in wheel.get(0) assert Outcome("Number 00", RouletteGame.StraightBet) in wheel.get(37)
def test_dozenbets_builder(): wheel = Wheel() builder = BinBuilder() dozen1 = Outcome("Dozen 1", RouletteGame.DozenBet) dozen2 = Outcome("Dozen 2", RouletteGame.DozenBet) builder._buildDozenBets(wheel) assert dozen1 in wheel.get(1) assert dozen2 not in wheel.get(1)
def __init__(self,u_color): self.front_wheel = Wheel(16) self.rear_wheel = Wheel(16) self.pedal = True self.handlebars = True self.frame = True self.brakes = True self.color = u_color self.speed = 0
def __init__(self, wheel_point1, wheel_radius1, wheel_point2, wheel_radius2, height): self.wheel1 = Wheel(wheel_point1, wheel_radius1 * 0.6, wheel_radius1) self.wheel2 = Wheel(wheel_point2, wheel_radius2 * 0.6, wheel_radius2) # TODO - Get the point coordinates to get the corners self.body = Rectangle( Point(wheel_point1.getX(), wheel_point1.getY() - height), Point(wheel_point2.getX(), wheel_point2.getY()))
def test_line_bets(): bin_builder = BinBuilder() wheel = Wheel() bin_builder.gen_line_bets(wheel) assert wheel.get_bin(1).outcomes == frozenset( [Outcome("1, 2, 3, 4, 5, 6", 5)]) assert wheel.get_bin(4).outcomes == frozenset( [Outcome("1, 2, 3, 4, 5, 6", 5), Outcome("4, 5, 6, 7, 8, 9", 5)])
def __init__(self): self.reducer = 100 * 52.0 / 11 self.len_chain = 3.7775 self.left_wheel = Wheel(1, '/dev/ttyS2', self.len_chain, self.reducer) self.left_wheel.ini_motor() self.right_wheel = Wheel(1, '/dev/ttyS3', self.len_chain, -self.reducer) self.right_wheel.ini_motor() self.dis_of_2wheels = 1.5
def test_cornerbet_builder(): wheel = Wheel() builder = BinBuilder() corner1 = Outcome("Corner 1-2-4-5", RouletteGame.CornerBet) builder._buildCornerBets(wheel) assert corner1 in wheel.get(1) corner36 = Outcome("Corner 32-33-35-36", RouletteGame.CornerBet) assert corner36 in wheel.get(36)
def test_colbet_builder(): wheel = Wheel() builder = BinBuilder() col1 = Outcome("Column 1", RouletteGame.ColumnBet) col2 = Outcome("Column 2", RouletteGame.ColumnBet) builder._buildColumnBets(wheel) assert col1 in wheel.get(1) assert col2 not in wheel.get(1) assert col2 in wheel.get(2)
def test_straightbet_builder(): wheel = Wheel() builder = BinBuilder() number1 = Outcome("Number 1", RouletteGame.StraightBet) builder._buildStraightBets(wheel) assert number1 in wheel.get(1) assert Outcome("Number 0", RouletteGame.StraightBet) in wheel.get(0) assert Outcome("Number 00", RouletteGame.StraightBet) in wheel.get(37)
def test_splitbet_builder(): wheel = Wheel() builder = BinBuilder() split1_2 = Outcome("Split 1-2", RouletteGame.SplitBet) builder._buildSplitBets(wheel) assert split1_2 in wheel.get(1) assert len(wheel.get(1)) == 2 assert len(wheel.get(2)) == 3 assert len(wheel.get(5)) == 4
def __init__(self, speed=80, frequency=1000): self.direction = Direction.Stop self.robotspeed = speed self.wheels = {} self.wheels[Axle.FrontLeft] = Wheel(23, 22, self.robotspeed, frequency) self.wheels[Axle.FrontRight] = Wheel(25, 24, self.robotspeed, frequency) self.wheels[Axle.BackLeft] = Wheel(27, 15, self.robotspeed, frequency) self.wheels[Axle.BackRight] = Wheel(14, 13, self.robotspeed, frequency) self.Stop()
def test_line_bets(): bin_builder = BinBuilder() wheel = Wheel() bin_builder.gen_line_bets(wheel) assert wheel.get_bin(1).outcomes == frozenset([ Outcome("1, 2, 3, 4, 5, 6", 5) ]) assert wheel.get_bin(4).outcomes == frozenset([ Outcome("1, 2, 3, 4, 5, 6", 5), Outcome("4, 5, 6, 7, 8, 9", 5) ])
def __init__(self): Wheel.__init__(self, 'TransportWheels') self.base_method = 'rotate around the axis in the vertical plane' # Creation of the dictionary to write object data #to a file in json and XML formats: self.key_value = collections.OrderedDict( zip(('classes', 'form', 'base_method', 'material', 'components','types'), ('TransportWheels(Wheel)', self.form, self.base_method, self.material, self.components, random.choice(self.types)) ) )
def test_dozen_bets(): bin_builder = BinBuilder() wheel = Wheel() bin_builder.gen_dozen_bets(wheel) assert wheel.get_bin(1).outcomes == frozenset([ Outcome("Dozen 1", 2) ]) assert wheel.get_bin(13).outcomes == frozenset([ Outcome("Dozen 2", 2) ]) assert wheel.get_bin(36).outcomes == frozenset([ Outcome("Dozen 3", 2) ])
def __init__(self, back_wheel_center, back_tire_radius, front_wheel_center, front_tire_radius, body_height): upper_left_point = Point(back_wheel_center.x, back_wheel_center.y - body_height) bottom_right_point = front_wheel_center self.body = Rectangle(upper_left_point, bottom_right_point) self.back_wheel = Wheel(back_wheel_center, back_tire_radius * Car.WHEEL_TO_TIRE_RATIO, back_tire_radius) self.front_wheel = Wheel(front_wheel_center, front_tire_radius * Car.WHEEL_TO_TIRE_RATIO, front_tire_radius)
def test_evenmoneybets_builder(): wheel = Wheel() builder = BinBuilder() red = Outcome("Red", RouletteGame.EvenMoneyBet) black = Outcome("Black", RouletteGame.EvenMoneyBet) builder._buildEvenMoneyBets(wheel) assert red in wheel.get(1) assert black in wheel.get(2) even = Outcome("Even", RouletteGame.EvenMoneyBet) assert even not in wheel.get(3) assert even in wheel.get(2)
def testBurst(self): wheel = Wheel() wheel.pressure = Wheel.BURST_PRESSURE / 2.0 self.assertEqual(wheel.flat, False) self.assertEqual(wheel.burst, False) wheel.pressure = Wheel.BURST_PRESSURE self.assertEqual(wheel.pressure, 0.0) self.assertEqual(wheel.flat, True) self.assertEqual(wheel.burst, True) wheel.pressure = Wheel.BURST_PRESSURE / 2.0 self.assertEqual(wheel.pressure, 0.0) self.assertEqual(wheel.flat, True) self.assertEqual(wheel.burst, True)
def test_even_money_bets(): bin_builder = BinBuilder() wheel = Wheel() bin_builder.gen_even_money_bets(wheel) assert wheel.get_bin(1).outcomes == frozenset([ Outcome("Low", 1), Outcome("Odd", 1), Outcome("Red", 1), ]) assert wheel.get_bin(24).outcomes == frozenset([ Outcome("High", 1), Outcome("Even", 1), Outcome("Black", 1), ])
class MotorController: def __init__(self): self.wheel1 = Wheel(input1 = LEFT_INPUT_1, input2 = LEFT_INPUT_2, encoder_pin = LEFT_ENCODER , forward_flags = [False , True] , reverse_flags = [True , False]) self.wheel2 = Wheel(input1 = RIGHT_INPUT_1 , input2 = RIGHT_INPUT_2, encoder_pin = RIGHT_ENCODER , forward_flags = [True , False] , reverse_flags = [False , True]) def forward(self , state_count = 1): current_state_count = 0 while current_state_count != state_count: self.wheel1.forward() self.wheel2.forward() current_state_count += 1 def reverse(self , state_count = 1): current_state_count = 0 while current_state_count != state_count: self.wheel1.reverse() self.wheel2.reverse() current_state_count += 1
def __init__(self): self.motor_controller = Adafruit_MotorHAT(i2c_address) self.FL = Wheel(self.motor_controller, FL_id, trim[0], invert=True) self.FR = Wheel(self.motor_controller, FR_id, trim[1], invert=True) self.RL = Wheel(self.motor_controller, RL_id, trim[2]) self.RR = Wheel(self.motor_controller, RR_id, trim[3]) self.all_wheels = [self.FL, self.FR, self.RL, self.RR] self.left_wheels = [self.FL, self.RL] self.right_wheels = [self.FR, self.RR] self.left_diag = [self.FL, self.RR] self.right_diag = [self.FR, self.RL] atexit.register(self.stop) self.stop()
def __init__(self): self.right_arm = Arm() self.left_arm = Arm() self.front_right_wheel = Wheel() self.back_right_wheel = Wheel() self.front_left_wheel = Wheel() self.back_left_wheel = Wheel()
class Car(): WHEEL_TO_TIRE_RATIO = 0.6 def __init__(self, back_wheel_center, back_tire_radius, front_wheel_center, front_tire_radius, body_height): upper_left_point = Point(back_wheel_center.x, back_wheel_center.y - body_height) bottom_right_point = front_wheel_center self.body = Rectangle(upper_left_point, bottom_right_point) self.back_wheel = Wheel(back_wheel_center, back_tire_radius * Car.WHEEL_TO_TIRE_RATIO, back_tire_radius) self.front_wheel = Wheel(front_wheel_center, front_tire_radius * Car.WHEEL_TO_TIRE_RATIO, front_tire_radius) def set_color(self, tire_color, wheel_color, body_color): self.body.setFill(body_color) self.back_wheel.set_color(wheel_color, tire_color) self.front_wheel.set_color(wheel_color, tire_color) def draw(self, win): self.body.draw(win) self.back_wheel.draw(win) self.front_wheel.draw(win) def animate(self, win, dx, dy, n): pass
def __init__(self): """ """ # engine rpm self._rpm = 100 #rev/min # vehicle mass self.mass = 1550 #kg FORD # current longitudinal speed self.speed = 0 #m/s # current acceleration self.acceleration = 0 #m/s**2 # current gear in the gearbox self.gear = 0 #pure # drag resistance self.drag_cd = 0.328 #pure FORD # final ratio on the drive wheels self.final_ratio = 3.61 #pure FORD # cg height self.cg_height = 1.0 #m # wheelbase, distance between the front and rear wheels self.wheelbase = 2.489 #m FORD self.efficiency = 0.75 # gears-engine scale factors FORD self.gear_ratios = [(3.583), (1.926), (1.206), (0.878), (0.689)] #pure # curve for the rpm-torque relation in the engine self.engine_rpm_torque_curve_params = optimize.curve_fit( self.rpm_torque_function, (0, 100, 2000, 3000, 4000, 5000, 6000), (10, 190, 230, 240, 250, 210, 180), p0=[-1, 1, 150])[0] #self.wheel_slip_longitudinal_force_curve_params = optimize.curve_fit(self.slip_longitudinal_force_function, # (-100.1, -20, -10, 0, 10, 20, 100.1), # (0, -4000, -6000, 0, 6000, 4000, 0), # p0=[6000, 1e-3])[0] self.max_gear_rpm = 5000 #rev/min self.thrust = 1 self.wheels = [ # rear Wheel(self.wheelbase * 0.5, drive=True), Wheel(self.wheelbase * 0.5, drive=True), # front Wheel(self.wheelbase * 0.5, drive=False), Wheel(self.wheelbase * 0.5, drive=False), ] self.vis_speed = [] self.vis_forces = [] self.vis_res_forces = [] self.vis_gears = [] self.vis_engine_rpm = [] self.vis_engine_torques = []
def __init__( self, back_wheel_pos, back_wheel_rad, front_wheel_pos, front_wheel_rad, car_height ): # constructor method to instantiate self.back_wheel = Wheel(back_wheel_pos, back_wheel_rad, back_wheel_rad + 5) # a class object self.front_wheel = Wheel( front_wheel_pos, front_wheel_rad, front_wheel_rad + 5 ) # attributes of the Car class are defined self.car_body = Rectangle( Point(back_wheel_pos.getX(), back_wheel_pos.getY() - car_height), front_wheel_pos # and initialized ) self.car_color = "" self.Road_1 = Line(Point(0, 100), Point(1200, 100)) self.Road_2 = Line(Point(0, 40), Point(1200, 40))
def test_run_the_wheel(): nrg = NonRandom([0, 37]) wheel = Wheel(nrg) outcome_0 = Outcome("0", 35) outcome_5 = Outcome("Five", 6) outcome_00 = Outcome("00", 35) wheel.add_outcome(0, outcome_0) wheel.add_outcome(0, outcome_5) wheel.add_outcome(37, outcome_00) wheel.add_outcome(37, outcome_5) bin = wheel.next() assert bin.outcomes == frozenset([outcome_0, outcome_5]) bin = wheel.next() assert bin.outcomes == frozenset([outcome_00, outcome_5])
def test_split_bets(): bin_builder = BinBuilder() wheel = Wheel() bin_builder.gen_split_bets(wheel) assert wheel.get_bin(1).outcomes == frozenset( [Outcome("1, 2", 17), Outcome("1, 4", 17)]) assert wheel.get_bin(20).outcomes == frozenset([ Outcome("17, 20", 17), Outcome("19, 20", 17), Outcome("20, 21", 17), Outcome("20, 23", 17), ]) assert wheel.get_bin(18).outcomes == frozenset([ Outcome("15, 18", 17), Outcome("17, 18", 17), Outcome("18, 21", 17), ])
def testSpecific(self): testDiameter: float = 22.0 testPressure: float = Wheel.BURST_PRESSURE / 2.0 wheel = Wheel(diameter=testDiameter, pressure=testPressure) self.assertEqual(wheel.pressure, testPressure) self.assertEqual(wheel.diameter, testDiameter) self.assertEqual(wheel.burst, False) self.assertEqual(wheel.flat, False)
def test_split_bets(): bin_builder = BinBuilder() wheel = Wheel() bin_builder.gen_split_bets(wheel) assert wheel.get_bin(1).outcomes == frozenset([ Outcome("1, 2", 17), Outcome("1, 4", 17) ]) assert wheel.get_bin(20).outcomes == frozenset([ Outcome("17, 20", 17), Outcome("19, 20", 17), Outcome("20, 21", 17), Outcome("20, 23", 17), ]) assert wheel.get_bin(18).outcomes == frozenset([ Outcome("15, 18", 17), Outcome("17, 18", 17), Outcome("18, 21", 17), ])
def test_corner_bets(): bin_builder = BinBuilder() wheel = Wheel() bin_builder.gen_corner_bets(wheel) assert wheel.get_bin(1).outcomes == frozenset([Outcome("1, 2, 4, 5", 8)]) assert wheel.get_bin(4).outcomes == frozenset([ Outcome("1, 2, 4, 5", 8), Outcome("4, 5, 7, 8", 8), ]) assert wheel.get_bin(7).outcomes == frozenset([ Outcome("4, 5, 7, 8", 8), Outcome("7, 8, 10, 11", 8), ]) assert wheel.get_bin(8).outcomes == frozenset([ Outcome("4, 5, 7, 8", 8), Outcome("5, 6, 8, 9", 8), Outcome("7, 8, 10, 11", 8), Outcome("8, 9, 11, 12", 8), ])
def test_build(): bin_builder = BinBuilder() wheel = Wheel() bin_builder.build_bins(wheel) wheel.get_bin(13).outcomes == frozenset([ Outcome("13", 35), Outcome("10, 13", 17), Outcome("13, 14", 17), Outcome("13, 16", 17), Outcome("13, 14, 15", 11), Outcome("10, 11, 13, 14", 8), Outcome("13, 14, 16, 17", 8), Outcome("10, 11, 12, 13, 14, 15", 5), Outcome("13, 14, 15, 16, 17, 18", 5), Outcome("Dozen 1", 2), Outcome("Column 1", 1), Outcome("Low", 1), Outcome("Odd", 1), Outcome("Black", 1), ])
def __init__(self, args): '''Constructor''' self.parser = msgParser.MsgParser() self.state = carState.CarState() self.control = carControl.CarControl() self.states = [] self.actions = [] self.filename = args.save_replay assert self.filename is not None, "Use --save_replay <filename>" from wheel import Wheel self.wheel = Wheel(args.joystick_nr, args.autocenter, args.gain, args.min_level, args.max_level, args.min_force) self.episode = 0 self.onRestart() self.show_sensors = args.show_sensors if self.show_sensors: from sensorstats import Stats self.stats = Stats(inevery=8)
def test_wheel_add(): outcome = Outcome("00", 35) wheel = Wheel(NonRandomNumberGenerator()) wheel.addOutcome(4, outcome) assert outcome in wheel.get(4) with pytest.raises(IndexError): wheel.get(40)
class Roulette(object): def __init__(self): self._wheel = Wheel() self._wheel.spin() def play(self): print(self._wheel.landed_number(), " line 32") print("What would you like to bet on") while True: games_played = 0 games_won = 0 games_played += 1 choice1 = input("Number/Pair/Color? [n/p/c]: ") if choice1 in ("N", "n"): choice2 = input("Pick a number [0-36]: ") playerbet = choice2 if playerbet == self._wheel.landed_number(): print("You WON!!!!") games_won += 1 else: print("You lost... Try again") break elif choice1 in ("P", "p"): choice3 = input("Odd or Even? [o/e]: ") playerbet = choice3 if playerbet == determine_pair(): print("You WON!!!!") Roulette.games_won += 1 else: print("You lost... Try again - Line 55") break elif choice1 in ("C", "c"): choice4 = input("Red or Black? [r/b]: ") playerbet = choice4 print(playerbet, "entered answer") wheelroll = self._wheel.landed_number() print(determine_color(wheelroll), "line 61") wheelcolor = 'determine_color(wheelroll)' playerbet = 'playerbet.strip()' wheelcolor = wheelcolor.strip() print(id(playerbet), id(wheelcolor)) if 'playerbet' == 'wheelcolor': print("You WON!!!!") Roulette.games_won += 1 else: print("You lost... Try again") break else: print("Issues encountered. Don't know why we are here") break print(playerbet, "line 71") print(self._wheel.landed_number(), "line 72")
def game_loop(): player = Player(mglobals.PLAYER) wheel = Wheel() player_ui = ui.PlayerUI() event_ui = ui.EventUI() player_ui.update(player.cash, player.heart, player.face) msg_ui = ui.MsgUI() utils.draw_board() player.render() player_ui.render() while True: event_ui.update(player.position) if player.position in mglobals.CellTypes.MSG.value and player.round > 0: msg_ui.update(player.position) msg_ui.play() for event in pygame.event.get(): if event.type == pygame.QUIT: return elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() quit() if event.key == pygame.K_RETURN: wheel.spin() wheel.show() # Move the player token across the board for _ in range(wheel.number): utils.draw_board() player_ui.render() player.advance(1) event_ui.update(player.position) if player.round > mglobals.ZERO: sleep(0.4) break sleep(0.4) pygame.display.update() event_ui.play() pygame.display.update() mglobals.CLK.tick(30)
def add_wheels(self, number): for count in range(number): self.wheels.append(Wheel())
def test_wheel_next(): outcome = Outcome("00", 35) wheel = Wheel(NonRandomNumberGenerator()) wheel.addOutcome(0, outcome) # Non random will return first assert outcome in wheel.next() outcome = Outcome("00", 35) wheel = Wheel(NonRandomNumberGenerator()) wheel.addOutcome(1, outcome) # Non random will return first assert outcome not in wheel.next() random_wheel = Wheel() for i in range(38): random_wheel.addOutcome(i, outcome) assert outcome in random_wheel.next()
def test_wheel_get(): outcome = Outcome("00", 35) wheel = Wheel(NonRandomNumberGenerator()) wheel.addOutcome(4, outcome) assert outcome in wheel.bins[4]
def init_wheel(self): debug_print_mtcall("Application", "init_wheel") self.wheel = Wheel(self.canbus)
class Driver(object): ''' A driver object for the SCRC ''' def __init__(self, args): '''Constructor''' self.parser = msgParser.MsgParser() self.state = carState.CarState() self.control = carControl.CarControl() self.state_size = 20 self.action_size = 3 self.model = LinearModel(args.replay_size, self.state_size, self.action_size) self.enable_training = args.enable_training self.enable_exploration = args.enable_exploration self.show_sensors = args.show_sensors self.exploration_decay_steps = args.exploration_decay_steps self.exploration_rate_start = args.exploration_rate_start self.exploration_rate_end = args.exploration_rate_end from wheel import Wheel self.wheel = Wheel(args.joystick_nr, args.autocenter, args.gain, args.min_level, args.max_level, args.min_force) self.steer_lock = 0.785398 self.max_speed = 100 #from plotlinear import PlotLinear #self.plot = PlotLinear(self.model, ['Speed', 'Angle', 'TrackPos'], ['Steer', 'Accel', 'Brake']) if self.show_sensors: from sensorstats import Stats self.stats = Stats(inevery=8) self.reset() def init(self): '''Return init string with rangefinder angles''' self.angles = [0 for x in range(19)] for i in range(5): self.angles[i] = -90 + i * 15 self.angles[18 - i] = 90 - i * 15 for i in range(5, 9): self.angles[i] = -20 + (i-5) * 5 self.angles[18 - i] = 20 - (i-5) * 5 return self.parser.stringify({'init': self.angles}) def getState(self): #state = np.array(self.state.getTrack()) state = np.array(self.state.getTrack() + [self.state.getSpeedX()]) assert state.shape == (self.state_size,) return state def getTerminal(self): return np.all(np.array(self.state.getTrack()) == -1) def getEpsilon(self): # calculate decaying exploration rate if self.total_train_steps < self.exploration_decay_steps: return self.exploration_rate_start - self.total_train_steps * (self.exploration_rate_start - self.exploration_rate_end) / self.exploration_decay_steps else: return self.exploration_rate_end def drive(self, msg): # parse incoming message self.state.setFromMsg(msg) # by default predict all controls by model state = self.getState() steer, accel, brake = self.model.predict(state) self.control.setSteer(max(-1, min(1, steer))) self.control.setAccel(max(0, min(1, accel))) #self.control.setBrake(max(0, min(1, brake))) # if not out of track turn the wheel according to model terminal = self.getTerminal() events = self.wheel.getEvents() for event in events: if self.wheel.isButtonDown(event, 0) or self.wheel.isButtonDown(event, 8): self.control.setGear(-1) elif self.wheel.isButtonDown(event, 1) or self.wheel.isButtonDown(event, 9): self.control.setGear(1) if self.control.getGear() >= 0: self.gear() # replace random exploration with user assistance epsilon = self.getEpsilon() # show sensors if self.show_sensors: self.state.botcontrol = 1 - epsilon self.state.mancontrol = (self.control.getGear() == -1) self.stats.update(self.state) print "epsilon: ", epsilon, "\treplay: ", self.model.count if (self.enable_training and terminal) or self.control.getGear() == -1 or (self.enable_exploration and random.random() < epsilon): if terminal or self.control.getGear() == -1: self.wheel.resetForce() self.control.setSteer(self.wheel.getWheel()) self.control.setAccel(self.wheel.getAccel()) self.control.setBrake(self.wheel.getBrake()) if self.enable_training and not terminal and self.control.getGear() != -1: action = (self.control.getSteer(), self.control.getAccel(), self.control.getBrake()) self.model.add(state, action) self.model.train() #self.plot.update() else: if terminal: self.steer() self.speed() else: steer = self.control.getSteer() assert -1 <= steer <= 1 wheel = self.wheel.getWheel() #print "steer:", steer, "wheel:", wheel self.wheel.generateForce(steer - wheel) self.total_train_steps += 1 return self.control.toMsg() def steer(self): angle = self.state.angle dist = self.state.trackPos self.control.setSteer((angle - dist*0.5)/self.steer_lock) def speed(self): speed = self.state.getSpeedX() accel = self.control.getAccel() if speed < self.max_speed: print "speed < max_speed", speed, self.max_speed accel += 0.1 if accel > 1: accel = 1.0 else: print "speed >= max_speed", speed, self.max_speed accel -= 0.1 if accel < 0: accel = 0.0 self.control.setAccel(accel) def gear(self): ''' rpm = self.state.getRpm() gear = self.state.getGear() if rpm > 7000: gear += 1 ''' speed = self.state.getSpeedX() gear = self.state.getGear() if speed < 25: gear = 1 elif 30 < speed < 55: gear = 2 elif 60 < speed < 85: gear = 3 elif 90 < speed < 115: gear = 4 elif 120 < speed < 145: gear = 5 elif speed > 150: gear = 6 self.control.setGear(gear) def onShutDown(self): pass def onRestart(self): self.episode += 1 print "Episode", self.episode def reset(self): self.wheel.resetForce() self.enable_training = True self.total_train_steps = 0 self.model.reset() self.episode = 0 self.onRestart() def test_mode(self): self.total_train_steps = self.exploration_decay_steps self.enable_training = False
import enum from engine import Engine from gearbox import GearBox from wheel import Wheel class CarType(enum.Enum): sedan = "SEDAN" wagon = "WAGON" engine = Engine(100, 8000, 7000, 6200, 180, False) gearbox = GearBox(6, "manual") wheelList = [ Wheel(20, "summer", 2.6, 100), Wheel(20, "summer", 2.6, 100), Wheel(20, "summer", 2.6, 100), Wheel(20, "summer", 2.6, 100) ] class Car: moving = False def __init__(self, actualCarType): self.actualCarType = actualCarType def Car(self, actualCarType): self.actualCarType = actualCarType