Пример #1
0
def create_problem_scenario(config):
    """
    Given a config dict describing the problem, create the moving objects and
    their relationship as specified in the problem description file
    
    Arguments:
        config: dict containing the definition of the moving objects as well
        as other configuration parameters
    
    Returns:
        dict containing the moving objects
    """
    movers = config['movers']  #definition of the moving objects of the problem
    moving_objects = {
    }  #dict storing all moving objects from the problem description

    #Create object
    for mover in movers:
        mover_obj = Mover(name=mover['name'],
                          r0=mover['r_0'],
                          v0=mover['v_0'],
                          speed=mover['speed'])

        #Store in the moving object dict
        moving_objects[mover_obj.get_name()] = mover_obj

    #Create pursuer-leader relationships
    for m in movers:
        name = m['name']
        leader_name = m['leader']
        if not leader_name is None:
            leader = moving_objects[leader_name]
            moving_objects[name].set_leader(leader)

    return moving_objects
Пример #2
0
    def run(self):
        """Runs the main process"""
        # Instantiating the initial properties for the application
        pygame.init()
        height, width = self.col * self.scale, self.row * self.scale
        # Setting the logo
        gameIcon = pygame.image.load('logo.png')
        pygame.display.set_icon(gameIcon)
        # Setting the height and width
        self.gameDisplay = pygame.display.set_mode((height, width))
        # Setting the caption
        pygame.display.set_caption('HM0-01')
        # Initializing the pixel property
        self.pixel = pygame.PixelArray(self.gameDisplay)

        # Drawing the map
        # Instantiating the mover object
        self.obj = Mover(self.pixel)
        self.obj.set_dimensions(self.col, self.row)
        # Setting the scale for that
        self.obj.set_scale(self.scale)

        # generating the blocks within the maze
        self.maze()
        # Finalizing the process of making the map
        self.generate_map()
Пример #3
0
    def __init__(self, path="", single_mode=False):
        self.path = path
        self.single_mode = single_mode
        self.mover = Mover()
        self.wheel_encoder = WheelEncoder()
        self.odom_publisher = OdometryPublisher(1 / (3.14 * BASE_WIDTH), path)
        self.now = None
        self.pid_list = self.load_settings()
        self.active_controller = None
        self.set_active_controller(5)

        # initializing ROS publishers, subscribers and messages
        self.prev_pwms = (0, 0)
        rospy.Subscriber('/cmd_vel', Twist, self.move, queue_size=1)
        rospy.Subscriber("/PID_settings",
                         PID_settings,
                         self.set_k,
                         queue_size=1)
        self.pub_l = rospy.Publisher("PID_l", PID_out, queue_size=10)
        self.pub_r = rospy.Publisher("PID_r", PID_out, queue_size=10)
        self.data_msg_l = PID_out(wheel="left")
        self.data_msg_r = PID_out(wheel="right")

        print("PID Master loaded")
        self.update_pwms()
Пример #4
0
class Navigator(tk.Frame):
    """
    Composite GUI element composed of a Mover and a Jumper, allowing a user to
    navigate an x-y space.
    """
    def __init__(self,
                 master,
                 move_callback: Callable[[str], None],
                 jump_callback: Callable[[int, int], None],
                 bg: str = "#ffffff"):
        """
        Initialise this Navigator.
        :param master: parent container of this Navigator
        :param move_callback: function to call when the user clicks on of the
        directional buttons
        :param jump_callback: function to call when the user clicks the jump
        button
        :param bg: background colour of this Navigator
        """
        super().__init__(master, bg=bg)

        self._mover = Mover(self, move_callback, bg=bg)
        self._mover.pack(side=tk.LEFT)

        self._jumper = Jumper(self, jump_callback, bg=bg)
        self._jumper.pack(side=tk.LEFT)

    def display_position(self, x: int, y: int) -> None:
        """
        Display a given (x, y) coordinate in this object's text entry fields.
        :param x: x coordinate to display
        :param y: y coordinate to display
        """
        self._jumper.display_position(x, y)
Пример #5
0
 def test_mover_returns_all_the_possible_next_moves_for_edges(self):
     moveStates = [[[0, 2, 3], [1, 8, 4], [7, 6, 5]],
                   [[1, 2, 3], [8, 0, 4], [7, 6, 5]],
                   [[1, 2, 3], [7, 8, 4], [0, 6, 5]]]
     target = Tile()
     target = Mover.move_left(target)
     results = []
     for tile in Mover.possible_moves(target):
         results.append(tile.layout)
     self.assertEqual(results, moveStates)
