コード例 #1
0
    def play_loop(self):
        """ Play Console-based game.

        @param ConsoleController self:
        @rtype: None

        """
        # moves should be in the form of two int, like 0 1
        # there is a whitespace between them
        # where 0 is the index of source stool
        # and 1 is the index of destination stool
        # type 'want to exit' to exit the game

        m = TOAHModel(self.number_of_stools)
        m.fill_first_stool(self.number_of_cheeses)
        move_ = input('please enter your move')
        while move_ != 'want to exit':
            try:
                move(m, int(move_[0]), int(move_[2]))
                print(m)
                move_ = input('please enter your move')
            except IllegalMoveError as e:
                print(e)
                move_ = input('please enter your move')
            except IndexError:
                print('Invalid input!')
                move_ = input('please enter your move')
            except ValueError:
                print('invalid input!')
                move_ = input('please enter your move')
コード例 #2
0
 def setUp(self):
     self.toah = TOAHModel(4)
     self.optimals = [
         0, 1, 3, 5, 9, 13, 17, 25, 33, 41, 49, 65, 81, 97, 113, 129, 161,
         193, 225, 257, 289, 321, 385, 449, 513, 577, 641, 705, 769, 897,
         1025, 1153, 1281, 1409, 1537, 1665, 1793, 2049, 2305, 2561, 2817,
         3073, 3329, 3585, 3841, 4097, 4609, 5121, 5633
     ]
コード例 #3
0
class ConsoleController:
    """ Controller for text console.
    """
    def __init__(self, number_of_cheeses, number_of_stools):
        """ Initialize a new ConsoleController self.

        @param ConsoleController self:
        @param int number_of_cheeses:
        @param int number_of_stools:
        @rtype: None
        """
        self.model = TOAHModel(number_of_stools)
        self.model.fill_first_stool(number_of_cheeses)

    def play_loop(self):
        """ Play Console-based game.

        @param ConsoleController self:
        @rtype: None

        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.
        """
        ex = False
        print("ok hit e to exit and m to move")
        while ex == False:

            I = input("so whatcha gonna do ")
            try:
                if I == "e":
                    print("GG")
                    ex = True
                    print(self.model)
                elif I == "m":
                    o = int(input("which cheese block you movin? "))
                    if o not in range(len(self.model.stools)):
                        raise FalseMoveError()
                    d = int(input("where you movin it to? "))
                    if d not in range(len(self.model.stools)):
                        raise FalseMoveError()
                    move(self.model, o, d)
                    print(self.model)
                else:
                    raise FalseMoveError()
            except FalseMoveError:
                print("Not a valid input")
            except ValueError:
                print("That's not a number")
コード例 #4
0
class ConsoleController:
    """ Controller for text console.
    """

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

        @param ConsoleController self:
        @param int number_of_cheeses:
        @param int number_of_stools:
        @rtype: None
        """
        self.number_of_cheeses = number_of_cheeses
        self.number_of_stools = number_of_stools
        self.tmodel = TOAHModel(self.number_of_stools)
        self.finished = False
        self.counter = 1

    def play_loop(self):
        """ Play Console-based game.

        @param ConsoleController self:
        @rtype: None

        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.tmodel.fill_first_stool(self.number_of_cheeses)

        print(self.tmodel)
        while not self.finished:
            x = input('Which stool index do you want to move a cheese from?')
            if x == 'end':
                self.finished = True
                return None
            y = input('Which stool index do you want to move the cheese to?')
            if y == 'end':
                self.finished = True
                return None
            try:
                move(self.tmodel, int(x), int(y))
                print(self.tmodel)
            except ValueError:
                print('That is an invalid move. Please try again')
            except IllegalMoveError:
                print('That is an invalid move. Please try again')
