示例#1
0
def move_cheeses(n: int, i, source: int, intermediate1: int, intermediate2,
                 destination: int) -> None:
    """Print moves to get n cheeses from source to destination, possibly
    using intermediate"""
    if i > 1:
        if n > 1:
            move_cheeses(n - i, i, source, destination, intermediate1,intermediate2)
            move_cheeses(i-1, i, source, intermediate2, destination, intermediate1)
            move_cheeses(1, i, source, intermediate1, intermediate2, destination)
            move_cheeses(i-1, i, intermediate1, source, intermediate2, destination)
            move_cheeses(n -i, i, intermediate2, intermediate1, source, destination)
        else:
            print("Move top cheese from {} to {}".format(source, destination))
    else: # just one cheese --- no recursion required!
        print("Move top cheese from {} to {}".format(intermediate2, destination)


if __name__ == '__main__' :
       NUM_CHEESES = 8
       DELAY_BETWEEN_MOVES = .5
       CONSOLE_ANIMATE = False
       # DO NOT MODIFY THE CODE BELOW.
       four_stools = TOAHModel(4)    
       four_stools.fill_first_stool(number_of_cheeses=NUM_CHEESES)
    
        tour_of_four_stools(four_stools, console_animate=CONSOLE_ANIMATE, delay_btw_moves=DELAY_BETWEEN_MOVES)
    
        print(four_stools.number_of_moves())
def tour_of_four_stools(model: TOAHModel, delay_btw_moves: float=0.5, console_animate: bool=False):
    """Move a tower of cheeses from the first stool in model to the fourth.

       model - a TOAHModel with a tower of cheese on the first stool
                and three other empty stools
       console_animate - whether to animate the tour in the console
       delay_btw_moves - time delay between moves in seconds IF 
                         console_animate == True
                         no effect if console_animate == False
    """
    the_four_stools(model, model.number_of_cheeses(), 0, 1, 2, 3) # stool starts at 0 and ends at 3
    if console_animate == True:
	    x = model.get_move_seq()
	    z = x.length()
	    y = model.number_of_cheeses()
	    model = TOAHModel(4)
	    model.fill_first_stool(y)
	    index = 0
	    time.sleep(delay_btw_moves)
	    print(model)
	    while index < z:
		    time.sleep(delay_btw_moves)
		    m = x.get_move(index)
		    model.move(m[0],m[1])
		    time.sleep(delay_btw_moves)
		    print(model)
		    time.sleep(delay_btw_moves)
		    index += 1
示例#3
0
    def __init__(self: 'ConsoleController',
                 number_of_cheeses: int, number_of_stools: int):
        """
        Initialize a new 'ConsoleController'.

        number_of_cheeses - number of cheese to tower on the first stool
        number_of_stools - number of stools
        """
        model = TOAHModel(number_of_stools)
        model.fill_first_stool(number_of_cheeses)
        self._model = model
示例#4
0
    def __init__(self: 'ConsoleController', number_of_cheeses: int,
                 number_of_stools: int) -> None:
        """
        Initialize a new 'ConsoleController'.
        """

        TOAHModel.__init__(self, number_of_stools)
        TOAHModel.fill_first_stool(self, number_of_cheeses)
        self.cheese_model = TOAHModel(number_of_stools)
        self.number_of_stools = number_of_stools
        self.cheese_model.fill_first_stool(number_of_cheeses)
示例#5
0
def tour_of_four_stools(model: 'TOAHModel',
                        delay_btw_moves: float = 0.5,
                        console_animate: bool = False):
    """Move a tower of cheeses from the first stool in model to the fourth.

       model - a TOAHModel with a tower of cheese on the first stool
                and three other empty stools
       console_animate - whether to animate the tour in the console
       delay_btw_moves - time delay between moves in seconds IF 
                         console_animate == True
                         no effect if console_animate == False
    
    >>> m = TOAHModel(4)
    >>> m.fill_first_stool(8)
    >>> tour_of_four_stools(m)
    >>> m.get_move_seq().length()
    33
    """

    # Use helper function to solve the problem
    four_stool_move(
        model,
        model.number_of_cheeses(),
        SRC_INDEX,  # src_stool
        DEST_INDEX,  # dest_stool
        (TEMP0_INDEX, TEMP1_INDEX))  # temp_stools

    # If animation is requested
    if (console_animate):
        # Get the MoveSequence from model
        move_seq = model.get_move_seq()

        # Create and set up a new 4-stool TOAHModel to animate
        anim_model = TOAHModel(4)
        anim_model.fill_first_stool(model.number_of_cheeses())
        # Print the initial state of anim_model
        print(anim_model)

        # Go through each move in move_seq
        for i in range(move_seq.length()):
            # Get the source and destination stool indices
            (src_stool, dest_stool) = move_seq.get_move(i)

            # Delay the next move
            time.sleep(delay_btw_moves)

            # Apply the move
            anim_model.move(src_stool, dest_stool)

            # Print the result
            print(anim_model)

    return
示例#6
0
class ConsoleController:
    def __init__(self: 'ConsoleController', number_of_cheeses: int,
                 number_of_stools: int) -> None:
        """
        Initialize a new 'ConsoleController'.
        """

        TOAHModel.__init__(self, number_of_stools)
        TOAHModel.fill_first_stool(self, number_of_cheeses)
        self.cheese_model = TOAHModel(number_of_stools)
        self.number_of_stools = number_of_stools
        self.cheese_model.fill_first_stool(number_of_cheeses)

    def play_loop(self: 'ConsoleController') -> None:
        '''    
        Console-based game. 
        TODO:
        -Start by giving instructions about how to enter moves (which is up to
        you). Be sure to provide some way of exiting the game, and indicate
        that in the instructions.
        -Use python's built-in function input() to read a potential move from
        the user/player. You should print an error message if the input does
        not meet the specifications given in your instruction or if it denotes
        an invalid move (e.g. moving a cheese onto a smaller cheese).
        You can print error messages from this method and/or from
        ConsoleController.move; it's up to you.
        -After each valid move, use the method TOAHModel.__str__ that we've 
        provided to print a representation of the current state of the game.
        '''
        instructions = input("In order to make a move, you must insert the \
initial_stool number and the final_stool number seperated by a comma. If you \
wish to exit the game, input 'exit' and answer'yes'. Press enter to begin!")

        prompt = input('Your move (initial_stool, final_stool):')
        while prompt != 'exit':
            new_list = prompt.split(sep=',')
            move_list = []
            try:
                int(new_list[0]) or int(new_list[1])
            except ValueError:
                print('Invalid entry! Try again')
                prompt = input('Your move (initial_stool, final_stool):')

            move_list.append(int(new_list[0]))
            move_list.append(int(new_list[1]))
            move(self.cheese_model, move_list[0], move_list[1])
            print(self.cheese_model.__str__())
            prompt = input('Your move (initial_stool, final_stool):')

        else:
            exit()
示例#7
0
class ConsoleController:
    def __init__(self: 'ConsoleController', number_of_cheeses: int,
                 number_of_stools: int):
        """
        Initialize a new 'ConsoleController'.

        number_of_cheeses - number of cheese to tower on the first stool                            
        number_of_stools - number of stools
        """
        self.number_of_cheeses = number_of_cheeses
        self.number_of_stools = number_of_stools
        self.model = TOAHModel(number_of_stools)
        self.model.fill_first_stool(number_of_cheeses)

    def play_loop(self: 'ConsoleController'):
        '''    
        Console-based game. 
        TODO:
        -Start by giving instructions about how to enter moves (which is up to
        you). Be sure to provide some way of exiting the game, and indicate
        that in the instructions.
        -Use python's built-in function input() to read a potential move from
        the user/player. You should print an error message if the input does
        not meet the specifications given in your instruction or if it denotes
        an invalid move (e.g. moving a cheese onto a smaller cheese).
        You can print error messages from this method and/or from
        ConsoleController.move; it's up to you.
        -After each valid move, use the method TOAHModel.__str__ that we've 
        provided to print a representation of the current state of the game.
        '''
        print('')
        print(
            'Move the top cheese from the origin stool to the destination stool'
        )
        print(
            'by entering the number within the number of stools you have entered'
        )
        print(
            '(number between 0 to the number of stools you entered before minus one'
        )
        print('since the order of stools starts with 0)')
        print('')
        print(self.model)
        origin = int(input('Please enter the original stool: '))
        dest = int(input('Please enter the destination stool: '))
        move(self.model, origin, dest)
示例#8
0
class ConsoleController:
    def __init__(self: 'ConsoleController', number_of_cheeses: int,
                 number_of_stools: int):
        """
        Initialize a new 'ConsoleController'.

        number_of_cheeses - number of cheese to tower on the first stool                            
        number_of_stools - number of stools
        """
        self.number_of_stools = TOAHModel(number_of_stools)
        self.number_of_cheeses = \
            self.number_of_stools.fill_first_stool(number_of_cheeses)

    def play_loop(self: 'ConsoleController'):
        '''    
        Console-based game. 
        TODO:
        -Start by giving instructions about how to enter moves (which is up to
        you). Be sure to provide some way of exiting the game, and indicate
        that in the instructions.
        -Use python's built-in function input() to read a potential move from
        the user/player. You should print an error message if the input does
        not meet the specifications given in your instruction or if it denotes
        an invalid move (e.g. moving a cheese onto a smaller cheese).
        You can print error messages from this method and/or from
        ConsoleController.move; it's up to you.
        -After each valid move, use the method TOAHModel.__str__ that we've 
        provided to print a representation of the current state of the game.
        '''

        print('You will have a number of Cheeses stacked on each other in \
        order of size.\n')
        print('You also have a number of stools and the the goal of the game\
        is to get all the Cheeses from one stool to the final stool.\n')
        print('In the process of this you are not allowed to stack a Cheese\
        that is bigger than another.\n')

        user_string = ''
        while user_string != 'Exit Game':
            first_move = input('What is the orgin of the Cheese?:')
            second_move = input('What is the destination of the Cheese?:')

            try:
                self.number_of_stools.move(int(first_move), int(second_move))
            except IllegalMoveError:
                print('You made a mistake, please try again')
            except ValueError:
                print('You made a mistake, please change your input to an int')

            print(self.number_of_stools)
            print(self.number_of_cheeses)

            user_string = input('To exit, type Exit Game. Anything 2 continue')
 def play_loop(self: 'ConsoleController'):
     '''    
     Console-based game. 
     TODO:
     -Start by giving instructions about how to enter moves (which is up to
     you). Be sure to provide some way of exiting the game, and indicate
     that in the instructions.
     -Use python's built-in function input() to read a potential move from
     the user/player. You should print an error message if the input does
     not meet the specifications given in your instruction or if it denotes
     an invalid move (e.g. moving a cheese onto a smaller cheese).
     You can print error messages from this method and/or from
     ConsoleController.move; it's up to you.
     -After each valid move, use the method TOAHModel.__str__ that we've 
     provided to print a representation of the current state of the game.
     '''
     
     m = TOAHModel(self.number_of_stools)
     m.fill_first_stool(self.number_of_cheeses)        
     print("Then enter 2 integers sperated by a comma. first integer will be the stool to move the cheese from and second will be the stool the cheese has to be moved")
     print("Enter 'exit' to exit")
     
    
     s = input("Enter your move: ")
     while (s != "exit"):
         l=s.split(',')
         if len(l)==2:
             if not (l[0].isalpha() and l[1].isalpha()):
                 move(m, int(l[0]),(int(l[1]))) # ask ta
             else:
                 raise IllegalInputError("Not valid input")
             
         else:
             raise IllegalInputError("Not valid input") 
                 
         s=input("Enter the next move: ")
    print('=========================================================================')
    print("However, please choose how many cheeses you want on your stool: ")
    how_many_cheeses = input()
    if how_many_cheeses == 'Finish':
        print('Thanks for playing! ')
        sys.exit('You have chosen to exit the program. Bye!')
    
    while how_many_cheeses.isdigit() == False or int(how_many_cheeses) <= 0:
        print("Please enter a numeral value that is greater than 0")
        how_many_cheeses = input()
    try:
        how_many_cheeses = int(how_many_cheeses)
    except:
        print('Bad input, try again!')
        how_many_cheeses = int(input())

        
            
    c1 = ConsoleController(how_many_cheeses,4)
    m5 = TOAHModel(c1.number_of_stools)
    m5.fill_first_stool(c1.number_of_cheeses)
    c1.play_loop()
    print('======================================================================')
    print('Below are the moves you made:')
    print(m5.get_move_seq())
    x = m5.get_move_seq()
    print("Total moves made: "+str(x.length()))
    print("Play again soon!")
    print('======================================================================')

示例#11
0
    moves = MoveSequence([])
    four_stool_solution(moves, cheese_num, 0, 1, 2, 3)

    #Then we apply it to our existing model, animating with delay if
    #requested.
    if console_animate:
        for move in moves._moves:
            print(model)
            model.move(move[0], move[1])
            time.sleep(delay_btw_moves)
        print(model)
    else:
        for move in moves._moves:
            model.move(move[0], move[1])


if __name__ == '__main__':
    NUM_CHEESES = 25
    DELAY_BETWEEN_MOVES = .1
    CONSOLE_ANIMATE = True

    # DO NOT MODIFY THE CODE BELOW.
    four_stools = TOAHModel(4)
    four_stools.fill_first_stool(number_of_cheeses=NUM_CHEESES)

    tour_of_four_stools(four_stools,
                        console_animate=CONSOLE_ANIMATE,
                        delay_btw_moves=DELAY_BETWEEN_MOVES)

    print(four_stools.number_of_moves())
class ConsoleController:

    def __init__(self: 'ConsoleController',
                 number_of_cheeses: int, number_of_stools: int):
        """
        Initialize a new 'ConsoleController'.

        number_of_cheeses - number of cheese to tower on the first stool,
                            not counting the bottom cheese acting as stool
        number_of_stools - number of stools, to be shown as large cheeses
        """
        self._model = TOAHModel(number_of_stools)
        self._model.fill_first_stool(number_of_cheeses)

    def get_model(self):
        """ (ConsoleController) -> TOAHModel
        Return the TOAHModel of this game.
        """
        return self._model

    def play_loop(self: 'ConsoleController'):
        '''
        Console-based game.
        TODO:
        -Start by giving instructions about how to enter moves (which is up to
        you). Be sure to provide some way of exiting the game, and indicate
        that in the instructions.
        -Use python's built-in function input() to read a potential move from
        the user/player. You should print an error message if the input does
        not meet the specifications given in your instruction or if it denotes
        an invalid move (e.g. moving a cheese onto a smaller cheese).
        You can print error messages from this method and/or from
        ConsoleController.move; it's up to you.
        -After each valid move, use the method TOAHModel.__str__ that we've
        provded to print a representation of the current state of the game.
        '''
        print(self.get_model())
        print(INSTRUCTIONS)

        print(DASH_SEPARATOR)
        cmd = input("Please enter your command: ")
        while(cmd != "quit"):
            # parse the user input to get src and dest stool index
            # re-enter if InvalidInputError exception caught
            try:
                src, dest = _instruction_filter(cmd)
            except InvalidInputError:
                print("Invalid Input!\nPlease follow the instruction!")
                print(INSTRUCTIONS + "\n" + DASH_SEPARATOR)
                cmd = input("Please enter your command: ")
                continue

            # perform move operation, re-enter command if exception caught
            try:
                move(self.get_model(), src, dest)
            except IllegalMoveError:
                print("Illegal Move!\nPlease follow the instruction!")
                print(INSTRUCTIONS + "\n" + DASH_SEPARATOR)
                cmd = input("Please enter your command: ")
                continue

            print(self.get_model())
            print(DASH_SEPARATOR)

            # check if the game is ended
            if (self._winning_check()):
                print("Congratulation!")
                cmd = "quit"
            else:
                cmd = input("Please enter your command: ")

        print("Thank you for playing.")

    def _winning_check(self):
        """ (ConsoleController) -> bool
        Return True if all cheeses are moved to the last stool.
        This represents the game is ended.
        """
        last_stool = self.get_model().get_stool(-1)
        return len(last_stool) == self.get_model().number_of_cheeses()
    if number_of_cheeses == 'quit':
        print('Good Game!')

    else:
        # check if it's the right input!
        number_of_cheeses = input_checker(number_of_cheeses)
        print('How many stools?')
        number_of_stools = input()

        # if user wants to leave, let them!
        if number_of_stools == 'quit':
            print('Good Game!')

        else:

            number_of_stools = input_checker(number_of_stools)
            # Create a new CC object and initialize with user's inputs
            new_cc = ConsoleController(int(number_of_cheeses),
                                       int(number_of_stools))
            # Also create a new TOAHModel which will be modified
            new_model = TOAHModel(int(number_of_stools))
            # Fill the first stool so the game can be played
            new_model.fill_first_stool(int(number_of_cheeses))
            # Print a string representation so user can visually see which
            # he/she plays the game
            print(new_model)
            print(new_model.number_of_moves())
            # keep looping until user wants to exit by typing 'quit'
            new_cc.play_loop()
	    model = TOAHModel(4)
	    model.fill_first_stool(y)
	    index = 0
	    time.sleep(delay_btw_moves)
	    print(model)
	    while index < z:
		    time.sleep(delay_btw_moves)
		    m = x.get_move(index)
		    model.move(m[0],m[1])
		    time.sleep(delay_btw_moves)
		    print(model)
		    time.sleep(delay_btw_moves)
		    index += 1
		    


if __name__ == '__main__':
    NUM_CHEESES = 9
    DELAY_BETWEEN_MOVES = 0.5
    CONSOLE_ANIMATE = True
    
    # DO NOT MODIFY THE CODE BELOW.
    four_stools = TOAHModel(4)    
    four_stools.fill_first_stool(number_of_cheeses=NUM_CHEESES)
    
    tour_of_four_stools(four_stools, 
                        console_animate=CONSOLE_ANIMATE,
                        delay_btw_moves=DELAY_BETWEEN_MOVES)
    
    print(four_stools.number_of_moves())
示例#15
0
                        console_animate: bool = False):
    """Move a tower of cheeses from the first stool in model to the fourth.

       model - a TOAHModel with a tower of cheese on the first stool
                and three other empty stools
       console_animate - whether to use ConsoleController to animate the tour
       delay_btw_moves - time delay between moves in seconds IF
                         console_animate == True
                         no effect if console_animate == False
    """
    # Call helper functions to move the cheese
    # If console_animate is true, print each step
    if (console_animate is True):
        # Pass true in the parameter to print
        four_stool_hanoi(model, model.number_of_cheeses(), 0, 1, 2, 3, True)
    # Otherwise don't print it
    else:
        four_stool_hanoi(model, model.number_of_cheeses(), 0, 1, 2, 3, False)