Пример #6
0
def level5(file_path):
    start = (1, 1)
    end = (26, 25)

    board = Board(file_path, 32)
    board.set_knight_location(start)

    mover = Mover(board)
    path = mover.find_longest_path(start, end)
    print path
    mover.move(path, display=True)
Пример #7
0
def level3(file_path):
    """Find the shortest path between the start and end positions"""
    start = (1, 1)
    end = (6, 6)

    # Set starting point
    board = Board(file_path, 8)
    board.set_knight_location(start)

    mover = Mover(board)
    path = mover.find_shortest_path(start, end)
    print path
    mover.move(path, display=True)
Пример #8
0
def level4(file_path):
    """Find the shortest path between the start and end of the 32x32
       weighted board, with additional constraints
    """
    start = (1, 1)
    end = (26, 25)

    board = Board(file_path, 32)
    board.set_knight_location(start)

    mover = Mover(board)
    path = mover.find_shortest_path(start, end)
    print path
    mover.move(path, display=True)
Пример #9
0
 def __init__(self, args):
     self.delta_theta = None
     # subprocess.Popen(
     #    [args['vrep_exec_path'], '-h', '-gREMOTEAPISERVERSERVICE_' + str(args['server_port']) + '_FALSE_TRUE',
     #     args['vrep_scene_file']])
     self.mover = Mover(args['server_ip'], args['server_port'])
     self.mover.init_client()
     self.per_step_reward = args['per_step_reward']
     self.final_reward = args['final_reward']
     self.tolerance = args['tolerance']
     self.server_ip, self.server_port = args['server_ip'], args['server_port']
     self.spawn_radius = args['spawn_radius']
     self.begin_pos = None
     self.goal = 0
Пример #10
0
    def __init__(self):
        #サーバー初期化
        baxter = baxter_interface.RobotEnable()
        baxter.enable()
        #右手を使う
        self.limb = "right"
        self.right = baxter_interface.Limb(self.limb)
        #アームの速度上限
        self.right.set_joint_position_speed(0.3)
        self.control_cmd = dict()
        self.IKservice = IKsolve(self.limb)
        self.Mover = Mover()

        self.rate = rospy.Rate(100000)
        #初期位置に移動
        self.right.move_to_neutral()
        #ReFlexHand初期化とか
        # Services can automatically call hand calibration

        self.calibrate_fingers = rospy.ServiceProxy(
            '/reflex_takktile/calibrate_fingers', Empty)
        self.calibrate_tactile = rospy.ServiceProxy(
            '/reflex_takktile/calibrate_tactile', Empty)

        # Services can set tactile thresholds and enable tactile stops
        self.enable_tactile_stops = rospy.ServiceProxy(
            '/reflex_takktile/enable_tactile_stops', Empty)
        self.disable_tactile_stops = rospy.ServiceProxy(
            '/reflex_takktile/disable_tactile_stops', Empty)
        self.set_tactile_threshold = rospy.ServiceProxy(
            '/reflex_takktile/set_tactile_threshold', SetTactileThreshold)

        # This collection of publishers can be used to command the hand
        self.command_pub = rospy.Publisher('/reflex_takktile/command',
                                           Command,
                                           queue_size=1)
        self.pos_pub = rospy.Publisher('/reflex_takktile/command_position',
                                       PoseCommand,
                                       queue_size=1)
        self.vel_pub = rospy.Publisher('/reflex_takktile/command_velocity',
                                       VelocityCommand,
                                       queue_size=1)

        # Constantly capture the current hand state
        #rospy.Subscriber('/reflex_takktile/hand_state', Hand, hand_state_cb)
        f1 = FingerPressure([10, 10, 10, 10, 10, 10, 10, 10, 1000])
        f2 = FingerPressure([10, 10, 10, 10, 10, 10, 10, 10, 1000])
        f3 = FingerPressure([10, 10, 10, 10, 10, 10, 10, 10, 1000])
        threshold = SetTactileThresholdRequest([f1, f2, f3])
Пример #11
0
    def __init__(self, drivechain, single_mode=False, path=""):
        self.path = path
        self.single_mode = single_mode
        self.mover = Mover()
        self.now = None
        # load up DriveChains
        self.load_drivechains()
        self.active_drivechain = None
        self.set_active_drivechain(5)

        # set up ROS publishers, subscribers and messages
        rospy.Subscriber('/cmd_vel', Twist, self.move, queue_size=1)

        print("MotionController loaded")
        self.update_pwms()
