Exemple #1
0
def nextUIState(bot, update):
    """
    Re-creates the dialog window to match the current state in working memory.
    """

    current_id = clips.Eval('(find-fact ((?s state-list)) TRUE)')[0].Slots['current']
    current_ui = clips.Eval('(find-fact ((?u UI-state)) (eq ?u:id %s))' % current_id)
    state = current_ui[0].Slots['state']
    if state == 'initial':
        clips.Assert('(next %s)' % current_id)
        clips.Run()
        nextUIState(bot, update)
    elif state == 'final':
        keyboard = [[KeyboardButton(text=emojize(':back: Previous', use_aliases=True))],
                    [KeyboardButton(text=emojize(':repeat: Restart', use_aliases=True))],
                    [KeyboardButton(text=emojize(':x: Cancel', use_aliases=True))]]
        update.message.reply_text(text=current_ui[0].Slots['display'],
                                  parse_mode=ParseMode.MARKDOWN,
                                  disable_web_page_preview=True,
                                  reply_markup=ReplyKeyboardMarkup(keyboard))
    else:
        keyboard = list()
        for answer in current_ui[0].Slots['valid-answers']:
            keyboard.append([KeyboardButton(text=answer)])
        if current_ui[0].Slots['help']:
            keyboard.append([KeyboardButton(text=emojize(':sos: Help', use_aliases=True))])
        if current_ui[0].Slots['why']:
            keyboard.append([KeyboardButton(text=emojize(':question: Why', use_aliases=True))])
        if len(clips.Eval('(find-fact ((?s state-list)) TRUE)')[0].Slots['sequence']) > 2:
            keyboard.append([KeyboardButton(text=emojize(':back: Previous', use_aliases=True))])
        keyboard.append([KeyboardButton(text=emojize(':x: Cancel', use_aliases=True))])
        update.message.reply_text(text=current_ui[0].Slots['display'],
                                  reply_markup=ReplyKeyboardMarkup(keyboard))
Exemple #2
0
def handleEvent(bot, update):
    """
    Triggers the next state in working memory based on which button is pressed.
    """

    current_id = clips.Eval(
        '(find-fact ((?s state-list)) TRUE)')[0].Slots['current']
    current_ui = clips.Eval('(find-fact ((?u UI-state)) (eq ?u:id %s))' %
                            current_id)
    response = update.message.text
    if response in current_ui[0].Slots['valid-answers']:
        if len(response.split(' ')) > 1:
            clips.Assert('(next %s "%s")' % (current_id, response))
        else:
            clips.Assert('(next %s %s)' % (current_id, response))
        clips.Run()
        nextUIState(bot, update)
    elif response == emojize(':sos: Help', use_aliases=True):
        help = current_ui[0].Slots['help']
        if not re.findall('_.+?_\(.*?\)', help):
            update.message.reply_text(text=help, parse_mode=ParseMode.MARKDOWN)
        else:
            keyboard = list()
            for pattern in re.findall('_.+?_\(.*?\)', help):
                keyboard.append([
                    InlineKeyboardButton(text=re.findall('_(.+?)_',
                                                         pattern)[0],
                                         callback_data=re.findall(
                                             '\((.*?)\)', pattern)[0])
                ])
            for link in re.findall('\(.*?\)', help):
                help = help.replace(link, '')
            update.message.reply_text(
                text=help,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup(keyboard))
    elif response == emojize(':question: Why', use_aliases=True):
        update.message.reply_text(text=current_ui[0].Slots['why'],
                                  parse_mode=ParseMode.MARKDOWN)
    elif response == emojize(':back: Previous', use_aliases=True):
        clips.Assert('(prev %s)' % current_id)
        clips.Run()
        nextUIState(bot, update)
    elif response == emojize(':repeat: Restart', use_aliases=True):
        new(bot, update)
    elif response == emojize(':x: Cancel', use_aliases=True):
        clips.Reset()
        update.message.reply_text(
            text='Bye! I hope we can talk again some day. 👋🏻',
            reply_markup=ReplyKeyboardRemove())
Exemple #3
0
 def set_value(self, value):
     self._value = value
     if (self._fact):
         sstr = '(bind ?*ans* (modify %d (name %s)) )' % (self._fact,
                                                          self.value)
         clips.SendCommand(sstr)
         self._fact = clips.Eval('?*ans*').Index
