Exemplo n.º 1
0
def main(argv, in_stream=sys.stdin, out_stream=sys.stdout):
    "Set up a session and run Curveship's main loop."
    return_code = 0
    try:
        out_streams = Multistream([out_stream])
        opts, args = parse_command_line(argv)
        out_streams = start_log(out_streams)
        world, discourse = initialize(args[0], args[1:], out_streams)
        discourse.debug = opts.debug
        if opts.autofile is not None:
            auto = open(opts.autofile, 'r+')
            discourse.initial_inputs = auto.readlines()
            auto.close()
        if len(world.act) > 0:
            _, id_list, world = simulator(None, world,
                                          discourse.spin['commanded'],
                                          world.act.values())
            focal_concept = world.concept[discourse.spin['focalizer']]
            reply_text, discourse = teller(id_list, focal_concept, discourse)
            presenter.present(reply_text, out_streams)
        while world.running:
            previous_time = time.time()
            world, discourse = each_turn(world, discourse, in_stream,
                                         out_streams)
            out_streams.log.write('#' + str(time.time() - previous_time))
    except joker.StartupError, err:
        presenter.present(err.msg, Multistream([sys.stderr]))
        return_code = 2
Exemplo n.º 2
0
def handle_input(user_input, world, discourse, in_stream, out_streams):
    """Deal with input obtained, sending it to the appropriate module.

    The commanded character's concept is used when trying to recognize
    commands."""
    c_concept = world.concept[discourse.spin['commanded']]
    user_input = recognizer.recognize(user_input, discourse, c_concept)
    if user_input.unrecognized:
        user_input = clarifier.clarify(user_input, c_concept, discourse,
                                       in_stream, out_streams)
    if user_input.command:
        user_input, id_list, world = simulator(user_input, world,
                                                  discourse.spin['commanded'])
        if hasattr(world.item['@cosmos'], 'update_spin'):
            discourse.spin = world.item['@cosmos'].update_spin(world, 
                                                               discourse)
        spin = discourse.spin
        if hasattr(world.item['@cosmos'], 'use_spin'):
            spin = world.item['@cosmos'].use_spin(world, discourse.spin)
        f_concept = world.concept[spin['focalizer']]
        tale, discourse = teller(id_list, f_concept, discourse)
        presenter.present(tale, out_streams)
    elif user_input.directive:
        texts, world, discourse = joker.joke(user_input.normal, world,
                                             discourse)
        for text in texts:
            if text is not None:
                presenter.present(text, out_streams)
    discourse.input_list.update(user_input)
    return (user_input, world, discourse)
Exemplo n.º 3
0
def handle_input(user_input, world, discourse, in_stream, out_streams):
    """Deal with input obtained, sending it to the appropriate module.

    The commanded character's concept is used when trying to recognize
    commands."""
    c_concept = world.concept[discourse.spin['commanded']]
    user_input = recognizer.recognize(user_input, discourse, c_concept)
    if user_input.unrecognized:
        user_input = clarifier.clarify(user_input, c_concept, discourse,
                                       in_stream, out_streams)
    if user_input.command:
        user_input, id_list, world = simulator(user_input, world,
                                               discourse.spin['commanded'])
        if hasattr(world.item['@cosmos'], 'update_spin'):
            discourse.spin = world.item['@cosmos'].update_spin(
                world, discourse)
        spin = discourse.spin
        if hasattr(world.item['@cosmos'], 'use_spin'):
            spin = world.item['@cosmos'].use_spin(world, discourse.spin)
        f_concept = world.concept[spin['focalizer']]
        tale, discourse = teller(id_list, f_concept, discourse)
        presenter.present(tale, out_streams)
    elif user_input.directive:
        texts, world, discourse = joker.joke(user_input.normal, world,
                                             discourse)
        for text in texts:
            if text is not None:
                presenter.present(text, out_streams)
    discourse.input_list.update(user_input)
    return (user_input, world, discourse)
Exemplo n.º 4
0
def main(argv, in_stream=sys.stdin, out_stream=sys.stdout):
    "Set up a session and run Curveship's main loop."
    return_code = 0
    try:
        out_streams = Multistream([out_stream])
        opts, args = parse_command_line(argv)
        out_streams = start_log(out_streams)
        world, discourse = initialize(args[0], args[1:], out_streams)
        discourse.debug = opts.debug
        if opts.autofile is not None:
            auto = open(opts.autofile, 'r+')
            discourse.initial_inputs = auto.readlines()
            auto.close()
        if len(world.act) > 0:
            _, id_list, world = simulator(None, world,
                                          discourse.spin['commanded'],
                                          world.act.values())
            focal_concept = world.concept[discourse.spin['focalizer']]
            reply_text, discourse = teller(id_list, focal_concept, discourse)
            presenter.present(reply_text, out_streams)
        while world.running:
            previous_time = time.time()
            world, discourse = each_turn(world, discourse, in_stream,
                                         out_streams)
            out_streams.log.write('#' + str(time.time() - previous_time))
    except joker.StartupError, err:
        presenter.present(err.msg, Multistream([sys.stderr]))
        return_code = 2
