Exemplo n.º 1
0
 def update(self):
     top_state = StateStack.peek()
     if top_state:
         while Command.has_queued_commands():
             top_state.on_command(Command.get_next())
         top_state.update()
     self.ticker.tick(Config.FPS)
Exemplo n.º 2
0
    def getCommand(self, text, UTCDiffInSeconds):
        logger.debug('getCommand started processing text: ' + text)
        logger.debug('----------')
        logger.debug('Processing command text:' + text)
        text = text.strip('/')

        if text[-12:] == '@domedomebot':
            text = text[:-12]

        if text.lower() in HELP:
            return Command('HELP')
        if text.lower() in START:
            return Command('START')

        #asteriskBugThrow(text)

        text = lazyTypingConverter(text)
        text = dateSpaceAdder(text)

        important, text = findImportant(text)
        logger.info('important:' + str(important))

        wordList = text.split()

        commandType, numberList = findCommandType(wordList)
        logger.info('commandType:' + commandType)
        logger.info('numberList:' + str(numberList))

        time = findTime(wordList)
        logger.info('time:' + str(time))

        linkList = findLink(wordList)
        logger.info('linkList:' + str(linkList))

        date, recurringString = findDate(wordList, UTCDiffInSeconds,
                                         commandType)
        recurringInteger = 0
        if len(numberList):
            recurringInteger = numberList[0]
        logger.info('date:' + str(date))
        logger.info('recurringString:' + recurringString)
        logger.info('recurringInteger:' + str(recurringInteger))

        location = findLocation(wordList)
        logger.info('location:' + location)

        #        removeFillerWords(wordList)

        name = (' '.join(wordList)).strip()
        if name: name = '{}{}'.format(name[0].upper(), name[1:])
        name = name.replace("'", "")
        logger.info('name:' + name)
        logger.info('----------')

        logger.debug('getCommand ended')
        return Command(
            commandType,
            Task(name, date, time, location, linkList, important, 1,
                 recurringString, recurringInteger), numberList)
Exemplo n.º 3
0
 def update(self):
     if (self.current_point < self.point_count):
         self.current_point += 1
     else:
         # somewhere in here we check for collision with the flag
         Command.dispatch(
             Command(Category.Ball,
                     lambda ball: ball.set_at(self.points[-1])))
Exemplo n.º 4
0
    def open_movement_menu(self, pos, tile):
        print(pos)
        movement_menu = Movement_menu(client.screen, (pos[0], pos[1], 72, 144),
                                      client.FontManager)

        pygame.event.clear(
        )  # clear the event queue so we can wait for player feedback.
        _listboxes = []
        _textboxes = []
        _buttons = []

        for UI_component in movement_menu.UI_components:
            UI_component.draw()  # blit them to the screen.

            if (isinstance(UI_component, ListBox)):
                _listboxes.append(UI_component)
            elif (isinstance(UI_component, TextBox)):
                _textboxes.append(UI_component)
            elif (isinstance(UI_component, Button)):
                _buttons.append(UI_component)

        print('len of _listboxes', end=': ')
        print(str(len(_listboxes)))

        print('opening movement menu')
        pygame.event.clear(
        )  # clear the event queue so we can wait for player feedback.
        clicked = ''
        while clicked == '':
            for UI_component in movement_menu.UI_components:
                UI_component.draw()  # blit them to the screen.

            pygame.display.flip(
            )  # flip the screen after we've .draw() the UI_components
            event = pygame.event.wait()  # wait for player input.
            if event.type == pygame.QUIT:
                client.disconnect()
                pygame.quit()
                exit()
            elif (event.type == pygame.MOUSEBUTTONUP):
                pos = pygame.mouse.get_pos()
                for listbox in _listboxes:
                    if pos[0] >= listbox.x and pos[
                            0] <= listbox.x + listbox.width:
                        if pos[1] >= listbox.y and pos[
                                1] <= listbox.y + listbox.height:
                            item_clicked = listbox.on_clicked(
                                event.button, pos[0] - listbox.x,
                                pos[1] - listbox.y)
                            print('movement_menu selected: ' +
                                  str(item_clicked.text))
                            clicked = item_clicked.text

        if (clicked == 'move'):
            print('clicked move. sending command')
            _command = Command(
                client.player.name, 'calculated_move',
                (tile['position'].x, tile['position'].y, tile['position'].z)
            )  # send calculated_move action to server and give it the position of the tile we clicked.
            return _command