if __name__ == '__main__':
    # DO NOT MODIFY THE CODE BELOW.
    four_stools = TOAHModel(4)
    four_stools.fill_first_stool(number_of_cheeses=5)

    tour_of_four_stools(four_stools,
                        console_animate=False,
                        delay_btw_moves=0.5)

    print(four_stools.number_of_moves())
示例#16
0
def tour_of_four_stools(model: TOAHModel,
                        delay_btw_moves: float = 0.5,
                        console_animate: bool = False) -> None:
    """Move a tower of cheeses from the first stool in model to the fourth.

       model - a TOAHModel with a tower of cheese on the first stool
                and three other empty stools
       console_animate - whether to animate the tour in the console
       delay_btw_moves - time delay between moves in seconds IF 
                         console_animate == True
                         no effect if console_animate == False
    """
    def move_three_stools(n: int, source: int, intermediate: int,
                          destination: int) -> None:
        """
        Print moves to get n cheeses from source to destination, possibly
        using intermediate
        """
        if n > 1:
            move_three_stools(n - 1, source, destination, intermediate)
            move_three_stools(1, source, intermediate, destination)
            move_three_stools(n - 1, intermediate, source, destination)
        else:
            model.move(source, destination)

    def move_four_stools(model: TOAHModel, n: int, source: int,
                         intermediate1: int, intermediate2: int,
                         destination: int) -> None:
        """
        Print moves to get n cheeses from source to destination, possibly
        using intermediates
        """
        def M(n) -> int:
            """
            return the minimum moves of moving n Cheeses on four stools
            >>> M(4)
            9
            """
            if n == 1:
                return 1
            else:
                moves = []
                for i in range(1, n):
                    moves.append(2 * M(n - i) + 2**i - 1)
                global mo
                mo = moves.copy()

            return min(moves)

        def find_i(n) -> int:
            """
            return the index of a in the global variable mo
            >>> find_i(9)
            1
            """
            return mo.index(n)

        def find(n):
            """
            return the index of M(n) in the global variable mo + 1
            since the index has a range from 1 to n(exclusive)
            >>>find(9)
            3
            """
            return find_i(M(n)) + 1

        if n > 1:
            move_four_stools(model, n - find(n), source, intermediate2,
                             destination, intermediate1)
            move_three_stools(find(n), source, intermediate2, destination)
            move_four_stools(model, n - find(n), intermediate1, source,
                             intermediate2, destination)
        else:
            model.move(source, destination)

    move_four_stools(model, NUM_CHEESES, 0, 1, 2, 3)
    model2 = TOAHModel(4)
    model2.fill_first_stool(NUM_CHEESES)
    print(model2)
    for moves in model.get_move_seq()._moves:
        if console_animate:
            time.sleep(delay_btw_moves)
            model2.move(moves[0], moves[1])
            print(model2)
