Beispiel #1
0
 def get_object_from_dict(values):
     direction = Direction()
     direction.type = XmlParser.get_direction_type(values)
     direction.name = XmlParser.get_title(values)
     direction.tag = XmlParser.get_tag(values)
     
     return direction
Beispiel #2
0
    def __init__(self, onCameraRead):
        if Kart._instance is None:
            Kart._instance = self

        self.direction = Direction()
        self.motor = Motor()
        self.camera = Camera(onCameraRead)
        self.camera.start()
Beispiel #3
0
    def __init__(self, player1, player2, n):
        self.p1 = player1
        self.p2 = player2

        self.board_size = n

        self.p1.pos = [self.board_size / 2, self.board_size / 4]
        self.p2.pos = [self.board_size / 2, 3 * self.board_size / 4]

        self.p1.direction = Direction().East
        self.p2.direction = Direction().West
Beispiel #4
0
    def __init__(self, program, xmax, ymax):
        # Color options
        self.__black = 0
        self.__white = 1

        # Location
        self.location = [0, 0]

        IntCode.__init__(self, program)
        Direction.__init__(self)
        Grid.__init__(self, xmax=xmax, ymax=ymax, default=self.__black)
Beispiel #5
0
    def move(self):
        if self.__follow_wall and self.__angular == 0:
            self.__follow_wall = False

        allowed_directions = self.__labyrinth.get_allowed_directions(self)
        if not self.__follow_wall:
            if self.__direction in allowed_directions:
                self.__labyrinth.move(self, self.__direction)
            else:
                self.__follow_wall = True
                self.turn_right()
        else:
            left = Direction.next_left(self.__direction)
            if left in allowed_directions:
                self.__labyrinth.move(self, left)
                self.turn_left()
            else:
                loop = 0
                while loop != 3:
                    if self.__direction in allowed_directions:
                        self.__labyrinth.move(self, self.__direction)
                        break
                    else:
                        self.turn_right()
                    loop += 1
                if loop == 3:
                    raise Exception("Infinite loop !")
Beispiel #6
0
def createRover(stringDirection="N"):
    x = 12
    y = 5
    startingPoint = Coordinates(x, y)
    direction = Direction(stringDirection)

    return Rover(startingPoint, direction)
Beispiel #7
0
    def move(self, rotation):
        currentValue = self.direction.value
        if rotation == 0:  # Turn Left
            self.direction = Direction((currentValue - 1) % 4)
        else:  # Turn Right
            self.direction = Direction((currentValue + 1) % 4)

        if self.direction == Direction.LEFT:
            self.x -= 1
        elif self.direction == Direction.RIGHT:
            self.x += 1
        elif self.direction == Direction.UP:
            self.y += 1
        elif self.direction == Direction.DOWN:
            self.y -= 1
        else:
            raise NotImplementedError
Beispiel #8
0
 def flood_fill(self, board, pos):
     d = Direction()
     spaces_filled = 0
     empty = 0
     filled = 1
     b = deepcopy(board)
     q = [pos]               # 2. Add node to the end of Q.
     while len(q) > 0:       # 4. While Q is not empty: 
         n = q.pop()         # 5. Set n equal to the last element of Q, and remove last element from Q     
         if b[n[0]][n[1]] == empty:   # 8. If the color of n is equal to target-color:
             b[n[0]][n[1]] = filled   # 9. Set the color of n to replacement-color.
             spaces_filled += 1
             q.append(d.get_new_coord(n, Direction.North)) # 10. Add North node to end of Q.
             q.append(d.get_new_coord(n, Direction.East))  # 11. Add East node to end of Q.
             q.append(d.get_new_coord(n, Direction.South))  # 12. Add South node to end of Q.
             q.append(d.get_new_coord(n, Direction.West))   # 13. Add West node to end of Q.
             
     return spaces_filled    # 14. Return.
 def __init__(self, maze_dim, dump_mazes=False):
     self.location = Position(0, 0)
     self.heading = Direction(0)
     self.maze_map = MazeMap(maze_dim)
     self.timestep = 0
     self.run_number = 0
     self.found_goal = False
     self.dump_mazes = dump_mazes
     self.planner = Planner(self.maze_map)  # planner needs to be set by sub-class
