コード例 #1
0
class Test:

    def setup_method(self, method):
        self.driver = webdriver.Firefox()
        self.driver.maximize_window()
        self.action = Action(self.driver)
        self.page = PageAction(self.driver)

    def teardown_method(self, method):
        self.driver.quit()

    def test(self):
        self.page.open("https://google.com")
        self.action.element(HomePageLoc.SEARCH_FIELD).type("python")
        self.action.element(HomePageLoc.SEARCH_FIELD).submit()
        t1 = self.action.element(HomePageLoc.RESULT_LINK).at(3).get_text()
        self.page.take_screenshot()
        t2 = self.action.element(HomePageLoc.RESULT_LINK).get_text()
        log.message(t1)
        self.action.element(HomePageLoc.RESULT_LINK).at(10).click()
        time.sleep(5)
        self.page.navigate_back()
        self.action.element(HomePageLoc.RESULT_LINK).click()
        print(t1)
        print(t2)
コード例 #2
0
class QLearning:
    def __init__(self,
                 environment: Environment,
                 epsilon,
                 epsilon_decay_rate,
                 solver='table',
                 q=None):
        self.state = State(environment.observation_space)
        self.action = Action(environment.action_space, epsilon,
                             epsilon_decay_rate)
        if solver == 'table':
            self.q = QFunction(learning_rate, discount_rate)
        elif solver == 'NN_agent':
            self.q = QAgent(learning_rate, discount_rate)
        self.q.initialize(self.state, self.action, q)
        self.episode = QEpisode(environment, self.state, self.action, self.q)
        self.environment = environment
        self.performance = Performance()

    def train(self, learning, discount, no_of_episodes):
        for ep_no in range(no_of_episodes):
            self.episode.initialize(learning, discount)
            show = True if (
                ep_no + 1
            ) % 50 == 0 else False  # if no_of_episodes - ep_no <= 2 else False
            reward = self.episode.play(show=show)
            self.performance.append(reward)
            if (ep_no + 1) % 10 == 0:
                self.performance.print(ep_no + 1,
                                       reset=True,
                                       custom=f'eps = {self.action.epsilon}')
            self.action.go_confident()
        self.environment.close()
        return self.performance
コード例 #3
0
ファイル: remote_data_config.py プロジェクト: ray3175/ray-sso
class RemoteSaveButton(Button):
    def __init__(self, obj_dict, **kwargs):
        kwargs.update({
            "text": "保存",
            "size_hint": [0.3, 0.125],
            "pos_hint": {
                "x": 0.35,
                "y": 0.2
            },
            "font_name": RAYSSO_FONT,
            "font_size": 30,
            "background_color": [0.247, 0.195, 0.24, 0.5]
        })
        super().__init__(**kwargs)
        self.__obj_dict = obj_dict
        self.__action = Action()
        self._init_data()

    def _init_data(self):
        for key, value in self.__action.get_remote_db_config().items():
            self.__obj_dict[key].text = value

    def on_release(self):
        user = self.__obj_dict["user"].text
        pwd = self.__obj_dict["pwd"].text
        host = self.__obj_dict["host"].text
        port = self.__obj_dict["port"].text
        db = self.__obj_dict["db"].text
        charset = self.__obj_dict["charset"].text
        if self.__action.set_remote_db_config(user, pwd, host, port, db,
                                              charset):
            self.__obj_dict["msg"].text = "保存成功!"
コード例 #4
0
ファイル: main.py プロジェクト: billalxcode/TextEditor
    def __init__(self):
        self.root = Tk()
        self.actions = Action(root=self.root)
        self.cores = Core()

        self.screensize = "400x600"  # default screen size

        self.filename = ""
        self.savepath = ""

        self.tabs = None