コード例 #5
0
class ConsoleController:
    """ Controller for text console.
    """
    def __init__(self, number_of_cheeses, number_of_stools):
        """ Initialize a new ConsoleController self.

        @param ConsoleController self:
        @param int number_of_cheeses:
        @param int number_of_stools:
        @rtype: None
        """

        self.number_of_stools = number_of_stools
        self.number_of_cheeses = number_of_cheeses

        self.toah = TOAHModel(number_of_stools)
        self.toah.fill_first_stool(number_of_cheeses)

        self.instructions = \
        ('The objective of the game is to move the given stack of cheeses \n'
         'to the right most stool with the least amount of moves.\n'
         'To move a block of cheese from stool X to stool Y \n'
         'enter stool numbers in the format x,y\n'
         "Enter 'Info' if you wish to read this message again\n"
         "Enter 'Quit' to exit the game")

    def play_loop(self):
        """ Play Console-based game.

        @param ConsoleController self:
        @rtype: None
        """
        print(self.instructions)
        command = input("Enter a move or type Quit to exit: ")
        while command != 'Quit':
            c = command.strip().split(',')
            try:
                if command == 'Info':
                    print(self.instructions)
                elif len(c) != 2 or not (c[0].isnumeric()
                                         and c[1].isnumeric()):
                    raise IllegalMoveError
                elif not 0 < int(c[0]) <= int(self.number_of_stools):
                    print('Error ' + c[0] + ' is not within the range\n')
                elif not 0 < int(c[1]) <= int(self.number_of_stools):
                    print('Error ' + c[1] + ' is not within the range\n')
                elif not self.toah.get_top_cheese(int(c[0]) - 1):
                    print('stool ' + str(int(c[0]) - 1) + ' has No cheese!')
                else:
                    move(self.toah, int(c[0]) - 1, int(c[1]) - 1)
                    print(self.toah)
            except IllegalMoveError:
                print(
                    'Incorrect input, input must be positve #,#, Info or Quit\n'
                )
            command = input("Enter a move or type Quit to exit: ")
        print("\nYou have successfully quit the game!")
コード例 #6
0
 def __init__(self, number_of_cheeses, number_of_stools):
     """ Initialize a new ConsoleController self.
     @param ConsoleController self:
     @param int number_of_cheeses:
     @param int number_of_stools:
     @rtype: None
     """
     self.model = TOAHModel(number_of_stools)
     self.model.fill_first_stool(number_of_cheeses)
コード例 #7
0
class ConsoleController:
    """ Controller for text console.
    """

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

        @param ConsoleController self:
        @param int number_of_cheeses:
        @param int number_of_stools:
        @rtype: None
        """

        self._model = TOAHModel(number_of_stools)
        self._num_cheeses = number_of_cheeses
        self._num_stools = number_of_stools

        self._model.fill_first_stool(num_cheeses) #Fill 1st stool to start game

    def play_loop(self):
        """ Play Console-based game.

        @param ConsoleController self:
        @rtype: None

        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.
        """

        while not self._model.is_done():

            start = input("Enter start stool: ")
            dest = input("Enter dest stool: ")

            if start == '' or dest == '':
                break
            else:
                start = int(start) - 1
                dest = int(dest) - 1
            # Now make the move.
            try:
                move(self._model, start, dest)
            except IllegalMoveError:
                print("Invalid Move!")

        print("Exiting the game now...\n")
コード例 #8
0
    def __init__(self, number_of_cheeses, number_of_stools, content_width,
                 content_height, cheese_scale):
        """ Initialize a new GUIView.

        @param GUIController self:
        @param int number_of_cheeses:
            number of cheeses for first stool
        @param int number_of_stools:
            number of stools
        @param float content_width:
            width, in pixels, of working area
        @param float content_height:
            height, in pixels, of working area
        @param float cheese_scale:
            height in pixels for showing cheese thicknesses, and to
            scale cheese diameters
        """
        self._model = TOAHModel(number_of_stools)
        self._stools = []
        self._cheese_to_move = None
        self._blinking = False
        self._number_of_stools = number_of_stools
        self.cheese_scale = cheese_scale
        self.root = tk.Tk()
        canvas = tk.Canvas(self.root,
                           background="blue",
                           width=content_width,
                           height=content_height)
        canvas.pack(expand=True, fill=tk.BOTH)
        self.moves_label = tk.Label(self.root)
        self.show_number_of_moves()
        self.moves_label.pack()
        # the dimensions of a stool are the same as a cheese that's
        # one size bigger than the biggest of the number_of_cheeses cheeses.
        for stool_ind in range(number_of_stools):
            width = self.cheese_scale * (number_of_cheeses + 1)
            x_cent = content_width * (stool_ind + 1) / (number_of_stools + 1.0)
            y_cent = content_height - cheese_scale / 2
            stool = StoolView(width, lambda s: self.stool_clicked(s), canvas,
                              self.cheese_scale, x_cent, y_cent)
            self._stools.append(stool)
        # Can't use self._model.fill_first_stool because we need to
        # use CheeseView objects instead of just Cheese objects.
        total_size = self.cheese_scale
        for sizeparam in range(1, number_of_cheeses + 1):
            size = (number_of_cheeses + 1 - sizeparam)
            width = self.cheese_scale * size
            x_cent = content_width / (number_of_stools + 1.0)
            y_cent = content_height - cheese_scale / 2 - total_size

            cheese = CheeseView(size, width, lambda c: self.cheese_clicked(c),
                                canvas, self.cheese_scale, x_cent, y_cent)
            self._model.add(cheese, 0)
            total_size += self.cheese_scale
コード例 #9
0
class ConsoleController:
    """ Controller for text console.
    """
    model = None

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

        @param ConsoleController self:
        @param int number_of_cheeses:
        @param int number_of_stools:
        @rtype: None
        """
        #pass
        self.model = TOAHModel(number_of_stools)
        self.model.fill_first_stool(number_of_cheeses)

    def play_loop(self):
        """ Play Console-based game.

        @param ConsoleController self:
        @rtype: None

        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.
        """
        line = 0
        while(1):
            line += 1
            print("\nStage "+ str(line) + "\n***************************************************\n")
            print(self.model.__str__())
            print("")
            cmd = int(input("1.move 2.quit : "))
            if(cmd == 1):
                ori = int(input("Origin: "))
                dest = int(input("Destination: "))
                move(self.model,ori,dest)

            elif(cmd == 2):
                break
            else:
                print("\033[31;1mWrong input  \033[0m")
        print("Bye~")
