Пример #1
0
    def __init__(self, trivia_question_repository, user_repository):
        Command.__init__(self)

        self._trivia_question_repository = trivia_question_repository
        self._user_repository = user_repository
        self._game_started = False
        self._current_question = None
Пример #2
0
    def apply_command(matches: Collection, query: str) -> List[Message]:
        match_id = query

        check: Union[Message,
                     ObjectId] = Command.check_match_id(match_id, "spectate")
        if isinstance(check, Message):
            return [check]

        object_id = check
        match = matches.find_one({"_id": object_id})
        if match is None:
            return [Command.error_msg("Match not found", "spectate", match_id)]
        if match["gameState"] == GameState.ENDED.value:
            return [Command.error_msg("Game ended", "spectate", match_id)]

        return [
            Message({
                "messageType": "spectate",
                "matchId": match_id
            }, True, match_id, True),
            Message(
                Command.generate_state_dict(
                    matches.find_one({"_id": object_id})),  # type: ignore
                False,
                match_id)
        ]
Пример #3
0
    def __init__(self, trivia_question_repository, user_repository):
        Command.__init__(self)

        self._trivia_question_repository = trivia_question_repository
        self._user_repository = user_repository
        self._game_started = False
        self._current_question = None
Пример #4
0
 def test_set_action_overrides_with_lambda(self):
     # Assemble
     c1 = Command()
     # Action
     c1.set_action(lambda x, y: x + y)
     # Assert
     self.assertEqual(3, c1.__do__(1, 2))
Пример #5
0
    def __init__(self, args):
        Command.__init__(self, args)
        self.apkFile = args.apk
        # print(type(args.perm))

        self.show_permission = args.perm      
        self.show_signature = args.sign
        self.components = args.comp 
Пример #6
0
    def test_set_action_overrides_with_function(self):
        c1 = Command()

        def my_action(): return 1

        c1.set_action(my_action)

        self.assertEqual(1, c1.__do__())
Пример #7
0
def test_when_executing_then_handle(mocker):
    on_handle_stub = mocker.stub(name='on_handle_stub')
    on_unregister_stub = mocker.stub(name='on_unregister_stub')
    command = Command([StubHandler(on_handle_stub, on_unregister_stub)])

    command.execute(HANDLED_DATA)

    on_handle_stub.assert_called_once_with(None)
    on_unregister_stub.assert_called_once()
Пример #8
0
def extract_command(message_text) -> Command:
    logging.info("Message Text:: {}".format(message_text))
    if len(message_text.split('me')) == 1:
        logging.info('Command Not Found ' + message_text)
        return Command(None, None)
    else:
        return Command(
            message_text.split('me')[0],
            message_text.split('me')[1])
Пример #9
0
    def test_set_action_overrides_with_function_and_allows_params(self):
        # Assemble
        c1 = Command()

        def my_action(x, y): return x + y

        # Action
        c1.set_action(my_action)

        # Assert
        self.assertEqual(3, c1.__do__(1, 2))
Пример #10
0
def test_given_multiple_handlers_when_executing_then_handle(mocker):
    on_handle_stub = mocker.stub(name='on_handle_stub')
    on_unregister_stub = mocker.stub(name='on_unregister_stub')
    command = Command([
        StubHandler(on_handle_stub, on_unregister_stub),
        StubHandler(on_handle_stub, on_unregister_stub)
    ])

    command.execute(HANDLED_DATA)

    on_handle_stub.assert_has_calls([call(None), call(ONCE_HANDLED_DATA)])
    assert on_unregister_stub.call_count == 2
Пример #11
0
    def test_set_previous_sets_node_correctly(self):
        # Assemble
        c1 = Command()
        c2 = Command()

        # Action
        c2.set_previous(c1)

        # Assert
        self.assertEqual(c1.get_next(), c2)
        self.assertEqual(c1.get_previous(), None)
        self.assertEqual(c2.get_next(), None)
        self.assertEqual(c2.get_previous(), c1)
