Пример #1
0
    def act(self, action):
        """Run an action represented by string <action>.

        Return a string representing either the new state or an error message,
        and whether the program should end.

        @type self: Controller
        @type action: str
        @rtype: (str, bool)
        """
        # TODO: Add to this method to handle different actions.
        if action == 'exit':
            return '', True
        elif action == "solve":
            return str(solve(self._puzzle)),True
        elif action == "solve-all":
            solution = solve_complete(self._puzzle)
            solution = list(map(lambda x: str(x), solution))
            return "\n".join(solution),True
        elif "hint" in action:
            if action[5].isdigit() and int(action[5]) >= 1:
                return str(hint_by_depth(self._puzzle,int(action[5]))),False
            else:
                return "Please enter input again!"
        elif self._puzzle.check(action) == ValueError:
            return "Incorrect input", False
        elif self._puzzle.check(action):
            return self._puzzle.move(action), True
        else:
            return self.state(), False
Пример #2
0
 def test_hint_can_reach_solution(self):
     s = SudokuPuzzle([['A', 'B', 'C', 'D'],
                       ['C', 'D', '', 'B'],
                       ['B', 'A', 'D', 'C'],
                       ['D', 'C', 'B', 'A']])
     for p in s.extensions():
         print(p)
     self.assertEqual(hint_by_depth(s, 10), '(1, 2) -> A')
Пример #3
0
 def test_hint_valid_state(self):
     s = SudokuPuzzle([['', 'B', 'C', 'D'],
                       ['C', 'D', '', 'B'],
                       ['B', '', 'D', 'C'],
                       ['D', 'C', 'B', '']])
     self.assertTrue(hint_by_depth(s, 3) in ['(0, 0) -> A',
                                             '(1, 2) -> A',
                                             '(2, 1) -> A',
                                             '(3, 3) -> A'])
Пример #4
0
    def act(self, action):
        """Run an action represented by string <action>.

        Return a string representing either the new state or an error message,
        and whether the program should end.

        @type self: Controller
        @type action: str
        @rtype: (str, bool)
        """
        if action == ':EXIT':
            return ('', True)
        elif action == ':SOLVE':
            return (solve(self._puzzle), True)
        elif action == ':SOLVE-ALL':
            return (solve_complete(self._puzzle), True)
        elif list(action)[0] == '(' and list(action)[-6:-1] == list(') -> '):
            newp = self._puzzle.move(action)
            self._tree.put_item((newp, action), self._puzzle)
            self._puzzle = newp
            return (newp, newp.is_solved())
        elif [x for x in list(abc) if x in list(action)]:
            newp = self._puzzle.move(action)
            self._tree.put_item((newp, action), self._puzzle)
            self._puzzle = newp
            return (newp, newp.is_solved())
        elif action == ':UNDO':
            parent = self._tree.find_par(self._puzzle)
            if parent != None:
                self._puzzle = parent.root[0]
            else:
                print("The previous state does not exist.")
            return (self._puzzle, self._puzzle.is_solved())
        elif action == ':ATTEMPTS':
            lst = self._tree.node_list()
            for i in range(len(lst)):
                if i != 0:
                    print(i.root[1])
                    print('----------------')
                    print(i.root[0])
            return (self.state(), False)
        elif list(action)[:5] == list(':HINT'):
            num = ''
            for i in range(len(list(action)) - 6):
                num += action[6 + i]
            x = hint_by_depth(self._puzzle, int(num))
            if x == 'No possible extensions!' or x == 'Already at a solution!':
                print(x)
                return (self.state(), False)
            return (x, self._puzzle.is_solved())
        else:
            return (self.state(), False)
Пример #5
0
    def _act_hint(self):
        """Returns a hint that will either solve the puzzle, or if the the puzzle leads to no more moves, return
        'No possible extensions!'. If the puzzle is already solved, return 'Already at a solution!'. Also, tells the
        program not to end.

        @type self: Controller
        @rtype: (str, bool)
        """
        if type(self._puzzle) == WordLadderPuzzle:
            hint = hint_by_breadth(self._puzzle)
        else:
            hint = hint_by_depth(self._puzzle)

        return 'Try entering: ' + hint, False