class ConsoleController:
    """
    A console-based interface for controlling a TOAHModel
    """
    def __init__(self: 'ConsoleController', number_of_cheeses: int,
                 number_of_stools: int):
        """
        Initialize a new 'ConsoleController'.

        number_of_cheeses - number of cheese to tower on the first stool
        number_of_stools - number of stools
        """
        # Initialize dict for converting the user command strings
        # to their methods
        self._cmd_to_method = {
            "MOVE": self.move,
            "HELP": self.help,
            "QUIT": self.quit,
            "EXIT": self.quit
        }

        # Create a TOAHModel with the specified number of stools
        self._model = TOAHModel(number_of_stools)

        # Put the TOAHModel in the starting config with the number of cheeses
        self._model.fill_first_stool(number_of_cheeses)

        return

    def move(self, params: 'list of str' = []):
        """(ConsoleController, list of str) -> NoneType
        Move a cheese from one stool to another.
        The 0th element of params represents the index of the source stool.
        The 1th element of params represents the index
            of the destination stool.
        
        If the input is invalid, or the move is illegal, 
        print an error message to the screen
        """
        # This method handles errors related to the command parameters entered
        # by the user
        try:
            # Try to convert the first two params to
            # positive ints (zero allowed)
            (src_stool, dest_stool) = (str_to_pos_int(p, True)
                                       for p in (params[0], params[1]))
        except IndexError:
            # Less than two parameters were given
            print("Error: MOVE operation requires two parameters")
            return
        except ValueError:
            # The parameters are not valid non-negative ints
            print("Error: MOVE parameters must be non-negative integers")
            return

        # Perform the move using the module function
        # This should print any errors due to illegal moves
        move(self._model, src_stool, dest_stool)

        return

    def help(self, params: 'list of str' = None):
        """
        Print a list of recognized commands and their discriptions.
        Ignore the content of params.
        """

        help_str = ("Console controller commands:\n"
                    "(not case sensitive)\n"
                    "\n"
                    "MOVE n1 n2\n"
                    "   Move the top cheese from the stool labeled n1\n"
                    "   to the stool labeled n2.\n"
                    "   n1 and n2 must be non-negative integers.\n"
                    "   Example: MOVE 0 2\n"
                    "\n"
                    "HELP\n"
                    "   Show these instructions again\n"
                    "\n"
                    "QUIT or EXIT\n"
                    "   End this console controller session\n")

        print(help_str)
        return

    def quit(self, params: 'list of str' = None):
        """(ConsoleController, list of str) -> NoneType
        Raise EndGameException to tell play_loop to end the game.
        Ignore the content of params.
        """
        raise EndGameException

    def play_loop(self: 'ConsoleController'):
        '''    
        Console-based game. 
        TODO:
        -Start by giving instructions about how to enter moves (which is up to
        you). Be sure to provide some way of exiting the game, and indicate
        that in the instructions.
        -Use python's built-in function input() to read a potential move from
        the user/player. You should print an error message if the input does
        not meet the specifications given in your instruction or if it denotes
        an invalid move (e.g. moving a cheese onto a smaller cheese).
        You can print error messages from this method and/or from
        ConsoleController.move; it's up to you.
        -After each valid move, use the method TOAHModel.__str__ that we've 
        provided to print a representation of the current state of the game.
        '''

        # Print help at the start of the game
        self.help()

        # Keep looping until EndGameException is raised
        continue_game = True
        while (continue_game):

            # print the current state of the game
            print(self._model)

            # Ask user for input
            user_inp = input('ToAH> ')

            # Only need to do stuff if the user entered something
            if (user_inp):

                # Split user input into words
                user_inp = user_inp.split()
                # The 0th word is the command,
                # convert it to all caps for case-insensitivity
                cmd = user_inp[0].upper()
                # The rest of the words are parameters for the command methods
                params = user_inp[1:]

                try:
                    # Try to call the method corresponding to the user command
                    self._cmd_to_method[cmd](params)

                except KeyError:
                    # if the command is unrecognized,
                    # tell the user to try again
                    print("Command unrecognized: please try again\n"
                          "or type HELP for a list of recognized commands.")

                except EndGameException:
                    # if EndGameException is raised, end the game
                    continue_game = False

        return