Exemplo n.º 5
0
def each_turn(world, discourse, in_stream, out_streams):
    'Obtain and processes input, if the session is interactive.'
    if discourse.spin['commanded'] is None:
        if hasattr(world.item['@cosmos'], 'interval'):
            world.item['@cosmos'].interval()
        _, id_list, world = simulator(None, world,
                                         discourse.spin['commanded'])
        focal_concept = world.concept[discourse.spin['focalizer']]
        reply_text, discourse = teller(id_list, focal_concept, discourse)
        presenter.present(reply_text, out_streams)
    else:
        if (hasattr(discourse, 'initial_inputs') and 
             len(discourse.initial_inputs) > 0):
            input_string = discourse.initial_inputs.pop(0)
            user_input = preparer.tokenize(input_string, discourse.separator)
            presenter.present('[> ' + input_string, out_streams, '', '')
        else:
            user_input = preparer.prepare(discourse.separator, 
                                          discourse.typo.prompt, in_stream, 
                                          out_streams)
        # After each input, present a newline all by itself.
        presenter.present('\n', out_streams, '', '')
        while len(user_input.tokens) > 0 and world.running:
            (user_input, world, discourse) = handle_input(user_input, world,
                                              discourse, in_stream,
                                              out_streams)
            presenter.present(discourse.input_list.show(1),
                              out_streams.log)
    return (world, discourse)
Exemplo n.º 6
0
def each_turn(world, discourse, in_stream, out_streams):
    'Obtain and processes input, if the session is interactive.'
    if discourse.spin['commanded'] is None:
        if hasattr(world.item['@cosmos'], 'interval'):
            world.item['@cosmos'].interval()
        _, id_list, world = simulator(None, world, discourse.spin['commanded'])
        focal_concept = world.concept[discourse.spin['focalizer']]
        reply_text, discourse = teller(id_list, focal_concept, discourse)
        presenter.present(reply_text, out_streams)
    else:
        if (hasattr(discourse, 'initial_inputs')
                and len(discourse.initial_inputs) > 0):
            input_string = discourse.initial_inputs.pop(0)
            user_input = preparer.tokenize(input_string, discourse.separator)
            presenter.present('[> ' + input_string, out_streams, '', '')
        else:
            user_input = preparer.prepare(discourse.separator,
                                          discourse.typo.prompt, in_stream,
                                          out_streams)
        # After each input, present a newline all by itself.
        presenter.present('\n', out_streams, '', '')
        while len(user_input.tokens) > 0 and world.running:
            (user_input, world,
             discourse) = handle_input(user_input, world, discourse, in_stream,
                                       out_streams)
            presenter.present(discourse.input_list.show(1), out_streams.log)
    return (world, discourse)
Exemplo n.º 7
0
    def main(self, argv, in_stream=sys.stdin, out_stream=sys.stdout):
        "Set up a session and run Curveship's main loop."
        return_code = 0

        out_streams = Multistream([out_stream])
        opts, args = self.parse_command_line(argv)
        out_streams = self.start_log(out_streams)
        self.world, self.discourse = self.initialize(args[0], args[1:], out_streams)
        self.discourse.debug = opts.debug
        if opts.autofile is not None:
            auto = open(opts.autofile, 'r+')
            self.discourse.initial_inputs = auto.readlines()
            auto.close()
        if len(self.world.act) > 0:
            _, id_list, self.world = self.simulator(None, self.world,
                                               self.discourse.spin['commanded'],
                                               self.world.act.values())
            focal_concept = self.world.concept[self.discourse.spin['focalizer']]
            reply_text, discourse = self.teller(id_list, focal_concept, self.discourse)
            initial_text = presenter.present(reply_text, out_streams)

        # Game().static_level()
        Game().curve_level(self, preparer, self.world, discourse, initial_text)

        try:
            if len(self.world.act) > 0:
                _, id_list, world = self.simulator(None, self.world,
                                              discourse.spin['commanded'],
                                              self.world.act.values())
                focal_concept = world.concept[discourse.spin['focalizer']]
                reply_text, discourse = self.teller(id_list, focal_concept, discourse)
                presenter.present(reply_text, out_streams)
            while world.running:
                previous_time = time.time()
                world, discourse = self.each_turn(world, discourse, in_stream,
                                             out_streams)
                out_streams.log.write('#' + str(time.time() - previous_time))

                for step in range(8):
                    self.display.show_frame()

        except joker.StartupError, err:
            presenter.present(err.msg, Multistream([sys.stderr]))
            return_code = 2