コード例 #5
0
def main(args):
    """Coordinate the skill. Main function called in IBM Cloud Functions"""

    ### Helper Functions ###

    def do_cleanup(paths: list) -> None:
        """Cleanup the leftover paths

           Args:
                paths: a list of paths to clean up
        """
        for path in paths:
            os.remove(path)

    def get_config(config_file_path: str) -> dict:
        """Load the skill config

           Args:
                config_file_path: location of config file
        """
        config = {}
        with open(config_file_path) as config_file:
            config = json.load(config_file)
        return config

    ### Main Function ###

    # Get args
    request_body = args
    config_file = args.get('config', './config.json')
    config = get_config(config_file)

    # # Build pieces
    storage = Storage(config, request_body)
    action = Action(config)

    # # Download --> ACTION --> Upload
    file_data = storage.file_data  # {name: "", id: 0000}
    file_path = storage.download_file()

    # Run Action
    action.do_action(file_path, file_data['id'])

    # Upload/Update new file
    results = action.push2storage(storage)

    # Clean up local files
    do_cleanup([file_path])

    # Return status
    return {"status": "success"}
コード例 #6
0
    def get_action(self, state: State,
                   time_less: datetime.timedelta) -> Action:
        # Actualizando tiempo limite
        time_out = time_less.seconds + time_less.microseconds / 1000000.0
        state.set_time_less(seconds=time_out)

        my_json = json.dumps(state.__dict__)
        my_json = my_json.translate(str.maketrans({'"': r'\"'}))
        self.command = f'{self.command_init} "{my_json}" {self.command_end}'

        # El resultado tiene que ser un print de un json
        # print(f"Ejecutando comando {self.command}")

        # Obteniendo el resultado con tiempo limite de 5 segundos
        self.result = None
        t = threading.Thread(target=self.get_result)
        t.start()
        # print("Tiempo limite para el hilo:", time_out)

        t.join(timeout=time_out)

        # Si no se obtuvo el resultado en 5 segundos salta un error
        if self.result is None:
            raise NameError("TimeOut")

        # Imprimiendo el resultado obtenido
        # print(f'Resultado obtenido {self.result}\n\n')

        result_json = json.loads(self.result)

        return Action(knight_id=int(result_json['knight_id']),
                      knight_movement=int(result_json['knight_movement']))
コード例 #7
0
ファイル: remote_data_config.py プロジェクト: ray3175/ray-sso
 def __init__(self, obj_dict, **kwargs):
     kwargs.update({
         "text": "保存",
         "size_hint": [0.3, 0.125],
         "pos_hint": {
             "x": 0.35,
             "y": 0.2
         },
         "font_name": RAYSSO_FONT,
         "font_size": 30,
         "background_color": [0.247, 0.195, 0.24, 0.5]
     })
     super().__init__(**kwargs)
     self.__obj_dict = obj_dict
     self.__action = Action()
     self._init_data()
コード例 #8
0
 def __init__(self,
              environment: Environment,
              epsilon,
              epsilon_decay_rate,
              solver='table',
              q=None):
     self.state = State(environment.observation_space)
     self.action = Action(environment.action_space, epsilon,
                          epsilon_decay_rate)
     if solver == 'table':
         self.q = QFunction(learning_rate, discount_rate)
     elif solver == 'NN_agent':
         self.q = QAgent(learning_rate, discount_rate)
     self.q.initialize(self.state, self.action, q)
     self.episode = QEpisode(environment, self.state, self.action, self.q)
     self.environment = environment
     self.performance = Performance()
コード例 #9
0
class TerminalLayout(GridLayout):
    def __init__(self, **kwargs):
        kwargs.update({
            "size_hint": [0.8, 0.75],
            "pos_hint": {"center_x": 0.5, "center_y": 0.575},
            "rows": 1
        })
        super().__init__(**kwargs)
        self.text = ""
        self._init_terminal_text_input()

    def _init_terminal_text_input(self):
        self.__terminal_text = TerminalTextInput(text=self.text)
        self.add_widget(self.__terminal_text)

    def migrate_active(self):
        self.__action = Action()
        threading.Thread(target=lambda : self.__action.db_data_remote2local(lambda text: self.append_text(text, "\n")), args=()).start()

    def append_text(self, text, split=None):
        if split:
            text += split
        self.text += text
        self.__terminal_text.update_text(self.text)
コード例 #10
0
import torch

