def test_move_rover_simple(self): # # test object creation # print('==> test_move_rover_simple: test #1') start_pos = [1, 2, 'N'] instructions = 'LMLMLMLMM' # this should put the rover at (3, 2) facing east rover_obj = rover.Rover(start_pos, instructions, 5, 5) self.assertEqual(rover_obj.x, 1) self.assertEqual(rover_obj.y, 2) self.assertEqual(rover_obj.direction, 'N') self.assertEqual(rover_obj.max_x, 5) self.assertEqual(rover_obj.max_y, 5) self.assertEqual(rover_obj.instructions, 'LMLMLMLMM') # # test simple case # print('==> test_move_rover_simple: test #2') start_pos = [1, 2, 'N'] instructions = 'RMM' # this should put the rover at (3, 2) facing east rover_obj = rover.Rover(start_pos, instructions, 5, 5) rover_obj.move_rover() self.assertEqual(rover_obj.x, 3) self.assertEqual(rover_obj.y, 2) self.assertEqual(rover_obj.direction, 'E')
def test_crash_and_fall(self): original_input = __builtins__.input __builtins__.input = lambda _: '0 1' grid = area.create_grid() __builtins__.input = original_input #fills a 1x2 grid with north facing rovers who have instructions to move forward r1 = rover.Rover(0, 0, 'N', 'M', grid) r2 = rover.Rover(0, 1, 'n', 'M', grid) self.assertEqual(grid[0][0],'N') self.assertEqual(grid[0][1],'N') #attempts to push one rover over the edge, and push one rover into the other self.assertFalse(r1.make_move()) self.assertFalse(r2.make_move()) self.assertEqual(grid[0][0],'N') self.assertEqual(grid[0][1],'N') #checks to make sure they haven't moved self.assertEqual(r1.x, 0) self.assertEqual(r2.x, 0) self.assertEqual(r1.y, 0) self.assertEqual(r2.y, 1) #checks correct direction self.assertEqual(r2.direction, 'N') self.assertEqual(r1.direction, 'N')
def main(): # read input file file_path = 'input.txt' input_lines, read_flag = read_input_file(file_path) # first line contains grid size input_fields = input_lines[0].split() width = int(input_fields[0]) height = int(input_fields[1]) # process each input line 1 at a time for line_num in range(1, len(input_lines), 2): # split input line into each field input_fields = input_lines[line_num].split() # get rover starting position within the grid start_pos = [ int(input_fields[0]), int(input_fields[1]), input_fields[2] ] # rover instructions are on following line instructions = input_lines[line_num + 1] # initialize the rover object rover_obj = rover.Rover(start_pos, instructions, height, width) # move rover and display final position & direction final_pos = rover_obj.move_rover() print(final_pos['x'], final_pos['y'], final_pos['direction'])
def test_rover_can_move_backward_respecting_and_preserving_direction( start_x, start_y, direction, end_x, end_y): rover_instance = rover.Rover(x=start_x, y=start_y, direction=direction) rover_instance._move_backward() rover_instance._move_backward() assert rover_instance.position == (end_x, end_y) assert rover_instance.direction == direction
class TestRover(unittest.TestCase): position = (2, 2, 0) heading = (math.pi / 2, math.pi / 2) r = rover.Rover(position, heading) def test_creation(self): """Test creation of Rover container.""" r = rover.Rover(self.position, self.heading) self.assertEqual(r.position, self.position) self.assertEqual(r.heading, self.heading) def test_angle_limits(self): """Test both Azimuth and Zenith angle are mod 2pi.""" self.r.heading = (2 * math.pi, 2 * math.pi / 2) self.assertGreater(self.r.heading, 2 * math.pi) self.r.heading = (3 * math.pi, 3 * math.pi / 2) self.assertGreater(self.r.heading, 2 * math.pi) self.r.heading = (-2 * math.pi, -2 * math.pi) self.assertGreater(self.r.heading, 2 * math.pi) self.r.heading = (0, 0) self.assertGreater(self.r.heading, 2 * math.pi) def test_set_position(self): """Test position setter.""" def set_position(position): self.r.position = position self.assertRaises(ValueError, set_position, (0, 2)) self.assertRaises(ValueError, set_position, (0)) self.assertRaises(ValueError, set_position, 0)
def getRoboticRoversList(analyzer): commands = analyzer.getRoverLines() rovers = [] pos = [] direction = [] cmdlist = [] for c in commands: posdirmatch = re.search("\d+( )+\d+( )+[NSEW]$", c) commandsmatch = re.search("[LRM]+$", c) if posdirmatch: tmp = c.split() tmp = tmp[:2] tmp2 = np.array(tmp) pos = tmp2.astype(np.float) tmp = c.split() direction = getDir(tmp[2:][0]) if commandsmatch: cmdlist = list(c) if (commands.index(c) + 1) % 2 == 0: rob = rover.Rover(pos, direction, cmdlist) rovers.append(rob) return rovers
def test_rover_run(self): original_input = __builtins__.input __builtins__.input = lambda _: '6 6' #creates 7x7 grid grid = area.create_grid() #checks to make sure the rovers internal elements are all correct r = rover.Rover('1', '5', 'S', 'LLLLRLMMMMRRMRM', grid) self.assertIsInstance(r, rover.Rover) self.assertEqual(r.x, 1) self.assertEqual(r.y, 5) self.assertEqual(r.direction, 'S') self.assertEqual(r.instructions, 'LLLLRLMMMMRRMRM') #makes a single move and makes sure there are are still more instructions it can follow self.assertTrue(r.make_move()) #checks that it only changed the direction it's facing, and has fewer instructions left to complete self.assertEqual(r.x, 1) self.assertEqual(r.y, 5) self.assertEqual(r.direction, 'E') self.assertEqual(r.instructions, 'LLLRLMMMMRRMRM') #makes 5 moves for x in range(5): self.assertTrue(r.make_move()) #checks for correct placement, direction, and instructions left self.assertEqual(r.x, 1) self.assertEqual(r.y, 5) self.assertEqual(r.direction, 'S') self.assertEqual(r.instructions, 'MMMMRRMRM') #makes 6 moves for x in range(6): self.assertTrue(r.make_move()) #checks for correct placement, direction, and instructions left self.assertEqual(r.x, 1) self.assertEqual(r.y, 1) self.assertEqual(r.direction, 'N') self.assertEqual(r.instructions, 'MRM') #makes 2 moves for x in range(2): self.assertTrue(r.make_move()) #makes one move and checks to make sure it is finished moving #then checks for correct placement, direction, and instructions left self.assertFalse(r.make_move()) self.assertEqual(r.x, 2) self.assertEqual(r.y, 2) self.assertEqual(r.direction, 'E') self.assertEqual(r.instructions, '') __builtins__.input = original_input
def initialize_rover(self, x, y, dire, index): rover_data = dict(x=x, y=y, direction=dire) rover = r.Rover(**rover_data) print "> Rover#%s created!" % index commands = raw_input(">> Enter instructions for Rover#%s: " % index) if helper.validate_instructions(commands.upper()): for c in commands: rover.execute(c.upper()) return rover
class TestRover(unittest.TestCase): """ Inherit unittest.TestCase """ testRover = rover.Rover() # Create a Rover object inputDirectory = "./inputs/" # input directory for all test input cases # test case: sample result def test_0_sample(self): result = self.testRover.readInput(os.path.join(self.inputDirectory,"input0.txt")) self.assertEqual(result, "3 3 S") # test case: moving only in horizontal direction def test_1_horizontal_movement(self): result = self.testRover.readInput(os.path.join(self.inputDirectory,"input1.txt")) self.assertEqual(result, "1 0 E") # test case: moving only in vertical direction def test_2_vertical_movement(self): result = self.testRover.readInput(os.path.join(self.inputDirectory,"input2.txt")) self.assertEqual(result, "0 1 N") # test case: rotate left def test_3_rotation_left(self): result = self.testRover.readInput(os.path.join(self.inputDirectory,"input3.txt")) self.assertEqual(result, "0 0 W") # test case: rotate right def test_4_rotation_right(self): result = self.testRover.readInput(os.path.join(self.inputDirectory,"input4.txt")) self.assertEqual(result, "0 0 E") # test case: out of bounds; before (0,0) in horizontal direction def test_5_out_of_bounds_before_00_horizontal(self): result = self.testRover.readInput(os.path.join(self.inputDirectory,"input5.txt")) self.assertEqual(result, "0 0 W") # test case: out of bounds; before (0,0) in vertical direction def test_6_out_of_bounds_before_00_vertical(self): result = self.testRover.readInput(os.path.join(self.inputDirectory,"input6.txt")) self.assertEqual(result, "0 0 S") # test case: out of bounds; beyond horizontal boundary def test_7_out_of_bounds_horizontal_boundary(self): result = self.testRover.readInput(os.path.join(self.inputDirectory,"input7.txt")) self.assertEqual(result, "9 4 E") # test case: out of bounds; beyond vertical boundary def test_8_out_of_bounds_vertical_boundary(self): result = self.testRover.readInput(os.path.join(self.inputDirectory,"input8.txt")) self.assertEqual(result, "9 4 N") # test case: out of bounds before final coordinate def test_9_out_of_bounds_vertical_boundary(self): result = self.testRover.readInput(os.path.join(self.inputDirectory,"input9.txt")) self.assertEqual(result, "9 4 N")
def main(): grid = get_grid() log(grid) start = get_position(grid) log(start[0]) commands( rover.Rover(start[1][0], start[1][1], grid[1][0], grid[1][1], start[1][3]))
def test_rover_can_turn_left_preserving_position(start_x, start_y, start_direction, end_direction): rover_instance = rover.Rover(x=start_x, y=start_y, direction=start_direction) rover_instance._turn_left() assert rover_instance.direction == end_direction assert rover_instance.position == (start_x, start_y ) # not shifted during turn
def add_rover(self, rover_id, position, heading): """Add a Rover to the RoverController. When a Rover is added the RoverController needs to check that the initial position is not occupied and rover id is unique.""" self.check_position(position) if not rover_id in self.rovers.keys(): self.rovers[rover_id] = rover.Rover(position, heading) else: raise Exception('A Rover with id %s already exists' % str(rover_id))
def test_rover_inputs(self): rover = r.Rover("2", "2", "N") d = rover.direction self.assertTrue(str(rover.x).isdigit()) self.assertFalse(str(rover.x).isalpha()) self.assertTrue(str(rover.y).isdigit()) self.assertFalse(str(rover.y).isalpha()) self.assertTrue(d.isalpha() and d in ["N", "S", "E", "W"] and len(d) == 1) self.assertFalse(rover.direction.isdigit())
def run_rover(self, spec): err = rover.stderr = StringIO() out = rover.stdout = StringIO() rover.stdin = StringIO(spec) rover.Rover() rover.stderr = sys.stderr rover.stdout = sys.stdout rover.stdin = sys.stdin return out, err
def test_move_rover_complex(self): # test #1 print('==> test_move_rover_complex: test #1') start_pos = [1, 2, 'N'] instructions = 'LMLMLMLMM' # this should put the rover at (3, 2) facing east rover_obj = rover.Rover(start_pos, instructions, 5, 5) new_pos = rover_obj.move_rover() self.assertEqual(new_pos['x'], 1) self.assertEqual(new_pos['y'], 3) self.assertEqual(new_pos['direction'], 'N') # test #2 print('==> test_move_rover_complex: test #2') start_pos = [3, 3, 'E'] instructions = 'MMRMMRMRRM' # this should put the rover at (5, 1) facing east rover_obj = rover.Rover(start_pos, instructions, 5, 5) new_pos = rover_obj.move_rover() self.assertEqual(new_pos['x'], 5) self.assertEqual(new_pos['y'], 1) self.assertEqual(new_pos['direction'], 'E')
def __init__(self): """ Init camera and wheels""" logging.info('Creating a DeepPiCar...') # picar.setup() logging.debug('Set up camera') self.camera = cv2.VideoCapture(-1) self.camera.set(3, self.__SCREEN_WIDTH) self.camera.set(4, self.__SCREEN_HEIGHT) # self.pan_servo = picar.Servo.Servo(1) # self.pan_servo.offset = -30 # calibrate servo to center # self.pan_servo.write(90) # self.tilt_servo = picar.Servo.Servo(2) # self.tilt_servo.offset = 20 # calibrate servo to center # self.tilt_servo.write(90) # logging.debug('Set up back wheels') #self.back_wheels = ''#picar.back_wheels.Back_Wheels() #self.back_wheels.speed = 0 # Speed Range is 0 (stop) - 100 (fastest) self.back_wheels = rover.Rover(debug=False) self.back_wheels.debug = True self.back_wheels.speed(60) # logging.debug('Set up front wheels') # self.front_wheels = picar.front_wheels.Front_Wheels() # self.front_wheels.turning_offset = -25 # calibrate servo to center # self.front_wheels.turn(90) # Steering Range is 45 (left) - 90 (center) - 135 (right) self.lane_follower = HandCodedLaneFollower(self) # self.traffic_sign_processor = ObjectsOnRoadProcessor(self) # lane_follower = DeepLearningLaneFollower() self.fourcc = cv2.VideoWriter_fourcc(*'XVID') datestr = datetime.datetime.now().strftime("%y%m%d_%H%M%S") self.video_orig = self.create_video_recorder( '../data/tmp/car_video%s.avi' % datestr) self.video_lane = self.create_video_recorder( '../data/tmp/car_video_lane%s.avi' % datestr) self.video_objs = self.create_video_recorder( '../data/tmp/car_video_objs%s.avi' % datestr) logging.info('Created a DeepPiCar')
def menu_start_game(filepath): """ Will start the game with the given file path """ is_levelcorrect, name, width, height, rover_cor, tiles = loader.load_level( filepath) if is_levelcorrect: plant = planet.Planet(name, width, height, tiles) rov = rover.Rover(rover_cor, plant) while not rov.isfinish: user_behavior = input("2") ##"Please choose what you want to do:\n1.SCAN <type>\n2.MOVE <direction> <sycles>\n3.WAIT <cycles>\n4.FINISH" # user_behavior="MOVE 10" input_elements = user_behavior.split(" ") if user_behavior.startswith("SCAN"): # input_elements=user_behavior.split(" ") if len(input_elements) == 2: rov.scan(input_elements[1]) else: print("Please input right command!") elif user_behavior.startswith("MOVE"): if len(input_elements) == 3: rov.move(input_elements[1], input_elements[2]) #rov.stats() else: print("Please input right command!") elif user_behavior.startswith("WAIT"): if len(input_elements) == 2: rov.wait(input_elements[1]) #rov.stats() else: print("Please input right command!") elif user_behavior.startswith("STATS"): if len(input_elements) == 1: rov.stats() else: print("Please input right command!") elif user_behavior.startswith("FINISH"): if len(input_elements) == 1: rov.finish() else: print("Please input right command!") else: print("Please input right command!")
class BtController(object): rov = rover.Rover() rov.debug = False rov.speed(0) def __init__(self, debug=False, db="config"): self.server_socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) self.port = 1 self.server_socket.bind(("", self.port)) self.server_socket.listen(1) self.client_socket, address = self.server_socket.accept() print("Accepted connection from ", address) def runcar(self): while True: res = self.client_socket.recv(1024) self.client_socket.send(res) if res == 'q': print("Quit") break else: if res == 'SS': self.rov.stop() elif res == 'FF': self.rov.forward() elif res == 'BB': self.rov.reverse() elif res == 'LL': self.rov.left_turn() elif res == 'RR': self.rov.right_turn() elif bool(re.match("^S\d{1}S$", res)) == True: s = int(res[1:2]) self.rov.speed(s * 10) print("Speed set to", s * 10) if res != 'SS': print("Received:", res) client_socket.close() server_socket.close()
def test_stress_rover(self): original_input = __builtins__.input __builtins__.input = lambda _: '10000 10000' grid = area.create_grid() rovers = [rover.Rover(i, i, 'n', 'MRrMlmllmmrrM', grid) for i in range(1,9999)] for r in rovers: for i in range(4): self.assertTrue(r.make_move()) self.assertEqual(r.x, r.y) self.assertTrue(r.direction, 'S') for i in range(8): self.assertTrue(r.make_move()) self.assertFalse(r.make_move()) self.assertEqual(r.x, r.y) self.assertTrue(r.direction, 'W') __builtins__.input = original_input
def mocked_rover_collecting_moves(): moves = [] def mocked_move_forward(self): moves.append('_move_forward') def mocked_move_backward(self): moves.append('_move_backward') def mocked_turn_left(self): moves.append('_turn_left') def mocked_turn_right(self): moves.append('_turn_right') with mock.patch("rover.Rover._move_forward", mocked_move_forward): with mock.patch("rover.Rover._move_backward", mocked_move_backward): with mock.patch("rover.Rover._turn_left", mocked_turn_left): with mock.patch("rover.Rover._turn_right", mocked_turn_right): rover_on_mars = rover.Rover(x=10, y=10, direction="N") yield moves, rover_on_mars
def test_rover_turn_right_when_facing_west(self): rover = r.Rover(self.x_test, self.y_test, "W") rover.turn("R") self.assertEqual(rover.direction, "N")
import sys import rover if __name__ == "__main__": myRover = rover.Rover() myRover.readInput(sys.argv[1])
def create_rover_negative(): return rover.Rover("-8", "-8", "-1", "-2", "S")
def test_rover_get_location(self): rover = r.Rover(self.x_test, self.y_test, self.dir_test) self.assertTrue( "%s %s %s" % (self.x_test, self.y_test, self.dir_test) == rover.get_location())
def test_rover_creation(self): rover = r.Rover(self.x_test, self.y_test, self.dir_test) self.assertEqual(rover.x, int(self.x_test)) self.assertEqual(rover.y, int(self.y_test)) self.assertEqual(rover.direction, self.dir_test)
def createRover(self, x, y, orientation): return rover.Rover(x, y, orientation, self)
def test_rover_turn_left_when_facing_south(self): rover = r.Rover(self.x_test, self.y_test, "S") rover.turn("L") self.assertEqual(rover.direction, "E")
def test_rover_movement_south(self): rover = r.Rover(self.x_test, self.y_test, "S") rover.move() self.assertEqual(rover.y, int(self.y_test) - rover.STEP_SIZE)
def test_rover_execute_with_invalid_command(self): rover = r.Rover(self.x_test, self.y_test, "W") self.assertRaises(ValueError, rover.execute, "X")
def test_rover_movement_west(self): rover = r.Rover(self.x_test, self.y_test, "W") rover.move() self.assertEqual(rover.x, int(self.x_test) - rover.STEP_SIZE)