Exemplo n.º 8
0
def initialize(if_file, spin_files, out_streams):
    'Load all files and present the header and prologue.'
    for startup_string in joker.session_startup(__version__):
        presenter.center(startup_string, out_streams)
    fiction = joker.load_fiction(if_file, ['discourse', 'items'],
                                 discourse_model.FICTION_DEFAULTS)
    presenter.center('fiction: ' + if_file, out_streams)
    world = world_model.World(fiction)
    world.set_concepts(fiction.concepts)
    for i in dir(fiction):
        if i[:8] == 'COMMAND_':            
            setattr(command_map, i.partition('_')[2], getattr(fiction, i))
            delattr(fiction, i)
    for (key, value) in discourse_model.SPIN_DEFAULTS.items():
        if key not in fiction.discourse['spin']:
            fiction.discourse['spin'][key] = value
    while len(spin_files) > 0:
        next_file = spin_files.pop(0)
        new_spin = joker.load_spin(fiction.discourse['spin'], next_file)
        fiction.discourse['spin'].update(new_spin)
        presenter.center('spin: ' + next_file, out_streams)
    presenter.present('\n', out_streams)
    presenter.present('', out_streams)
    discourse = discourse_model.Discourse(fiction.discourse)
    reply = joker.show_frontmatter(discourse)
    if 'prologue' in discourse.metadata:
        reply += '\n\n' + joker.show_prologue(discourse.metadata)
    presenter.present(reply, out_streams)
    return (world, discourse)
Exemplo n.º 9
0
def initialize(if_file, spin_files, out_streams):
    'Load all files and present the header and prologue.'
    for startup_string in joker.session_startup(__version__):
        presenter.center(startup_string, out_streams)
    fiction = joker.load_fiction(if_file, ['discourse', 'items'],
                                 discourse_model.FICTION_DEFAULTS)
    presenter.center('fiction: ' + if_file, out_streams)
    world = world_model.World(fiction)
    world.set_concepts(fiction.concepts)
    for i in dir(fiction):
        if i[:8] == 'COMMAND_':
            setattr(command_map, i.partition('_')[2], getattr(fiction, i))
            delattr(fiction, i)
    for (key, value) in discourse_model.SPIN_DEFAULTS.items():
        if key not in fiction.discourse['spin']:
            fiction.discourse['spin'][key] = value
    while len(spin_files) > 0:
        next_file = spin_files.pop(0)
        new_spin = joker.load_spin(fiction.discourse['spin'], next_file)
        fiction.discourse['spin'].update(new_spin)
        presenter.center('spin: ' + next_file, out_streams)
    presenter.present('\n', out_streams)
    presenter.present('', out_streams)
    discourse = discourse_model.Discourse(fiction.discourse)
    reply = joker.show_frontmatter(discourse)
    if 'prologue' in discourse.metadata:
        reply += '\n\n' + joker.show_prologue(discourse.metadata)
    presenter.present(reply, out_streams)
    return (world, discourse)
Exemplo n.º 10
0
def clarify(user_input, concept, discourse, in_stream, out_streams):
    'States that input was not understood or attempts to disambiguate input.'

    if len(user_input.normal) == 0 and len(user_input.possible) == 0:
        clarification = ('(It\'s not clear what "' + str(user_input) +
        '" means. Try typing some other command to ' +
        concept.item[discourse.spin['commanded']].noun_phrase(discourse) + '.)')
    else:
        question = '(Is this a command to '
        commands = []
        options = []
        for possibility in user_input.possible:
            commands.append(english_command(possibility, concept, discourse))
            options.append('(' + str(len(commands)) + ') "' +
                           commands[-1] + '"')
        options.append('(' + str(len(commands) + 1) + ') none of these')
        question += discourse.list_phrases(options, conjunction='or') + '?)'
        question = re.sub('",', ',"', question)
        presenter.present(question, out_streams)
        choose_a_number = preparer.prepare(discourse.separator,
                          '(1-' + str(len(commands) + 1) + ')? ', in_stream)
        selected = None
        if len(choose_a_number.tokens) == 1:
            try:
                selected = int(choose_a_number.tokens[0])
            except ValueError:
                pass
        if selected is None or selected < 1 or selected > len(commands):
            clarification = ('\n(Since you did not select '+
                             discourse.list_phrases(range(1, len(commands) + 1),
                             conjunction='or') + ', the command "' + 
                             str(user_input) +
                             '" cannot be understood. Try something else.)')
        else:
            clarification = '\n(Very well ...)'
            user_input.category = 'command'
            user_input.normal = user_input.possible[selected-1]

    presenter.present(clarification, out_streams)
    return user_input
