def __init__(self, blue_robots=None, yellow_robots=None, ball_pos=(0, 0)): if yellow_robots is None: yellow_robots = [] if blue_robots is None: blue_robots = [] self.message = [] self.field = field.Field() self.ball = ball.Ball(pos=ball_pos) self.robots = [] self.running = False for robot_ in blue_robots: self.robots.append( robot.Robot('blue', self.field, robot_['start_position'], robot_['orientation'], radio_id=robot_['radio_id'], vision_id=robot_['vision_id'])) for robot_ in yellow_robots: self.robots.append( robot.Robot('yellow', self.field, robot_['start_position'], robot_['orientation'], radio_id=robot_['radio_id'], vision_id=robot_['vision_id']))
def findShortestTime(self, permutation, order): # OD format : {'time':time, 'robotType':type} robotX = robot.Robot("x") robotY = robot.Robot("y") robotZ = robot.Robot("z") robotsList = [robotX, robotY, robotZ] orderWeight = order.getTotalWeight() outputDict = {'time': sys.maxsize, 'robotType': None} for currentRobot in robotsList: if orderWeight <= currentRobot.maxWeight: totalTime = 0.0 previousNode = permutation[0] for node in permutation: if node.id == previousNode.id: continue totalTime += (node.getNbObjects() * PICKUP_TIME) distance = node.neighborsDict[previousNode.id] timeConstant = ( currentRobot.formulaConstant + (currentRobot.weight * currentRobot.formulaSlope)) travelTime = (timeConstant * distance) totalTime += travelTime currentRobot.weight += node.getNodeWeight() previousNode = node if totalTime < outputDict['time']: outputDict['time'] = totalTime outputDict['robotType'] = currentRobot.type return outputDict
def setupScenario1(self): start = (self.ring.rect.centerx, self.ring.rect.centery) dest = self.ring.pointOnRing() self.robots.append(robot.Robot(self.robotSpeed, start, 1, colours.BLUE)) self.robots.append( robot.Robot(self.robotSpeed, start, -1, colours.GREEN)) self.ring.draw(self.screen) for bot in self.robots: bot.drawRobot(self.screen) return dest
def testCapabilitiesHashIncludesContextAndFilter(self): robot1 = robot.Robot('Robot1') robot1.register_handler(events.WaveletSelfAdded, lambda: '') robot2 = robot.Robot('Robot2') robot2.register_handler(events.WaveletSelfAdded, lambda: '', context=events.Context.ALL) self.assertNotEqual(robot1.capabilities_hash(), robot2.capabilities_hash()) robot3 = robot.Robot('Robot3') robot2.register_handler(events.WaveletSelfAdded, lambda: '', context=events.Context.ALL, filter="foo") self.assertNotEqual(robot1.capabilities_hash(), robot2.capabilities_hash()) self.assertNotEqual(robot1.capabilities_hash(), robot3.capabilities_hash()) self.assertNotEqual(robot2.capabilities_hash(), robot3.capabilities_hash())
def get_robot(): robot_instace = getattr(g, '_robot', None) if robot_instace is None: botdata = robot.load_robot(app.config["ROBOT_CONFIG_PATH"], app.config['SMOOCHBOT_NAME']) robot_instace = g._robot = robot.Robot(botdata) return robot_instace
def main(): # DATA # Holds the information about game logic state (game or manual) autonomy = threading.Event() autonomy.clear() # Stop signal for all threads stop_flag = threading.Event() stop_flag.clear() # For remotely changing thrower speed (works with robot_thrower_calibration as r) q_thrower_speed = queue.Queue() # OBJECTS basket = bask.Basket("thresh/thresh_basket_pink.txt") balls = ball.Balls("thresh/thresh_ball.txt") camera_thread = cam.ImageCapRS2(stop_flag) camera = cam.Camera(basket, balls, camera_thread, stop_flag) mainboard = r.Mainboard(autonomy, stop_flag) # For testing only thrower using remote control #robot = r.Robot(mainboard, camera, autonomy, stop_flag, balls, basket, q_thrower_speed) robot = r.Robot(mainboard, camera, autonomy, stop_flag, balls, basket) # Manual control thread_manual_control = threading.Thread(name="manual", target=remote_control.gamepad, args=(mainboard, autonomy, stop_flag, q_thrower_speed), daemon=True) thread_manual_control.start() # The main loop for our program, use to display values etc robot.autopilot()
def init_new_map(walls, init_position): environment = env.Environment(screen, COLOR_ENVIROMENT, walls) robot = rb.Robot(screen, 2 * ROBOT_RADIUS, MAX_VELOCITY, MAX_DISTANCE_SENSOR) robot.position = init_position robot.use_sensors(walls) return environment, robot
def main(): # Open Image File as a coloured image img = utils.open_image(settings.settingsImagePath) # Retrieve filtered image walls = utils.apply_vision_filter(img) ground = utils.apply_ground_filter(img) # Initialize Bot with startup settings bot = robot.Robot(x=settings.settingsStartX, y=settings.settingsStartY, direction=settings.settingsFaceDirection, wall_map=walls, ground_map=ground, no_of_squares_per_side=settings.settingsGridSideSquares, cell_side_length=len(img) // settings.settingsGridSideSquares) # Initialize user bot scripts src = settings.settingsSrcClass(bot) # Run setup src.setup() loop_img = numpy.copy(img) while True: # Refresh Screen utils.refresh_screen(loop_img, bot) # Loop loop_img = numpy.copy(img) ret = src.loop(loop_img) if ret == SimulationRunStatus.STOP_SIMULATION: # If stop simulation signal, Exit break
def comm_task_on_pc(targets, max_step=100, imgsdir="1080p"): #读取模板文件 targets = vision.read_templates(targets, imgsdir) ###设置callback### #delay_exec - 单步延迟,delay_run - 命令组与命令组之间的延迟 cb_delay = DelayCallBack("delay", delay_exec=3.0, delay_run=0.0) #计数和DEBUG用的callback task_couter = Counter() cb_print = PrintCallBack("printer", task_couter, False) #初始化executor,并绑定callback executor = Executor(PC_bind, [cb_print, cb_delay]) #识别图像的感应器 sensor = VisionSensor(vision.caper_pc, vision.matcher_comm, targets) #组装机器人 rb = robot.Robot("rb01", executor, sensor) robot.Robot.active(rb) #激活机器人 #rb.max_step = max_step #防止无限循环,可以不设置 #rb.work_forever("bz1",task_couter,100) #开始工作 print(rb.__class__.active_robots.keys(), rb.__class__) return rb, task_couter
def test_prev(): x = 0 y = 0 rot = 0 capacity = 100 r = robot.Robot(x, y, rot, capacity, map_dict) assert r.prev().x == 0 assert r.prev().y == -1 r.right() assert r.prev().x == -1 assert r.prev().y == 0 r.right() assert r.prev().x == -1 assert r.prev().y == 1 r.right() assert r.prev().x == 0 assert r.prev().y == 1 r.right() assert r.prev().x == 1 assert r.prev().y == 0 r.right() assert r.prev().x == 1 assert r.prev().y == -1 r.right() assert r.prev().x == 0 assert r.prev().y == -1
def startBot(): robot = rob.Robot() robot.stop() robot.set_sensor(1, 'light') # potentiall change the port numbers later robot.set_sensor(2, 'light') # potentially change the port numbers later time.sleep(1) return robot
def doTasks(self): rt = robot.Robot() try: if rt.bind(rt.findWindowForeground(), "dx2", "dx", "dx", 0): rt.setPath("res") # Check time netTimeStr = rt.getWebTime() netTime = datetime.datetime.strptime(netTimeStr, "%Y-%m-%d %H:%M:%S") targetTime = netTime.replace(second=0) if (netTime.hour == 20 and netTime.minute > 45) or netTime.hour > 20: targetTime = targetTime.replace(day=netTime.day + 1, hour=20, minute=45) else: targetTime = targetTime.replace(hour=20, minute=45) rt.sleep((targetTime.timestamp() - netTime.timestamp()) * 1000, 0) while True: pic = rt.findPic( 0, 0, 1280, 720, "Drink.bmp", "333333", 0.9, 0) if pic[0] != -1: rt.rightClick(pic[1], pic[2]) rt.sleep(50) rt.mouseMove(1, 1) rt.sleep(200) finally: rt.unbind()
def __init__(self, win): self.ep = 0 self.ga = 2 self.al = 2 self.stepCount = 0 # Initialize GUI self.initGUI(win) # Initialize environment self.basket = robot.Basket(self.canvas, self.canvas.winfo_reqwidth() - 5 - 50, 100, self.canvas.winfo_reqwidth() - 5, 150, 'blue') self.basketPole = self.canvas.create_rectangle(self.canvas.winfo_reqwidth() - 10, 150, self.canvas.winfo_reqwidth(), self.canvas.winfo_reqheight(), fill='black') self.robot = robot.Robot(self.canvas, 10, 150, 50, 190, 'red', self.basket) self.robotEnvironment = robot.RobotEnvironment(self.robot) # Init Agent simulationFn = lambda agent: \ simulation.SimulationEnvironment(self.robotEnvironment,agent) actionFn = lambda state: \ self.robotEnvironment.getPossibleActions(state) self.learner = qlearningAgents.QLearningAgent(actionFn=actionFn) self.learner.setEpsilon(self.epsilon) self.learner.setLearningRate(self.alpha) self.learner.setDiscount(self.gamma) # Start GUI self.running = True self.stopped = False self.stepsToSkip = 0 self.thread = threading.Thread(target=self.run) self.thread.start()
def main(): ir = ir_sensor.IRSensor() mycar = robot.Robot() ultrasonic = ultrasonic_sensor.UltrasonicSensor() try: while True: r = ultrasonic.measure_average() print "ultrasonic sensor detects obstacle at %.1f cm " % r if r < 10.0 or ir.detectObstacle() == direction_enum.DirectionEnum( ).FRONT: print "Obstacle detected in front" mycar.backward() mycar.stop() time.sleep(0.5) nextAction(mycar, ultrasonic) time.sleep(0.5) elif ir.detectObstacle() == direction_enum.DirectionEnum().LEFT: print "Obstacle detected on Left" mycar.stop() nextAction(mycar, ultrasonic) time.sleep(0.5) elif ir.detectObstacle() == direction_enum.DirectionEnum().RIGHT: print "Obstacle detected on Right" mycar.stop() nextAction(mycar, ultrasonic) time.sleep(0.5) else: print "No Obstacle detected" mycar.forward() time.sleep(0.5) except KeyboardInterrupt as e: print e finally: mycar.cleanup()
def do_test_case(self, config, executor): # Create a list storing TotalUsers & UnreadyUsers self.totalAndUnreadyUsers = [int(config['COPY']), int(config['COPY'])] # Create a flag to determine all users are ready to submit self.allReady = [False] # number of copy cnt = 0 # number of the starting place start = 0 path = "" # choose the data path if config['ROLE'] == 'S': self.role = 0 path = self.STUDENT_CSV_PATH else: self.role = 1 path = self.INSTRUCTOR_CSV_PATH with open(path, newline='') as csvfile: rows = csv.reader(csvfile) for row in rows: # pass the row until the next available one if (start < self.next_to_use[self.role]): start += 1 continue if (cnt >= config["COPY"]): break if (row[0] != 'No.'): cnt += 1 executor.submit(robot.Robot().launch, row, config['TASK'], self.totalAndUnreadyUsers, self.allReady) time.sleep(self.WAIT_TIME_SPAWN_TEST) self.next_to_use[self.role] += cnt
def main(): http_fetcher = fetcher.HTTPFetcher() rb = robot.Robot(http_fetcher, [ ('/.*', AHandler), ]) worker.Worker(rb).start() IOLoop.instance().start()
def test_robot_parametrs(x, y, width, length): robot_obj = robot.Robot(x, y, width, length) assert robot_obj.length == length assert robot_obj.length == length assert robot_obj.x_position == x assert robot_obj.y_position == y assert robot_obj.get_coodrd() == (x, y)
def __init__(self, todo, max_distance, max_steering, verbose=False): self.todo = todo #Integer number of boxes in the warehouse self.boxCounter = 0 self.max_distance = max_distance #Maximum movement per move/turn self.max_steering = max_steering #Maximum steering angle per move/turn self.verbose = verbose #Optional flag you can toggle from the testing suite. self.robot = robot.Robot(max_distance = max_distance, max_steering = max_steering) self.Helper = Helper() self.Grid = self.Helper.Init() self.Grid[self.Helper.BOX_INDEX_ZERO][self.Helper.BOX_INDEX_ZERO] = '@' self.ExploredGrid = self.Helper.Init_explored() self.DropOff = [0.0, 0.0] self.MapDimensions = {} self.BoxPositions = [] self.CurrentBox = [] self.TargetBox = None self.robot_has_box = None self.robot_is_crashed = None self.boxes_delivered = None self.data = None self.FoundBox = False self.error_x = [] self.error_y = [] self.RefineMeasurements = [] self.start = True self.firstBox = True self.AngleTry = [] self.lastX = self.robot.x self.lastY = self.robot.y self.lastBearing = self.robot.bearing self.realX = 0.0 self.realY = 0.0 self.realbearing = 0.0 self.Relift = False self.LastMove = None self.LastMove_processed = None self.exploring = True self.MoveList = [] self.count = 0 self.recursion = 0 # Known map size # To update value functions later self.MapDimensions['min_x'] = self.Helper.BOX_INDEX_ZERO * 2 self.MapDimensions['max_x'] = 0 self.MapDimensions['min_y'] = self.Helper.BOX_INDEX_ZERO * 2 self.MapDimensions['max_y'] = 0
def main(): robot = rob.Robot() robot.stop() robot.set_sensor(1, 'light') time.sleep(1) baseLight = 2300 # figure out the line's sensor reading by observation baseSpeed = [-15, -15] # use calibrate only if checking sensor values # calibrate(robot) lightSensor = find_line_right(robot) kp = 0.285 # figure out this value later kd = 0.0 # gotta tune this value # rotates to the right lastErr = 0 first = True while (True): lightSensed = robot.get_sensor(1) # print(lightSensed) err = (lightSensed - baseLight) if (first): first = False dErr = 0 else: dErr = lastErr - err pControl = err * kp dControl = dErr * kd newPowLeft = baseSpeed[0] + (pControl + dControl) newPowRight = baseSpeed[1] - (pControl + dControl) robot.drive_robot_power(newPowLeft, newPowRight) lastErr = err time.sleep(0.01)
def __init__(self, state_machine_name, webserver_port, interbot_enabled=True): self.pic_control_channel = None self.pic_log_channel = None self.turret_channel = None self.interbot_channel = None self.interbot_server = None self.mediaplayer_channel = None self.web_server = None self.robot = robot.Robot(self) self.fsms = [] self.state_machine_name = state_machine_name self.webserver_port = webserver_port self.stopping = False self.is_match_started = False self.map = graphmap.Map(self) self.next_timers = [] self.timers = [] self.last_ka_date = datetime.datetime.now() self.start_date = None self.packet_queue = collections.deque() self.interbot_enabled = interbot_enabled self.exit_value = 0 self.sysinfo = sysinfo.SysInfo(self) self.metrics_timer = Timer(self, 5000, metrics.write, single_shot=False) self.metrics_timer.start()
def program(): r = robot.Robot() r.close_mouth() r.avoid_wall(45, 50, 110, 30) r.open_mouth() r.drive(500, power=2000) r.close_mouth()
def main(): key = 0 lastKey = 0 shaggy = robot.Robot() terminal_functions.init() print_main_menu() while key != 'q': if terminal_functions.kbhit(): key = terminal_functions.getch() lastKey = key if lastKey == 'c': shaggy.ConnectTo("10.42.0.249", 5006) if lastKey == 'f': shaggy.Fuzzy() if lastKey == 'b': shaggy.Braitenberg() if lastKey == 's': shaggy.ShutDown() break print("QUIT")
def start_client(socket_path): """ function to start the client :socket_path: path to create the file """ # create a robot object magellan = robot.Robot(x=0, y=-4, phi=0) magellan.set_map([[0, 0], [3, 5], [5, -7], [-1, 8], [-8, -9], [-8, 8]]) # open a socket if os.path.exists(socket_path): client = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) client.connect(socket_path) print("Initialised client socket.") print("Sending 'DONE' shuts down the server and quits.") for _ in range(1000): magellan.move([1, 0.25]) cur_state = magellan.get_state().tostring() readings = magellan.sense().reshape(-1, 1).tostring() client.send(cur_state) client.send(readings) client.send("DONE".encode('utf-8')) client.close() else: print("Couldn't Connect! to {}".format(socket_path)) print("Shutting down the worker")
def mainloop(): pygame.init() size = width, height = 1280, 720 viewport = pygame.Rect( 0, -height + round((2.2 + CHARGERS_PER_STATION) * TILE_SIZE), width, height) screen = pygame.display.set_mode(size, pygame.OPENGL | pygame.RESIZABLE) robots = [ bots.Robot(x, y) for x in range(0, width // TILE_SIZE, 3) for y in range(-1 - CHARGERS_PER_STATION, -1, 1) ] clock = pygame.time.Clock() paused = False tick = 0 srates = { bot: round(SENSOR_RATE * (0.2 + 0.8 * random.random())) for bot in robots } from time import time while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.VIDEORESIZE: viewport.size = event.size size = event.size screen = pygame.display.set_mode(size, pygame.RESIZABLE) if event.type == pygame.KEYDOWN and event.key == 32: paused = not paused pressed = pygame.key.get_pressed() viewport.y += pressed[pygame.K_DOWN] - pressed[pygame.K_UP] viewport.x += pressed[pygame.K_RIGHT] - pressed[pygame.K_LEFT] """ LOGIC """ if not paused: for idx, r in enumerate(robots): modulus = FRAME_RATE // srates[r] if tick % modulus == idx % modulus: sd = SensorData(r, robots) if False and sd.collided: paused = True r.sensorData(sd) for robot in robots: robot.tick() """ DRAWING """ screen.fill((0, 0, 0)) level.draw_tiles(screen, viewport) for r in robots: r.draw(screen, viewport) """ DISPLAY AND TIMING""" pygame.display.flip() clock.tick(FRAME_RATE) tick += 1
def test_part_two(self): "Test part two example of Robot object" # 1. Create Robot object from text myobj = robot.Robot(part2=True, text=aoc_24.from_text(PART_TWO_TEXT)) # 2. Check the part two result self.assertEqual(myobj.part_two(verbose=False), PART_TWO_RESULT)
def test_part_one(self): "Test part one example of Robot object" # 1. Create Robot object from text myobj = robot.Robot(text=aoc_24.from_text(PART_ONE_TEXT)) # 2. Check the part one result self.assertEqual(myobj.part_one(verbose=False), PART_ONE_RESULT)
def load_robots(self): robots = [robot.Robot()] robot_file = settings.get_robot_file() if robot_file: robots = [] with open(robot_file) as f: data = f.read().split() for i in range(0, len(data), 3): r = robot.Robot() r.set_code(data[i].strip()) r.position = tuple( [int(x) for x in data[i + 1].split(',')]) r.theta = float(data[i + 2]) r.id = i / 3 + 1 robots.append(r) self.show_ids = True return robots
def test_drop_undef(): x = -2 y = 2 rot = 2 capacity = 15 r = robot.Robot(x, y, rot, capacity, deepcopy(map_dict)) assert r.drop(9) == 'undef' assert not r.sum()
def __init__(self): self.sense = Sense(self) self.think = Think(self) self.act = Act(self) self.robot = robot.Robot(self) # self.pad = gamepad.Pad(self) self.stateMachine = StateMachine(self) self.commandQueue = CommandQueue(self) self.speechQueue = SpeechQueue()
def init_node(self): rospy.init_node('cimap_explorer', anonymous=False) self._num_robots = rospy.get_param("/num_robots") self._robot_perception_distance = rospy.get_param( "/robot_prerception_distance", 1) self._experiment_id = rospy.get_param("/experiment_id", 0) self._map_name = rospy.get_param("/map_name", 'default') self.swarm = [robot.Robot(i) for i in range(self._num_robots)] self.stoptime = rospy.get_param("/stoptime", 60)