示例#18
0
class ConsoleController:
    
    def __init__(self: 'ConsoleController', 
                 number_of_cheeses: int, number_of_stools: int):
        """
        Initialize a new 'ConsoleController'.

        number_of_cheeses - number of cheese to tower on the first stool                            
        number_of_stools - number of stools
        """
        self.number_of_cheeses = number_of_cheeses
        self.number_of_stools = number_of_stools
        self.model = TOAHModel(number_of_stools)
        self.cheeses = self.model.fill_first_stool(number_of_cheeses)
        self.play_loop()
                
    def play_loop(self: 'ConsoleController'):
        '''    
        Console-based game. 
        TODO:
        -Start by giving instructions about how to enter moves (which is up to
        you). Be sure to provide some way of exiting the game, and indicate
        that in the instructions.
        -Use python's built-in function input() to read a potential move from
        the user/player. You should print an error message if the input does
        not meet the specifications given in your instruction or if it denotes
        an invalid move (e.g. moving a cheese onto a smaller cheese).
        You can print error messages from this method and/or from
        ConsoleController.move; it's up to you.
        -After each valid move, use the method TOAHModel.__str__ that we've 
        provided to print a representation of the current state of the game.
        '''
        print ("Welcome to Towers Of Anne Hoy!")
        print ("Instructions: The stool numbers start from 0.")
        print ("Please enter the source stool when prompted.")
        print ("Source stool is the stool number to move the cheese from.")
        print ("Please enter the destination stool when prompted.")
        print ("Destination stool is the stool number to move the cheese to.")
        print ("Enter 'e' to exit.")
        print (" ")
        print (self.model)
        print (" ")
        print ("Let's start!")
        print (" ")

        while True: 
            try:
                if self.model.end_game_stool == self.model.stool_lst[-1]:
                    print ("GAME OVER!")
                    raise SystemExit
                self.play_loop
                origin_stool = input("Please enter the source stool: ")
                if origin_stool == 'e':
                    print ("***Thanks for playing!***")
                    raise SystemExit    
                dest_stool = input("Please enter the destination stool: ")
                if dest_stool == 'e':
                    print ("***Thanks for playing!***")
                    raise SystemExit 
                move(self.model, int(origin_stool), int(dest_stool))
                print (self.model)
                print ("Number of moves so far: "
                       +str(self.model.number_of_moves()))
                print (" ")
            except ValueError:
                print ("***Bad input***")
