Ejemplo n.º 1
0
 def test_alphabetical(self):
     word_ladder = WordLadderPuzzle('mare', 'mire')
     # Should have 4 extensions: 'care', 'male', 'mars', 'mire',
     # in that order.
     exts = word_ladder.extensions()
     self.assertEqual(len(exts), 4)
     self.assertTrue(exts[-1].is_solved())
Ejemplo n.º 2
0
def test_word_ladder_eq_doctest() -> None:
    """Test WordLadder.__eq__ on the provided doctest"""
    wl1 = WordLadderPuzzle("me", "my", {"me", "my", "ma"})
    wl2 = WordLadderPuzzle("me", "my", {"me", "my", "mu"})
    wl3 = WordLadderPuzzle("me", "my", {"ma", "me", "my"})
    assert wl1.__eq__(wl2) is False
    assert wl1.__eq__(wl3) is True
Ejemplo n.º 3
0
 def test_alphabetical(self):
     word_ladder = WordLadderPuzzle('mare', 'mire')
     # Should have 4 extensions: 'care', 'male', 'mars', 'mire',
     # in that order.
     exts = word_ladder.extensions()
     self.assertEqual(len(exts), 4)
     self.assertTrue(exts[-1].is_solved())
Ejemplo n.º 4
0
 def test_no_duplicates(self):
     word_ladder = WordLadderPuzzle('mare', 'mire')
     exts = word_ladder.extensions()
     should_be_care = exts[0]
     # Only one extension: 'cars'. 'mare' should not be revisited.
     self.assertEqual(len(should_be_care.extensions()), 1)
     should_be_cars = should_be_care.extensions()[0]
     # 'cars' should extend to 'mars'.
     self.assertEqual(len(should_be_cars.extensions()), 1)
     should_be_mars = should_be_cars.extensions()[0]
     # 'mars' has no more extensions.
     self.assertEqual(len(should_be_mars.extensions()), 0)
Ejemplo n.º 5
0
 def test_no_duplicates(self):
     word_ladder = WordLadderPuzzle('mare', 'mire')
     exts = word_ladder.extensions()
     should_be_care = exts[0]
     # Only one extension: 'cars'. 'mare' should not be revisited.
     self.assertEqual(len(should_be_care.extensions()), 1)
     should_be_cars = should_be_care.extensions()[0]
     # 'cars' should extend to 'mars'.
     self.assertEqual(len(should_be_cars.extensions()), 1)
     should_be_mars = should_be_cars.extensions()[0]
     # 'mars' has no more extensions.
     self.assertEqual(len(should_be_mars.extensions()), 0)
Ejemplo n.º 6
0
def main():
    """Prompt the user to configure and play the game.

    @rtype: None
    """
    game = input("Do you want to play Sudoku (s) or Word Ladder (w)? ")
    while game != "s" and game != "w":
        print("That is not a valid input.")
        game = input(
            "Do you want to play Sudoku (s) or Word Ladder (w)? ").lower()

    if game == "s":
        view_type = "text"
        g = SudokuPuzzle([['', '', '', 'A'], ['D', '', 'B', ''],
                          ['C', '', '', ''], ['', 'B', '', 'D']])
        print(
            "\n\nTo make a move: use the format (<row>, <column>) -> letter.")
    elif game == "w":
        view_type = input(
            "Would you like to play in text mode or web mode? ").lower()
        if view_type != "web" and view_type != "text":
            print(
                "That is not a valid mode, you will be playing in text mode.")
            view_type = "text"
        choice = input(
            "Do you want to choose your start and end words? (y/n) ")
        if choice == "y":
            print(
                "Your starting and ending words should have the same length.")
            start = input("What would you like your starting word to be? ")
            end = input("What would you like your ending word to be? ")
            while len(start) != len(end):
                print(
                    "Your starting and ending words don't have the same length. Please try again."
                )
                start = input("What would you like your starting word to be? ")
                end = input("What would you like your ending word to be? ")
        else:
            start = "rock"
            end = "taco"
        g = WordLadderPuzzle(start, end)
        print(
            "\n\nTo make a move, type a word which does not differ by more than one letter from the current word."
        )

    if view_type == "text":
        print("To quit the game, type exit.")
        print("To ask for a solution, type :SOLVE.")
        print("To ask for a hint, type :HINT.")
        print("To undo a move, type :UNDO.")
        print(
            "To look at your past moves from this current game state, type :ATTEMPTS.\n"
        )

    c = Controller(g, mode=view_type)