Пример #12
0
    def __init__(self, num_players: int, player_names: List[str]):
        LOG.info("Call to GameBoard.__init__")

        self.red_deck = CardDeck(
            "People"
        )  # Are these the right color to category mappings?  If we want to stick with colors, that's fine
        self.white_deck = CardDeck("Events")
        self.blue_deck = CardDeck("Places")
        self.green_deck = CardDeck("Independence Day")

        self.die = Die(num_sides=6)
        self.game_positions = GamePositions()

        self.players = []
        self.current_player = None  # It might be useful to have this property to easily access the player whose turn it is
        self.direction = ""  # The direction the player has chosen to move (not yet sure what values this can take)

        self.pixel_to_position_scaling_factor = 78  # Multiple a game_position location (in matrix) by this number to get the pixel location equivalent
        self.pixel_to_position_offset = (
            12, 12
        )  # add these x and y values to the scaled pixel location to get starting square (since it isn't in top left corner)

        colors = ['red', 'white', 'blue', 'green']
        for player_num in range(0, num_players):
            self.players.append(
                Mover(name=player_names[player_num],
                      mover_color=colors[player_num],
                      start_pos_x=0,
                      start_pos_y=0))
Пример #13
0
 def test_move_up_gives_a_board_with_the_blank_in_the_middle(self):
     inital = Tile()
     swap = list(inital.layout[1])
     inital.layout[1] = list(inital.layout[2])
     inital.layout[2] = swap
     expectedTile = [[1, 2, 3], [7, 0, 5], [8, 6, 4]]
     self.assertEqual(Mover.move_up(inital).layout, expectedTile)
Пример #14
0
 def expand(self, tile):
     for outcome in Mover.possible_moves(tile):
         if (outcome.layout == Tile().layout):
             return outcome.history
         if (self.original.layout != outcome.layout and
             (tile.history == [] or outcome.layout != tile.history[-1])):
             self.queue.insert(outcome,
                               self.gofH(outcome) + len(tile.history))
Пример #15
0
class Game:
    def __init__(self):
        self.track_m = TrackManager()
        self.agent = Mover(pygame.math.Vector2(200, 200), 0)
        self.game_started = False

    def start(self):
        self.agent.__init__(self.track_m.active_track.start_pos, 0)
        self.track_m.active_track.start()
        self.game_started = True

    def update(self):
        if self.game_started:
            self.agent.update()
            if self.track_m.active_track.crossed_active_checkpoint(
                    self.agent.prev_pos, self.agent.pos):
                self.track_m.active_track.next_checkpoint()
Пример #16
0
 def __init__(self):
     super(GlassWall, self).__init__()
     self.set_child(DataPoint(DataTypes.GAME_PIECE_TYPE, GamePieceTypes.TERRAIN))
     self.set_child(Mover())
     self.set_child(Position())
     self.set_child(DungeonLevel())
     self.set_child(GraphicChar(colors.FLOOR_BG, colors.WHITE, icon.GLASS_WALL))
     self.set_child(CharPrinter())
     self.set_child(Flag("is_solid"))
Пример #17
0
 def __init__(self):
     super(PoolOfBlood, self).__init__()
     self.set_child(DataPoint(DataTypes.GAME_PIECE_TYPE, GamePieceTypes.DUNGEON_TRASH))
     self.set_child(Position())
     self.set_child(DungeonLevel())
     self.set_child(Description("A pool of blood.", "A pool of blood."))
     self.set_child(GraphicChar(None, colors.RED, random.choice(icon.BLOOD_ICONS)))
     self.set_child(CharPrinter())
     self.set_child(Mover())
Пример #18
0
 def test_mover_returns_all_the_possible_next_moves(self):
     moveStates = [[[1, 0, 3], [8, 2, 4], [7, 6, 5]],
                   [[1, 2, 3], [0, 8, 4], [7, 6, 5]],
                   [[1, 2, 3], [8, 4, 0], [7, 6, 5]],
                   [[1, 2, 3], [8, 6, 4], [7, 0, 5]]]
     results = []
     for tile in Mover.possible_moves(Tile()):
         results.append(tile.layout)
     self.assertEqual(results, moveStates)