Exemple #4
0
 def set_flag(self, flag, value):
     self.flags[flag] = value
     if (self._fact):
         sstr = '(bind ?*ans* (modify %d (%s %s)) )' % (self._fact, flag,
                                                        value)
         clips.SendCommand(sstr)
         self._fact = clips.Eval('?*ans*').Index
Exemple #5
0
 def set_children(self, children):
     self._children=children
     if(self._fact):
         child_ids=[str(child._id) for child in self.children]
         sstr='(bind ?*ans* (modify %d (children %s)) )' % (self._fact, ' '.join(self.child_ids))
         clips.SendCommand(sstr)
         self._fact=clips.Eval('?*ans*').Index
Exemple #6
0
 def set_number(self, number):
     self._number=number
     if(number in [MatlabParser.INT,  MatlabParser.FLOAT,  MatlabParser.NUMBER]):
         self.set_flag('is_scalar', True)
     if(self._fact):
         sstr='(bind ?*ans* (modify %d (name %s)) )' % (self._fact, self.name)
         clips.SendCommand(sstr)
         self._fact=clips.Eval('?*ans*').Index
Exemple #7
0
def start(bot, update):
    """
    Sends a welcome message when the command /start is issued.
    """

    clips.Reset()
    clips.Run()
    update.message.reply_text(text='Hello %s! 🤖' % update.message.from_user.first_name,
                              reply_markup=ReplyKeyboardRemove())
    update.message.reply_text(clips.Eval('(find-fact ((?u UI-state)) (eq ?u:state initial))')[0].Slots['display'])
Exemple #8
0
    def __init__(self, **kw):
        import posixpath
        self.python_path = []
        self.bootstrap_file = None
        self.model = None
        self.initial_facts = None
        self.initial_facts_dir = None
        self.trace = None
        self.main = None

        if kw.has_key("main"):
            self.main = kw["main"]
        else:
            raise ValueError, "ZPP MAIN not passed to CLP"
        if kw.has_key("python"):
            self.python_path = kw["python"]
        if kw.has_key("trace") and kw["trace"] != None:
            self.trace = kw["trace"].lower().strip()
        if kw.has_key("bootstrap") and check_file_read(kw["bootstrap"]):
            self.bootstrap_file = kw["bootstrap"]
        if kw.has_key("model") and check_file_read(kw["model"]):
            self.model = kw["model"]
        else:
            self.model = None
        if kw.has_key("initial_facts") and check_file_read(
                kw["initial_facts"]):
            self.initial_facts = kw["initial_facts"]
        if kw.has_key("initial_facts_dir") and check_file_read(
                kw["initial_facts_dir"]):
            self.initial_facts = kw["initial_facts_dir"]
        if kw.has_key("model_path") and check_directory(kw["model_path"]):
            self.model_path = kw["model_path"]
        else:
            self.model_path = None
        if kw.has_key("models"):
            self.models = kw["models"]
        else:
            self.models = []
        ENV.__init__(self)
        if self.trace != None:
            try:
                clips.Eval("(watch %s)" % self.trace)
            except:
                raise ValueError, "Invalid option for the (watch %s)" % self.trace
        PYLOADER.__init__(self, self.python_path)
        self.ReloadClipsModules()
        self.ReloadClipsModels()
        self.ReloadInitialFacts()
Exemple #9
0
def addf(a, b):
    return a + b


print addf("egg", "spam")
print addf(2, 4)