コード例 #10
0
def move(model, origin, dest):
    """ Apply move from origin to destination in model.
    May raise an IllegalMoveError.
    @param TOAHModel model:
        model to modify
    @param int origin:
        stool number (index from 0) of cheese to move
    @param int dest:
        stool number you want to move cheese to
    @rtype: None
    """
    TOAHModel.move(model, origin, dest)
コード例 #11
0
class ConsoleController:
    """ Controller for text console.
    """
    def __init__(self, number_of_cheeses, number_of_stools):
        """ Initialize a new ConsoleController self.

        @param ConsoleController self:
        @param int number_of_cheeses:
        @param int number_of_stools:
        @rtype: None
        """
        self.model = TOAHModel(number_of_stools)
        self.model.fill_first_stool(number_of_cheeses)

    def play_loop(self):
        """ Play Console-based game.

        @param ConsoleController self:
        @rtype: None

        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('Instruction: "1 3" means move top cheese from the first stool'
              'to the third stool \nEnter "end" to exit.')
        print(self.model)
        count = 1
        move_ = input('Enter move {}: '.format(count))
        while move_ != 'end':
            try:
                move_list = move_.split()
                move(self.model, int(move_list[0]) - 1, int(move_list[1]) - 1)
            except IndexError:
                print('Invalid input!')
            except ValueError:
                print('Invalid input!')
            except IllegalMoveError as e:
                print(e)
            else:
                count += 1
            print(self.model)
            move_ = input('Enter move {}: '.format(count))
コード例 #12
0
class ConsoleController:
    """ Controller for text console.
    """

    def __init__(self, number_of_cheeses, number_of_stools):
        """ Initialize a new ConsoleController self.
        @param ConsoleController self:
        @param int number_of_cheeses:
        @param int number_of_stools:
        @rtype: None
        """
        self.model = TOAHModel(number_of_stools)
        self.model.fill_first_stool(number_of_cheeses)

    def play_loop(self):
        """ Play Console-based game.
        @param ConsoleController self:
        @rtype: None
        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.
        """

        while True:
            play = input('Please enter move: ')

            if play == "q":
                return False
            result = play.split()
            from_ = int(result[0])
            to_ = int(result[1])

            try:
                if to_ > len(self.model._stools):
                    raise IllegalMoveError("Stool does not exist")
                else:
                    self.model.move(from_, to_)

            except IllegalMoveError as IE:
                print(IE)
                pass

            print(self.model)
コード例 #13
0
    def __init__(self, number_of_cheeses, number_of_stools):
        """ Initialize a new ConsoleController self.

        @param ConsoleController self:
        @param int number_of_cheeses:
        @param int number_of_stools:
        @rtype: None
        """
        self.number_of_cheeses = number_of_cheeses
        self.number_of_stools = number_of_stools
        self.tmodel = TOAHModel(self.number_of_stools)
        self.finished = False
        self.counter = 1
コード例 #14
0
    def __init__(self, number_of_cheeses, number_of_stools):
        """ Initialize a new ConsoleController self.

        @param ConsoleController self:
        @param int number_of_cheeses:
        @param int number_of_stools:
        @rtype: None
        """

        self._model = TOAHModel(number_of_stools)
        self._num_cheeses = number_of_cheeses
        self._num_stools = number_of_stools

        self._model.fill_first_stool(num_cheeses) #Fill 1st stool to start game
コード例 #15
0
    def play_loop(self):
        """ Play Console-based game.
        @param ConsoleController self:
        @rtype: None
        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.
        """
        game = TOAHModel(self.number_of_stools)
        game.fill_first_stool(self.number_of_cheeses)
        print("~~~~~~~~~~WELCOME TO FAIYAZ AND RASU'S GAME~~~~~~~~~~\n")
        print("~~~~~~~~~~OBJECTIVES~~~~~~~~~~")
        print(
            "To Move the entire stack of cheese from one stool to another stool\n"
        )
        print("~~~~~~~~~~INSTRUCTIONS~~~~~~~~~~")
        print("1. Move cheese from one stool to another one at a time \n"
              "2. Can only move the top most cheese from a stool \n"
              "3. Can't place a larger cheese over a smaller cheese \n"
              "4. To exit the game, enter 'exit'")
        print('START \n \n ')
        print(game)
        start = 'Open'
        while start != 'exit':
            origin = int(
                input(
                    "Enter the stool from which you want to move the cheese. "
                    + "Stools range from 0 to " +
                    str(self.number_of_stools - 1) + ': '))
            final = int(
                input("Now enter the stool you want to "
                      "move the slice of cheese to. Stools range from 0 to " +
                      str(self.number_of_stools - 1) + '\n'))
            try:
                move(game, origin, final)
            except IllegalMoveError as error:
                print("!!!!!!You caused an error!!!!!!!")
                print(error)

            print(game)
            start = input("type 'exit' to exit")
コード例 #16
0
    def __init__(self, number_of_cheeses, number_of_stools):
        """ Initialize a new ConsoleController self.

        @param ConsoleController self:
        @param int number_of_cheeses:
        @param int number_of_stools:
        @rtype: None
        """
        self.model = TOAHModel(number_of_stools)

        self.model.fill_first_stool(number_of_cheeses)

        #the complete model of the model
        self.model_complete = TOAHModel(number_of_stools)
        self.model_complete._stools[number_of_stools -
                                    1] = self.model._stools[0][0:]
コード例 #17
0
    def play_loop(self):
        """ Play Console-based game.

        @param ConsoleController self:
        @rtype: None

        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.
        """
        show_instruction()
        won_message = False
        toah = TOAHModel(self.number_of_stools)
        model = toah.get_move_seq(). \
            generate_toah_model(self.number_of_stools, self.number_of_cheeses)
        print(model)
        movement = input("Input your move: ")
        while movement != "end":
            try:
                result = extract_input(movement)
                move(model, result[0], result[1])
            except IllegalMoveError as message:
                print(message)
            except ValueError:
                print('This is a invalid input')
            except IndexError:
                print('This is a invalid input')
            except TypeError:
                print('This is a invalid input')
            else:
                print(model)
            if len(model.get_stool()[-1]) == self.number_of_cheeses:
                movement = "end"
                won_message = True
            else:
                movement = input("Input your move: ")
        display_won_message(won_message)
コード例 #18
0
    def __init__(self, number_of_cheeses, number_of_stools):
        """ Initialize a new ConsoleController self.

        @param ConsoleController self:
        @param int number_of_cheeses:
        @param int number_of_stools:
        @rtype: None
        """

        if isinstance(number_of_cheeses, int) and isinstance(
                number_of_stools, int):
            self.number_of_cheeses = number_of_cheeses
            self.number_of_stools = number_of_stools
            self.model = TOAHModel(self.number_of_stools)
            self.model.fill_first_stool(self.number_of_cheeses)
            self.complete = self.model._stools[0][:]

        else:
            print("Please enter a NUMBER of cheeses and a NUMBER of stools")
コード例 #19
0
    def __init__(self, number_of_cheeses, number_of_stools):
        """ Initialize a new ConsoleController self.

        @param ConsoleController self:
        @param int number_of_cheeses:
        @param int number_of_stools:
        @rtype: None
        """

        self.cheese_model = TOAHModel(number_of_stools)
        self.cheese_model.fill_first_stool(number_of_cheeses)
        self.number_of_cheese = number_of_cheeses
        self.number_of_stools = number_of_stools

        print("Welcome to the game. ")
        print("You will be asked to input the number of cheeses and "\
              "stools that you would like to play with")
        print("Make sure your inputs are a single int of how many cheeses "\
              "or stools you would like.")
        print("If you would like to stop playing, simply type 'quit'. ")
コード例 #20
0
    def play_loop(self):
        """ Play Console-based game.

        @param ConsoleController self:
        @rtype: None

        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(stool)
        m.fill_first_stool(cheese)
        print(m)
        cond_check = True
        while cond_check:
            move_lst = []
            user_input = input('give me instruction')
            # check condition
            check_end(user_input)
            if cond_check:
                user_input = user_input.split(',')
                try:
                    move_lst.append(int(user_input[0]))
                    move_lst.append(int(user_input[1]))
                    move(m, move_lst[0], move_lst[1])
                except Exception as a:
                    print("input should be in the format int,int ", a)
                finally:
                    print(m)
                    if len(m.get_stools_lst()[-1]) == cheese:
                        print("you win")
