コード例 #1
0
class Director:
    """A code template for a person who directs the game. The responsibility of 
    this class of objects is to control the sequence of play.
    """
    def __init__(self):
        """
        Class constructor itself.
        Args:
            self(Director): creates an instance of Director.
        """
        self._console = Console()
        self._keep_playing = True
        self._roster = Roster()
        self._move = None
        self._secret_code = Secret_Code()

        def start_game(self):
            """
            Initiates the game through a loop (hopefully) controlling the sequence of play as well.
            """
            pass

        def _prepare_game(self):
            """
            Responsible in preparing the game prior to it being initiated (excluding prior to be opened). This will
            be getting the names of those players and placing them in a roster type format. This is through the use of
            the Roster.py class.
            """
            for p in range(2):
                name - self.console.read(f'Enter a name for player {n + 1}: ')
                player = Player(name)
                self._roster.add_player(player)

        def _#TODO:
            pass
コード例 #2
0
ファイル: director.py プロジェクト: robbieswan/Python-Week-6
class Director:
    """A code template for a person who directs the game. The responsibility of 
    this class of objects is to control the sequence of play.
    
    Stereotype:
        Controller

    Attributes:
        board (Hunter): An instance of the class of objects known as Board.
        console (Console): An instance of the class of objects known as Console.
        keep_playing (boolean): Whether or not the game can continue.
        move (Rabbit): An instance of the class of objects known as Move.
        roster (Roster): An instance of the class of objects known as Roster.
    """

    def __init__(self):
        """The class constructor.
        
        Args:
            self (Director): an instance of Director.
        """
        self._board = Board()
        self._console = Console()
        self._keep_playing = True
        self._move = None
        self._roster = Roster()
        
    def start_game(self):
        """Starts the game loop to control the sequence of play.
        
        Args:
            self (Director): an instance of Director.
        """
        self._prepare_game()
        while self._keep_playing:
            self._get_inputs()
            self._do_updates()
            self._do_outputs()

    def _prepare_game(self):
        """Prepares the game before it begins. In this case, that means getting the player names and adding them to the roster.
        
        Args:
            self (Director): An instance of Director.
        """
        for n in range(2):
            name = self._console.read(f"Enter a name for player {n + 1}: ")
            player = Player(name)
            self._roster.add_player(player)
    
    def _get_inputs(self):
        """Gets the inputs at the beginning of each round of play. In this case,
        that means getting the move from the current player.

        Args:
            self (Director): An instance of Director.
        """
        # display the game board
        board = self._board.to_string()
        self._console.write(board)
        # get next player's move
        player = self._roster.get_current()
        self._console.write(f"{player.get_name()}'s turn:")
        pile = self._console.read_number("What pile to remove from? ")
        stones = self._console.read_number("How many stones to remove? ")
        move = Move(stones, pile)
        player.set_move(move)

    def _do_updates(self):
        """Updates the important game information for each round of play. In 
        this case, that means updating the board with the current move.

        Args:
            self (Director): An instance of Director.
        """
        player = self._roster.get_current()
        move = player.get_move()
        self._board.apply(move)
 
    def _do_outputs(self):
        """Outputs the important game information for each round of play. In 
        this case, that means checking if there are stones left and declaring the winner.

        Args:
            self (Director): An instance of Director.
        """
        if self._board.is_empty():
            winner = self._roster.get_current()
            name = winner.get_name()
            print(f"\n{name} won!")
            self._keep_playing = False
        self._roster.next_player()