Пример #12
0
class Client(Updater):
    COMMANDS = [
        Command('hello', funs.hello),
        Command('start', funs.start),
        Command('morning', funs.morning),
        Command('weather', funs.weather),
        Command('help', funs.help),
        Command('income', funs.income),
        Command('outflow', funs.outflow),
        Command('balance', funs.balance)
    ]

    def __init__(self, **kwargs):
        super().__init__(token=os.environ.get('TELEGRAM_KEY', 'XXX'), **kwargs)
        self.__init_client()

    def __init_client(self):
        for command in self.COMMANDS:
            self.__add_command(command())

    def __add_command(self, command):
        self.dispatcher.add_handler(command)

    def run(self):
        self.start_polling()
        self.idle()
Пример #13
0
def test_given_next_command_when_executing_then_pass_handled_data(mocker):
    on_handle_stub = mocker.stub(name='on_handle_stub')
    on_unregister_stub = mocker.stub(name='on_unregister_stub')

    commands = [
        Command([StubHandler(on_handle_stub, on_unregister_stub)]),
        Command([StubHandler(on_handle_stub, on_unregister_stub)])
    ]

    handled_data = HANDLED_DATA
    for command in commands:
        handled_data = command.execute(handled_data)

    on_handle_stub.assert_has_calls([call(None), call(ONCE_HANDLED_DATA)])
    assert on_unregister_stub.call_count == 2
Пример #14
0
def game_socket(ws: WebSocket) -> None:
    while not ws.closed:
        query = ws.receive()
        if query is None:
            continue

        print(f"Received:`{query}`")

        messages: List[Message]
        for command in commands:
            if command.command_matches(query):
                messages = command.apply_command(
                    matches, query[len(command.STARTS_WITH):])
                break
        else:
            messages = [Command.error_msg("Invalid command sent", query)]
            pass

        for message in messages:
            if message.add_sender_to_spectate_map:
                add_client_to_map(message.match_id, ws)

            msg_to_send_str = to_json_str(message.message)
            if message.reply_to_only_sender:
                ws.send(msg_to_send_str)
            else:
                removed_clients: List[WebSocket] = []
                for client in game_clients[message.match_id]:
                    try:
                        client.send(msg_to_send_str)
                    except WebSocketError:
                        removed_clients.append(client)
                for client in removed_clients:
                    game_clients[message.match_id].remove(client)
Пример #15
0
    def test_dispatches_to_hardware(self):
        with MockHardware() as hardware_service:
            dispatcher = Dispatcher(hardware_service)

            current_state = State(color=Color(100, 100, 100),
                                  buzzer_pattern=BuzzerPattern.NONE)

            command = Command(color=Color(110, 110, 110),
                              duration=100,
                              buzzer_pattern=BuzzerPattern.NONE)

            now = 0

            next_state = dispatcher.dispatch(current_state, command, now)

            self.assertEqual(next_state.color.r, 100)
            self.assertEqual(next_state.color.g, 100)
            self.assertEqual(next_state.color.b, 100)
            self.assertEqual(hardware_service.color_last_called_with.r, 100)
            self.assertEqual(hardware_service.color_last_called_with.g, 100)
            self.assertEqual(hardware_service.color_last_called_with.b, 100)
            self.assertEqual(hardware_service.color_called_count, 1)

            now = 10

            next_state = dispatcher.dispatch(next_state, command, now)

            self.assertEqual(next_state.color.r, 101)
            self.assertEqual(next_state.color.g, 101)
            self.assertEqual(next_state.color.b, 101)
            self.assertEqual(hardware_service.color_last_called_with.r, 101)
            self.assertEqual(hardware_service.color_last_called_with.g, 101)
            self.assertEqual(hardware_service.color_last_called_with.b, 101)
            self.assertEqual(hardware_service.color_called_count, 2)

            now = 90

            next_state = dispatcher.dispatch(next_state, command, now)

            self.assertEqual(next_state.color.r, 109)
            self.assertEqual(next_state.color.g, 109)
            self.assertEqual(next_state.color.b, 109)
            self.assertEqual(hardware_service.color_last_called_with.r, 109)
            self.assertEqual(hardware_service.color_last_called_with.g, 109)
            self.assertEqual(hardware_service.color_last_called_with.b, 109)
            self.assertEqual(hardware_service.color_called_count, 3)

            now = 100

            next_state = dispatcher.dispatch(next_state, command, now)

            self.assertEqual(next_state.color.r, 110)
            self.assertEqual(next_state.color.g, 110)
            self.assertEqual(next_state.color.b, 110)
            self.assertEqual(hardware_service.color_last_called_with.r, 110)
            self.assertEqual(hardware_service.color_last_called_with.g, 110)
            self.assertEqual(hardware_service.color_last_called_with.b, 110)
            self.assertEqual(hardware_service.color_called_count, 4)