import clips
clips.RegisterPythonFunction(addf)
print clips.Eval('(python-call addf "egg" "spam")')
print clips.Eval('(python-call addf 2 4)')
def init_human_game(player_formation,
                    computer_team,
                    player_as,
                    number_turns,
                    dont_save=False):
    """
    Intialize the clips environment
    """

    player_num = 0
    team_a = None
    team_b = None
    name_team_a = ''
    name_team_b = ''

    team_a_piece = xdg.get_data_path('images/piece-orange.png')
    team_b_piece = xdg.get_data_path('images/piece-violete.png')
    default_piece = xdg.get_data_path('images/piece-default.png')

    formacion_temporal_player = None
    formacion_temporal_pc = None

    formacion_temporal_player = parsear_fichero_formacion(player_formation)
    player_formation = formacion_temporal_player
    formacion_temporal_pc = parsear_fichero_formacion(computer_team[1])

    computer_team = (computer_team[0], formacion_temporal_pc)

    if player_as == 'A':
        player_num = 1
        team_a = player_formation
        team_b = computer_team
        name_team_a = filenames.extract_simple_name_es((None, team_a))
        name_team_b = filenames.extract_name_expert_system(team_b)
    else:
        player_num = -1
        team_b = player_formation
        team_a = computer_team
        name_team_b = filenames.extract_simple_name_es((None, team_b))
        name_team_a = filenames.extract_name_expert_system(team_a)

    aux_team_a = (name_team_a, team_a_piece)
    aux_team_b = (name_team_b, team_b_piece)

    clips.Eval('(reset)')
    clips.Eval('(clear)')

    clips.EngineConfig.Strategy = clips.RANDOM_STRATEGY

    random.seed()
    clips.Eval("(seed %d)" % random.randint(0, 9999))

    funciones.LoadFunctions(clips)
    f1.init_world(clips, number_turns)

    try:
        f1.LoadFunctions(clips)
    except Exception:
        print clips.ErrorStream.Read()
        exit(-1)

    mover.LoadFunctions(clips)
    texto.LoadFunctions(clips)
    traducirF.LoadFunctions(clips)
    traducirM.LoadFunctions(clips)

    if player_num == 1:
        int_team = mirroring.interactive_formation(team_a)
        temp_team = mirroring.mirroring_team(team_b[1])

        try:
            clips.Load(int_team)
        except clips.ClipsError:
            os.remove(int_team)
            raise FileError(_('Error parsing the file ') + team_a)

        try:
            clips.Load(temp_team)
        except clips.ClipsError:
            os.remove(temp_team)
            raise FileError(_('Error parsing the file ') + team_b[1])

        os.remove(int_team)
        os.remove(temp_team)

        fB.LoadFunctions(clips)
        temp_rules = mirroring.mirroring_rules(team_b[0])
        try:
            clips.Load(temp_rules)
        except clips.ClipsError:
            os.remove(temp_rules)
            raise FileError(_('Error parsing the file ') + team_b[0])
        os.remove(temp_rules)
    else:
        try:
            clips.Load(team_a[1])
        except clips.ClipsError:
            raise FileError(_('Error parsing the file ') + team_a[1])

        int_team = mirroring.interactive_formation(team_b)
        temp_team = mirroring.mirroring_team(int_team)

        try:
            clips.Load(temp_team)
        except clips.ClipsError:
            os.remove(temp_team)
            raise FileError(_('Error parsing the file ') + team_a[1])
        os.remove(temp_team)

        fA.LoadFunctions(clips)
        try:
            clips.Load(team_a[0])
        except clips.ClipsError:
            raise FileError(_('Error parsing the file ') + team_a[0])

    interaccion.LoadFunctions(clips, player_as)

    interaccion.interaction_object = r_intact.HumanInteraction(
        aux_team_a, aux_team_b, default_piece, player_num, number_turns)

    clips.Reset()  # restart the environment

    clips.Run()  # start the simulation

    interaccion.interaction_object.finish()

    _stream = clips.StdoutStream.Read()  # print the output

    # print _stream
    # print interaccion.interaction_object.define_winner()

    if not dont_save:
        _rename_output_file(_generate_file_name(name_team_a, name_team_b))

    if os.path.isfile("resultado.txt"):
        os.remove('resultado.txt')

    os.remove(formacion_temporal_pc)
    os.remove(formacion_temporal_player)

    clips.Eval('(reset)')
    clips.Eval('(clear)')
Exemple #11
0
 def evaluate(self):
     return clips.Eval(str(self.to_lisp())).encode()
import clips
def py_square(x):
        return x * x