Beispiel #10
0
class Kart:
    _instance = None

    def __init__(self, onCameraRead):
        if Kart._instance is None:
            Kart._instance = self

        self.direction = Direction()
        self.motor = Motor()
        self.camera = Camera(onCameraRead)
        self.camera.start()

    def turn(self, angle):
        self.direction.changeRotation(angle)

    def move(self, speed):
        if speed > 0:
            self.motor.forward()
        else:
            self.motor.stop()
Beispiel #11
0
    def addItem(self, newWeight, newValue):
        j = 0
        current = -1
        n = self.size
        withinLimit = True
        cur_i = self.options.data[0]
        newOptions: MaxSparseList = MaxSparseList(
            (cur_i[0], cur_i[1], Direction(False, cur_i[2])), self.limit)

        for cur_i in self.options[1:]:
            while withinLimit:
                cur_j = self.options[j]
                weight = cur_j[0] + newWeight
                if weight > self.limit:
                    withinLimit = False
                    break
                c = weight - cur_i[0]
                if c > 0:
                    break
                else:
                    newOptions.append((weight, cur_j[1] + newValue,
                                       Direction(True, cur_j[2])))
                j += 1
            last_el = newOptions[-1]
            if last_el[0] == cur_i[0]:
                if last_el[1] > cur_i[1]:
                    continue
                else:
                    newOptions.pop()
            newOptions.append((cur_i[0], cur_i[1], Direction(False, cur_i[2])))

        for cur_j in self.options[j:]:
            weight = cur_j[0] + newWeight
            if weight > self.limit:
                break
            newOptions.append(
                (weight, cur_j[1] + newValue, Direction(True, cur_j[2])))

        self.options = newOptions
        self.size = len(newOptions)
        return
Beispiel #12
0
    def flood_fill(self, board, pos):
        d = Direction()
        spaces_filled = 0
        empty = 0
        filled = 1
        b = deepcopy(board)
        q = [pos]  # 2. Add node to the end of Q.
        while len(q) > 0:  # 4. While Q is not empty:
            n = q.pop(
            )  # 5. Set n equal to the last element of Q, and remove last element from Q
            if b[n[0]][n[
                    1]] == empty:  # 8. If the color of n is equal to target-color:
                b[n[0]][n[
                    1]] = filled  # 9. Set the color of n to replacement-color.
                spaces_filled += 1
                q.append(d.get_new_coord(
                    n, Direction.North))  # 10. Add North node to end of Q.
                q.append(d.get_new_coord(
                    n, Direction.East))  # 11. Add East node to end of Q.
                q.append(d.get_new_coord(
                    n, Direction.South))  # 12. Add South node to end of Q.
                q.append(d.get_new_coord(
                    n, Direction.West))  # 13. Add West node to end of Q.

        return spaces_filled  # 14. Return.
 def reset(self):
     """
     Move the robot back to 0,0 and facing north. Also changes the run_number to 1. Call this when you are ready to
     start the second run.
     :return: Returns the reset string for convenience.
     """
     self.location = Position(0, 0)
     self.heading = Direction(0)
     self.run_number = 1
     print "Number of moves in first run: {}".format(self.timestep)
     print "Exploration efficiency: {}".format(self.get_exploration_efficiency())
     self.planner.replan(self.location, self.heading)
     return "Reset", "Reset"
Beispiel #14
0
 def __init__(self, sides_, x_, y_):
     """ 
     Constructor 
     
     init(list, int, int)
     
     sides_ - list of sides of outputs (type Side)
     x_ - coordinate x
     y_ - coordinate y
     """
     self.outputs = [Direction(side) for side in sides_]
     self.x = x_
     self.y = y_
     self.block_rotate = False
Beispiel #15
0
    def getWaypoints(self, path):
        waypoints = []
        direction = Direction()
        previous = self.start
        previous.direction = direction.start

        for node in path:
            if (node.step_direction != previous.step_direction):
                waypoints.append(node)
                previous = node
            else:
                continue
        waypoints.append(self.end)

        return waypoints
