Beispiel #1
0
def run(args):
    split_server = args.server.split(":")
    args.server = split_server[0]
    args.port = int((len(split_server) == 2 and split[1])) or args.port

    joueur.client.connect(args.server, args.port, args.print_io)

    joueur.client.send("alias", args.game)
    game_name = joueur.client.wait_for_event("named")

    module_str = "games." + camel_case_converter(game_name)

    spec = importlib.util.find_spec(module_str)
    if spec is None:
        error_code.handle_error(error_code.GAME_NOT_FOUND, None, "Could not find the module for game '{}'.".format(game_name))

    try:
        module = importlib.import_module(module_str) # should load Game and AI to load based on the game selected in args
    except ImportError as e:
        error_code.handle_error(error_code.REFLECTION_FAILED, e, "Could not import game module: '{}'.".format(module_str))

    game = module.Game()
    try:
        ai = module.AI(game)
    except:
        error_code.handle_error(error_code.AI_ERRORED, sys.exc_info()[0], "Could not initialize AI class. Probably a syntax error in your AI.")
    manager = GameManager(game)

    joueur.client.setup(game, ai, manager)

    joueur.client.send("play", {
        'gameName': game_name,
        'password': args.password,
        'requestedSession': args.session,
        'clientType': "Python",
        'playerName': args.name or ai.get_name() or "Python Player",
        'playerIndex': args.index,
        'gameSettings': args.game_settings
    })

    lobby_data = joueur.client.wait_for_event("lobbied")

    print(color.text("cyan") + "In lobby for game '" + lobby_data['gameName'] + "' in session '" + lobby_data['gameSession'] + "'." + color.reset())

    manager.set_constants(lobby_data['constants'])

    start_data = joueur.client.wait_for_event("start")

    print(color.text("green") + "Game is starting." + color.reset())

    ai.set_player(game.get_game_object(start_data['playerID']))
    try:
        ai.start()
        ai.game_updated()
    except:
        error_code.handle_error(error_code.AI_ERRORED, sys.exc_info()[0], "AI errored during game initialization")

    joueur.client.play()
Beispiel #2
0
    def _do_order(self, order, arguments):
        callback = getattr(self, camel_case_converter(order))

        if callback != None:
            try:
                return callback(*arguments)
            except:
                error_code.handle_error(error_code.AI_ERRORED, sys.exc_info()[0], "AI caused exception while trying to execute order '{}'.".format(order))
        else:
            error_code.handle_error(error_code.REFLECTION_FAILED, message="AI has no function '' to respond with.".format(order))
Beispiel #3
0
    def _do_order(self, order, arguments):
        callback = getattr(self, camel_case_converter(order))

        if callback != None:
            try:
                return callback(*arguments)
            except:
                handle_error(ErrorCode.ai_errored, sys.exc_info()[0], "AI caused exception while trying to execute order '" + order + "'.")
        else:
            handle_error(ErrorCode.reflection_failed, message="AI has no function '" + order + "' to respond with")