示例#19
0
class ConsoleController:

    def __init__(self: 'ConsoleController',
                 number_of_cheeses: int, number_of_stools: int):
        """
        Initialize a new 'ConsoleController'.

        number_of_cheeses - number of cheese to tower on the first stool,
                            not counting the bottom cheese acting as stool
        number_of_stools - number of stools, to be shown as large cheeses
        """
        # REPRESENTATION INVARIANT
        # self._number_of_cheeses is an integer which represents the number
        # of cheeses in the game
        # self._number_of_stools is an integer which represents the number
        # of stools in the game
        # self._model is a TOAHModel, which represents the game as a whole
        self._number_of_cheeses = number_of_cheeses
        self._number_of_stools = number_of_stools
        self._model = TOAHModel(self._number_of_stools)
        # Fill the first stool with the amount of cheese entered
        self._model.fill_first_stool(self._number_of_cheeses)

    def play_loop(self: 'ConsoleController'):
        '''
        (ConsoleController) -> NoneType
        Console-based game.
        TODO:
        -Start by giving instructions about how to enter moves (which is up to
        you). Be sure to provide some way of exiting the game, and indicate
        that in the instructions.
        -Use python's built-in function input() to read a potential move from
        the user/player. You should print an error message if the input does
        not meet the specifications given in your instruction or if it denotes
        an invalid move (e.g. moving a cheese onto a smaller cheese).
        You can print error messages from this method and/or from
        ConsoleController.move; it's up to you.
        -After each valid move, use the method TOAHModel.__str__ that we've
        provided to print a representation of the current state of the game.
        '''
        exit = False
        print("Welcome to the TOWER OF ANNE HOY")
        print("To get started, move the top cheese from the first stool.")
        print("To move a cheese from the first stool, enter '1'.")
        print("To move a cheese from the nth stool, enter 'n-1'")
        print("You may only stack smaller cheeses on top of eachother")
        print("To exit the game, type 'END' at any time.")
        # Create a while loop to await user input
        while(exit is False):
            # Get the stool index from the user to move the first cheese
            print("<Enter a stool index to move its' top cheese>")
            origin = input()
            # If the input was "END", then end the game
            if origin == "END":
                exit = True
            # Otherwise continue
            else:
                # Check if the user entered a valid stool index
                if (int(origin) < 0 or
                        int(origin) >= self._model.number_of_stools()):
                    raise IllegalMoveError("Given stool does not exist.")
                # Get the stool index for the destination of the cheese
                print ("<Enter a stool index to place the cheese on>")
                destination = input()
                # Again, check if the user wants to end
                if destination == "END":
                    exit = True
                # If not, then continue the game
                else:
                    # Check if the user entered a valid stool index
                    if (int(destination) < 0 or
                            int(
                            destination) >= self._model.number_of_stools()):
                        raise IllegalMoveError("Given stool does not exit.")
                    # Call the move method
                    move(self._model, int(origin), int(destination))
                    # Print the state of the game
                    print(self._model)