コード例 #3
0
class Director:
    """A code template for a person who directs the game. The responsibility of 
    this class of objects is to control the sequence of play.
    
    Stereotype:
        Controller

    Attributes:
        _board (Board): An instance of the class of objects known as Board.
        _console (Console): An instance of the class of objects known as Console.
        keep_playing (boolean): Whether or not the game can continue.
        code: the code for the game
        _moves (Move): Instances of the class of objects known as Move.
        _roster (Roster): An instance of the class of objects known as Roster.
    """

    def __init__(self):
        """The class constructor.
        
        Args:
            self (Director): an instance of Director.
        """
        self._board = Board()
        self._console = Console()
        self.keep_playing = True
        
        self.code = self._board.numbers_to_guess

        self._moves = [Move(self.code, '----'), Move(self.code, '----')]
        self._roster = Roster()

    def start_game(self):
        """Starts the game loop to control the sequence of play.
        
        Args:
            self (Director): an instance of Director.
        """
        self._prepare_game()
        while self.keep_playing:
            self.print_board()
            self.turn()

    def _prepare_game(self):
        """Prepares the game before it begins. In this case, that means getting the player names and adding them to the roster.
        
        Args:
            self (Director): An instance of Director.
        """
        player = [None, None]
        for n in range(2):
            name = self._console.get_name()
            player[n] = Player(name)
        self._roster.add_player(player[0], player[1])
    
    def print_board(self):
        """Outputs the important game information for each round of play.

        Args:
            self (Director): An instance of Director.
        """
        # display the game board
        board = self._board.to_string(self._roster, self._moves[0], self._moves[1])
        self._console.write(board)


    def turn(self):
        """Gets input from player, applies input, checks to see if player won, selects next player

        Args:
            self (Director): An instance of Director.
        """
        # get player's move
        player = self._roster.get_current()
        self._console.write(f"{player.get_name()}'s turn:")
        guess = self._console.read_number("What is your guess? ")
        self._moves[self._roster.current].update_guess(guess)
        player.set_move(self._moves[self._roster.current])

        # check for victory
        if str(guess) == str(self.code):
            self._console.write(f'\n{player.get_name()} won!')
            self.keep_playing = False

        # next player
        self._roster.next_player()
コード例 #4
0
ファイル: director.py プロジェクト: Dbenjamy/cse210-tc06
class Director:
    """A code template for a person who directs the game. The responsibility of 
    this class of objects is to control the sequence of play.
  
    Attributes:
        console (Console): An instance of the class of objects known as Console.
        roster (Roster): An instance of the class of objects known as Roster.
    """

    def __init__(self):
        """The class constructor.
        
        Args:
            self (Director): an instance of Director.
        """
        self._console = Console()
        self._keep_playing = True
        self._move = Move()
        self._roster = Roster()
        self._logic = Logic()
        
    def start_game(self):
        """Starts the game loop to control the sequence of play.
        
        Args:
            self (Director): an instance of Director.
        """
        self._get_name()
        while self._keep_playing:
            self._get_inputs()
            self._do_updates()
            self._do_outputs()
            

    def _get_name(self):
        """Prepares the game before it begins. In this case, that means getting the player names and adding them to the roster.
        
        Args:
            self (Director): An instance of Director.
        """
        for n in range(2):
            name = self._console.read(f"Enter a name for player {n + 1}: ")
            player = Player(name)
            self._roster.add_player(player)
            
            

    
    def _get_inputs(self):
        """Gets the inputs at the beginning of each round of play. In this case,
        that means getting the move from the current player.

        Args:
            self (Director): An instance of Director.
        """
        # display the game board
        self._console._print_board(self._roster._the_roster[0],self._roster._the_roster[1])
        # get next player's move
        player = self._roster.get_current()
        self._console.write(f"{player.player_name}'s turn:")

        guess = self._console.read_number("What is your next guess? ")
        #could send to player or logic. Who controls the numbers?
        self._roster.get_current().guess = guess

    def _do_updates(self):
        """Updates the important game information for each round of play. In 
        this case, that means updating the logic/roster with the current move.

        Args:
            self (Director): An instance of Director.
        """
        player = self._roster.get_current()
        self._logic.check_number(str(player.guess), player)
        self._roster.get_current().hint = "".join(self._logic.result)
        self._move.as_string(str(self._roster.get_current().guess),str(self._roster.get_current().hint))
 
    def _do_outputs(self):
        """Outputs the important game information for each round of play. In 
        this case, that means checking if there are stones left and declaring the winner.

        Args:
            self (Director): An instance of Director.
        """
        if self._roster.get_current().win:
            winner = self._roster.get_current().player_name
            print(f"\n{winner} won!")
            self._keep_playing = False
        self._roster.next_player()