Beispiel #16
0
    def pick_move(self, board, op_pos):
        moves = self.applicable_moves(board)
        scores = np.array([0] * len(moves))  # every move can have a score

        for ind, m in enumerate(moves):
            new_board = self.apply_move(m, board)
            newp = [self.pos[0] + m[0], self.pos[1] + m[1]]
            scores[ind] = self.heuristic.eval(board, new_board, newp, op_pos)

        # find all 'best moves'
        best_move_indices = np.where(scores == (max(scores)))[0]

        # if more than one 'best move' is found, choose randomly
        best_move = moves[random.choice(best_move_indices)]

        if DEBUG:
            print 'Scores', scores
            print 'Move', Direction().__str__(best_move)
        return best_move
Beispiel #17
0
    def compute_key(self, key):
        tmp_direction = Direction.NULL
        if key == pygame.K_ESCAPE:
            return False
        elif key == pygame.K_LEFT:
            tmp_direction = Direction.LEFT
        elif key == pygame.K_RIGHT:
            tmp_direction = Direction.RIGHT
        elif key == pygame.K_UP:
            tmp_direction = Direction.UP
        elif key == pygame.K_DOWN:
            tmp_direction = Direction.DOWN

        # Make sure that the new direction is valid
        # (the snake cannot go back on UP if it was going DOWN)
        if Direction.is_movement_valid(self.player.previous_direction,
                                       tmp_direction):
            self.player.direction = tmp_direction

        return True
Beispiel #18
0
    def move(self, amount, turn_letter):
        prev_direction = self.current_direction
        prev_x = self.curr_x
        prev_y = self.curr_y

        self.current_direction = Direction.get_new_direction(self.current_direction, turn_letter)

        if self.current_direction.index_value == Direction.NORTH:
            self.curr_y += amount
        elif self.current_direction.index_value == Direction.SOUTH:
            self.curr_y -= amount
        elif self.current_direction.index_value == Direction.EAST:
            self.curr_x += amount
        elif self.current_direction.index_value == Direction.WEST:
            self.curr_x -= amount
        else:
            raise "Oh boy..."

        print "[" + str(prev_direction) + "] + [" + str(amount) + str(turn_letter) + "] = " + str(self.current_direction)
        print "(" + str(prev_x) + "," + str(prev_y) + ") -> (" + str(actor.curr_x) + "," + str(actor.curr_y) + ")"
        print
Beispiel #19
0
	def play(self):
		"""Play the game."""
		previousDirection = None
		listener = KeyListener()

		# Start the key listener
		listener.start()
		# Get the command for clearing the screen (dependent on OS)
		clearScreen = "cls" if platform.system() == "Windows" else "clear"
		# Place the first food
		self.placeFood()

		# Main game loop
		while not self.gameOver() and not listener.quit:
			# Display the game
			os.system(clearScreen)
			self.display(listener.paused)

			# Delay movement for the specified time
			time.sleep(self.speed)

			# Update the current direction
			currentDirection = listener.direction

			# Snake cannot immediately reverse direction
			if currentDirection == Direction.opposite(previousDirection):
				currentDirection = previousDirection

			# Move the snake if not paused
			if not listener.paused:
				self.move(currentDirection)

			# Store previous direction
			previousDirection = currentDirection

		# End the key listener
		listener.end()

		# Pause for 1 second
		time.sleep(1)
Beispiel #20
0
 def __init__(self):
     self.direction = Direction().North