Exemplo n.º 5
0
 def train_model_from_mfccbank(cls, mfccbank, em_gaussians, em_iterations):
     commands = []
     print("Start training!")
     count_phrases = mfccbank.count_phrases()
     print("Commands to train: %d" % count_phrases)
     for i in range(count_phrases):
         commands.append(
             Command.init_from_mfccphrase(mfccbank.get_phrase(i),
                                          em_gaussians, em_iterations))
         print("Trained commands: %d/%d" % (i + 1, count_phrases))
     return Model(commands)
Exemplo n.º 6
0
    def login(self, dt):
        # we'll do the below to login and recieve a list of characters.
        self.connect(self.LoginWindow.serverIP.text,
                     int(self.LoginWindow.serverPort.text))

        # set our client_name for future sending.
        self.client_name = self.LoginWindow.username.text

        command = Command(self.LoginWindow.username.text, "login", ["noargs"])
        self.send(command)
        # -------------------------------------------------------
        clock.schedule_interval(self.check_messages_from_server, 0.1)
    def get_command(self):
        """
        Extract a command from the buffer, if the buffer contains is a sequence of words that represents a command.
        Otherwise, return None.

        Pre-condition:
            - the first element of the word buffer is a "start command" word (or the word buffer is empty)
        Parameters:
            - none
        Return:
            - command: a move command (ie. Move object), a normal command (ie. Command object), or None
        """
        command = None
        word_ndx = 0
        possible_formats = self.command_formats.copy()

        self.log.debug(f"Before command extraction: {self.words}")

        # Check to see if the sequence of the first 'word_ndx' number of words matches a command format
        while word_ndx < len(self.words) and len(possible_formats) > 0:
            format_ndx = 0

            # Loop through every possible format
            while format_ndx < len(possible_formats):
                possible_format = possible_formats[format_ndx]

                if self.words[word_ndx] in self.keywords_dictionary[possible_format.get_word_type(word_ndx)]:
                    # Fix the 2/to misinterpretation
                    if self.words[word_ndx] == '2' and possible_format.get_word_type(word_ndx) == 'to':
                        self.words[word_ndx] = 'to'

                    # If the first 'word_ndx' number of words matches a command format,
                    # set the return value to the command that the first 'word_ndx' number of words represents
                    if possible_format.length == word_ndx + 1:
                        if possible_format.name.find('move') != -1:
                            command = MoveCommand(self.words[:word_ndx + 1])
                        elif possible_format.name.find('single') != -1:
                            command = Command(self.words[:word_ndx + 1])
                        possible_formats.pop(format_ndx)
                    else:
                        format_ndx += 1

                # Remove all invalid formats
                else:
                    possible_formats.pop(format_ndx)
            word_ndx += 1

        if command is not None:
            del self.words[:command.length]

        self.log.debug(f"After extraction: {self.words}")

        return command
Exemplo n.º 8
0
    def test_bot_command(self, command_text, print_response=True):
        cmd = Command(command_text)
        res = cmd.response

        if print_response:
            self._print_response(res, command_text)

        if res.text is not None:
            text = res.text.lower()
            self.assertFalse(text.startswith("no") and "available" in text)

        if res.image is not None:
            self.assertTrue(
                isinstance(res.image, str) or isinstance(res.image, BytesIO))
Exemplo n.º 9
0
    def send_completed_character(self, dt):
        # gather up all the character info from the chargen window and send it. the 'commit' button

        self.character.name = self.CharacterGenerationWindow.main_frame.get_child(
        )[0, 1].text
        self.character.gender = self.CharacterGenerationWindow.main_frame.get_child(
        )[0, 3].text
        _data = encode_packet(self.character)

        # set this before sending the command to keep things in order.
        self.state = "character_select"

        command = Command(self.client_name, "completed_character", [_data])
        self.send(command)
Exemplo n.º 10
0
 def handle_realtime_input(self, keys):
     if keys[K_LEFT]:
         Command.dispatch(
             Command(Category.Golfer,
                     lambda golfer: golfer.handle_keypress(Keys.Left)))
     if keys[K_RIGHT]:
         Command.dispatch(
             Command(Category.Golfer,
                     lambda golfer: golfer.handle_keypress(Keys.Right)))