Пример #16
0
def load_commands(message_sender, tg_logger = None):
    global logger
    global commands

    logger = tg_logger
    commands = []
    for cls in Command.__subclasses__():
        command = cls(logger, message_sender)
        commands.append(command)
Пример #17
0
    def apply_command(matches: Collection, query: str) -> List[Message]:
        match_id = query

        check: Union[Message, ObjectId] = Command.check_match_id(match_id, "state")
        if isinstance(check, Message):
            return [check]

        object_id = check
        match = matches.find_one({"_id": object_id})
        if match is None:
            return [Command.error_msg("Match not found", "state", match_id)]

        return [
            Message(
                Command.generate_state_dict(match),
                True,
                match_id
            )
        ]
Пример #18
0
    def command(self,
                coro: Callable
                ) -> Callable[[fortnitepy.FriendMessage], Any]:
        if not asyncio.iscoroutinefunction(coro):
            raise TypeError("Function must be a coroutine")
        self.register_command(coro.__name__, Command(coro, self.command_prefix)
                              )

        def inner(*args, **kwargs):
            return coro(*args, **kwargs)
        return inner
Пример #19
0
    def test_all_execute_when_no_errors_are_thrown(self):
        # Setup command chain with mocked __do__ functions
        c2 = Command()
        c1 = Command(next=c2)
        c1.__do__ = Mock()
        c2.__do__ = Mock()

        # Action
        c1.run()

        # Assert all functions called
        c1.__do__.assert_called_once()
        c2.__do__.assert_called_once()
Пример #20
0
    def test_child_command_rolls_back_self_on_exception(self):
        # Assemble command chain with mocked __do__ functions
        # Initial command triggered will throw exception
        c1 = Command()
        c2 = Command(previous=c1)
        c2.__do__ = Mock(side_effect=Exception('Oh No!'))
        c2.__undo__ = Mock()

        # Action
        c1.run()

        # Assert command 2 was rolled back
        c2.__undo__.assert_called_once()
Пример #21
0
    def test_chained_command_does_not_execute_if_parent_throws_exception(self):
        # Assemble command chain with mocked __do__ functions
        # Initial command triggered will throw exception
        c1 = Command()
        c2 = Command(previous=c1)
        c1.__do__ = Mock(side_effect=Exception('Oh No!'))
        c2.__do__ = Mock()

        # Action
        c1.run()

        # Assert command one was called (Threw an exception) and c2 was not called
        c1.__do__.assert_called_once()
        c2.__do__.assert_not_called()
Пример #22
0
    def test_constructor_links_next_node_when_passed_in_constructor(self):
        # Assemble
        c2 = Command()
        c1 = Command(next=c2)

        # Assert
        self.assertEqual(c1.get_next(), c2)
        self.assertEqual(c2.get_previous(), c1)
Пример #23
0
 def __init__(self):
     self.prompt = "➜ "
     self.banner = """
     n0framework
     Powered by n0b0dy@Eur3kA
     """
     self.session = None
     self.commandReg = CommandRegister()
     self.serviceReg = ServiceRegister()
     self.history = FileHistory("/framelog/history.txt")
     for cmd in Command.find_all():
         self.commandReg.register(cmd())
     for service in Service.find_all():
         self.serviceReg.register(service())
Пример #24
0
 def __init__(self, parent, frame, **kwargs):
     """ Constructor must be called after objects_container is set!!!
     Because of notebook wanting itself to be parent, we pass frame as another variable """
     super(ObjectsCanvas, self).__init__(parent, **kwargs)
     self.frame = frame
     self.SetDoubleBuffered(True)
     self.size = 0, 0
     self.SetName("ObjectCanvas")
     self.commands = Command()
     self.saved_command = self.commands
     self.canvas_size = [1, 1] # w, h
     self.view_point = [0, 0]  # x, y
     self.filepath = None
     self.zoom = 1
     self.update_bounds()
     self.do_bindings()