Пример #6
0
    def _hint(self, action):
        """Returns a hint based on the players action

        Precondition: action must be in the following format: ':HINT n'
         where n is an integer.

        @type self: Controller
        @type action: str
        @rtype: str
        """
        try:
            number = action[6:]
            number = int(number)
        except ValueError:
            return "That is not a proper value. Try again."

        return hint_by_depth(self._puzzle, number)
Пример #7
0
    def to_hint(self, action):
        """ To give hint of the puzzle at current state.

        @type action: str
        @rtype: tuple
        """
        typed = action.split()
        if len(typed) == 2:
            try:
                n = int(typed[1])
            except ValueError:
                message = 'Please type the number of moves!'
                return (message, False)
            if n < 1:
                message = 'Please type a positive number!'
                return (message, False)
            else:
                hint = hint_by_depth(self._puzzle, n)
                return (hint, False)
        else:
            message = 'Please type the number of moves!'
            return (message, False)
Пример #8
0
 def test_hint_no_possible_extensions(self):
     s = SudokuPuzzle([['A', 'B', 'C', 'D'],
                       ['C', 'D', '', 'B'],
                       ['B', 'A', 'D', 'C'],
                       ['C', '', 'A', 'A']])
     self.assertEqual(hint_by_depth(s, 10), 'No possible extensions!')
Пример #9
0
 def test_hint_already_solved(self):
     s = SudokuPuzzle([['A', 'B', 'C', 'D'],
                       ['C', 'D', 'A', 'B'],
                       ['B', 'A', 'D', 'C'],
                       ['D', 'C', 'B', 'A']])
     self.assertEqual(hint_by_depth(s, 10), 'Already at a solution!')
Пример #10
0
 def test_hint_valid_state(self):
     s = SudokuPuzzle([['', 'B', 'C', 'D'], ['C', 'D', '', 'B'],
                       ['B', '', 'D', 'C'], ['D', 'C', 'B', '']])
     self.assertTrue(
         hint_by_depth(s, 3) in
         ['(0, 0) -> A', '(1, 2) -> A', '(2, 1) -> A', '(3, 3) -> A'])
Пример #11
0
 def test_hint_can_reach_solution(self):
     s = SudokuPuzzle([['A', 'B', 'C', 'D'], ['C', 'D', '', 'B'],
                       ['B', 'A', 'D', 'C'], ['D', 'C', 'B', 'A']])
     for p in s.extensions():
         print(p)
     self.assertEqual(hint_by_depth(s, 10), '(1, 2) -> A')
Пример #12
0
 def test_hint_no_possible_extensions(self):
     s = SudokuPuzzle([['A', 'B', 'C', 'D'], ['C', 'D', '', 'B'],
                       ['B', 'A', 'D', 'C'], ['C', '', 'A', 'A']])
     self.assertEqual(hint_by_depth(s, 10), 'No possible extensions!')
Пример #13
0
 def test_hint_already_solved(self):
     s = SudokuPuzzle([['A', 'B', 'C', 'D'], ['C', 'D', 'A', 'B'],
                       ['B', 'A', 'D', 'C'], ['D', 'C', 'B', 'A']])
     self.assertEqual(hint_by_depth(s, 10), 'Already at a solution!')
Пример #14
0
    def act(self, action):
        """Run an action represented by string <action>.

        Return a string representing either the new state or an error message,
        and whether the program should end.

        @type self: Controller
        @type action: str
        @rtype: (str, bool)
        """
        # : Add to this method to handle different actions.
        if action == 'exit':
            return '', True

        elif action == ":SOLVE":
            solution = solve(self._puzzle)
            if solution is None:
                return "There is no solution for this Puzzle!", True
            else:
                return str(solution), True

        elif action == ":SOLVE-ALL":
            solutions = solve_complete(self._puzzle)
            if len(solutions) == 0:
                return "There are no solutions for this Puzzle!", True
            else:
                values = [str(solution) for solution in solutions]
                return "\n".join(values), True

        elif action == ":UNDO":
            value = self._tree.undo()
            if value is None:
                print("There is no previous state.")
            else:
                self._puzzle = value
            return str(self._puzzle), self._puzzle.is_solved()

        elif action == ":ATTEMPTS":
            self._tree.attempts()
            return str(self._puzzle), self._puzzle.is_solved()

        elif len(action) > 5 and action[0:6] == ":HINT ":
            n = action[6:]
            try:
                n = int(n)
                print(hint_by_depth(self._puzzle, n))
                print()
                return str(self._puzzle), self._puzzle.is_solved()
            except:
                return "Invalid action, please try again.", False

        else:
            # Parse the action to the puzzle and make the move
            try:
                value = self._puzzle.move(action)
                self._puzzle = value
                # add the state into the tree
                self._tree.act(action, self._puzzle)
                #
                return str(value), value.is_solved()
            except:
                return "Invalid action, please try again.", False