from src import model
from src import util
from src.body import Body
from src.hand import Hand
from src.track import track
from src import util
from src.action import Action

body_estimation = Body('model/body_pose_model.pth')

hand_estimation = Hand('model/hand_pose_model.pth')
hand_estimation = False
action_estimation = Action(
    'model/epoch500-loss0.6013291-val_loss0.6036168-acc0.9833.pth',
    ['sit', 'stand', 'walk'])

print(f"Torch device: {torch.cuda.get_device_name()}")

cap = cv2.VideoCapture(0)
width, height = 256, 256
cap.set(3, width)
cap.set(4, height)

new_id = 1
pre_rec_list = []
pre_id_list = []
num_frame = 0
while True:
    num_frame += 1
コード例 #11
0
    def callback_client_handle(self, connection_object, data):
        #print("Server: Recieved data \""+str(data)+"\" from client \""+str(connection_object.address)+"\".")
        # use the data to determine what player is giving the command and if they are logged in yet.

        if (isinstance(
                data,
                Command)):  # the data we recieved was a command. process it.
            if (data.command == 'login'):
                if (data.args[0] == 'password'
                    ):  # TODO: put an actual password system in.
                    print('password accepted for ' + str(data.ident))
                    if (not data.ident in self.players
                        ):  # this player doesn't exist in the world yet.
                        # check and see if the players has logged in before.
                        tmp_player = self.worldmap.get_player(
                            data.ident)  # by 'name'
                        if (tmp_player is not None):  # player exists
                            print('player exists. loading.')
                            self.players[data.ident] = tmp_player
                            self.players[
                                data.ident].position = tmp_player.position
                            self.localmaps[
                                data.
                                ident] = self.worldmap.get_chunks_near_position(
                                    self.players[data.ident].position)
                        else:  # new player
                            print('new player joined.')
                            self.players[data.ident] = Player(data.ident)
                            self.players[data.ident].position = random.choice(
                                self.starting_locations)
                            self.worldmap.put_object_at_position(
                                self.players[data.ident],
                                self.players[data.ident].position)
                            self.localmaps[
                                data.
                                ident] = self.worldmap.get_chunks_near_position(
                                    self.players[data.ident].position)

                    print('Player ' + str(data.ident) +
                          ' entered the world at position ' +
                          str(self.players[data.ident].position))
                    self.callback_client_send(connection_object,
                                              self.players[data.ident])
                else:
                    print('password not accepted.')
                    connection_object.disconnect()

            if (data.command == 'request_player_update'):
                self.callback_client_send(connection_object,
                                          self.players[data.ident])

            if (data.command == 'request_localmap_update'):
                self.localmaps[
                    data.ident] = self.worldmap.get_chunks_near_position(
                        self.players[data.ident].position)
                self.callback_client_send(connection_object,
                                          self.localmaps[data.ident])

            # all the commands that are actions need to be put into the command_queue then we will loop through the queue each turn and process the actions.
            if (data.command == 'move'):
                self.players[data.ident].command_queue.append(
                    Action(self.players[data.ident], 'move', [data.args[0]]))

            if (data.command == 'bash'):
                self.players[data.ident].command_queue.append(
                    Action(self.players[data.ident], 'bash', [data.args[0]]))

            if (data.command == 'create_blueprint'):  #  [result, direction])
                # args 0 is ident args 1 is direction.
                print('creating blueprint ' + str(data.args[0]) +
                      ' for player ' + str(self.players[data.ident]))
                # blueprint rules
                # * there should be blueprints for terrain, furniture, items, and anything else that takes a slot up in the Worldmap.
                # * they act as placeholders and then 'transform' into the type they are once completed.
                # Blueprint(type, recipe)
                position_to_create_at = None
                if (data.args[1] == 'south'):
                    position_to_create_at = Position(
                        self.players[data.ident].position.x,
                        self.players[data.ident].position.y + 1,
                        self.players[data.ident].position.z)
                elif (data.args[1] == 'north'):
                    position_to_create_at = Position(
                        self.players[data.ident].position.x,
                        self.players[data.ident].position.y - 1,
                        self.players[data.ident].position.z)
                elif (data.args[1] == 'east'):
                    sposition_to_create_at = Position(
                        self.players[data.ident].position.x + 1,
                        self.players[data.ident].position.y,
                        self.players[data.ident].position.z)
                elif (data.args[1] == 'west'):
                    position_to_create_at = Position(
                        self.players[data.ident].position.x - 1,
                        self.players[data.ident].position.y,
                        self.players[data.ident].position.z)

                _recipe = server.RecipeManager.RECIPE_TYPES[data.args[0]]
                type_of = _recipe['type_of']
                bp_to_create = Blueprint(type_of, _recipe)

                self.worldmap.put_object_at_position(bp_to_create,
                                                     position_to_create_at)

            if (data.command == 'calculated_move'):
                print(
                    'Recieved calculated_move action. let\'s build a path for '
                    + str(data.ident))

                _position = Position(data.args[0], data.args[1], data.args[2])
                _route = self.calculate_route(
                    self.players[data.ident].position, _position
                )  # returns a route from point 0 to point 1 as a series of Position(s)
                print(_route)
                # fill the queue with move commands to reach the tile.
                _x = self.players[data.ident].position.x
                _y = self.players[data.ident].position.y
                _z = self.players[data.ident].position.z
                action = None
                if (_route is None):
                    print('No _route possible.')
                    return
                for step in _route:
                    _next_x = step.x
                    _next_y = step.y
                    _next_z = step.z
                    if (_x > _next_x):
                        action = Action(self.players[data.ident], 'move',
                                        ['west'])
                    elif (_x < _next_x):
                        action = Action(self.players[data.ident], 'move',
                                        ['east'])
                    elif (_y > _next_y):
                        action = Action(self.players[data.ident], 'move',
                                        ['north'])
                    elif (_y < _next_y):
                        action = Action(self.players[data.ident], 'move',
                                        ['south'])
                    elif (_z < _next_z):
                        action = Action(self.players[data.ident], 'move',
                                        ['up'])
                    elif (_z > _next_z):
                        action = Action(self.players[data.ident], 'move',
                                        ['down'])
                    self.players[data.ident].command_queue.append(action)
                    # pretend as if we are in the next position.
                    _x = _next_x
                    _y = _next_y
                    _z = _next_z

            if (data.command == 'move_item_to_player_storage'
                ):  # when the player clicked on a ground item.
                print('RECIEVED: move_item_to_player_storage', str(data))
                _player = self.players[data.ident]
                _from_pos = Position(data.args[0], data.args[1], data.args[2])
                _item_ident = data.args[3]
                print(_player, _from_pos, _item_ident)
                # first check if the player can carry that item.
                # then find a spot for it to go (open_containers)
                # then send the player the updated version of themselves so they can refresh.

            if (data.command == 'move_item'):
                # client sends 'hey server. can you move this item from this to that?'
                _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.

                # need to parse where it's coming from and where it's going.
                if (_from_type == 'bodypart.equipped'):
                    for bodypart in _player_requesting.body_parts[:]:  # iterate a copy to remove properly.
                        if (_item in bodypart.equipped):
                            _from_list = bodypart.equipped
                            _from_list.remove(_item)
                            _to_list.append(_item)
                            print('moved correctly.')
                            return
                elif (_from_type == 'bodypart.equipped.container'):
                    for bodypart in _player_requesting.body_parts[:]:  # iterate a copy to remove properly.
                        for item in bodypart.equipped:  #could be a container or not.
                            if (isinstance(item,
                                           Container)):  # if it's a container.
                                for item2 in item.contained_items[:]:  # check every item in the container.
                                    if (item2 is _item):
                                        from_list = item.contained_items
                                        _from_list.remove(_item)
                                        _to_list.append(_item)
                                        print('moved correctly.')
                                        return
                elif (_from_type == 'position'):
                    _from_list = self.worldmap.get_tile_by_position(
                        _position)['items']
                    if (_item in _from_list):
                        _from_list.remove(_item)
                        _to_list.append(_item)
                        print('moved correctly.')
                        return
                elif (
                        _from_type == 'blueprint'
                ):  # a blueprint is a type of container but can't be moved from it's world position.
                    for item in self.worldmap.get_tile_by_position(
                            _position)['items']:
                        if (isinstance(item) == Blueprint
                            ):  # only one blueprint allowed per space.
                            _from_list = item.contained_items
                            _from_list.remove(_item)
                            _to_list.append(_item)
                            print('moved correctly.')
                            return

                ### possible move types ###
                # creature(held) to creature(held) (give to another player)
                # creature(held) to position(ground) (drop)
                # creature(held) to bodypart (equip)
                # bodypart to creature(held) (unequip)
                # bodypart to position (drop)

                # position to creature(held) (pick up from ground)
                # position to bodypart (equip from ground)
                # position to position (move from here to there)

                # creature to blueprint (fill blueprint)

                # blueprint to position (empty blueprint on ground)
                # blueprint to creature (grab from blueprint)

        return super(Server,
                     self).callback_client_handle(connection_object, data)