コード例 #21
0
class ConsoleController:
    """ Controller for text console.
    """
    def __init__(self, number_of_cheeses, number_of_stools):
        """ Initialize a new ConsoleController self.

        @param ConsoleController self:
        @param int number_of_cheeses:
        @param int number_of_stools:
        @rtype: None
        """
        self.model = TOAHModel(number_of_stools)
        self.model.fill_first_stool(number_of_cheeses)
        self.number_of_stools = number_of_stools

    def play_loop(self):
        """ Play Console-based game.

        @param ConsoleController self:
        @rtype: None

        """
        print("Instructions: To move a cheese from the first stool to "
              "the second, input '0 to 1' \n Enter 'ex' to exit")
        move_count = 1
        print(self.model)
        move_in = input('Enter Move ' + str(move_count) + ':')
        while move_in != 'ex':
            move_in = move_in.split()
            if len(move_in) == 3 and move_in[1] == 'to' and \
                    (move_in[0].isnumeric() and move_in[2].isnumeric()):
                try:
                    self.model.move(int(move_in[0]), int(move_in[-1]))
                    move_count += 1
                except IllegalMoveError as e:
                    print(e)
            else:
                print("Invalid Input Syntax")
            print(self.model)
            move_in = input('Enter Move ' + str(move_count) + ':')