Пример #25
0
def main():
    admin = os.getenv('ADMIN_USER')
    telegram_token = os.getenv('TELEGRAM_TOKEN')
    with open('version', 'r') as v:
        version = v.read().rstrip()
    with open('handlers/greeters.yml') as f:
        gs = f.read()
    handlers = []
    for g in yaml.full_load_all(gs):
        handlers.append(g)
    handlers.append(
        Command('versio', 'La meva versió és {}', [version],
                Filters.chat(username=admin)))
    handlers.append(Roller('roll', '', '', None))

    r = Rostollador(admin, telegram_token, handlers)
    r.start()
Пример #26
0
    def test_dispatches_to_hardware_with_buzzer(self):
        with MockHardware() as hardware_service:
            dispatcher = Dispatcher(hardware_service)

            current_state = State(color=Color(100, 100, 100),
                                  buzzer_pattern=BuzzerPattern.NONE)

            command = Command(color=Color.no_change(),
                              duration=100,
                              buzzer_pattern=BuzzerPattern(duration=10,
                                                           strength=1))

            now = 0

            next_state = dispatcher.dispatch(current_state, command, now)

            self.assertEqual(next_state.color.r, 100)
            self.assertEqual(next_state.color.g, 100)
            self.assertEqual(next_state.color.b, 100)
            self.assertEqual(next_state.buzzer_pattern.strength, 1)
            self.assertEqual(hardware_service.motor_called_count, 1)
            self.assertEqual(hardware_service.motor_state, 1)

            now = 10

            next_state = dispatcher.dispatch(next_state, command, now)

            self.assertEqual(next_state.color.r, 100)
            self.assertEqual(next_state.color.g, 100)
            self.assertEqual(next_state.color.b, 100)
            self.assertEqual(next_state.buzzer_pattern.strength, 1)
            self.assertEqual(hardware_service.motor_called_count, 2)
            self.assertEqual(hardware_service.motor_state, 1)

            now = 90

            next_state = dispatcher.dispatch(next_state, command, now)

            self.assertEqual(next_state.color.r, 100)
            self.assertEqual(next_state.color.g, 100)
            self.assertEqual(next_state.color.b, 100)
            self.assertEqual(next_state.buzzer_pattern.strength, 0)
            self.assertEqual(hardware_service.motor_stop_called_count, 1)
            self.assertEqual(hardware_service.motor_state, 0)
Пример #27
0
    def apply_command(matches: Collection, query: str) -> List[Message]:
        # Command format: move [match_id] [token] [card] [move]
        # Example: move 5f9c394ee71e1740c218587b iq2V39W9WNm0EZpDqEcqzoLRhSkdD3lY boar a1a2
        split = query.split(" ")
        match_id, token, card_name, move = split

        check: Union[Message,
                     ObjectId] = Command.check_match_id(match_id, "move")
        if isinstance(check, Message):
            return [check]

        object_id = check
        match = matches.find_one({"_id": object_id})
        if match is None:
            return [Command.error_msg("Match not found", "move", match_id)]
        if match["gameState"] == GameState.ENDED.value:
            return [Command.error_msg("Game ended", "move", match_id)]

        if token == match["tokenBlue"]:
            color = "blue"
        elif token == match["tokenRed"]:
            color = "red"
        else:
            return [Command.error_msg("Token is incorrect", "move", match_id)]

        if move[0] not in "abdce" or move[1] not in "12345" or move[
                2] not in "abcde" or move[3] not in "12345":
            move = "none"
        if card_name not in ALL_BASE_CARD_NAMES:
            card_name = "none"
        if move == "none" or card_name == "none":
            return [
                Command.error_msg("'move' or 'card' not given properly",
                                  "move", match_id)
            ]

        board = str_to_board(match["board"])
        piece_pos = notation_to_pos(move[:2])

        if match["currentTurn"] != color:
            return [
                Command.error_msg("Cannot move when it is not your turn",
                                  "move", match_id)
            ]

        if board[piece_pos.y][piece_pos.x].color.value != color:
            return [
                Command.error_msg(
                    "Cannot move opponent's pieces or empty squares", "move",
                    match_id)
            ]

        move_pos = notation_to_pos(move[2:])
        move_card = get_card_from_name(card_name)
        cards = get_cards_from_names(match["cards"][color])
        new_board: Optional[Board] = apply_move(piece_pos, move_pos, move_card,
                                                cards, board)

        if new_board is None:
            return [Command.error_msg("Invalid move", "move", match_id)]

        winner = check_win_condition(new_board)
        state = GameState.ENDED.value if winner != Player.NONE else GameState.IN_PROGRESS.value

        moves = match["moves"]
        moves.append(f"{card_name}:{move}")
        side_card: str = match["cards"]["side"]
        new_cards: List[str] = match["cards"][color]
        new_cards[new_cards.index(card_name)] = side_card

        enemy = "red" if color == "blue" else "blue"
        enemy_cards = match["cards"][enemy]

        matches.find_one_and_update({"_id": object_id}, {
            "$set": {
                "board": board_to_str(new_board),
                "moves": moves,
                "currentTurn": "blue" if color == "red" else "red",
                "cards": {
                    enemy: enemy_cards,
                    color: new_cards,
                    "side": card_name
                },
                "gameState": state,
                "winner": winner.value
            }
        })

        return [
            Message({
                "messageType": "move",
                "matchId": match_id
            }, True, match_id),
            Message(
                Command.generate_state_dict(
                    matches.find_one({"_id": object_id})),  # type: ignore
                False,
                match_id)
        ]