コード例 #5
0
class Director:
    """A code template for a person who directs the game. The responsibility of 
    this class of objects is to control the sequence of play.
    
    Stereotype:
        Controller

    Attributes:
        _board (Board): An instance of the class of objects known as Board.
        _console (Console): An instance of the class of objects known as Console.
        _keep_playing (boolean): Whether or not the game can continue.
        _move (Move): An instance of the class of objects known as Move.
        _roster (Roster): An instance of the class of objects known as Roster.
    """
    def __init__(self):
        """The class constructor.
        
        Args:
            self (Director): an instance of Director.
        """
        self._board = Board()
        self._console = Console()
        self._keep_playing = True
        self._roster = Roster()
        self.num_players = 0

    def start_game(self):
        """Starts the game loop to control sequence of play.

        Args:
            self(Director): an instance of Director.
        """
        self._prepare_game()
        while self._keep_playing:
            self._get_inputs()
            self._do_updates()
            self._do_outputs()

    def _prepare_game(self):
        """Prepares game. That means getting player names and adding them
        to the roster.

        Args:
            self (Director): An instance of Director.
        """
        prompt = "How many players? (2-6): "
        self.num_players = self._console.read_number(prompt)
        while True:
            if (self.num_players > 6):
                self._console.write("Please choose less than 7 players.")
                self.num_players = self._console.read_number(prompt)
            elif (self.num_players < 2):
                self._console.write("Please choose more than 1 player.")
                self.num_players = self._console.read_number(prompt)
            else:
                break
        for i in range(self.num_players):
            p_name = self._console.read(
                f'Player {(i+1)}, please enter your name: ')
            p_code = self._board.get_code()
            player = Player(p_name, p_code)
            self._roster.add_player(player)

    def _get_inputs(self):
        """Gets the inputs at the beginning of each round of play. For this
        game, gets move from current player.

        Args:
            self(Director): An instance of Director.
        """
        player = self._roster.get_current()
        self._console.write(f"{player.get_name()}'s turn")
        prompt = "Please enter your guess (1000-9999): "
        guess = self._console.read_number(prompt)
        while True:
            if (guess < 1000):
                self._console.write("Please enter a guess over 1000.")
                guess = self._console.read_number(prompt)
            elif (guess > 9999):
                self._console.write("Please enter a guess under 9999.")
                guess = self._console.read_number(prompt)
            else:
                break
        move = Move(guess)
        player.set_move(move.get_guess())

    def _do_updates(self):
        """Updates important game information for each round of play. For
        this game, the board is updated with the current guess.

        Args:
            self(Director): An instance of Director.
        """
        player = self._roster.get_current()
        move = player.get_move()
        code = player.get_code()
        self._board.apply(move, code)
        player.set_hint(self._board.get_hint())

    def _do_outputs(self):
        """Outputs the important game information for each round of play.
        For this game, a hint is printed from the board. If the code
        matches the guess exactly, a winner is declared.

        Args:
            self(Director): An instance of Director.
        """
        if self._board.matches_code():
            winner = self._roster.get_current()
            name = winner.get_name()
            self._console.write(f'\n{name} won!')
            self._keep_playing = False
        print()
        for _ in range(self.num_players):
            self._roster.next_player()
            move = self._roster.get_current().get_move()
            hint = self._roster.get_current().get_hint()
            name = self._roster.get_current().get_name()
            text = (f"Player {name}: {move}, {hint}")
            self._console.write(text)
        self._roster.next_player()