Exemplo n.º 11
0
 def handle_input_event(self, event):
     if event.type == MOUSEBUTTONDOWN and event.button == 1:
         print("adding a command")
         Command.dispatch(
             Command(Category.SwingMeter,
                     lambda meter: meter.handle_click()))
     elif event.type == MOUSEBUTTONUP and event.button == 1:
         Command.dispatch(
             Command(Category.SwingMeter,
                     lambda meter: meter.handle_unclick()))
Exemplo n.º 12
0
 def ping(self, dt):
     command = Command(client.character.name, "ping")
     client.send(command)
Exemplo n.º 13
0
    def open_equipment_menu(self):
        self.screen.fill((55, 55, 55), special_flags=pygame.BLEND_SUB) # darken the screen to indicate an action is required.
        equipment_menu = Equipment_Menu(self.screen, (0, 0, 400, 496), self.FontManager, self.player.body_parts)

        # work out the internal list of UI_components so we can iterate them if needed.
        _listboxes = []
        _textboxes = []
        _buttons = []
        _equipment_buttons = []
        for UI_component in equipment_menu.UI_components:
            UI_component.draw() # blit them to the screen.

            if(isinstance(UI_component, ListBox)):
                _listboxes.append(UI_component)
            elif(isinstance(UI_component, TextBox)):
                _textboxes.append(UI_component)
            elif(isinstance(UI_component, Button)):
                _buttons.append(UI_component)
            elif(isinstance(UI_component, Equipment_Button)):
                _equipment_buttons.append(UI_component)

        # clicking on a area where an item is equipped.
        #  with no item 'grabbed' and no item in slot.
        #   open menu > equip/wear item -> parse_items_for_equippable_locations()[] -> click_item() -> wear_item()
        # with item 'grabbed' and no item in slot
        #  check_equippable() -> wear/weild item
        # with no item 'grabbed' and item in slot
        #  'grab' item
        # with item grabbed and item in slot
        #  swap()?
        # with item 'grabbed' and cursor outside equipment screen.
        #  drop() item on ground relative the the position of the equipment screen (drop right on screen drops right of player)
        # click a container with an item 'grabbed'
        #  put() item in container. (containers can only hold empty containers. or closed containers.)

        # now that we've drawn the equipment menu we need to wait until the player clicks a UI_component.
        pygame.event.clear() # clear the event queue so we can wait for player feedback.
        sidebar_components = []
        _grabbed = self.player.grabbed
        while True:
            self.screen.blit(equipment_menu.surface, (equipment_menu.x, equipment_menu.y))
            for UI_component in equipment_menu.UI_components:
                UI_component.draw() # blit them to the screen.
            pygame.display.flip() # flip the screen after we've .draw() the UI_components
            event = pygame.event.wait() # wait for player input.
            if event.type == pygame.QUIT:
                client.disconnect()
                pygame.quit()
                sys.exit()
            elif(event.type == pygame.MOUSEBUTTONDOWN):
                # dragging from somwhere. we need to keep drawing so handle that
                # wait until we let go of the mouse and handle it.
                pass
            elif(event.type == pygame.MOUSEBUTTONUP):
                # we clicked somewhere while the equipment screen is up.
                # if we clicked an equipment tile we need to open a sub-menu for options for that the item can do. (activate, equip, etc..)
                pos = pygame.mouse.get_pos()
                for UI_component in equipment_menu.UI_components:
                    if pos[0] >= UI_component.position[0] and pos[0] <= UI_component.position[0] + 24:
                        if pos[1] >= UI_component.position[1] and pos[1] <= UI_component.position[1] + 24:
                            print('clicked', UI_component )
                            if(_grabbed is None): # the temporary spot where the cursor is holding the item.
                                _grabbed = UI_component.item
                                UI_component.item = None # this only happens locally for now. the server doesn't care about the item on the cursor.
                            else: # we are holding an item
                                if(UI_component.item is None):
                                    UI_component.item = _grabbed
                                    _grabbed = None # place the item into the blank spot.
                                    #TODO: tell the server to move the item server-side
                                else:

                                    _tmp1 = UI_component.item # swap the items.
                                    _tmp2 = _grabbed
                                    UI_component.item = _tmp2
                                    _grabbed = _tmp1
                                    _tmp1 = None
                                    _tmp2 = None

                                    #_grabbed = _tmp1
                                    #TODO: tell the server to swap the items server-side
                                    '''
                                    _player_requesting = self.players[data.ident]
                                    _item = data.args[0] # the item we are moving.
                                    _from_type = data.args[1] # creature.held_item, creature.held_item.container, bodypart.equipped, bodypart.equipped.container, position, blueprint
                                    _from_list = [] # the object list that contains the item. parse the type and fill this properly.
                                    _to_list = data.args[2] # the list the item will end up. passed from command.
                                    _position = Position(data.args[3], data.args[4], data.args[5]) # pass the position even if we may not need it.
                                    '''

                                    _command = Command(self.player.name, 'move_item', (tile['position'].x, tile['position'].y, tile['position'].z)) # send calculated_move action to server and give it the position of the tile we clicked.
                                    return _command

            elif(event.type == pygame.KEYUP):
                # when we want to do something with the keyboard.
                if event.key == pygame.K_m:
                    #(m)ove an item
                    pass
                elif(event.key == pygame.K_ESCAPE): # close the menu
                    return