Пример #15
0
 def test_hint_can_reach_solution(self):
     s = SudokuPuzzle([['A', 'B', 'C', 'D'],
                       ['C', 'D', '', 'B'],
                       ['B', 'A', 'D', 'C'],
                       ['D', 'C', 'B', 'A']])
     self.assertEqual(hint_by_depth(s, 2), '(1, 2) -> A')
Пример #16
0
    def act(self, action):
        """Run an action represented by string <action>.

        Return a string representing either the new state or an error message,
        and whether the program should end.

        @type self: Controller
        @type action: str
        @rtype: (str, bool)
        """
        # TODO: Add to this method to handle different actions.

        # if the action command is 'EXIT'
        if action == ':EXIT':
            # return empty string and the program should end
            return ('', True)
        # else if the action command is 'SOLVE'
        elif action == ':SOLVE':
            # solve the puzzle
            state = solve(self._puzzle)
            # if the state exists
            if state:
                # return the solution, and the program should end
                return (str(state), True)
            # otherwise return the error message, the program should end
            return ('Failed to solve from this point!', True)
        # else if the action command is 'SOLVE-ALL'
        elif action == ':SOLVE-ALL':
            # get the all possible solution
            states = solve_complete(self._puzzle)
            # if the states exist
            if states:
                # return the all solutions in the correct format, and the
                # program should end
                return ('\n'.join(map(str, states)), True)
            # otherwise return the error message, and program should end
            return ('Failed to solve from this point!', True)
        # else if the action command let the program give hint
        elif action.startswith(':HINT'):
            # split the action command to the list of parts
            parts = action.split(' ')
            # if the length of parts are 2
            if len(parts) != 2:
                # return the error message for action, the program should
                # not end
                return ('Incorrect action format for hints!', False)
            # try the following firstly
            try:
                # get the index 1 of parts
                n = int(parts[1])
            # else raise value error
            except ValueError:
                # return the error message for action, the program
                # should not end
                return ('Incorrect action format for hints!', False)
            # if the n is less than 1
            if n < 1:
                # return the error message for action, the program should
                # not end
                return ('Incorrect action format for hints!', False)
            # otherwise get the hint by calling hint by depth function,
            # the program should not end
            return (hint_by_depth(self._puzzle, n), False)
        # if the action command is 'UNDO'
        elif action == ':UNDO':
            # return the string of the new current state and the current
            # state of puzzle
            result, self._puzzle = self._movetree.undo()
            # return the string of new current state and the program should
            # not end
            return (result, False)
        # else if the action command is 'ATTEMPTS'
        elif action == ':ATTEMPTS':
            # return the all resulting from the user made at the current state
            # and the program should not end
            return (self._movetree.attempts(), False)
        # if the action command is ':'
        elif action == ':':
            # return the current state of puzzle, and the program should
            # not end
            return (self.state(), False)
        # otherwise
        else:
            # try following
            try:
                # get the current state of puzzleafter given move
                state = self._puzzle.move(action)
            # else the value error
            except ValueError as e:
                # return the string of e, and the program should not end
                return (str(e), False)
            # update the puzzle after move
            self._puzzle = state
            # get the puzzle state by finding the node of move from tree
            self._movetree.do(state, action)
            # return the current puzzle state
            # and check whether it has been solved
            return (self.state(), state.is_solved())