Beispiel #21
0
class Snake:
    """
    This class represents a snake itself.
    It has, most importantly, a body and a direction.
    
    This snake can exist in N dimensions, and as such can have N directions.
    
    --------------------------------------------------------------------------
    Properties
    --------------------------------------------------------------------------
    snakeSegments:      List of Snake_Segment type object
        Represents the snake's body. The 0th segment is the head and is treated
        as such, the rest of the segments follow the head traveling where it u-
        sed to be. The body is important only for the cases of collision, and
        non-trivial food spawning. 
        
    direction:          A single direction object
        Represents the snake's direction of travel. Realistically only affects
        the head
    
    segmentsToGrow:     An integer
        Represents the number of segments the snake has to grow. It will grow
        by one segment in length per turn, and the number of segments gained by
        eating food could hypothetically be variable.
    """
    def __init__(self, position, segmentsPerFood=1):
        self.snakeSegments = [Snake_Segment(position)]
        self.direction = Direction()
        self.segmentsToGrow = 0
        self.segmentsPerFood = 1

    def ChangeDirection(self, direction):
        """
        input: 
            direction - direction type object
                Indicates the direction in which the snake's head will travel
        output:
            none
        
        Description:
            Changes the direction in which the snake's head travels. Must pass
            a validity check first.
        """
        if len(self.snakeSegments) == 1 or not (
                self.snakeSegments[0].position + direction
                == self.snakeSegments[1].position):
            return self.direction.ChangeDirection(direction)
        else:
            return False

    def Move(self):
        """
        input:
            none
        output:
            none
            
        Description:
            Moves the snake's head one unit in the direction of travel, as def-
            ined by self.direction. The rest of the snake's body will move to
            where the previous segment used to be.
        
        """
        grow = self.segmentsToGrow > 0

        if (grow):
            self.segmentsToGrow -= 1
            lastPosition = Position(
                self.snakeSegments[-1].position.coordinates)

        oldSnakeSegments = [
            Snake_Segment(Position(snakeSeg.position.coordinates[:]))
            for snakeSeg in self.snakeSegments
        ]
        for index, segment in enumerate(self.snakeSegments[1:]):
            self.snakeSegments[index +
                               1].position.coordinates = oldSnakeSegments[
                                   index].position.coordinates[:]

        if (grow):
            self.snakeSegments.append(Snake_Segment(lastPosition))

        self.snakeSegments[
            0].position = self.snakeSegments[0].position + self.direction

    def Eat(self):
        """
        input:
            none
        output:
            none
            
        Description:
            Called by the game once the snake eats some food. Causes the snake
            to grow on subsequent turns. Increases the dimensionality of the s-
            nake by one.
        """
        self.segmentsToGrow += self.segmentsPerFood
        for i, e in enumerate(self.snakeSegments):
            self.snakeSegments[i].position.coordinates.append(0)

        self.direction.directionalCoordinates.append(0)
Beispiel #22
0
 def applicable_moves(self, board):
     opp_direction = Direction().opposite_direction(self.direction)
     moves = Direction().get_others(opp_direction)
     return moves
Beispiel #23
0
def paintAndMove(robot, panel, inputs):
    paint_used = panel[robot.x][robot.y] == 0 and inputs[0] == 1

    robot.paint(panel, inputs[0])
    robot.move(Direction(inputs[1]))
    return paint_used
Beispiel #24
0
    def loads(self, noaa_string):
        ''' load in a report (or set) from a string '''
        self.raw = noaa_string
        self.weather_station = noaa_string[4:10]
        self.wban = noaa_string[10:15]
        expected_length = int(noaa_string[0:4]) + self.PREAMBLE_LENGTH
        actual_length = len(noaa_string)
        if actual_length != expected_length:
            msg = "Non matching lengths. Expected %d, got %d" % (
                expected_length, actual_length)
            raise ish_reportException(msg)

        try:
            self.datetime = datetime.strptime(noaa_string[15:27], '%Y%m%d%H%M')
        except ValueError:
            ''' some cases, we get 2400 hours, which is really the next day, so 
      this is a workaround for those cases '''
            time = noaa_string[15:27]
            time = time.replace("2400", "2300")
            self.datetime = datetime.strptime(time, '%Y%m%d%H%M')
            self.datetime += timedelta(hours=1)

        self.report_type = ReportType(noaa_string[41:46].strip())

        self.latitude = float(noaa_string[28:34]) / self.GEO_SCALE
        self.longitude = float(noaa_string[34:41]) / self.GEO_SCALE
        self.elevation = int(noaa_string[46:51])
        ''' other mandatory fields '''
        self.wind_direction = Direction(noaa_string[60:63], Direction.RADIANS,
                                        noaa_string[63:64])
        self.wind_observation_direction_type = noaa_string[64:64]
        self.wind_speed = Speed(
            int(noaa_string[65:69]) / float(self.SPEED_SCALE),
            Speed.METERSPERSECOND, noaa_string[69:70])
        self.sky_ceiling = Distance(int(noaa_string[70:75]), Distance.METERS,
                                    noaa_string[75:76])
        self.sky_ceiling_determination = noaa_string[76:77]
        self.visibility_distance = Distance(int(noaa_string[78:84]),
                                            Distance.METERS,
                                            noaa_string[84:85])
        self.visibility_variability = noaa_string[85:86]
        self.visibility_variability_quality = noaa_string[86:87]

        self.air_temperature = Temperature(
            int(noaa_string[87:92]) / self.TEMPERATURE_SCALE, Units.CELSIUS,
            noaa_string[92:93])
        self.dew_point = Temperature(
            int(noaa_string[93:98]) / self.TEMPERATURE_SCALE, Units.CELSIUS,
            noaa_string[98:99])

        self.humidity = Humidity(str(self.air_temperature),
                                 str(self.dew_point))
        self.sea_level_pressure = Pressure(
            int(noaa_string[99:104]) / self.PRESSURE_SCALE,
            Pressure.HECTOPASCALS, noaa_string[104:104])
        ''' handle the additional fields '''
        additional = noaa_string[105:108]
        if additional == 'ADD':
            position = 108
            while position < expected_length:
                try:
                    (position, (addl_code, addl_string)) = self._get_component(
                        noaa_string, position)
                    self._additional[addl_code] = addl_string
                except ish_reportException, err:
                    ''' this catches when we move to remarks section '''
                    break