Exemplo n.º 14
0
#
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Cataclysm LD Client',
                                     epilog="Please start the client with a first and last name for your character.")
    parser.add_argument('--host', metavar='Host', help='Server host', default='localhost')
    parser.add_argument('-p', '--port', metavar='Port', type=int, help='Server port', default=6317)
    parser.add_argument('first_name', help='Player\'s first name')
    parser.add_argument('last_name', help='Player\'s last name')

    args = parser.parse_args()
    ip = args.host
    port = args.port

    client = Client(args.first_name, args.last_name)
    client.connect(ip, port)
    command = Command(client.player.name, 'login', ['password'])
    client.send(command)
    command = Command(client.player.name, 'request_localmap_update')
    client.send(command)
    command = None
    last_time = time.time()
    while True:
        # if we recieve an update from the server process it. do this first.
        next_update = client.receive(False)
        if(next_update is not None):
            #print('--next_update--') # we recieved a message from the server. let's process it.
            #print(next_update)
            if(isinstance(next_update, Player)):
                #print('got playerupdate')
                client.player = next_update # client.player is updated
            if(isinstance(next_update, list)): # this is the list of chunks for the localmap
Exemplo n.º 15
0
 def ping(self, dt):
     command = Command(self.username, "ping")
     client.send(command)
Exemplo n.º 16
0
 def __commands_from_json(cls, obj):
     commands = []
     for c in iter(obj):
         commands.append(Command.from_json_obj(c))
     return commands
Exemplo n.º 17
0
 def choose_character(self, name):
     self.state = "main"
     self.character_name = name
     command = Command(self.client_name, "choose_character", [name])
     self.send(command)
Exemplo n.º 18
0
    def __init__(self):
        ################################################################
        # For all Controllables

        ################################
        # CONTROLLABLE: Cancel
        def _cancel_inst(session, actor):
            torefund = None
            if actor.queue != []:
                #torefund = actor.queue[-1][0].cost # NOTE: Uncomment when player
                # will be charged at command-click, not -start
                del actor.queue[-1]
            else:
                if not actor.current.is_placeholder:
                    torefund = actor.current.command.cost
                    actor.current = StartedCommand.placeholder()
                    actor.busy = False
            if torefund is not None:
                owner = actor.owner
                owner.refund_rsrc(torefund)

        self.cancel = Command('cancel',
                              _cancel_inst,
                              None,
                              grouped=False,
                              queueable=False,
                              duration=0)

        ################################################################
        # For Units

        ################################
        # UNIT: Move
        def _move_inst(session, actor, coords):
            actor.dest = Point(*coords)
            actor.request_path()

        def _move_end(scmd):
            actor = scmd.actor
            return True if actor.coords == actor.dest else False

        self.move = Command('move',
                            _move_inst,
                            None,
                            grouped=True,
                            queueable=False,
                            end=_move_end,
                            takes_pt=True,
                            cost=(0, 0, 0))

        ################################
        # UNIT: Stop movement
        def _stop_inst(session, actor):
            actor.dest = actor.coords.copy()
            actor.node = Point(-1, -1)
            actor.nodes = []
            actor.direction = Point(0, 0)

        self.stop = Command('stop',
                            _stop_inst,
                            None,
                            grouped=True,
                            queueable=False,
                            duration=0)

        ################################################################
        # For specific objects

        ################################
        # COMMAND: Train worker
        def _train_worker_deld(session, actor, coords):
            obj = o.Worker(session, Point(*coords), actor.owner)
            session.add_object(obj)

        self.train_worker = Command('train_worker',
                                    None,
                                    _train_worker_deld,
                                    grouped=False,
                                    queueable=True,
                                    cost=(50, 0, 0),
                                    duration=22,
                                    takes_pt=True)

        ################################
        # COMMAND: Train soldier
        def _train_soldier_deld(session, actor, coords):
            obj = o.Soldier(session, Point(*coords), actor.owner)
            session.add_object(obj)

        self.train_soldier = Command('train_soldier',
                                     None,
                                     _train_soldier_deld,
                                     grouped=False,
                                     queueable=True,
                                     cost=(100, 0, 0),
                                     duration=45,
                                     takes_pt=True)