コード例 #12
0
ファイル: main.py プロジェクト: billalxcode/TextEditor
class TE:
    def __init__(self):
        self.root = Tk()
        self.actions = Action(root=self.root)
        self.cores = Core()

        self.screensize = "400x600"  # default screen size

        self.filename = ""
        self.savepath = ""

        self.tabs = None

    #========== Command callback ==========#
    #---------- Files menu bar callback ----------#
    def newfile_callback(self, event=None):
        if self.tabs == None:
            self.root.title("Untitled* - Text Editor")
            self.filename = "untitled.txt"
            self.tabs = self.actions.newTabs()
        else:
            self.closewidget_callback()
            self.tabs = None
            self.newfile_callback()

    def openfile_callback(self, event=None):
        if self.tabs == None:
            path = self.actions.askOpenFile()
            names = self.cores.get_filename(path)[0]
            self.root.title(names + " - Text Editor")

            self.filename = path
            self.savepath = path
            content = self.cores.readfile(path=self.filename)

            self.tabs = self.actions.newTabs(content=content)
        else:
            self.closewidget_callback()
            self.tabs = None
            self.openfile_callback()

    def savefile_callback(self, event=None):
        if self.tabs != None:
            if self.savepath == "":
                self.savepath = self.actions.askSaveFile()

            print(self.savepath)
            names = self.cores.get_filename(self.savepath)[0]
            self.root.title(names + " - Text Editor")

            self.cores.writeFile(self.savepath, self.tabs.get("1.0", END))

    def saveasfile_callback(self, event=None):
        if self.tabs != None:
            self.savepath = self.actions.askSaveFile()
            print(self.savepath)
            names = self.cores.get_filename(self.savepath)[0]
            self.root.title(names + " - Text Editor")

            self.cores.writeFile(self.savepath, self.tabs.get("1.0", END))

    def closewidget_callback(self, event=None):
        if self.tabs != None:
            self.tabs.pack_forget()

    def quit_callback(self, event=None):
        self.root.destroy()

    #---------- Edit menu bar callback ----------#
    def undo_callback(self, event=None):
        if self.tabs != None:
            self.tabs.event_generate("<<Undo>>")

    def reundo_callback(self, event=None):
        if self.tabs != None:
            self.tabs.event_generate("<<Redo>>")

    def cuttext_callback(self):
        if self.tabs != None:
            self.tabs.event_generate("<<Cut>>")

    def copytext_callback(self):
        if self.tabs != None:
            self.tabs.event_generate("<<Copy>>")

    def pastetext_callback(self):
        if self.tabs != None:
            self.tabs.event_generate("<<Paste>>")

    def selectall_callback(self, event=None):
        if self.tabs != None:
            self.tabs.tag_add(SEL, "1.0", END)
            self.tabs.mark_set(INSERT, "1.0")
            self.tabs.see(INSERT)

    #---------- Help menu bar callback ----------#
    def about_callback(self):
        self.actions.about()

    #---------- Get screen size ----------#
    def get_screen_size(self):
        width = self.root.winfo_screenwidth()
        height = self.root.winfo_screenheight()
        self.screensize = str(width) + "x" + str(height)
        return width, height

    #---------- Set menubar ----------#
    def set_menubar(self):
        menubar = Menu(self.root)
        #---------- Files menu ----------#
        files = Menu(menubar, tearoff=0)
        menubar.add_cascade(label="File", menu=files)
        files.add_command(label="New file", command=self.newfile_callback)
        files.add_command(label="Open file", command=self.openfile_callback)
        files.add_command(label="Save", command=self.savefile_callback)
        files.add_command(label="Save as", command=self.saveasfile_callback)
        files.add_separator()
        files.add_command(label="Close window",
                          command=self.closewidget_callback)
        files.add_command(label="Quit", command=self.quit_callback)
        #---------- CTRL + N (New tabs) ----------#
        self.root.bind("<Control-n>", self.newfile_callback)
        self.root.bind("<Control-N>", self.newfile_callback)
        #---------- CTRL + O (Open file) ----------#
        self.root.bind("<Control-o>", self.openfile_callback)
        self.root.bind("<Control-O>", self.openfile_callback)
        #---------- CTRL + S (Save file) ----------#
        self.root.bind("<Control-s>", self.savefile_callback)
        self.root.bind("<Control-S>", self.savefile_callback)
        #---------- CTRL + Shift + S (Save as file) ----------#
        self.root.bind("<Control-Shift-s>", self.saveasfile_callback)
        self.root.bind("<Control-Shift-S>", self.saveasfile_callback)
        #---------- CTRL + W (Close window) ----------#
        self.root.bind("<Control-w>", self.closewidget_callback)
        self.root.bind("<Control-W>", self.closewidget_callback)
        #---------- CTRL + Q (Quit) ----------#
        self.root.bind("<Control-q>", self.quit_callback)
        self.root.bind("<Control-Q>", self.quit_callback)

        #---------- Edit menu ----------#
        edits = Menu(menubar, tearoff=0)
        menubar.add_cascade(label="Edit", menu=edits)
        edits.add_command(label="Undo", command=self.undo_callback)

        edits.add_command(label="Reundo", command=self.reundo_callback)
        edits.add_separator()
        edits.add_command(label="Cut", command=self.cuttext_callback)
        edits.add_command(label="Copy", command=self.copytext_callback)
        edits.add_command(label="Paste", command=self.pastetext_callback)
        edits.add_command(label="Select all", command=self.selectall_callback)
        #---------- CTRL + Z (Undo) ----------#
        self.root.bind("<Control-z>", self.undo_callback)
        self.root.bind("<Control-Z>", self.undo_callback)
        #---------- CTRL + Shift + Z (Redo) ----------#
        self.root.bind("<Control-Shift-z>", self.reundo_callback)
        self.root.bind("<Control-Shift-Z>", self.reundo_callback)
        #---------- CTRL + A (Select All) ----------#
        self.root.bind("<Control-a>", self.selectall_callback)
        self.root.bind("<Control-A>", self.selectall_callback)

        #---------- Help menu ----------#
        help_menu = Menu(menubar, tearoff=0)
        menubar.add_cascade(label="Help", menu=help_menu)
        help_menu.add_command(label="About", command=self.about_callback)

        self.root.config(menu=menubar)

    #---------- Setup window ----------#
    def setup(self):
        self.get_screen_size()

        self.root.title("Text Editor")
        self.root.geometry(self.screensize)

        self.set_menubar()

    def main(self):
        self.root.mainloop()
