Пример #1
0
 def test_rule_variadic_translation(self):
     rule = Functor(':-', 2)
     and_ = Functor(',', 2)
     assert_equal(
         prefix_gdl_statement_to_prolog('(<= foo 1 2 3 4)'),
         rule(Term.from_atom_name('foo'),
              and_(Term.from_atom_name('1'),
                   and_(Term.from_atom_name('2'),
                        and_(Term.from_atom_name('3'),
                             Term.from_atom_name('4'))))))
Пример #2
0
    def check_parse_atoms(*atoms):
        terms = []
        for atom in atoms:
            term = Term.from_atom_name(atom)
            terms.append(term)
            TestPrefixGdlStatementToPrologAtom.check_parse_statement(
                term, atom)

        TestPrefixGdlStatementToPrologAtom.check_parse_statements(
            Term.from_list_terms(terms), '\n'.join(atoms))
Пример #3
0
    def apply_moves(self, moves):
        """A new game state representing the game after a move is applied.

        Returns a new state, this state is unchanged.

        Args:
            moves (dict) : Dict of `Role` => `Action`, one entry per role.

        Returns:
            GeneralGameState: The new game state.
        """
        with Frame() as f:
            game_id_term = self._game_id_term()

            moves_term = Term.from_list_terms([
                self._does_functor(Term.from_atom(role._atom),
                                   action._term_record.get())
                for (role, action) in moves.items()])

            # prepare_moves(game_id, moves_term, PreparedMoves)
            prepared_moves = f.term()
            try:
                self._prepare_moves_predicate(
                    game_id_term, moves_term, prepared_moves, check=True)
            except PrologCallFailed:
                raise ValueError(
                    'Invalid move set. Possibly not 1 move per role.')

            # NewMoveHistory = [PreparedMoves | old_move_history]
            new_move_history = Term.from_cons_list(prepared_moves,
                                                   self.move_history.get())

            # truth_history(game_id, NewMoveHistory, old_truth_history,
            #               NewTruthHistory)
            new_truth_history = f.term()
            try:
                self._truth_history_4_predicate(
                    game_id_term, new_move_history, self.truth_history.get(),
                    new_truth_history, check=True)
            except PrologCallFailed:
                raise ValueError('Invalid moves: {}'.format(
                    {str(role): str(action)
                     for role, action in moves.items()}))

            # final_truth_state(NewTruthHistory, NewTruthState)
            new_truth_state = f.term()
            self._final_truth_state_predicate(
                new_truth_history, new_truth_state, check=True)

            return GeneralGameState(
                game=self.game,
                move_history_term=new_move_history,
                truth_history_term=new_truth_history,
                truth_state_term=new_truth_state,
            )
Пример #4
0
    def utility(self, role):
        """The utility of the current state for the given role."""
        with Frame():
            utility = Term()
            utility_query = self._goal_functor(
                Term.from_atom(role._atom), utility)
            self._query_term(utility_query)(check=True)

            if utility.is_atom():
                return int(utility.get_atom_name())
            else:
                return int(utility)
Пример #5
0
    def roles(self):
        """An iterator of the game roles.

        Yields:
            Role: A game role.
        """
        with Frame():
            role_variable = Term()
            role_query_term = self._role_functor(role_variable)

            with self._stateless_query(role_query_term) as q:
                while q.next_solution():
                    yield Role._from_atom(role_variable.get_atom())
Пример #6
0
    def legal_actions(self, role):
        """An iterator of legal actions for role in the current state."""
        with Frame() as f:
            action = f.term()
            action_query = self._legal_functor(
                Term.from_atom(role._atom), action)

            query = self._query(action_query)
            for action_assignment in query.term_assignments(action,
                                                            persistent=True):
                yield Action._from_term_record(action_assignment)
Пример #7
0
    def create_game(self, game_id, game_description):
        """Create a game with the given game_id using the game description.

        Args:
            game_id (str)          : Game is created with this ID.
            game_description (str) : Game description given in Game Description
                Language (GDL).
        """
        with Frame():
            self._create_game_predicate(
                Term.from_atom_name(game_id),
                prefix_gdl_statements_to_prolog(game_description),
                check=True)