コード例 #22
0
def tour_of_four_stools(model, delay_btw_moves=0.5, animate=False):
    """ Move a tower of cheeses from the first stool in model to the fourth.

    @type model: TOAHModel
        TOAHModel with tower of cheese on first stool and three empty
        stools
    @type delay_btw_moves: float
        time delay between moves if console_animate is True
    @type animate: bool
        animate the tour or not
    """
    mock_model = TOAHModel(model.get_number_of_stools())
    mock_model.fill_first_stool(model.get_number_of_cheeses())
    number_cheeses = model.get_number_of_cheeses()
    four_stools_move(model, number_cheeses, 0, 1, 3)
    i = 0
    move_seq = model.get_move_seq()
    move_times = move_seq.length()
    while animate:
        time.sleep(delay_btw_moves)
        ori = move_seq.get_move(i)[0]
        des = move_seq.get_move(i)[1]
        mock_model.move(ori, des)
        print(mock_model)
        i = i + 1
        if i == move_times:
            animate = False
コード例 #23
0
    def __init__(self, number_of_cheeses, number_of_stools):
        """ Initialize a new ConsoleController self.

        @param ConsoleController self:
        @param int number_of_cheeses:
        @param int number_of_stools:
        @rtype: None
        """

        self.number_of_stools = number_of_stools
        self.number_of_cheeses = number_of_cheeses

        self.toah = TOAHModel(number_of_stools)
        self.toah.fill_first_stool(number_of_cheeses)

        self.instructions = \
        ('The objective of the game is to move the given stack of cheeses \n'
         'to the right most stool with the least amount of moves.\n'
         'To move a block of cheese from stool X to stool Y \n'
         'enter stool numbers in the format x,y\n'
         "Enter 'Info' if you wish to read this message again\n"
         "Enter 'Quit' to exit the game")