コード例 #13
0
 def setup_method(self, method):
     self.driver = webdriver.Firefox()
     self.driver.maximize_window()
     self.action = Action(self.driver)
     self.page = PageAction(self.driver)
コード例 #14
0
ファイル: main.py プロジェクト: CloudWorkers/cloudworker
def start():
    '''Start the Application'''

    log = configure_log()
    log.info('Starting Cloud Worker Node Agent')
    log.info('--------------------------')

    args = parse_args()

    settings = {'base_url': args.server,
                'secret': args.secret,
                'client_id': C.CLIENT_ID,
                'client_secret': C.CLIENT_SECRET,
                'username': C.USERNAME,
                'password': C.PASSWORD}

    server = Server(settings)

    node = Node(server)

    #Send the hostname, ip etc to the server
    node.send_info()

    #Update the node status to ready
    node.update_node_status(C.STATUS_READY)

    #Get Config
    config = Config(server, node)

    actions = Action(server, node)
    processor = Processor()
    workers = Worker(server, node, processor)
    output = Output(server, node)

    finished = False

    #Loop forever (kind of)
    while not finished:
        log.info('Looping')
        log.info('--------------------------')

        #Update last seen date
        node.update_node_date()

        #Get config
        config.refresh()

        #Get actions
        num_pending = actions.get_pending()

        #Respond to actions
        if actions.has_pending():
            message = 'Responding to %d Actions ...' % num_pending
            output.send(message)

            actions.respond_to_pending()


        #Get workers/commands
        workers.refresh()
        workers.process_workers()

        #TODO
        #Respond to/run commands
        #Send output to server


        log.info('Sleeping for %d seconds ...', 
                 config.get(C.CONFIG_POLL_PERIOD))
        time.sleep(config.get(C.CONFIG_POLL_PERIOD))