Beispiel #4
0
def run(args):
    split_server = args.server.split(":")
    args.server = split_server[0]
    args.port = int((len(split_server) == 2 and split[1])) or args.port

    module_str = "games." + camel_case_converter(args.game)

    spec = importlib.util.find_spec(module_str)
    if spec is None:
        error_code.handle_error(error_code.GAME_NOT_FOUND, None, "Could not find the module for game '{}'.".format(args.game))

    try:
        module = importlib.import_module(module_str) # should load Game and AI to load based on the game selected in args
    except ImportError as e:
        error_code.handle_error(error_code.REFLECTION_FAILED, e, "Could not import game module: '{}'.".format(module_str))

    game = module.Game()
    try:
        ai = module.AI(game)
    except:
        error_code.handle_error(error_code.AI_ERRORED, sys.exc_info()[0], "Could not initialize AI class. Probably a syntax error in your AI.")
    manager = GameManager(game)

    joueur.client.setup(game, ai, manager, args.server, int(args.port), print_io=args.print_io)

    joueur.client.send("play", {
        'gameName': game.name,
        'password': args.password,
        'requestedSession': args.session,
        'clientType': "Python",
        'playerName': args.name or ai.get_name() or "Python Player",
        'playerIndex': args.index,
        'gameSettings': args.game_settings
    })

    lobby_data = joueur.client.wait_for_event("lobbied")

    print(color.text("cyan") + "In lobby for game '" + lobby_data['gameName'] + "' in session '" + lobby_data['gameSession'] + "'." + color.reset())

    manager.set_constants(lobby_data['constants'])

    start_data = joueur.client.wait_for_event("start")

    print(color.text("green") + "Game is starting." + color.reset())

    ai.set_player(game.get_game_object(start_data['playerID']))
    try:
        ai.start()
        ai.game_updated()
    except:
        error_code.handle_error(error_code.AI_ERRORED, sys.exc_info()[0], "AI errored during game initialization")

    joueur.client.play()
    def _merge_delta(self, state, delta):
        delta_length = -1
        if self._DELTA_LIST_LENGTH in delta:
            delta_length = delta[self._DELTA_LIST_LENGTH]
            del delta[
                self.
                _DELTA_LIST_LENGTH]  # we don't want to copy this key/value over to the state, it was just to signify it is an array

        if delta_length > -1:  # then this part in the state is an array
            while len(
                    state
            ) > delta_length:  # remove elements off the array to make it's size correct.
                state.pop()
            while len(
                    state
            ) < delta_length:  # append elements on the array to make it's size correct.
                state.append(None)

        for key in delta:  # deltas will always be objects when iterating through, arrays just have keys of numbers
            d = delta[key]
            state_key = key  # array's keys are real numbers, not strings e.g. "1"
            key_in_state = False

            if isinstance(state, list):
                state_key = int(key)
                key_in_state = state_key < len(state)
            else:
                if isinstance(state, DeltaMergeable):
                    state_key = "_" + camel_case_converter(state_key)
                key_in_state = state_key in state

            value = d
            if d == self._DELTA_REMOVED:
                value = None
                if key_in_state:
                    del state[state_key]
            elif is_game_object_reference(
                    d):  # then this is a shallow reference to a game object
                value = self.game.get_game_object(d['id'])
            elif is_object(d) and key_in_state and is_object(state[state_key]):
                value = None
                self._merge_delta(state[state_key], d)
            elif not key_in_state and is_object(d):
                if isinstance(d, dict):
                    state[state_key] = [] if d in self._DELTA_LIST_LENGTH else {}
                    value = None
                    self._merge_delta(state[state_key], d)

            if value != None:
                if isinstance(state_key, int) or isinstance(state, dict):
                    state[state_key] = value
                else:
                    setattr(state, state_key, value)
Beispiel #6
0
    def _merge_delta(self, state, delta):
        delta_length = -1
        if self._DELTA_LIST_LENGTH in delta:
            delta_length = delta[self._DELTA_LIST_LENGTH]
            del delta[self._DELTA_LIST_LENGTH] # we don't want to copy this key/value over to the state, it was just to signify it is an array

        if delta_length > -1: # then this part in the state is an array
            while len(state) > delta_length: # remove elements off the array to make it's size correct.
                state.pop()
            while len(state) < delta_length: # append elements on the array to make it's size correct.
                state.append(None)

        for key in delta: # deltas will always be objects when iterating through, arrays just have keys of numbers
            d = delta[key]
            state_key = key # array's keys are real numbers, not strings e.g. "1"
            key_in_state = False

            if isinstance(state, list):
                state_key = int(key)
                key_in_state = state_key < len(state)
            else:
                if isinstance(state, DeltaMergeable):
                    state_key = "_" + camel_case_converter(state_key)
                key_in_state = state_key in state

            value = d
            if d == self._DELTA_REMOVED:
                value = None
                if key_in_state:
                    del state[state_key]
            elif is_game_object_reference(d): # then this is a shallow reference to a game object
                value = self.game.get_game_object(d['id'])
            elif is_object(d) and key_in_state and is_object(state[state_key]):
                value = None
                self._merge_delta(state[state_key], d)
            elif not key_in_state and is_object(d):
                if isinstance(d, dict):
                    state[state_key] = [] if d in self._DELTA_LIST_LENGTH else {}
                    value = None
                    self._merge_delta(state[state_key], d)

            if value != None:
                if isinstance(state_key, int) or isinstance(state, dict):
                    state[state_key] = value
                else:
                    setattr(state, state_key, value)