Beispiel #25
0
 def set_direction(self):
     self.direction = Direction(self.get_mhdr())
Beispiel #26
0
    def WhereToGo(self, node):

        diagonal_distance = sqrt(2) * self.robotResolution
        map_data = self.map.data
        possibleNodes = []

        direction = Direction()
        #Hacky code begins
        North = AStarNode(round(node.point.x, 3),
                          round(node.point.y + self.robotResolution, 3))
        North.g = node.g + self.robotResolution
        North.step_direction = direction.n

        NorthEast = AStarNode(round(node.point.x + self.robotResolution, 3),
                              round(node.point.y + self.robotResolution, 3))
        NorthEast.g = node.g + diagonal_distance
        NorthEast.step_direction = direction.ne

        East = AStarNode(round(node.point.x + self.robotResolution, 3),
                         round(node.point.y, 3))
        East.g = node.g + self.robotResolution
        East.step_direction = direction.e

        SouthEast = AStarNode(round(node.point.x + self.robotResolution, 3),
                              round(node.point.y - self.robotResolution, 3))
        SouthEast.g = node.g + diagonal_distance
        SouthEast.step_direction = direction.se

        South = AStarNode(round(node.point.x, 3),
                          round(node.point.y - self.robotResolution, 3))
        South.g = node.g + self.robotResolution
        South.step_direction = direction.s

        SouthWest = AStarNode(round(node.point.x - self.robotResolution, 3),
                              round(node.point.y - self.robotResolution, 3))
        SouthWest.g = node.g + diagonal_distance
        SouthWest.step_direction = direction.sw

        West = AStarNode(round(node.point.x - self.robotResolution, 3),
                         round(node.point.y, 3))
        West.g = node.g + self.robotResolution
        West.step_direction = direction.w

        NorthWest = AStarNode(round(node.point.x - self.robotResolution, 3),
                              round(node.point.y + self.robotResolution, 3))
        NorthWest.g = node.g + diagonal_distance
        NorthWest.step_direction = direction.nw

        if (self.getMapIndex(North) < len(map_data)
                and self.getMapIndex(North) > 0):
            if (map_data[self.getMapIndex(North)] not in [100]):
                possibleNodes.append(North)

        if (self.getMapIndex(NorthEast) < len(map_data)
                and self.getMapIndex(NorthEast) > 0):
            if (map_data[self.getMapIndex(NorthEast)] not in [100]):
                possibleNodes.append(NorthEast)

        if (self.getMapIndex(East) < len(map_data)
                and self.getMapIndex(East) > 0):
            if (map_data[self.getMapIndex(East)] not in [100]):
                possibleNodes.append(East)

        if (self.getMapIndex(SouthEast) < len(map_data)
                and self.getMapIndex(SouthEast) > 0):
            if (map_data[self.getMapIndex(SouthEast)] not in [100]):
                possibleNodes.append(SouthEast)

        if (self.getMapIndex(South) < len(map_data)
                and self.getMapIndex(South) > 0):
            if (map_data[self.getMapIndex(South)] not in [100]):
                possibleNodes.append(South)

        if (self.getMapIndex(SouthWest) < len(map_data)
                and self.getMapIndex(SouthWest) > 0):
            if (map_data[self.getMapIndex(SouthWest)] not in [100]):
                possibleNodes.append(SouthWest)

        if (self.getMapIndex(West) < len(map_data)
                and self.getMapIndex(West) > 0):
            if (map_data[self.getMapIndex(West)] not in [100]):
                possibleNodes.append(West)

        if (self.getMapIndex(NorthWest) < len(map_data)
                and self.getMapIndex(NorthWest) > 0):
            if (map_data[self.getMapIndex(NorthWest)] not in [100]):
                possibleNodes.append(NorthWest)

        return possibleNodes