Exemplo n.º 11
0
 def __init__(self, f):
     self.bgc = "white"
     self.form = f
     self.presenter = present(self)
     self.place_startpage()
Exemplo n.º 12
0
from lexer import Lexer
from parser import parse
from prompter import displayprompt, readexpression, displayerror, welcome, bye, displayresult
from presenter import present
from lisptypes import LispException
from evaluator import evaluate, defaultenv

welcome()
displayprompt()
environment = defaultenv()
while True:
    try:
        displayresult(
            present(evaluate(parse(Lexer(readexpression())), environment)))
    except LispException as e:
        displayerror(str(e))
    except (KeyboardInterrupt, EOFError):
        bye()
        exit(0)
    except BaseException as e:
        displayerror(str(e))
Exemplo n.º 13
0
    if len(log_files) == 0:
        latest = 0
    else:
        latest = max([int(log_file) for log_file in log_files])
    log_file = 'logs/' + str(latest + 1) + '.log'
    try:
        log = file(log_file, 'w')
    except IOError, err:
        msg = ('Unable to open log file "' + log_file + '" for ' +
               'writing due to this error: ' + str(err))
        raise joker.StartupError(msg)
    # So that we output to the screen and the log file:
    out_streams.streams.append(log)
    # And indicate that this stream is the log file:
    out_streams.log = log
    presenter.present('\nLogged to: ' + log_file + '\nSession started ' +
                      time.strftime("%Y-%m-%d %H:%M:%S"), out_streams)
    return out_streams


def initialize(if_file, spin_files, out_streams):
    'Load all files and present the header and prologue.'
    for startup_string in joker.session_startup(__version__):
        presenter.center(startup_string, out_streams)
    fiction = joker.load_fiction(if_file, ['discourse', 'items'],
                                 discourse_model.FICTION_DEFAULTS)
    presenter.center('fiction: ' + if_file, out_streams)
    world = world_model.World(fiction)
    world.set_concepts(fiction.concepts)
    for i in dir(fiction):
        if i[:8] == 'COMMAND_':            
            setattr(command_map, i.partition('_')[2], getattr(fiction, i))
Exemplo n.º 14
0
        latest = 0
    else:
        latest = max([int(log_file) for log_file in log_files])
    log_file = 'logs/' + str(latest + 1) + '.log'
    try:
        log = file(log_file, 'w')
    except IOError, err:
        msg = ('Unable to open log file "' + log_file + '" for ' +
               'writing due to this error: ' + str(err))
        raise joker.StartupError(msg)
    # So that we output to the screen and the log file:
    out_streams.streams.append(log)
    # And indicate that this stream is the log file:
    out_streams.log = log
    presenter.present(
        '\nLogged to: ' + log_file + '\nSession started ' +
        time.strftime("%Y-%m-%d %H:%M:%S"), out_streams)
    return out_streams


def initialize(if_file, spin_files, out_streams):
    'Load all files and present the header and prologue.'
    for startup_string in joker.session_startup(__version__):
        presenter.center(startup_string, out_streams)
    fiction = joker.load_fiction(if_file, ['discourse', 'items'],
                                 discourse_model.FICTION_DEFAULTS)
    presenter.center('fiction: ' + if_file, out_streams)
    world = world_model.World(fiction)
    world.set_concepts(fiction.concepts)
    for i in dir(fiction):
        if i[:8] == 'COMMAND_':
Exemplo n.º 15
0
                reply_text, discourse = self.teller(id_list, focal_concept, discourse)
                presenter.present(reply_text, out_streams)
            while world.running:
                previous_time = time.time()
                world, discourse = self.each_turn(world, discourse, in_stream,
                                             out_streams)
                out_streams.log.write('#' + str(time.time() - previous_time))

                for step in range(8):
                    self.display.show_frame()

        except joker.StartupError, err:
            presenter.present(err.msg, Multistream([sys.stderr]))
            return_code = 2
        except KeyboardInterrupt, err:
            presenter.present('\n', out_streams)
            return_code = 2
        except EOFError, err:
            presenter.present('\n', out_streams)
            return_code = 2
        finally:
            in_stream.close()
            out_streams.close()

        return return_code


if __name__ == '__main__':
    sys.exit(Main(sys.argv))