Пример #8
0
    def all_actions(self, role):
        """Iterator over all possible actions for `role` in this game.

        This does not represent the legal actions in some state.
        It is an iterator of all actions which may be available to role at some
        time in the game.

        Args:
            role (Role) : Get actions for this role.

        Yields:
            Action: A possible action for `role` in this game.
        """
        with Frame() as f:
            action_variable = f.term()
            input_query_term = self._input_functor(
                Term.from_atom(role._atom), action_variable)

            query = self._stateless_query(input_query_term)
            for action in query.term_assignments(action_variable,
                                                 persistent=True):
                yield Action._from_term_record(action)
Пример #9
0
    def __init__(self, game,
                 move_history_term=None,
                 truth_history_term=None,
                 truth_state_term=None):
        self.game = game

        with Frame():
            if move_history_term is None:
                move_history_term = Term.from_nil()
            self.move_history = TermRecord(move_history_term)

            if truth_history_term is None:
                truth_history_term = Term()
                self._truth_history_3_predicate(
                    self._game_id_term(), move_history_term,
                    truth_history_term, check=True)
            self.truth_history = TermRecord(truth_history_term)

            if truth_state_term is None:
                truth_state_term = Term()
                self._final_truth_state_predicate(
                    truth_history_term, truth_state_term, check=True)
            self.truth_state = TermRecord(truth_state_term)
Пример #10
0
 def test_compound_term_one_atom(self):
     assert_equal(prefix_gdl_statement_to_prolog('(foo arg)'),
                  Functor('foo', 1)(Term.from_atom_name('arg')))
Пример #11
0
 def _game_id_term(self):
     return Term.from_atom_name(self.game_id())
Пример #12
0
 def test_compound_term_nexted(self):
     assert_equal(
         prefix_gdl_statement_to_prolog('(foo (bar 1 2) (baz 3))'),
         Functor('foo', 2)(Functor('bar', 2)(Term.from_atom_name('1'),
                                             Term.from_atom_name('2')),
                           Functor('baz', 1)(Term.from_atom_name('3'))))
Пример #13
0
 def is_terminal(self):
     """True if the current game state is terminal."""
     with Frame():
         return self._query_term(Term.from_atom(self._terminal_atom))()
Пример #14
0
 def test_rule_symbol_translation(self):
     assert_equal(prefix_gdl_statement_to_prolog('(<= foo bar)'),
                  Functor(':-', 2)(Term.from_atom_name('foo'),
                                   Term.from_atom_name('bar')))
Пример #15
0
 def test_atom_term(self):
     assert_equal(prolog_term_to_prefix_gdl(Term.from_atom_name('foo')),
                  'foo')
Пример #16
0
 def _stateful_query(self, state, *queries):
     return Query.call_term(self.game_manager._game_state_term(
         Term.from_atom_name(self.game_id), state, *queries))
Пример #17
0
 def _stateless_query(self, *queries):
     return self._stateful_query(
         Term.from_atom(self._empty_game_state), *queries)
Пример #18
0
 def test_compound_term_mixed_atomic(self):
     term = prefix_gdl_statement_to_prolog('(foo arg1 ?arg2 arg3)')
     assert_equal(term.get_functor(), Functor('foo', 3))
     assert_equal(term.get_arg(0), Term.from_atom_name('arg1'))
     assert_true(term.get_arg(1).is_variable())
     assert_equal(term.get_arg(2), Term.from_atom_name('arg3'))
Пример #19
0
 def test_compound_term(self):
     assert_equal(prolog_term_to_prefix_gdl(
         Functor('foo', 2)(Term.from_atom_name('bar'),
                           Term.from_atom_name('2'))),
         '(foo bar 2)')
Пример #20
0
    prolog_term_to_prefix_gdl,
)

__all__ = [
    'GeneralGameManager',
    'GeneralGame',
    'GeneralGameState',
    'Role',
    'Action',
    'GameProposition',
]

logger = logging.getLogger(__name__)

# Read in game state rules
Functor('consult', 1)(Term.from_atom_name(
    os.path.join(prolog_dir, 'ggp_state.pl')))()


class GeneralGameManager(object):
    """Manage game descriptions using SWI-Prolog"""
    _ggp_state = Module(Atom('ggp_state'))
    _game_id_predicate = Predicate(functor=Functor(Atom('game_id'), 1),
                                   module=_ggp_state)
    _create_game_predicate = Predicate(functor=Functor(Atom('create_game'), 2),
                                       module=_ggp_state)
    _game_state_functor = Functor(Atom('game_state'), 3)
    _game_state_predicate = Predicate(functor=_game_state_functor,
                                      module=_ggp_state)
    _and_predicate = Predicate.from_name_arity(',', 2)

    def __init__(self):