Beispiel #7
0
def run(args):
    split_server = args.server.split(":")
    args.server = split_server[0]
    args.port = int((len(split_server) == 2 and split[1])) or args.port

    module_str = "games." + camel_case_converter(args.game)
    try:
        module = importlib.import_module(module_str) # should load Game and AI to load based on the game selected in args
    except ImportError as e:
        handle_error(ErrorCode.game_not_found, e, "Could not find game module: '" + module_str + "'")

    game = module.Game()
    ai = module.AI(game)
    manager = GameManager(game)

    joueur.client.setup(game, ai, manager, args.server, int(args.port), print_io=args.print_io)

    joueur.client.send("play", {
        'gameName': game.name,
        'password': args.password,
        'requestedSession': args.session,
        'clientType': "Python",
        'playerName': args.name or ai.get_name() or "Python Player",
        'gameSettings': args.game_settings
    })

    lobby_data = joueur.client.wait_for_event("lobbied")

    print("In Lobby for game '" + lobby_data['gameName'] + "' in session '" + lobby_data['gameSession'] + "'")

    manager.set_constants(lobby_data['constants'])

    start_data = joueur.client.wait_for_event("start")

    print("Game starting")

    ai.set_player(game.get_game_object(start_data['playerID']))
    try:
        ai.start()
        ai.game_updated()
    except:
        handle_error(ErrorCode.ai_errored, sys.exc_info()[0], "AI errored during game initialization")

    joueur.client.play()
Beispiel #8
0
def run(args):
    split_server = args.server.split(":")
    args.server = split_server[0]
    args.port = int((len(split_server) == 2 and split_server[1])) or args.port

    joueur.client.connect(args.server, args.port, args.print_io)

    joueur.client.send("alias", args.game)
    game_name = joueur.client.wait_for_event("named")

    module_str = "games." + camel_case_converter(game_name)

    spec = importlib.util.find_spec(module_str)
    if spec is None:
        error_code.handle_error(
            error_code.GAME_NOT_FOUND,
            None,
            'Could not find the module for game "{}".'.format(game_name)
        )

    try:
        # should load Game and AI to load based on the game selected in args
        module = importlib.import_module(module_str)
    except ImportError as e:
        error_code.handle_error(
            error_code.REFLECTION_FAILED,
            e,
            'Could not import game module: "{}".'.format(module_str)
        )

    game = module.Game()
    try:
        ai = module.AI(game)
    except:
        error_code.handle_error(
            error_code.AI_ERRORED,
            sys.exc_info()[0],
            'Could not initialize the AI class. ' +
            'Probably a syntax error in your AI.'
        )

    manager = GameManager(game)

    joueur.client.setup(game, ai, manager)

    ai.set_settings(args.ai_settings)

    joueur.client.send("play", {
        'gameName': game_name,
        'password': args.password,
        'requestedSession': args.session,
        'clientType': "Python",
        'playerName': args.name or ai.get_name() or "Python Player",
        'playerIndex': args.index,
        'gameSettings': args.game_settings
    })

    lobby_data = joueur.client.wait_for_event("lobbied")

    if lobby_data['gameVersion'] != module.game_version:
        print("""{}WARNING: Game versions do not match.
-> Your local game version is:     {}
-> Game Server's game version is:  {}

Version mismatch means that unexpected crashes may happen due to differing game structures!{}""".format(
            color.text('yellow'),
            str(module.game_version)[:8],
            str(lobby_data['gameVersion'])[:8],
            color.reset()
        )
    )

    print('{}In Lobby for game "{}" in session "{}".{}'.format(
            color.text("cyan"),
            lobby_data['gameName'],
            lobby_data['gameSession'],
            color.reset()
        )
    )

    manager.set_constants(lobby_data['constants'])

    start_data = joueur.client.wait_for_event("start")

    print(color.text("green") + "Game is starting." + color.reset())

    ai.set_player(game.get_game_object(start_data['playerID']))
    try:
        ai.start()
        ai.game_updated()
    except:
        error_code.handle_error(
            error_code.AI_ERRORED,
            sys.exc_info()[0],
            'AI errored during game initialization'
        )

    joueur.client.play()