Пример #19
0
def setup():
	size(850, 600)
	title("Art Generator")
	background(250)

	global movers
	movers = []
	for i in range(mover_num):
		movers.append(Mover())
Пример #20
0
def set_dungeon_feature_components(dungeon_feature):
    dungeon_feature.set_child(
        DataPoint(DataTypes.GAME_PIECE_TYPE, GamePieceTypes.DUNGEON_FEATURE))
    dungeon_feature.set_child(Position())
    dungeon_feature.set_child(DungeonLevel())
    dungeon_feature.set_child(GraphicChar(None, colors.RED,
                                          icon.FOUNTAIN_FULL))
    dungeon_feature.set_child(CharPrinter())
    dungeon_feature.set_child(Mover())
    dungeon_feature.set_child(IsDungeonFeature())
Пример #21
0
 def __init__(self):
     super(Water, self).__init__()
     self.set_child(DataPoint(DataTypes.GAME_PIECE_TYPE, GamePieceTypes.TERRAIN))
     self.set_child(Mover())
     self.set_child(Position())
     self.set_child(DungeonLevel())
     self.set_child(GraphicChar(colors.BLUE_D,
                                colors.BLUE,
                                icon.WATER))
     self.set_child(CharPrinter())
Пример #22
0
 def __init__(self):
     super(Floor, self).__init__()
     self.set_child(DataPoint(DataTypes.GAME_PIECE_TYPE, GamePieceTypes.TERRAIN))
     self.set_child(Mover())
     self.set_child(Position())
     self.set_child(DungeonLevel())
     self.set_child(GraphicChar(colors.FLOOR_BG,
                                colors.FLOOR_FG,
                                icon.CENTER_DOT))
     self.set_child(CharPrinter())
     self.set_child(Flag(Floor.FLOOR_FLAG))
Пример #23
0
    def set_up_new_entity_with_dungeon(self, dungeon_level):
        entity = Composite()
        entity.set_child(Mover())

        entity.set_child(Position())
        entity.set_child(DataPoint(DataTypes.GAME_PIECE_TYPE, GamePieceTypes.ENTITY))
        dungeon_level_component = DungeonLevel()
        dungeon_level_component.value = dungeon_level
        entity.set_child(dungeon_level_component)

        return entity
Пример #24
0
    def __init__(self,
                 master,
                 move_callback: Callable[[str], None],
                 jump_callback: Callable[[int, int], None],
                 bg: str = "#ffffff"):
        """
        Initialise this Navigator.
        :param master: parent container of this Navigator
        :param move_callback: function to call when the user clicks on of the
        directional buttons
        :param jump_callback: function to call when the user clicks the jump
        button
        :param bg: background colour of this Navigator
        """
        super().__init__(master, bg=bg)

        self._mover = Mover(self, move_callback, bg=bg)
        self._mover.pack(side=tk.LEFT)

        self._jumper = Jumper(self, jump_callback, bg=bg)
        self._jumper.pack(side=tk.LEFT)
Пример #25
0
 def __init__(self):
     super(Unknown, self).__init__()
     self.set_child(DataPoint(DataTypes.GAME_PIECE_TYPE, GamePieceTypes.TERRAIN))
     self.set_child(Mover())
     self.set_child(Position())
     self.set_child(DungeonLevel())
     self.set_child(CharPrinter())
     self.set_child(GraphicChar(colors.BLACK,
                                colors.BLACK,
                                ' '))
     self.set_child(Flag("is_unknown"))
     self.set_child(Flag("is_solid"))
Пример #26
0
class TestMoverMethods(unittest.TestCase):

    PWM_LEFT = 33
    PWM_RIGHT = 12
    GPIO_MOTOR1 = 11
    GPIO_MOTOR2 = 15
    GPIO_MOTOR3 = 16
    GPIO_MOTOR4 = 18

    testMover = Mover(debug=True)

    # setting up the Mover() object calls the GPIO (in some way)
    def test_moverSetup(self, MockGPIO):
        gpio = MockGPIO()
        assert MockGPIO.called  # basic assertion

    def test_startPWM(self, MockGPIO):
        gpio = MockGPIO(side_effect=RuntimeError(
            'A PWM object already exists for this GPIO channel'))
        self.testMover.start_pwm()

    def test_stop(self, MockGPIO):
        gpio = MockGPIO()
        self.testMover.stop()
        MockGPIO.assert_has_calls([call()])

    def test_moveForward(self, MockGPIO):
        self.testMover.forward()
        MockGPIO.assert_has_calls([
            call(self.GPIO_MOTOR1, False),
            call(self.GPIO_MOTOR2, True),
            call(self.GPIO_MOTOR3, False),
            call(self.GPIO_MOTOR4, True)
        ])

    def test_moveBackward(self, MockGPIO):
        self.testMover.reverse()
        MockGPIO.assert_has_calls([
            call(self.GPIO_MOTOR1, True),
            call(self.GPIO_MOTOR2, False),
            call(self.GPIO_MOTOR3, True),
            call(self.GPIO_MOTOR4, False)
        ])

    def test_teardown(self, MockGPIO):
        gpio = MockGPIO()
        self.testMover.teardown()
        MockGPIO.assert_has_calls(
            [call()])  # this is the best we can do, test that it was called

    @classmethod
    def tearDownClass(self):
        GPIO.cleanup()