Пример #28
0
    def __init__(self):
        Command.__init__(self)

        self._request_uri = "http://api.urbandictionary.com/v0/define?term={}"
Пример #29
0
 def __init__(self):
     Command.__init__(self, "set")
Пример #30
0
    def __init__(self, quote_repository):
        Command.__init__(self)

        self._quote_repository = quote_repository
Пример #31
0
 def __init__(self):
     Command.__init__(self)
     self._request_uri = "http://api.giphy.com/v1/gifs/random?tag={}&api_key={}"
     self._api_key = "dc6zaTOxFJmzC"
Пример #32
0
 def __init__(self):
     Command.__init__(self, "compile")
Пример #33
0
    def apply_command(matches: Collection, query: str) -> List[Message]:
        split = query.split(" ")
        match_id = split[0]

        check: Union[Message,
                     ObjectId] = Command.check_match_id(match_id, "join")
        if isinstance(check, Message):
            return [check]

        object_id = check
        username = "******".join(split[1:])
        match = matches.find_one({"_id": object_id})
        if match is None:
            return [Command.error_msg("Match not found", "join", match_id)]
        if match["gameState"] != GameState.WAITING_FOR_PLAYER.value:
            return [Command.error_msg("Not allowed to join", "join", match_id)]

        token: str = token_hex(32)
        color: str = "red" if match["tokenRed"] == "" else "blue"
        board, blue_cards, red_cards, side_card = init_game()
        usernames = match["usernames"]
        usernames[color] = username
        indices = match["indices"]
        indices[color] = 1

        matches.find_one_and_update({"_id": object_id}, {
            "$set": {
                f"token{color.title()}": token,
                "usernames": usernames,
                "indices": indices,
                "gameState": GameState.IN_PROGRESS.value,
                "board": board_to_str(board),
                "moves": [],
                "currentTurn": side_card.color.value,
                "cards": {
                    "blue": [i.name for i in blue_cards],
                    "red": [i.name for i in red_cards],
                    "side": side_card.name
                },
                "startingCards": {
                    "blue": [i.name for i in blue_cards],
                    "red": [i.name for i in red_cards],
                    "side": side_card.name
                },
                "winner": Player.NONE.value
            }
        })

        return [
            Message(
                {
                    "messageType": "join",
                    "matchId": match_id,
                    "token": token,
                    "index": 1
                }, True, match_id),
            Message(
                Command.generate_state_dict(
                    matches.find_one({"_id": object_id})),  # type: ignore
                False,
                match_id)
        ]
Пример #34
0
 def __init__(self):
     Command.__init__(self)
     self._request_uri = "http://api.fixer.io/latest?base={}&symbols={}"
Пример #35
0
 def __init__(self):
     Command.__init__(self, "add")
Пример #36
0
 def __init__(self, loud=False):
     Command.__init__(self)
     self.volume = 8 if not loud else 16
Пример #37
0
 def __init__(self, **kwargs):
     Command.__init__(self, **kwargs)
     if type(self).params is None:
         type(self).params = ParamPipe()
         self.setup()