Ejemplo n.º 7
0
def play_word_ladder(puz: WordLadderPuzzle) -> None:
    """
    Simple text UI to play a given word ladder plus puzzle
    """
    print("Controls:\n" "q to quit\n" "HINT for hint\n" "Good luck!\n")
    while not puz.is_solved():
        next_word = input(f"{puz}\ntype your next word: ")
        if next_word == "q":
            return
        elif next_word == "HINT":
            puz = BfsSolver().solve(puz)[1]
        else:
            next_puzzle = WordLadderPuzzle(next_word, puz.to_word,
                                           puz.word_set)
            if next_puzzle in puz.extensions():
                puz = next_puzzle
            else:
                print("invalid move, keep trying!\n"
                      "q to quit\n"
                      "HINT for hint\n")
    print("SOLVED!")
Ejemplo n.º 8
0
def test_word_ladder_get_difficulty() -> None:
    """Test WordLadder.get_difficulty on TRIVIAL and EASY puzzles."""
    wl1 = WordLadderPuzzle("done", "done", {"done"})
    assert wl1.get_difficulty() == TRIVIAL

    wl2 = WordLadderPuzzle("come", "done", {"come", "cone", "done"})
    assert wl2.get_difficulty() == EASY
Ejemplo n.º 9
0
def make_word_ladder(difficulty: str = 'easy',
                     target_word: str = 'cost',
                     word_set: Optional[Set[str]] = None) -> \
        Optional[WordLadderPuzzle]:
    """
    Return a random WordLadderPlusPuzzle with the specified <difficulty> or None
    if there is no such puzzle.

    <difficulty> is one of 'easy' (default), 'medium', 'hard'.

    The other parameters are:

    <target_word> (default 'cost') - the word to use as the to_word

    <word_set> (default None) - the words to use in the WordLadderPuzzle
        (if None, uses load_words to use words from a file)

    The from_word is drawn randomly from word_set. Different from_words
    should be tried until either they have all been tried or a puzzle with
    the correct difficulty was found.

    Note: this is a rather inefficient way to do this
    (once you finish the assignment, you can try writing a
     smarter puzzle maker!)

    """
    if word_set is None:
        word_set = load_words()
    my_words = list(word_set)
    shuffle(my_words)  # try random from_words to make a puzzle
    for from_word in my_words:
        if len(from_word) == len(target_word):
            puz = WordLadderPuzzle(from_word, target_word, word_set)
            if puz.get_difficulty() == difficulty:
                return puz
    return None
Ejemplo n.º 10
0
def test_word_ladder_extensions_doctest() -> None:
    """Test WordLadder.__str__ on the provided doctest"""
    wl1 = WordLadderPuzzle("me", "my", {"me", "be", "my"})
    wl2 = WordLadderPuzzle("be", "my", {"me", "be", "my"})
    wl3 = WordLadderPuzzle("my", "my", {"me", "be", "my"})

    msg1 = f"{wl1.extensions()} is missing some valid puzzle states"
    msg2 = f"{wl1.extensions()} contains extra invalid puzzle states"

    assert all([wlp in wl1.extensions() for wlp in [wl2, wl3]]), msg1
    assert all([wlp in [wl2, wl3] for wlp in wl1.extensions()]), msg2
Ejemplo n.º 11
0
 def test_invalid_word2(self):
     word_ladder = WordLadderPuzzle('mare', 'mire')
     with self.assertRaises(ValueError):
         # In dictionary, but not one letter away.
         word_ladder.move('cars')
Ejemplo n.º 12
0
 def test_move_simple(self):
     word_ladder = WordLadderPuzzle('mare', 'mire')
     new_ladder = word_ladder.move('mire')
     self.assertTrue(new_ladder.is_solved())
Ejemplo n.º 13
0
 def test_invalid_word1(self):
     word_ladder = WordLadderPuzzle('mare', 'mire')
     with self.assertRaises(ValueError):
         # Not in dictionary
         word_ladder.move('maze')
Ejemplo n.º 14
0
 def test_solved_extension(self):
     word_ladder = WordLadderPuzzle('mire', 'mare')
     self.assertTrue(word_ladder.extensions()[0].is_solved())
Ejemplo n.º 15
0
                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


if __name__ == '__main__':
    from sudoku_puzzle import SudokuPuzzle

    s = SudokuPuzzle([['', '', '', ''], ['', '', '', ''], ['C', 'D', 'A', 'B'],
                      ['A', 'B', 'C', 'D']])

    # c1 = Controller(s)

    from word_ladder_puzzle import WordLadderPuzzle
    w = WordLadderPuzzle("make", "cure")

    c2 = Controller(w)
Ejemplo n.º 16
0
 def test_is_solved_start(self):
     word_ladder = WordLadderPuzzle('mist', 'mist')
     self.assertTrue(word_ladder.is_solved())
Ejemplo n.º 17
0
 def test_invalid_word2(self):
     word_ladder = WordLadderPuzzle('mare', 'mire')
     with self.assertRaises(ValueError):
         # In dictionary, but not one letter away.
         word_ladder.move('cars')