Exemplo n.º 19
0
    def check_messages_from_server(self, dt):
        # commands recieved while in the login window
        next_update = client.receive(False)
        if self.state == "login":
            # we recieved a message from the server. let's process it.
            if next_update is not None:
                print("--next_update in login--")
                if isinstance(next_update, list):
                    # list of characters.
                    # print("list:", next_update)
                    # open the character select screen.
                    self.gui.clear()
                    self.gui.add(CustomBackground())
                    self.CharacterSelectWindow = CharacterSelectWindow(
                        next_update)
                    self.CharacterSelectWindow.create_button.push_handlers(
                        on_click=self.create_new_character)
                    self.gui.add(self.CharacterSelectWindow)
                    self.state = "character_select"

                if isinstance(next_update, str):
                    if next_update == "disconnect":
                        self.disconnect()
                        return

                if isinstance(next_update, str):
                    # server sent salt
                    _hashedPW = hashPassword(self.LoginWindow.password.text,
                                             next_update)
                    command = Command(
                        self.LoginWindow.username.text,
                        "hashed_password",
                        [str(_hashedPW)],
                    )

                    # send back hashed password.
                    self.send(command)

        if self.state == "character_select":
            if next_update is not None:
                print("--next_update in character_select--")
                if isinstance(next_update, list):
                    # list of characters.
                    # re-fresh the character select screen.
                    self.gui.clear()

                    self.gui.add(CustomBackground())
                    self.CharacterSelectWindow = CharacterSelectWindow(
                        next_update)
                    self.CharacterSelectWindow.create_button.push_handlers(
                        on_click=self.create_new_character)
                    self.gui.add(self.CharacterSelectWindow)
                    for button in self.CharacterSelectWindow.vbox_for_characterlist:
                        if button.text != "Create a Character":
                            button.push_handlers(on_click=lambda w: self.
                                                 choose_character(w.text))

        if self.state == "main":
            if next_update is not None:
                self.gui.clear()
                #print("next_update in main", type(next_update))
                _raw_nine_chunks = decode_packet(next_update)
                # we recieved a localmap from the server.
                self.gui.add(
                    self.main_window(_raw_nine_chunks, self.character_name))
            elif time.time() - self.last_request > 1.0:
                command = Command(self.client_name, "request_localmap_update",
                                  [self.character_name])
                self.send(command)
                self.last_request = time.time()

        if self.state == "character_gen":
            if next_update is not None:
                print("--next_update in character_gen--")