Пример #38
0
class ObjectsCanvas(wx.ScrolledWindow):
    def __init__(self, parent, frame, **kwargs):
        """ Constructor must be called after objects_container is set!!!
        Because of notebook wanting itself to be parent, we pass frame as another variable """
        super(ObjectsCanvas, self).__init__(parent, **kwargs)
        self.frame = frame
        self.SetDoubleBuffered(True)
        self.size = 0, 0
        self.SetName("ObjectCanvas")
        self.commands = Command()
        self.saved_command = self.commands
        self.canvas_size = [1, 1] # w, h
        self.view_point = [0, 0]  # x, y
        self.filepath = None
        self.zoom = 1
        self.update_bounds()
        self.do_bindings()
        
    def zoom_out(self):
        if self.zoom >=0.25:
            self.zoom -= 0.1
            self.update_bounds()
            self.Refresh()
            
    def zoom_in(self):
        self.zoom += 0.1
        self.update_bounds()
        self.Refresh()
        
    def zoom_restore(self):
        self.zoom = 1
        self.update_bounds()
        self.Refresh()
        
    @property
    def strategy(self):
        return self.frame.strategy
        
    def do_bindings(self):
        self.Bind(wx.EVT_PAINT, self.on_paint_event)
        self.Bind(wx.EVT_SIZE,  self.on_size_event)
        self.Bind(wx.EVT_LEFT_DOWN, self.on_left_button_down)
        self.Bind(wx.EVT_LEFT_UP, self.on_left_button_up)
        self.Bind(wx.EVT_MOTION, self.on_mouse_motion)
        self.Bind(wx.EVT_LEFT_DCLICK, self.on_left_button_dclick)
        self.Bind(wx.EVT_RIGHT_DOWN, self.on_right_button_down)
        self.Bind(wx.EVT_RIGHT_UP, self.on_right_button_up)
        self.Bind(wx.EVT_SCROLLWIN, self.on_scroll)
    
    @property
    def is_changed(self):
        return self.commands is not self.saved_command
    
    @property
    def has_unsaved_changes(self):
        if self.is_changed:
            return True
        if self.filepath is None:
            if self.petri.places or self.petri.transitions:
                return True
        return False
        
    def GetObjectsInRect(self, lx, ly, tx, ty):
        for obj in self.get_objects_iter():
            if not obj.is_selectable():
                continue
            obj.unselect_temporary()
            if obj.in_rect(lx, ly, tx, ty):
                yield obj
        
    def get_name(self):
        result = self.GetName()
        if self.has_unsaved_changes:
            result = '*'+result
        return result
        
    def load_from_file(self, filepath, format):
        net = None
        with open(filepath, 'rb') as f:
            data = f.read()
        net = format.import_net(data)
        self.update_title(filepath)
        self.filepath = filepath
        self.petri = net
    
    def update_title(self, filepath):
        basename = osp.basename(filepath)
        title = osp.splitext(basename)[0]
        self.SetName(title)
        
    def save_to_file(self, filepath, net, format):
        if format.persistent:
            self.update_title(filepath)
        data = format.export_net(net)
        with open(filepath, 'wb') as f:
            f.write(data)
        if format.persistent:
            self.filepath = filepath
            self.saved_command = self.commands
        
    def on_scroll(self, event):
        orientation = event.GetOrientation()
        event.Skip()
        wx.CallAfter(self.process_scroll_event, orientation)

    def process_scroll_event(self, orientation):
        if not self.strategy.is_moving_objects:
            pos = self.GetScrollPos(orientation)
            rng = self.GetScrollRange(orientation) - self.GetScrollThumb(orientation)
            if rng==0:
                self.Refresh()
                return
            ind = 1 if orientation == wx.VERTICAL else 0
            new_vp = (float(pos) / rng) * (self.canvas_size[ind] - self.size[ind])
            self.view_point[ind] = int(new_vp)
            self.Refresh()
            
    def append_command(self, command):
        if command.does_nothing:
            return
        self.commands = self.commands.add_command(command)
        self.frame.on_command_append()
        
    def update_frame_menu(self):
        self.frame.update_menu()
        
    def undo(self):
        if self.can_undo():
            self.commands = self.commands.go_prev()
            self.Refresh()
            
    def can_undo(self):
        return self.strategy.allow_undo_redo and self.commands.has_prev()
        
    def redo(self):
        if self.can_redo():
            self.commands = self.commands.go_next()
            self.Refresh()
            
    def can_redo(self):
        return self.strategy.allow_undo_redo and self.commands.has_next()
    
    def can_select(self):
        return self.strategy.can_select
    
    can_cut = can_delete = can_paste = can_copy = can_select
    
    def copy(self):
        if self.can_copy():
            self.on_copy()
        
    def on_copy(self):
        raise NotImplementedError
            
    def paste(self):
        if self.can_paste():
            self.on_paste()
            
    def on_paste(self):
        raise NotImplementedError
            
    def cut(self):
        if self.can_cut():
            self.on_cut()
            
    def on_cut(self):
        raise NotImplementedError
            
    def delete(self):
        if self.can_delete():
            self.on_delete()
            
    def on_delete(self):
        raise NotImplementedError
            
    def select_all(self):
        if self.can_select():
            self.strategy.on_select_all()
    
    def save(self, format):
        return self.save_as(filepath=self.filepath, format=format)
    
            
    def save_as(self, format, filepath=None):
        if filepath is None:
            while True:
                print format
                dlg = wx.FileDialog(
                    self, message="Save file as ...", 
                    defaultFile="", wildcard=format.get_wildcard(), style=wx.SAVE
                    )
                if dlg.ShowModal() == wx.ID_OK:
                    filepath = dlg.GetPath()
                else:
                    return
                if not osp.exists(filepath):
                    break       
                if not osp.isfile(filepath):
                    continue
                dlg = wx.MessageDialog(self, message='File (%s) already exists. Overwrite it?'%filepath, style=wx.YES_NO|wx.CANCEL|wx.CENTER)
                result = dlg.ShowModal()
                dlg.Destroy()
                if result == wx.ID_YES:
                    break
                elif result == wx.ID_NO:
                    continue
                elif result == wx.ID_CANCEL:
                    return
        if not filepath:
            return
        self.save_to_file(filepath, self.petri, format=format)
        return True
        
    def on_size_event(self, event):
        self.size = event.GetSize()
        self.update_bounds()
        self.Refresh()
        
    def on_paint_event(self, event):
        dc = SmartDC(self)
        w, h = self.size
        dc.SetPen(wx.WHITE_PEN)
        dc.SetBrush(wx.WHITE_BRUSH)
        dc.DrawRectangleOnScreen(0,0,w,h)
        self.draw(dc, w, h)
        
    def on_left_button_down(self, event):
        if self.strategy.need_capture_mouse:
            self.mouse_in = True
            self.on_lbutton_timer()
        self.strategy.on_left_down(event)
        self.SetFocus()
        
    def on_right_button_down(self, event):
        self.strategy.on_right_down(event)
        
    def on_right_button_up(self, event):
        self.strategy.on_right_up(event)
        
    def on_left_button_dclick(self, event):
        self.strategy.on_left_dclick(event)
        self.SetFocus()
        
    def on_key_down(self, event):    
        self.strategy.on_key_down(event)

    def on_lbutton_timer(self, *args, **kwargs):
        """ Dirty hack to catch the moment when mouse leaves window and capture it. wx.EVT_LEAVE_WINDOW is not always sent. """
        x, y, w, h = self.GetScreenRect()
        w -= constants.VSCROLL_X
        h -= constants.HSCROLL_Y
        mx, my = wx.GetMousePosition()
        state = wx.GetMouseState()
        if not state.LeftDown():
            if self.HasCapture():
                self.ReleaseMouse()
            return
        mouse_in = x <= mx <= x+w and y <= my <= y+h
        if mouse_in and not self.mouse_in:
            if self.HasCapture():
                self.ReleaseMouse()
        elif not mouse_in and self.mouse_in:
            self.CaptureMouse()
        self.mouse_in = mouse_in
        wx.CallLater(20, self.on_lbutton_timer)
        
    def get_object_at(self, x, y):
        """ Gets object under given virtual position """
        # Check in reverse order so the topmost object will be selected
        for obj in self.get_objects_reversed_iter():
            if obj.contains_point(x, y):
                return obj
        
    def on_mouse_motion(self, event):
        self.strategy.on_motion(event)
        
    def on_left_button_up(self, event):
        self.strategy.on_left_up(event)
        
    def get_objects_iter(self):
        raise NotImplementedError
        
    def get_objects_reversed_iter(self):
        raise NotImplementedError
            
    def update_bounds(self):
        """ Update canvas size and adjust scrollbars to it """
        if self.strategy.is_moving_objects:
            # Do not update when user is moving something, because it will cause mess.
            return
        max_x, max_y = 0, 0
        for obj in self.get_objects_iter():
            x,y = obj.get_position()
            w,h = obj.get_size()
            max_x = max(max_x, x+w)
            max_y = max(max_y, y+h)
        max_x = max_x * self.zoom
        max_y = max_y * self.zoom
        max_x = max(max_x+constants.RIGHT_OFFSET, self.size[0]-constants.VSCROLL_X)
        max_y = max(max_y+constants.BOTTOM_OFFSET, self.size[1]-constants.HSCROLL_Y)
        self.canvas_size[0], self.canvas_size[1] = max_x, max_y
        prev_x, prev_y = self.GetScrollPos(wx.HORIZONTAL), self.GetScrollPos(wx.VERTICAL)
        self.SetScrollbars(1, 1, max_x, max_y)
        self.Scroll(prev_x, prev_y)
        self.process_scroll_event(wx.VERTICAL)
        self.process_scroll_event(wx.HORIZONTAL)
        
    def screen_to_canvas_coordinates(self, point):
        x, y = point
        vx, vy = self.view_point
        x = x / self.zoom
        y = y / self.zoom
        return (x+vx, y+vy)
    
    def canvas_to_screen_coordinates(self, point):
        x, y = point
        x = (x - self.view_point[0])*self.zoom
        y = (y - self.view_point[1])*self.zoom
        return (x, y)
            
    def draw(self, dc, w, h):
        for obj in self.get_objects_iter():
            obj.draw(dc, self.zoom)
        self.strategy.draw(dc, self.zoom)