Beispiel #27
0
 def walk_forward(self, steps):
     self.x_coord += steps * Direction.get_i_component(self.direction)
     self.y_coord += steps * Direction.get_j_component(self.direction)
 def orientation() -> Direction:
     return Direction(randint(0, 1))
Beispiel #29
0
    def _getLineConfiguration(self, nLine):

        # if the data directory does not exist, create it
        if not os.path.exists(self.sDirectory):
            os.makedirs(self.sDirectory)

        sFilename = ('route_' + str(nLine) + '_directionsTable.txt')
        sFilename = os.path.join(self.sDirectory, sFilename)

        try:
            bFileExists = os.path.isfile(sFilename)
            bUpdatedToday = (datetime.date.today() == datetime.date.fromtimestamp(os.path.getmtime(sFilename)))

        except OSError:
            bFileExists = False
            bUpdatedToday = False

        # configuration files are only updated once a day
        if bFileExists is False or bUpdatedToday is False:

            output = Line(id=nLine)

            sRoute = '&r=' + str(nLine)
            try:
                urlHandle = urllib.urlopen(self.sUrlNextbus + self.sCommandGetStops
                                           + self.sAgency + sRoute + self.sFlags)
                xml = urlHandle.read()
                urlHandle.close()
                root = etree.fromstring(xml)

            except Exception as e:
                print "Could not load configuration: %s" % e
                return

            lStops = {}

            for elementA in root:
                if elementA.tag == 'route':
                    for elementB in elementA:

                        if elementB.tag == 'stop':
                            stopID = elementB.attrib['tag']

                            lStops[stopID] = Stop(
                                id=elementB.attrib['tag'],
                                name=elementB.attrib['title'],
                                latitude=elementB.attrib['lat'],
                                longitude=elementB.attrib['lon']
                            )

                        if elementB.tag == 'direction':
                            sBusDirection = elementB.attrib['tag']
                            direction = Direction(line=nLine, id=sBusDirection, title=elementB.attrib['title'])

                            for elementC in elementB:
                                direction.addStop(lStops[elementC.attrib['tag']])

                            output.addDirection(direction)

            # Write out direction "variables" table to a file
            fhDirections = open(sFilename, 'wb')
            pickle.dump(output, fhDirections)
            fhDirections.close()

            return output

        # route information is cached, so just restore it
        else:
            fhDirections = open(sFilename, 'rb')
            output = pickle.load(fhDirections)
            fhDirections.close()
            return output
Beispiel #30
0
        elif self.current_direction.index_value == Direction.EAST:
            self.curr_x += amount
        elif self.current_direction.index_value == Direction.WEST:
            self.curr_x -= amount
        else:
            raise "Oh boy..."

        print "[" + str(prev_direction) + "] + [" + str(amount) + str(turn_letter) + "] = " + str(self.current_direction)
        print "(" + str(prev_x) + "," + str(prev_y) + ") -> (" + str(actor.curr_x) + "," + str(actor.curr_y) + ")"
        print

    def get_distance_traveled(self):
        return abs(self.curr_x) + abs(self.curr_y)