コード例 #6
0
class Console:
    """A code template for a person who directs the game. The responsibility of
    this class of objects is to control the sequence of play.

    Stereotype:
        Service Provider, Interfacer

    Attributes:
        roster (Roster): An instance of the class of objects known as Roster.
    """
    def __init__(self):
        """The class constructor.

        Args:
            self (Console): an instance of Console.
        """

        self._roster = Roster()
        self._paint = Paint()

        self.stop_game = False
        self.__show_menu = True
        self.__logo = []
        self.__fame = []
        self.__rules = []

        with open("mastermind/assets/logo.txt") as data:
            next(data)
            for line in data:
                self.__logo.append(line)

        with open("mastermind/assets/fame.txt") as data:
            next(data)
            for line in data:
                self.__fame.append(line)

        with open("mastermind/assets/rules.txt") as data:
            next(data)
            for line in data:
                self.__rules.append(line)

    def clear_screen(self):
        """Detects OS type and sends appropriate console command to clear screen.

        Args:
            self (Console): An instance of Console.
        """
        os.system('cls' if os.name == 'nt' else 'clear')

    def ask_stop_game(self):
        """Returns bool indicating whether game should continue running.

        Args:
            self (Console): an instance of Console.
        """
        return self.stop_game

    def restart_menu(self):
        """Returns bool indicating whether game should continue running.

        Args:
            self (Console): an instance of Console.
        """
        self.__show_menu = True

    def confirm_start(self, player=str):
        """Returns bool indicating whether game should continue running.

        Args:
            self (Console): an instance of Console.
            player (string): name of player for turn confirmation.
        """
        self.clear_screen()
        print("\n" * 11)
        pass_text = "Pass the device to " + player
        print(f"{pass_text : ^100}")
        input(f"{'Press ENTER when ready.' : ^100}")
        return self.stop_game

    def cool_print(self, text=str, newline=True, margin=21, rate=.02):
        """Prints text in typewriter style.

        Args:
            self (Console): an instance of Console.
            text (str): Text to print.
            newline (bool): whether to end with carriage return
        """
        print(" " * margin, end='')
        for letter in text:
            sleep(.02)
            stdout.write(letter)
            stdout.flush()
        if newline:
            print()

    def play_turn(self,
                  player=str,
                  code=str,
                  history=list,
                  stats=tuple,
                  redo=False):
        """Displays board and prompts for player guess. Returns tuplet of
        guess (string) and time taken to guess in seconds (float).

        Args:
            self (Console): an instance of Console.
            player (string): name of player.
            code (string): code to be guessed, for hint generation.
            history (list): list of (guess, hint) tuples.
            stats (tuple): Tuple of total round points and playtime of player.
            redo (bool): whether this is a repeat prompt due to invalid guess.
        """
        self.clear_screen()

        if redo:
            print('\n' * 15)
            self.cool_print("KEYCODE IS 4-DIGIT NUMBER BETWEEN 1000 AND 9999")
            self.cool_print("PRESS ENTER TO RE-ATTEMPT")
            input(" " * 21)
            self.clear_screen()

        self._paint.paint_screen(player, history, stats)
        self.cool_print("RUNNING: d42k_10ckp1ck32.exe")
        self.cool_print("ENTER 4-DIGIT KEYCODE:", newline=False)

        start = time()

        guess = input(" ")

        end = time()
        elapsed = end - start

        return (guess, elapsed)

    def show_hint(self, hint=str):
        """Displays hint for player.

        Args:
            self (Console): an instance of Console.
            hint (str).
        """
        self.clear_screen()
        print('\n' * 15)
        self.cool_print("ERROR 210.04-TC6: [KEYCODE INCORRECT]")
        self.cool_print("DATA CORRUPTED. ATTEMPTING TO DECRYPT METADATA.")
        print()
        sleep(.6)
        self.cool_print(f"[!] METADATA RECOVERED: {hint}")
        print()
        self.cool_print("PRESS ENTER TO REATTEMPT", newline=False)
        input()

    def __print_logo(self, left=5, top=2, bottom=2):
        """Prints logo to screen. Has optional x and y parameters to offset logo
        by specified amount of lines and spaces.

        Args:
            self (Console): An instance of Console.
            left (int): Number of spaces to offset logo from left of screen
            top (int): Number of lines to offset logo from top of screen
            bottom (int): Number of spaces to print below logo
        """

        print('\n' * top, end="")

        for line in self.__logo:
            print((" " * left) + line, end="")

        print('\n' * bottom, end="")

    def __print_rules(self, left=0):
        """Prints rules to screen. Has optional x and y parameters to offset logo
        by specified amount of lines and spaces.

        Args:
            self (Console): An instance of Console.
            left (int): Number of spaces to offset rules from left of screen

        """

        for line in self.__rules:
            print((" " * left) + line, end="")

    def menu(self):
        """Shows menu to start game.

        Args:
            self (Console): an instance of Console.
        """

        while self.__show_menu and not self.stop_game:

            p_num = 0
            if self._roster.get_roster():
                p_num = len(self._roster.get_roster())

            add_text = "Add/Remove Players [" + str(p_num) + " registered]"
            choice_list = [(add_text, "add"), "Rules",
                           ("Leaderboard", "scores"), "Quit"]

            if self._roster.get_roster():
                choice_list.insert(0, "START")

            questions = [
                inquirer.List(
                    'selection',
                    message="MENU (Use ↑ and ↓ to select, ENTER to confirm)",
                    choices=choice_list,
                    carousel=True,
                    default="add")
            ]

            self.clear_screen()
            self.__print_logo()
            selection = inquirer.prompt(questions)['selection'].lower()

            if selection == "start":
                self.__show_menu = False
                return self._roster.get_roster()
            elif selection == "add":
                self.__add_players()
            elif selection == "rules":
                self.__show_rules()
            elif selection == "scores":
                self.__show_scoreboard()
            elif selection == "quit":
                self.__quit()

    def __add_players(self):
        """Asks records player names.

        Args:
            self (Console): an instance of Console.
        """
        players_list = []
        players_list.extend([("NEW PLAYER", "**new**")])
        players_list.extend(self._roster.get_roster())
        players_list.extend([("BACK TO MENU", "**menu**")])

        players = [
            inquirer.List(
                'selection',
                message="ADD/REMOVE (Use ↑ and ↓ to select, ENTER to confirm)",
                choices=players_list,
                default="NEW PLAYER",
                carousel=True)
        ]

        self.clear_screen()
        self.__print_logo()
        selection = inquirer.prompt(players)['selection']

        if selection == "**menu**":
            pass
        elif selection == "**new**":
            name = self.__prompt_name()
            if name:
                self._roster.add_player(name)
        else:
            delete = inquirer.confirm(f"Do you want to remove '{selection}'?",
                                      default=True)
            if delete:
                self._roster.remove_player(selection)
            input(f"'{selection}' removed. Press ENTER to continue.")

    def __prompt_name(self):
        """Prompts for player name,.

        Args:
            self (Console): an instance of Console.
        """
        self.clear_screen()
        self.__print_logo()

        name = input("[!] Enter new player name and press ENTER:\n\n   ")
        if not (2 < len(name) < 16):
            self.clear_screen()
            self.__print_logo()
            print("Username must be between 3 and 15 characters.")
            input("Press ENTER to return to player menu.")
        elif name in self._roster.get_roster():
            self.clear_screen()
            self.__print_logo()
            print("Player already exists.")
            input("Press ENTER to return to player menu.")
        else:
            return name

    def __show_rules(self):
        """Asks records player names.

        Args:
            self (Console): an instance of Console.
        """
        self.clear_screen()
        self.__print_logo()
        self.__print_rules(left=20)
        input()

    def __show_scoreboard(self):
        """Asks records player names.

        Args:
            self (Console): an instance of Console.
        """
        self.clear_screen()

        print('\n' * 2, end="")
        for line in self.__fame:
            print((" " * 5) + line, end="")
        print('\n' * 2, end="")

        with open("mastermind/assets/scores.json", "r") as data:
            board = list(load(data).items())

        space = " " * 11
        print(f"{space}RANK     {'PLAYER':<30}" +
              f"{'TIME':>7} (seconds){'POINTS':>29}\n")

        lines_printed = 0
        for idx, entry in enumerate(board[:10]):
            lines_printed += 1
            space = " " * 10
            n = idx + 1
            year, month, day, time = entry[0].split(" ")
            points = entry[1]["points"]
            playtime = entry[1]["playtime"]
            player = entry[1]["player"]

            print(f"{space}{n:>4}.     {player:<30}" +
                  f"{playtime:>7,.2f}{points:>36}/15")

        lines = "\n" * (12 - lines_printed)
        print(f"{lines}{space}", end="")
        sleep(.25)
        self.cool_print("Press ENTER to return to player menu.",
                        newline=False,
                        margin=0)
        input()

    def __quit(self):
        """Asks records player names.

        Args:
            self (Console): an instance of Console.
        """
        self.clear_screen()
        self.__print_logo()
        print('\n' * 3)
        self.cool_print("THANKS FOR PLAYING!")
        sleep(2)
        self.stop_game = True