Пример #39
0
 def __init__(self):
     Command.__init__(self)
Пример #40
0
 def __init__(self):
     Command.__init__(self, "list")
Пример #41
0
    def __init__(self, message_repository, message=None):
        Command.__init__(self)

        self._message_repository = message_repository
        self.message = message
Пример #42
0
    def __init__(self):
        Command.__init__(self)

        self._request_uri = "http://api.openweathermap.org/data/2.5/weather?q={}&appid={}"
        self._api_key = os.getenv("WEATHER_API_KEY")
Пример #43
0
 def __init__(self):
     Command.__init__(self, "clone")
Пример #44
0
 def __init__(self):
     Command.__init__(self, "deps")
Пример #45
0
import random

from constants import game as gc
from commands.command import Command
from commands.move_command import MoveCommand
from constants import command as cc

COMMAND_LIST = Command.__subclasses__()

random.seed(gc.RAND_SEED)


# GODS PLAN
def create_a_choice(parents=None):
    command_generation_function = {
        MoveCommand: _create_move_command,
    }
    next_choice = random.choice(COMMAND_LIST)
    command, command_kwargs = command_generation_function.get(next_choice)(
        parents)
    return command, command_kwargs


def _create_move_command(parents):
    if parents:
        # TODO: Parent 50/50 here
        pass
    else:
        return MoveCommand, {
            cc.DIRECTION: random.choice(list(cc.DIRECTION_MAP.values()))
        }
Пример #46
0
 def __init__(self):
     Command.__init__(self)
     self._request_uri = "http://api.giphy.com/v1/gifs/random?tag={}&api_key={}"
     self._api_key = "dc6zaTOxFJmzC"
Пример #47
0
from commands.command import Command
from linker.linker import Linker

action1 = Command()
action1.set_action(lambda: print("Hello from Action 1!"))
action2 = Command()
action2.set_action(lambda: print("Hello from Action 2!"))

action1.run()

linker = Linker()
linker.load('./flow.yml')
linker.validate()
linker.link()
Пример #48
0
 def __init__(self, loud=False):
     Command.__init__(self)
     self.volume = 8 if not loud else 16
Пример #49
0
    def __init__(self, message_repository, message = None):
        Command.__init__(self)

        self._message_repository = message_repository
        self.message = message
Пример #50
0
 def __init__(self, client, api_key):
     Command.__init__(self)
     self.client = client
     self.api_key = api_key