if __name__ == '__main__':
    input = "R1, L3, R5, R5, R5, L4, R5, R1, R2, L1, L1, R5, R1, L3, L5, L2, R4, L1, R4, R5, L3, R5, L1, R3, L5, R1, L2, R1, L5, L1, R1, R4, R1, L1, L3, R3, R5, L3, R4, L4, R5, L5, L1, L2, R4, R3, R3, L185, R3, R4, L5, L4, R48, R1, R2, L1, R1, L4, L4, R77, R5, L2, R192, R2, R5, L4, L5, L3, R2, L4, R1, L5, R5, R4, R1, R2, L3, R4, R4, L2, L4, L3, R5, R4, L2, L1, L3, R1, R5, R5, R2, L5, L2, L3, L4, R2, R1, L4, L1, R1, R5, R3, R3, R4, L1, L4, R1, L2, R3, L3, L2, L1, L2, L2, L1, L2, R3, R1, L4, R1, L1, L4, R1, L2, L5, R3, L5, L2, L2, L3, R1, L4, R1, R1, R2, L1, L4, L4, R2, R2, R2, R2, R5, R1, L1, L4, L5, R2, R4, L3, L5, R2, R3, L4, L1, R2, R3, R5, L2, L3, R3, R1, R3"

    # 253 is answer
    chris_input = "L1, L5, R1, R3, L4, L5, R5, R1, L2, L2, L3, R4, L2, R3, R1, L2, R5, R3, L4, R4, L3, R3, R3, L2, R1, L3, R2, L1, R4, L2, R4, L4, R5, L3, R1, R1, L1, L3, L2, R1, R3, R2, L1, R4, L4, R2, L189, L4, R5, R3, L1, R47, R4, R1, R3, L3, L3, L2, R70, L1, R4, R185, R5, L4, L5, R4, L1, L4, R5, L3, R2, R3, L5, L3, R5, L1, R5, L4, R1, R2, L2, L5, L2, R4, L3, R5, R1, L5, L4, L3, R4, L3, L4, L1, L5, L5, R5, L5, L2, L1, L2, L4, L1, L2, R3, R1, R1, L2, L5, R2, L3, L5, L4, L2, L1, L2, R3, L1, L4, R3, R3, L2, R5, L1, L3, L3, L3, L5, R5, R1, R2, L3, L2, R4, R1, R1, R3, R4, R3, L3, R3, L5, R2, L2, R4, R5, L4, L3, L1, L5, L1, R1, R2, L1, R3, R4, R5, R2, R3, L2, L1, L5"
    input = "R8, R4 , R4, R8"
  #   input = "R1, L3, R5, R5, R5, L4, R5, R1, R2, L1, L1, R5"
  #   input = "R1, L3, R5, R5, R5, L4, R5, R1, R2, L1, L1, R5, R1, L3, L5, L2, R4"
  #   input = "R5, L5, R5, R3"
    actor = Actor(starting_direction=Direction(Direction.NORTH))
    vectors = input.replace(" ", "").split(",")

    for vector in vectors:
        actor.move(amount=int(vector[1]), turn_letter=vector[0])
    print actor.get_distance_traveled()
Beispiel #31
0
 def __init__(self):
     self._buggy = Buggy(Coordinate(0, 0), Direction('N'))
Beispiel #32
0
 def turn_left(self):
     self.__direction = Direction.next_left(self.__direction)
     self.__angular -= 1
Beispiel #33
0
 def turn_right(self):
     self.__direction = Direction.next_right(self.__direction)
     self.__angular += 1