Exemplo n.º 20
0
    def open_items_on_ground(self, pos, tile):
        self.items_on_ground_background = pygame.image.load(
            './img/items_on_ground.png').convert_alpha()
        _start_item_x = 400
        _start_item_y = 250
        self.screen.blit(self.items_on_ground_background,
                         (_start_item_x, _start_item_y))
        _items = tile['items']  #need to get the items from the position
        _page = 0  # internal int to keep track of what _item_groups page we are looking at currently.
        _max_items_per_group = 16
        # draw a box for the contained items.

        _item_groups = defaultdict(list)
        # first find out how many items we have and sort them into groups.

        # i need them 'paginated' so the order could be used as as x, y locations.
        _count = 0
        _group = 0
        for item in _items:
            if (_count > _max_items_per_group):
                _group = _group + 1
                _count = 0
            _item_groups[_group].append(item)
            _count = _count + 1

        # now that we've drawn the open_items_on_ground menu we need to wait until the player clicks a item.
        pygame.event.clear(
        )  # clear the event queue so we can wait for player feedback.
        while True:
            # blit the current _page worth of items.
            #TODO: take into consideration where the window opens.

            _item_x = _start_item_x + 3  # adjust for within image offset.
            _item_y = _start_item_y + 13

            # blit
            for item in _item_groups[_page]:
                print(item)
                fg = self.TileManager.TILE_TYPES[item.ident]['fg']
                self.screen.blit(self.TileManager.TILE_MAP[fg],
                                 (_item_x, _item_y))
                _item_x = _item_x + 24
                if (_item_x > 24 * 3 + _start_item_x):
                    _item_y = _item_y + 24
                    _item_x = _start_item_x + 3

            pygame.display.flip()  # flip the screen
            event = pygame.event.wait()  # wait for player input.
            if event.type == pygame.QUIT:
                client.disconnect()
                pygame.quit()
                sys.exit()
            elif (event.type == pygame.MOUSEBUTTONDOWN):
                # dragging to somwhere. need a check for bounds of the item while the mouse is being heldself.
                pass
            elif (event.type == pygame.MOUSEBUTTONUP):
                # we clicked somewhere while the menu is up.
                # if we clicked an item we need to get the position and see what item it was.
                pos = pygame.mouse.get_pos()
                print('pos:', pos)
                _x_count = 0
                _y_count = 0
                for item in _item_groups[_page]:
                    print('item.ident:', item.ident, end=' ')
                    # return the item clicked and do something with it.
                    _item_x_min = _x_count * 24 + _start_item_x
                    _item_x_max = _x_count * 24 + 23 + _start_item_x
                    print(_item_x_min, ',', _item_x_max)

                    if (_x_count > 3):
                        _x_count = 0
                        _y_count = _y_count + 1
                    _item_y_min = _y_count * 24 + _start_item_y
                    _item_y_max = _y_count * 24 - 23 + _start_item_x
                    print(_item_y_min, _item_y_max)

                    if (pos[0] > _item_x_min and pos[0] < _item_x_max):
                        # print('in x')
                        if (pos[1] > _item_y_min and pos[1] < _item_y_max):
                            print('clicked', str(item.ident))

                            # now we know the ident of the item we can pass that info to the server and let it parse and handle it.

                            _command = Command(
                                self.player.name,
                                'move_item_to_player_storage',
                                (tile['position'].x, tile['position'].y,
                                 tile['position'].z, item.ident)
                            )  # ask the server to pickup the item by ident. #TODO: is there a better way to pass it to the server without opening ourselves up to cheating?
                            return _command

            elif (event.type == pygame.KEYUP):
                # when we want to do something with the keyboard.
                if event.key == pygame.K_m:
                    #(m)ove an item
                    pass
                elif (event.key == pygame.K_ESCAPE):  # close the menu
                    return
Exemplo n.º 21
0
            model = Models()
            model.execute(http, command_to_execute)

    for key, value in command_to_execute["data_source"].items():
        if value is not None:
            #logger.debug("key exists "+str(key))
            logger.debug("Executing the command input")
            data_source = Data_source()
            data_source.execute(http, command_to_execute)

    for key, value in command_to_execute["data_output"].items():
        if value is not None:
            #logger.debug("key exists "+str(key))
            logger.debug("Executing the command output")
            data_output = Data_output()
            data_output.execute(http, command_to_execute)

    for key, value in command_to_execute["command"].items():
        if value is not None:
            #logger.debug("key exists "+str(key))
            logger.debug("Executing the command")
            command = Command()
            command.execute(http, command_to_execute)

    for key, value in command_to_execute["instance"].items():
        if value is not None:
            #logger.debug("key exists "+str(key))
            logger.debug("Creating an instance")
            instance = Instance()
            instance.execute(http, command_to_execute)
Exemplo n.º 22
0
 def on_key_press(symbol, modifiers):
     if symbol == KEY.RETURN:
         print('return')
     if symbol == KEY.W:
         command = Command(args.name, 'move', ['north'])
         client.send(command)
Exemplo n.º 23
0
 def ping(dt):
     command = Command(client.player.name, 'ping')
     client.send(command)
Exemplo n.º 24
0
    parser.add_argument('-p',
                        '--port',
                        metavar='Port',
                        type=int,
                        help='Server port',
                        default=6317)
    parser.add_argument('name', help='Player\'s name')

    args = parser.parse_args()
    ip = args.host
    port = args.port

    client = Client(args.name)
    client.connect(ip, port)

    command = Command(args.name, 'login', ['password'])
    client.send(command)
    command = Command(args.name, 'request_chunk')
    client.send(command)
    command = None

    def check_messages_from_server(dt):
        next_update = client.receive(False)

        if (next_update is not None):
            if (isinstance(next_update, Player)):
                client.player = next_update  # self.player is updated
                print('updated player')
            elif (isinstance(next_update, Chunk)):
                client.chunk = next_update
                client.parse_chunk_data()