コード例 #15
0
    def callback_client_handle(self, connection_object, data):
        # print("Server: Recieved data \""+str(data)+"\" from client \""+str(connection_object.address)+"\".")
        # use the data to determine what player is giving the command and if they are logged in yet.

        if (isinstance(
                data,
                Command)):  # the data we recieved was a command. process it.
            if (data.command == 'login'):
                if (data.args[0] == 'password'
                    ):  # TODO: put an actual password system in.
                    print('password accepted for ' + str(data.ident))
                    tmp_player = self.worldmap.get_player(
                        data.ident)  # by 'name'
                    if (tmp_player is not None):  # player exists
                        print('player exists. loading.')
                    else:
                        print('player doesnt exist yet.')
                        tmp_player = Player(2, 2, str(data.ident))
                        self.worldmap.add_player_to_worldmap(
                            tmp_player, Position(10, 10))

                    print('Player ' + str(data.ident) +
                          ' entered the world at position ' +
                          str(tmp_player.position))
                    self.callback_client_send(connection_object, tmp_player)
                else:
                    print('password not accepted.')
                    connection_object.disconnect()

            # all the commands that are actions need to be put into the command_queue then we will loop through the queue each turn and process the actions.
            if (data.command == 'move'):
                tmp_player = self.worldmap.get_player(data.ident)  # by 'name'
                tmp_player.command_queue.append(
                    Action(tmp_player, 'move', [data.args[0]]))
                tmp_chunk = self.worldmap.get_chunk_by_player(data.ident)
                self.callback_client_send(connection_object, tmp_chunk)

            if (data.command == 'request_chunk'):
                # find the chunk the player is on and send it to them.
                print('player wants a map update.')
                tmp_chunk = self.worldmap.get_chunk_by_player(data.ident)
                self.callback_client_send(connection_object, tmp_chunk)

            if (data.command == 'move_item'):
                # client sends 'hey server. can you move this item from this to that?'
                _player_requesting = tmp_player
                _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]
                )  # pass the position even if we may not need it.

            if (data.command == 'ping'):
                # pong - this keeps the client connected if they haven't done anything in awhile and there's been no chunk updates.
                print('pong')

        return super(Server,
                     self).callback_client_handle(connection_object, data)
コード例 #16
0
 def migrate_active(self):
     self.__action = Action()
     threading.Thread(target=lambda : self.__action.db_data_remote2local(lambda text: self.append_text(text, "\n")), args=()).start()
コード例 #17
0
from src.action import Action
from src.cli import parse_arguments

args = parse_arguments()
if args.action == 'solve':
    Action.solve(args)
elif args.action == 'generate':
    Action.generate(args)
else:
    raise Exception(
        "Unexpected error, argparse validation should not allow for this")