Ejemplo n.º 18
0
            ':UNDO',
            ':ATTEMPTS',
            ':UNDO',
            ':UNDO',
            ':ATTEMPTS',
            ':SOLVE'
        ],
        # If you omit the following filename,
        # the output will be printed to the console.
        # Otherwise, after you run the program, open
        # the new file to see the output.
        'solved.txt')

    run_controller(s, [':HINT1', 'exit'])

    s = WordLadderPuzzle('mare', 'cars')

    run_controller(s, [
        'mare', ':ATTEMPTS', ':HINT 10', 'mire', ':UNDO', 'male', ':UNDO',
        ':ATTEMPTS', 'mars', 'cars'
    ])

    s = WordLadderPuzzle('mars', 'mist')

    run_controller(s, [
        'mare', 'cars', ':HINT 10', ':UNDO', ':UNDO', 'mire', ':UNDO',
        ':ATTEMPTS', ':SOLVE'
    ])

    s = SudokuPuzzle([['A', 'B', 'C', 'D'], ['', '', '', ''], ['', '', '', ''],
                      ['', '', '', '']])
Ejemplo n.º 19
0
def test_word_ladder_str_doctest() -> None:
    """Test WordLadder.__str__ on the provided doctest"""
    wl1 = WordLadderPuzzle("me", "my", {"me", "my", "ma"})
    wl2 = WordLadderPuzzle("me", "my", {"me", "my", "mu"})
    assert str(wl1) == 'me -> my'
    assert str(wl2) == 'me -> my'
Ejemplo n.º 20
0
 def test_move_simple(self):
     word_ladder = WordLadderPuzzle('mare', 'mire')
     new_ladder = word_ladder.move('mire')
     self.assertTrue(new_ladder.is_solved())
Ejemplo n.º 21
0
            # 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())


if __name__ == '__main__':
    from sudoku_puzzle import SudokuPuzzle
    s = SudokuPuzzle([['', '', '', ''], ['', '', '', ''], ['C', 'D', 'A', 'B'],
                      ['A', 'B', 'C', 'D']])
    c = Controller(s)

    from word_ladder_puzzle import WordLadderPuzzle
    s = WordLadderPuzzle('ye', 'ac')
    c = Controller(s)
Ejemplo n.º 22
0
 def test_solved_extension(self):
     word_ladder = WordLadderPuzzle('mire', 'mare')
     self.assertTrue(word_ladder.extensions()[0].is_solved())
Ejemplo n.º 23
0
 def test_one_extensions(self):
     word_ladder = WordLadderPuzzle('mire', 'mare')
     self.assertEqual(len(word_ladder.extensions()), 1)
Ejemplo n.º 24
0
 def test_no_extensions(self):
     word_ladder = WordLadderPuzzle('mist', 'mare')
     self.assertEqual(word_ladder.extensions(), [])
Ejemplo n.º 25
0
 def test_is_not_solved_start(self):
     word_ladder = WordLadderPuzzle('mist', 'mare')
     self.assertFalse(word_ladder.is_solved())
Ejemplo n.º 26
0
def test_word_ladder_is_solved_doctest() -> None:
    """Test WordLadder.is_solved on the provided doctest"""
    wl1 = WordLadderPuzzle("me", "me", {"me", "my"})
    wl2 = WordLadderPuzzle("me", "my", {"me", "my"})
    assert wl1.is_solved() is True
    assert wl2.is_solved() is False
Ejemplo n.º 27
0
 def test_is_solved_start(self):
     word_ladder = WordLadderPuzzle('mist', 'mist')
     self.assertTrue(word_ladder.is_solved())
Ejemplo n.º 28
0
 def test_is_not_solved_start(self):
     word_ladder = WordLadderPuzzle('mist', 'mare')
     self.assertFalse(word_ladder.is_solved())
Ejemplo n.º 29
0
 def test_no_extensions(self):
     word_ladder = WordLadderPuzzle('mist', 'mare')
     self.assertEqual(word_ladder.extensions(), [])
Ejemplo n.º 30
0
 def test_one_extensions(self):
     word_ladder = WordLadderPuzzle('mire', 'mare')
     self.assertEqual(len(word_ladder.extensions()), 1)
Ejemplo n.º 31
0
        return "Already at a solution!"
    elif n == 1:
        if moves is []:
            return "No possible extensions!"
        else:
            for result in moves:
                if result.is_solved():
                    return True

            return moves[0]
    else:
        for i in moves:
            x = hint_by_depth(i, n-1)
            if x:
                return i
            elif x == i:
                return i





if __name__ == '__main__':
    from word_ladder_puzzle import WordLadderPuzzle
    from sudoku_puzzle import SudokuPuzzle


    s = WordLadderPuzzle("mare","mist")
    for i in s.extensions():
        print(i)
Ejemplo n.º 32
0
 def test_invalid_word1(self):
     word_ladder = WordLadderPuzzle('mare', 'mire')
     with self.assertRaises(ValueError):
         # Not in dictionary
         word_ladder.move('maze')