コード例 #24
0
    def play_loop(self):
        """ Play Console-based game.

        @param ConsoleController self:
        @rtype: None

        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.
        """

        is_int = False
        toah_game = TOAHModel(self.number_of_stools)
        toah_game.fill_first_stool(self.number_of_cheeses)
        print(toah_game)
        print("Welcome to the Tour of Anne Hoy Game.")
        print(
            "Enter a non-integer value such as a string(a) or a float(13.5) to quit the game."
        )
        print('')

        run = True

        while run:
            try:
                cheese_origin = int(
                    input("Choose a stool number to move the cheese from: "))
                cheese_dest = int(
                    input("Choose the stool you want to move the cheese to: "))
                toah_game.move(cheese_origin, cheese_dest)
                print(toah_game)

            except IllegalMoveError:
                print("Invalid move. Please reenter.")
                print("")

            except IndexError:
                print("Invalid stool number. Please reenter.")
                print("")

            except ValueError:
                print("")
                print("Game Ended. Thank you for playing.")
                run = False
コード例 #25
0
    def play_loop(self):
        """ Play Console-based game.

        @param ConsoleController self:
        @rtype: None

        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("Instruction: Player enter the start stool and destination stool"
              " at every time. \n"
              "Be ware you should enter the number of stool. "
              "i.e.'1' means first stool. Player can\n"
              "quit this game by enter 'E' when a messauge pop out.\n"
              "Be careful, "
              "You can't put big cheese over smaller ones! Good luck!\n"
              "=============================================================="
              "===================\n ")
        model = TOAHModel(self.number_of_stools)
        model.fill_first_stool(self.number_of_cheeses)
        ext = ""
        print(model)
        while ext is not "E":
            try:
                origin = int(input("Please enter the origin of movement---> "))
                dest = int(
                    input("Please enter the destination of "
                          "movement---> "))
                model.move(origin - 1, dest - 1)
            except IllegalMoveError as e:
                print(e)
            except ValueError:
                print("Please read instruction carefully,"
                      " and enter a positive integer.")
            finally:
                print(model)
                ext = input("Type E to exit game or any other to keep playing"
                            "---> ")
        print("Game over")
コード例 #26
0
def animate_hanoi(reference_model, delay):
    """ animate the movements in the console window one by one;
     delay each movement by the given <delay>

    @type reference_model: TOAHModel
    @type delay: float
    @rtype: None
    """
    toah = TOAHModel(reference_model.get_number_of_stools())
    toah.fill_first_stool(reference_model.get_number_of_cheeses())
    for i in range(reference_model.number_of_moves()):
        movement = reference_model.get_move_seq().get_move(i)
        toah.move(movement[0], movement[1])
        time.sleep(delay)
        print(toah)
コード例 #27
0
ファイル: tour.py プロジェクト: mcgarrye/portfolio
def tour_of_four_stools(model, delay_btw_moves=0.5, animate=False):
    """Move a tower of cheeses from the first stool in model to the fourth.

    @type model: TOAHModel
        TOAHModel with tower of cheese on first stool and three empty
        stools
    @type delay_btw_moves: float
        time delay between moves if console_animate is True
    @type animate: bool
        animate the tour or not
    """
    move_cheeses(model, model.get_number_of_cheeses(), 0, 1, 2, 3)
    if animate:
        new_model = TOAHModel(4)
        new_model.fill_first_stool(model.get_number_of_cheeses())
        for i in range(model.number_of_moves()):
            new_model.move(model.get_move_seq().get_move(i)[0],
                           model.get_move_seq().get_move(i)[1])
            print(new_model)
            time.sleep(delay_btw_moves)
コード例 #28
0
def tour_of_four_stools(model, delay_btw_moves=0.5, animate=False):
    """Move a tower of cheeses from the first stool in model to the fourth.

    @type model: TOAHModel
        TOAHModel with tower of cheese on first stool and three empty
        stools
    @type delay_btw_moves: float
        time delay between moves if CONSOLE_ANIMATE is True
    @type animate: bool
        animate the tour or not
    """
    move_four_stools(model, model.get_number_of_cheeses(), [0, 3, 1, 2])

    if animate:
        animate_model = TOAHModel(4)
        animate_model.fill_first_stool(model.get_number_of_cheeses())
        move_seq = model.get_move_seq()
        print(animate_model)
        for i in range(move_seq.length()):
            (src_stool, dst_stool) = move_seq.get_move(i)
            time.sleep(delay_btw_moves)
            animate_model.move(src_stool, dst_stool)
            print(animate_model)
コード例 #29
0
                print("!!!!!!You caused an error!!!!!!!")
                print(error)
            print(game)
            start = input("type 'exit' to exit or press enter to continue")


if __name__ == '__main__':
    stool = int(
        input(
            "Enter the number of stools you would want to play the game with: "
        ))
    if stool <= 0:
        while stool <= 0:
            print('Number of stools have to be greater than 0')
            stool = int(input('Enter again: '))
    model = TOAHModel(stool)
    cheese = int(
        input(
            "Now, enter the number of cheeses you would want to play the game "
            "with: "))
    if cheese <= 0:
        while cheese <= 0:
            print('Number of cheeses have to be greater than 0')
            cheese = int(input('Enter again: '))
    console = ConsoleController(cheese, stool)
    console.play_loop()
    # You should initiate game play here. Your game should be playable by
    # running this file.
    # Leave lines below as they are, so you will know what python_ta checks.
    # You will need consolecontroller_pyta.txt in the same folder.
    import python_ta
コード例 #30
0
class GUIController:
    """ Graphical User Interface (GUI) controller

    === Attributes ===
    @param float cheese_scale: height in pixels to scale
        cheese height
    @param root tk.Tk: tkinter root window
    """

    def __init__(self, number_of_cheeses, number_of_stools, content_width,
                 content_height, cheese_scale):
        """ Initialize a new GUIView.

        @param GUIController self:
        @param int number_of_cheeses:
            number of cheeses for first stool
        @param int number_of_stools:
            number of stools
        @param float content_width:
            width, in pixels, of working area
        @param float content_height:
            height, in pixels, of working area
        @param float cheese_scale:
            height in pixels for showing cheese thicknesses, and to
            scale cheese diameters
        """
        self._model = TOAHModel(number_of_stools)
        self._stools = []
        self._cheese_to_move = None
        self._blinking = False
        self._number_of_stools = number_of_stools
        self.cheese_scale = cheese_scale
        self.root = tk.Tk()
        canvas = tk.Canvas(self.root,
                           background="blue",
                           width=content_width, height=content_height)
        canvas.pack(expand=True, fill=tk.BOTH)
        self.moves_label = tk.Label(self.root)
        self.show_number_of_moves()
        self.moves_label.pack()
        # the dimensions of a stool are the same as a cheese that's
        # one size bigger than the biggest of the number_of_cheeses cheeses.
        for stool_ind in range(number_of_stools):
            width = self.cheese_scale * (number_of_cheeses + 1)
            x_cent = content_width * (stool_ind + 1)/(number_of_stools + 1.0)
            y_cent = content_height - cheese_scale / 2
            stool = StoolView(width,
                              lambda s: self.stool_clicked(s),
                              canvas,
                              self.cheese_scale,
                              x_cent,
                              y_cent)
            self._stools.append(stool)
        # Can't use self._model.fill_first_stool because we need to
        # use CheeseView objects instead of just Cheese objects.
        total_size = self.cheese_scale
        for sizeparam in range(1, number_of_cheeses+1):
            size = (number_of_cheeses + 1 - sizeparam)
            width = self.cheese_scale * size
            x_cent = content_width / (number_of_stools + 1.0)
            y_cent = content_height - cheese_scale / 2 - total_size
            cheese = CheeseView(size,
                                width,
                                lambda c: self.cheese_clicked(c),
                                canvas,
                                self.cheese_scale,
                                x_cent,
                                y_cent)
            self._model.add(cheese, 0)
            total_size += self.cheese_scale

    def cheese_clicked(self, cheese):
        """ React to cheese being clicked: if not in the middle of blinking
        then select cheese for moving, or for moving onto.

        @param GUIController self:
        @param CheeseView cheese:
            clicked cheese
        @rtype: None
        """
        if not self._blinking:
            self.select_cheese(cheese)

    def stool_clicked(self, stool):
        """ React to cheese being clicked: if not in the middle of blinking
        then select cheese for moving, or for moving onto.

        @param GUIController self:
        @param StoolView stool:
            clicked stool
        @rtype: None
        """
        if not self._blinking:
            self.select_stool(stool)

    def select_cheese(self, cheese):
        """ Select top cheese.

        If no cheese is selected to move, then select the cheese at
        top of clicked_cheese's stool (which may be clicked_cheese
        itself) and highlight it.
        If selected_cheese is already highlighted, then unhighlight it.
        Otherwise try to move self._cheese_to_move onto the stool that
        clicked_cheese is on.

        @param GUIController self:
        @param CheeseView cheese:
            clicked cheese
        @rtype: None
        """
        stool = self._stools[self._model.get_cheese_location(cheese)]
        stool_index = self.stool_index(stool)
        cheese = self._model.get_top_cheese(stool_index)
        # print(stool, stool_index, cheese)
        if self._cheese_to_move is None:
            self._cheese_to_move = cheese
            self._cheese_to_move.highlight(True)
            self.root.update()
        elif self._cheese_to_move is cheese:
            self._cheese_to_move.highlight(False)
            self._cheese_to_move = None
            self.root.update()
        else:
            self.select_platform_for_move(cheese, stool_index)

    def select_stool(self, dest_stool):
        """ Initiate a move.

        If there is already some cheese highlighted (i.e.
        self._cheese_to_move is not None), unless
        self._cheese_to_move is on dest_stool, in which case do nothing.

        @param GUIController self:
        @type dest_stool: StoolView
        @rtype: None
        """
        if self._cheese_to_move is not None:
            origin_stool = self._stools[
                self._model.get_cheese_location(self._cheese_to_move)]
            dest_stool_index = self.stool_index(dest_stool)
            origin_stool_index = self.stool_index(origin_stool)
            if origin_stool_index != dest_stool_index:
                top_cheese = self._model.get_top_cheese(dest_stool_index)
                if top_cheese is None:
                    self.select_platform_for_move(dest_stool, dest_stool_index)
                else:
                    self.select_platform_for_move(top_cheese, dest_stool_index)

    def select_platform_for_move(self, platform, stool_index):
        """ Show the cheese move on screen, and update the model.

        Change self._cheese_to_move's coordinates so that it's on top of
        platform.

        @param GUIController self:
        @param PlatformView platform:
        @param int stool_index:
        @rtype: None
        """
        if self._cheese_to_move is not None:
            try:
                from_stool = self._model.get_cheese_location(
                    self._cheese_to_move)
                self._model.move(from_stool, stool_index)
                self._cheese_to_move.place(platform.x_center, platform.y_center
                                           - self.cheese_scale)
                self.show_number_of_moves()
            except IllegalMoveError as e:
                print(e)
                self._blinking = True
                for i in range(10):
                    self._cheese_to_move.highlight(i % 2 != 0)
                    self.root.update()
                    time.sleep(0.1)
                self._blinking = False
            self._cheese_to_move.highlight(False)
            self._cheese_to_move = None
            self.root.update()

    def stool_index(self, stool):
        """ Return the index of stool.

        @param GUIController self:
        @param StoolView stool:
        @rtype: int

        >>> gui = GUIController(5, 4, 1024, 320, 20)
        >>> s = gui.get_stool(0)
        >>> gui.stool_index(s) == 0
        True
        >>> gui.stool_index(s) == 1
        False
        """
        return self._stools.index(stool)

    def show_number_of_moves(self):
        """Show the number of moves so far.

        @param GUIController self:
        @rtype: None
        """
        self.moves_label.config(text="Number of moves: " +
                                str(self._model.number_of_moves()))

    def get_stool(self, i):
        """ Return ith stool.

        @param GUIController self:
        @param int i:
        @rtype: StoolView

        # examples not really practical here
        """
        return self._stools[i]

    def get_top_cheese(self, i):
        """ Return the top cheese from ith stool.


        @param GUIController self:
        @param int i:
        @rtype: CheeseView

        # examples not really practical here
        """
        return self._model.get_top_cheese(i)