コード例 #7
0
class Director:
    """
    A code template for a person who directs the game. The responsibility of 
    this class of objects is to keep track of the score and control the 
    sequence of play.
    
    Attributes:
        _console = An instance of the Console class
        _logic = An instance of the Logic class
        _roster = An instance of the Roseter class
        _keep_playing (boolean) = Defines whether or not the game loop should continue
        _player_guess (string) = Holds the most recent player's guess
        _passcode (string) = The code the players are trying to guess. Since this is a static attribute, 
                             it is convient to define it here and use it throughout the program instead of 
                             calling the on the _logic class every time. 
    """
    def __init__(self):

        self._passcode = ''
        self._player_guess = ''
        self._keep_playing = True
        self._console = Console()
        self._roster = Roster()
        self._logic = Logic()

    def start_game(self):
        """
        Starts the game loop
        """

        self._prepare_game()
        while self._keep_playing == True:
            self._get_input()
            self._do_updates()
            self._do_output()

    def _prepare_game(self):
        """Prepares the game before it begins. 
           This entails :
                Adding each play to the board
                Creating and displaying the intial board
                Setting the passcode

        Args:
        self (Director): An instance of Director.
        """

        # A simple loop to identify each player and add them to the roster
        self._console.write("Welcome to the H.A.C.K.")
        for n in range(2):
            name = self._console.read(f"Enter a name for player {n + 1}: ")
            player = Player(name)
            if n == 0:
                self.player1 = player
            else:
                self.player2 = player
            self._roster.add_player(player)

        # Creates the board class with the two new players
        self._board = Board(self.player1, self.player2)

        #Creates the first board and displays it to the terminal
        board = self._board.create_board_string()
        self._console.write(board)

        #Uses the logic class to set the passcode that will be used for the game
        self._logic.set_passcode()

    def _get_input(self):
        """
        Asks the user for their guess each round, also switches the turns before any further actions
        """
        #Begins the turn system
        self._roster.next_player()

        #Retrieves and displays whoever's turn it is
        self.current_player = self._roster.get_current()
        self._console.write(f"{self.current_player.get_name()}'s guess:")
        Thread(target=self._console.timer_for_turn).start()
        Thread(target=self._console.read_for_turn).start()
        time.sleep(self._console._countdown)

        self._player_guess = self._console._answer

    def _do_updates(self):
        """
        An in depth "if" statement that updates key game information based on the user's input and current player

        """
        # If the player is number 1, then the board is updated according to what they entered. The same is true for player 2.
        if self._roster.current == 0:

            self.player1.set_guess(self._player_guess)

            player1_hint = self._logic.get_hint(self._logic.get_passcode(),
                                                self.player1.get_guess())
            self.player1.set_hint(player1_hint)

            board = self._board.update_board(self.player1.get_guess(),
                                             self.player1.get_hint(),
                                             self.player2.get_guess(),
                                             self.player2.get_hint())
            self._console.write(board)

        elif self._roster.current == 1:

            self.player2.set_guess(self._player_guess)

            player2_hint = self._logic.get_hint(self._logic.get_passcode(),
                                                self.player2.get_guess())
            self.player2.set_hint(player2_hint)

            board = self._board.update_board(self.player1.get_guess(),
                                             self.player1.get_hint(),
                                             self.player2.get_guess(),
                                             self.player2.get_hint())
            self._console.write(board)

    def _do_output(self):
        """
        Determines if the game will continue or end
        """

        if self._logic.is_correct(self._player_guess) == True:
            self._console.write(
                f'{self._roster.get_current().get_name()} Wins!!')
            self._console.write("""
___________________ __________    _____________________________________________________________
\__    ___/\_____  \ ______   \  /   _____/\_   _____/\_   ___ \______   \_   _____/\__    ___/
  |    |    /   |   \|     ___/  \_____  \  |    __)_ /    \  \/|       _/|    __)_   |    |   
  |    |   /    |    \    |      /        \ |        \|     \___|    |   \|        \  |    |   
  |____|   \_______  /____|     /_______  //_______  / \______  /____|_  /_______  /  |____|   
                   \/                   \/         \/         \/       \/        \/            
   _____ _____________________   _____     .____________                                       
  /  _  \ |_____   \_   _____/  /  _  \    |   ____/_   |                                      
 /  /_\  \|       _/|    __)_  /  /_\  \   |____  \ |   |                                      
/    |    \    |   \|        \/    |    \  /       \|   |                                      
\____|__  /____|_  /_______  /\____|__  / /______  /|___|                                      
        \/       \/        \/         \/         \/                   
            You're in...""")
            self._keep_playing = False

        elif self._logic.is_correct(self._player_guess) == False:
            self._keep_playing == True