class RobotController(object):
    """
    This is the base class for all robot controllers. You must override next_move and initialize self.planner in
    a sub-class.
    """
    def __init__(self, maze_dim, dump_mazes=False):
        self.location = Position(0, 0)
        self.heading = Direction(0)
        self.maze_map = MazeMap(maze_dim)
        self.timestep = 0
        self.run_number = 0
        self.found_goal = False
        self.dump_mazes = dump_mazes
        self.planner = Planner(self.maze_map)  # planner needs to be set by sub-class

    def next_move(self, sensors):
        """
        This is the main method to implement for a controller. Make sure that the move the controller returns is a valid
        move (it doesn't try to go through walls). If it does, the location and heading class members will be incorrect.
        :param sensors: The distance in squares to the next wall for the left, middle and right sensors.
        :return: The sub-class should return the next move as a (int, int). The first is the rotation
        (could be -90, 0 or 90), the second is the number of squares to move (from -3 to 3).
        """
        raise NotImplemented("Implement by overriding in sub-class.")

    def update(self, sensors):
        """
        Convenience function for updating the maze, re-planning (if the maze was updated), and dumping the maze for
        debugging.
        :param sensors:
        :return: True if maze was updated
        """
        self.timestep += 1
        maze_updated = self.maze_map.update(self.location, self.heading, sensors)
        if maze_updated:
            self.planner.replan(self.location, self.heading)
        if self.dump_mazes:
            self.maze_map.dump_to_file(os.path.join(os.curdir, "known_maze.txt"))
        return maze_updated

    def move(self, rotation, movement):
        """
        Update the current location and heading for the class. This should be called in the sub-class after choosing
        a move.
        :type rotation: int
        :type movement: int
        :param rotation: The rotation to perform
        :param movement: The number of squares to move
        :return: None
        """
        self.heading = self.heading.rotate(rotation)
        direction_of_movement = self.heading if movement > 0 else self.heading.flip()
        for i in range(abs(movement)):
            self.location = self.location.add(direction_of_movement)
        if self.maze_map.at_goal(self.location):
            self.found_goal = True

    def reset(self):
        """
        Move the robot back to 0,0 and facing north. Also changes the run_number to 1. Call this when you are ready to
        start the second run.
        :return: Returns the reset string for convenience.
        """
        self.location = Position(0, 0)
        self.heading = Direction(0)
        self.run_number = 1
        print "Number of moves in first run: {}".format(self.timestep)
        print "Exploration efficiency: {}".format(self.get_exploration_efficiency())
        self.planner.replan(self.location, self.heading)
        return "Reset", "Reset"

    def show_current_policy_and_map(self):
        """
        For visualization of the maze and policy when using the A* planner.
        :return: None
        """
        vis = Visualizer(self.maze_map.dim)
        vis.draw_maze(Maze('known_maze.txt'))
        vis.draw_policy(reversed(self.planner.policy), self.location, self.heading)
        vis.show_window()

    def get_exploration_efficiency(self):
        return self.maze_map.get_num_known_walls() / float(self.timestep)
Beispiel #35
0
 def __init__(self, position, segmentsPerFood=1):
     self.snakeSegments = [Snake_Segment(position)]
     self.direction = Direction()
     self.segmentsToGrow = 0
     self.segmentsPerFood = 1
Beispiel #36
0
    def random_free_place(self, org, n=1):
        num = 8
        free = [True] * num
        x = org.get_point().get_x()
        y = org.get_point().get_y()
        q = 0
        # *********************
        if (y - n < 0):  # TOP
            free[q] = False
        else:
            free[q] = self.field_free(x, y - n)

        q += 1
        if (x + n >= self._width or y - n < 0 or (self._board_type == df.const.HEXAGON and x % 2 == 1)):  # RIGHT_TOP
            free[q] = False
        else:
            free[q] = self.field_free(x + n, y - n)

        q += 1
        if (x + n >= self._width):  # RIGHT
            free[q] = False
        else:
            free[q] = self.field_free(x + n, y)

        q += 1
        if (x + n >= self._width or y + n >= self._height or (
                self._board_type == df.const.HEXAGON or x % 2 == 0)):  # RIGHT_DOWN
            free[q] = False
        else:
            free[q] = self.field_free(x + n, y + n)

        q += 1
        if (y + n >= self._height):  # DOWN
            free[q] = False
        else:
            free[q] = self.field_free(x, y + n)

        q += 1
        if (x - n < 0 or y + n >= self._height or (self._board_type == df.const.HEXAGON or x % 2 == 0)):  # LEFT_DOWN
            free[q] = False
        else:
            free[q] = self.field_free(x - n, y + n)

        q += 1
        if (x - n < 0):  # LEFT
            free[q] = False
        else:
            free[q] = self.field_free(x - n, y)

        q += 1
        if (x - n < 0 or y - n < 0 or (self._board_type == df.const.HEXAGON or x % 2 == 1)):  # LEFT_TOP
            free[q] = False
        else:
            free[q] = self.field_free(x - n, y - n)

        # ***************************

        directions = []
        for i in range(num):
            if (free[i] is True):
                directions.append(i)
        if (not directions):
            return None
        if (directions):
            rand_num = rand.randint(0, len(directions) - 1)
            # print(directions[rand_num])
            return Point(x, y, Direction(directions.pop(rand_num)))
Beispiel #37
0
 def get_pos_from_move(self, move):
     direction = Direction.get_direction_from_pos_move(self, move)
     return self.get_next_position(direction)