class ConsoleController:
    def __init__(self: 'ConsoleController', number_of_cheeses: int,
                 number_of_stools: int):
        """
        Initialize a new 'ConsoleController'.

        number_of_cheeses - number of cheese to tower on the first stool
        number_of_stools - number of stools
        """
        self.model = TOAHModel(number_of_stools)
        self.model.fill_first_stool(number_of_cheeses)
        self.has_seen_instructions = False

    def intro(self: 'ConsoleController') -> None:
        """
        Simply prints an introduction to the console.
        """
        print('--------------------------------------------------')
        print('|    Welcome to the Towers of Anne Hoi game!     |')
        print('|       Can you move all of the cheeses?         |')
        print("|Be careful though, you can't put a cheese on top|")
        print('|              of a smaller cheese.              |')
        print('|                   Good Luck!                   |')
        print('--------------------------------------------------')

    def display_instructions(self: 'ConsoleController'):
        """
        Prints instructions to the console.
        """
        print("Moves are entered in the following format:")
        print("'Location Stool' 'Destination Stool'")
        print("Separated by a space. ex. '1 2' moves the cheese")
        print("from the first stool to the second.")

    def process_query(self: "ConsoleController", query: str):
        """
        Takes an input, and applies the appropriate command.

        """
        #applies the move if it is indeed a move, or prints instructions
        #the only other valid command is exit which is accounted for in
        #play_loop
        if is_move(query):
            relocation = query.split()
            #I decided to make the first stool 1 instead of 0
            #since it seems more intuitive to a user who doesn't
            #program.
            location = int(relocation[0]) - 1
            destination = int(relocation[1]) - 1
            move(self.model, location, destination)
        elif query.lower() == 'i':
            self.has_seen_instructions = False

    def play_loop(self: 'ConsoleController'):
        '''
        Console-based game.
        TODO:
        -Start by giving instructions about how to enter moves (which is up to
        you). Be sure to provide some way of exiting the game, and indicate
        that in the instructions.
        -Use python's built-in function input() to read a potential move from
        the user/player. You should print an error message if the input does
        not meet the specifications given in your instruction or if it denotes
        an invalid move (e.g. moving a cheese onto a smaller cheese).
        You can print error messages from this method and/or from
        ConsoleController.move; it's up to you.
        -After each valid move, use the method TOAHModel.__str__ that we've
        provided to print a representation of the current state of the game.
        '''
        self.intro()
        query = ''
        print(self.model)

        while not query.lower() == 'e':
            #So that we only see the instructions when wanted
            if not self.has_seen_instructions:
                self.display_instructions()
                self.has_seen_instructions = True
            else:
                print(self.model)
            print("Type 'i' to see instructions again. 'e' to exit")
            query = input("Please enter a move:")
            self.process_query(query)
        print("Goodbye!")
示例#21
0
def tour_of_four_stools(model: TOAHModel, delay_btw_moves: float=0.5,
                        console_animate: bool=False):
    """Move a tower of cheeses from the first stool in model to the fourth.

       model - a TOAHModel with a tower of cheese on the first stool
                and three other empty stools
       console_animate - whether to use ConsoleController to animate the tour
       delay_btw_moves - time delay between moves in seconds IF
                         console_animate == True
                         no effect if console_animate == False
    """
    src = 0
    spare_1 = 1
    spare_2 = 2
    dest = 3
    num_cheeses = model.number_of_cheeses()

    rec_four_stools(model, num_cheeses, src, spare_1, spare_2, dest,
                    delay_btw_moves, console_animate)

if __name__ == '__main__':
    # DO NOT MODIFY THE CODE BELOW.
    model = TOAHModel(4)
    model.fill_first_stool(number_of_cheeses=8)

    tour_of_four_stools(model, console_animate=True, delay_btw_moves=0.5)
    print(model.number_of_moves())

    # some debug code below, don't forget to comment it #
    # print(model.get_move_seq().get_moves())