Пример #27
0
class ConnectFour():
    """Contains input checker, and 'order' of functions to play the game.
    Intended to be called in Terminal"""
    def __init__(self):
        self.makemoves = Mover()
        self.checkwins = Wins()

    def check_input(self):
        while True:
            newmove = input("Please make a move. It is " +
                            self.makemoves.player + "'s turn!")
            try:
                newmove = int(newmove)
            except:
                print("Error! Please use a numeric input.")
            else:
                if newmove > 0 and newmove < 8:
                    break
                else:
                    print("Error! Please use an input between 1 and 7.")
        return newmove

    def play_game(self):
        counter = 0
        self.makemoves.board.board_print()
        while counter < 42:
            self.makemoves.make_move(self.check_input())
            self.makemoves.board.board_print()
            wincheck = self.checkwins.check_win(
                position=self.makemoves.moveinfo,
                player=self.makemoves.player,
                board=self.makemoves.board.board)
            if wincheck == 'R':
                print("Game over! Red wins!")
                break
            elif wincheck == 'B':
                print("Game over! Black wins!")
                break
            else:
                self.makemoves.change_player()
Пример #28
0
def set_cloud_components(game_state, cloud, density):
    cloud.set_child(DataPoint(DataTypes.ENERGY, -gametime.single_turn))
    cloud.set_child(DataPoint(DataTypes.GAME_PIECE_TYPE, GamePieceTypes.CLOUD))
    cloud.set_child(DataPoint(DataTypes.GAME_STATE, game_state))
    cloud.set_child(CharPrinter())
    cloud.set_child(Position())
    cloud.set_child(DungeonLevel())
    cloud.set_child(Mover())
    cloud.set_child(GraphicChar(None, None, 178))
    cloud.set_child(DataPoint(DataTypes.DENSITY, density))
    cloud.set_child(DataPoint(DataTypes.MOVEMENT_SPEED, gametime.single_turn))
    cloud.set_child(StatusFlags([StatusFlags.FLYING]))
    cloud.set_child(CloudChangeAppearanceShareTileEffect())
Пример #29
0
    def __init__(self):
        super(Chasm, self).__init__()
        self.set_child(DataPoint(DataTypes.GAME_PIECE_TYPE, GamePieceTypes.TERRAIN))
        self.set_child(Mover())
        self.set_child(Position())
        self.set_child(DungeonLevel())
        self.set_child(GraphicChar(colors.BLACK, colors.DARKNESS, icon.CHASM2))
        self.set_child(CharPrinter())
        self.set_child(Flag("is_chasm"))

        self.set_child(PlayerFallDownChasmAction())
        self.set_child(FallRemoveNonPlayerNonFlying())
        self.set_child(PromptPlayerChasm())
Пример #30
0
    def __connect_hotkeys(self, root):
        r = root
        r.bind("<Key-a>", lambda ev: self.__add_mark_and_select_it())
        r.bind("<Prior>", lambda ev: self.__choose_prev_mark())
        r.bind("<Next>", lambda ev: self.__choose_next_mark())
        r.bind("<Delete>", lambda ev: self.__remove_mark())

        self.__mover = Mover(root, self.__move_mark)
        self.__rotator = Rotator(root, self.__rotate_mark)
        r.bind("<Control-Left>", lambda ev: self.__change_width(-self.__W_C))
        r.bind("<Control-Right>", lambda ev: self.__change_width(self.__W_C))
        r.bind("<Control-Up>", lambda ev: self.__change_length(self.__L_C))
        r.bind("<Control-Down>", lambda ev: self.__change_length(-self.__L_C))