clips.RegisterPythonFunction(py_square)
print clips.Eval("(python-call py_square 7)")
print clips.Eval("(python-call py_square 0.7)")
    def __startGame(self):
        """Intialize rules and facts of the main environment.

        This function loads differents modules and create an environment that provides
        the proper context where a game can be played.
        """
        clips.Eval('(clear)')

        clips.EngineConfig.Strategy = clips.RANDOM_STRATEGY

        random.seed()
        clips.Eval("(seed " + str(random.randint(0, 9999)) + ")")

        try:
            # Se cargan una serie de funciones de utilidad, como "minimo" o "mov-valido"
            funciones.LoadFunctions(clips)

            # Se inicializan las opciones de juego (deffacts)
            f1.init_world(clips, self.number_turns)

            # Se cargan las plantillas ficha-r, ficha, mueve y obstaculo
            # además de las reglas para el control de los turnos
            f1.LoadFunctions(clips)
            mover.LoadFunctions(clips)
            texto.LoadFunctions(clips)
            traducirF.LoadFunctions(clips)
            traducirM.LoadFunctions(clips)

            nombreFicheroObstaculos = parsear_fichero_obstaculos.generar_reglas_obstaculos(
            )
            if nombreFicheroObstaculos:
                clips.Load(nombreFicheroObstaculos)
                os.unlink(nombreFicheroObstaculos)

        except clips.ClipsError as e:
            logging.error("####################")
            logging.error("ERROR de clips: %s", e)
            logging.error("Mensaje: ")
            logging.error(clips.ErrorStream.Read())
            logging.error("####################")

            raise FileError("W===============TTTT")

        logging.info("Parseando ficheros de formación...")
        temp_form_A = parsear_fichero_formacion.parsear_fichero_formacion(
            self.teamA[1], "A")
        temp_form_B = parsear_fichero_formacion.parsear_fichero_formacion(
            self.teamB[1], "B")

        self.teamA = (self.teamA[0], temp_form_A)
        self.teamB = (self.teamB[0], temp_form_B)

        temp_team = mirroring.mirroring_team(self.teamB[1])

        logging.info('Cargando %s', self.teamA[1])
        #create a temporally file that mirror the formation of B team,
        #because it's written thinking in A team
        try:
            clips.Load(self.teamA[1])
        except clips.ClipsError as e:
            logging.error("####################")
            logging.error("ERROR de clips: %s", e)
            logging.error("Mensaje: ")
            logging.error(clips.ErrorStream.Read())
            logging.error("####################")

            raise FileError(
                _('Error parsing the file ') + self.teamA[1] + "\n" + e)

        logging.info('Cargando %s', self.teamB[1])

        try:
            clips.Load(temp_team)
        except clips.ClipsError as e:
            logging.error("####################")
            logging.error("ERROR de clips: %s", e)
            logging.error("Mensaje: ")
            logging.error(clips.ErrorStream.Read())
            logging.error("####################")

            os.remove(temp_team)
            raise FileError(_('Error parsing the file ') + self.teamB[1])

        os.remove(temp_team)
        os.remove(temp_form_A)
        os.remove(temp_form_B)

        try:
            fA.LoadFunctions(clips)
            logging.info('Cargando %s', self.teamA[0])
            clips.Load(self.teamA[0])
        except clips.ClipsError as e:
            logging.error("####################")
            logging.error("ERROR de clips: %s", e)
            logging.error("Mensaje: ")
            logging.error(clips.ErrorStream.Read())
            logging.error("####################")
            raise FileError(_('Error parsing the file ') + self.teamA[0])

        temp_rules = mirroring.mirroring_rules(self.teamB[0])

        #same thing that for the formation, but this time using the rules

        try:
            fB.LoadFunctions(clips)
            logging.info('Cargando %s', self.teamB[0])
            clips.Load(temp_rules)
        except clips.ClipsError as e:
            os.remove(temp_rules)
            logging.error("####################")
            logging.error("ERROR de clips: %s", e)
            logging.error("Mensaje: ")
            logging.error(clips.ErrorStream.Read())
            logging.error("####################")

            raise FileError(
                _('Error parsing the file ') + self.teamB[0] + "\n")

        os.remove(temp_rules)

        clips.Reset()  #restart the environment

        clips.Run()  #start the simulation

        t = clips.StdoutStream.Read()  #print the output

        clipsOutputFile = open("clipsOutputFile", "w")
        clipsOutputFile.write(t)
        clipsOutputFile.close()

        f = clips.FactList()

        last_fact = f[len(f) - 1].PPForm()
        prev_last_fact = f[len(f) - 2].PPForm()

        winner = self.__define_winner(last_fact, prev_last_fact)

        return winner