Esempio n. 1
0
 def run(self):
     """Run the game until the player wins or exhausts lives."""
     phrase = Phrase(choice(self._phrases))
     phrase.display()
     while not self._gameover:
         guess = input("Guess a letter: ")
         if guess in phrase._guessed:
             print("You already guessed {}. Try another letter.".format(
                 guess))
             phrase.display()
             continue
         if phrase.check_guess(guess):
             print("Correct guess!")
             phrase.display()
             if phrase.check_game():
                 self._gameover = True
                 print("You won! Game over.")
         else:
             print("Incorrect guess.")
             self._lives -= 1
             print("You have {} out of 5 lives remaining!".format(
                 self._lives))
             phrase.display()
             if self._lives <= 0:
                 self._gameover = True
                 print("You have no more lives. Game over.")
Esempio n. 2
0
class Game():
    def __init__(self):
        import re, random
        from phrasehunter.phrase import Phrase

        with open("phrasehunter/phrase_master_list.txt") as open_file:
            data = open_file.read()

        # Ensure there is at least one valid phrase in phrase_master_list.txt.
        try:
            random_phrase = random.choice(re.findall(r'[\w ]+[^\n\d_]', data))
            self.current_phrase = Phrase(random_phrase)

        except IndexError as err:
            print(
                "There are currently no saved phrases. Please add at least one valid"
                " phrase before playing the game.")

    def start_game(self, *args):
        print('Welcome to the Guess-That-Phrase! Guess the phrase to win!')

        # Display the initial phrase with hidden characters.
        for char in self.current_phrase.collection:
            print(char.show(), end=" ")
        print("\n")
        while self.current_phrase.correct_count < self.current_phrase.length and self.current_phrase.incorrect_count < int(
                5):

            # Collect user guesses.
            self.current_phrase.check_guess(
                input('What letter would you like to guess?   '))

        # If there are five incorrect guesses, the player loses.
        if self.current_phrase.incorrect_count == 5:
            print('Sorry, you lose. Only five incorrect guesses are allowed.')

        # If the player guesses all characters in the phrase, they win.
        elif self.current_phrase.correct_count == self.current_phrase.length:
            print('Congratulations! You guessed the phrase. You win.')
        print("Would you like to play again?")
class Game:
    '''
    Play one Game of Phrase Hunter
    '''
    def __init__(self, phrases):
        '''
        :param phrases: list of phrases which can be used for the game
        :type phrases: list of tuples (each tuple contains phrase and author)
        Attributes:
            phrase = one quote (selected randomly from the list of quotes passed in)
            won = flag to indicate whether game won or not, True or False
            lives = count of number of lives a player has left.  Starts at 5, reduces by 1 for
                each incorrect guess
            letters_guessed = a list which keeps track of which letters the player has guessed
        '''
        self.phrase = Phrase(phrases[random.randint(0, len(phrases) - 1)])
        self.won = False
        self.lives = 5
        self.letters_guessed = []

    def get_guess(self):
        """
        Control the process of getting a guess from the player
        Keep asking for guess until it is valid (i.e. a single letter a-z, case insensitive)
        :return: the guessed letter
        :rtype: str
        :raises: ValueError - if user input invalid (i.e. not a single letter)
        """
        guessed_char = ''
        valid_guess = False
        while not valid_guess:
            try:
                guessed_char = input('Enter a letter (a-z): ')
                if len(guessed_char) > 1:
                    raise ValueError(
                        'Too many characters entered - please enter only one letter'
                    )
                if len(guessed_char) < 1:
                    raise ValueError('Nothing entered - please enter a letter')
                if re.search(r'[^A-Za-z]', guessed_char):
                    raise ValueError(
                        'Invalid character entered - please enter a letter (a-z) '
                    )
                if guessed_char.lower() in self.letters_guessed:
                    raise ValueError(
                        "You've already guessed this letter, try again ")
            except ValueError as err:
                print(err)
                continue
            valid_guess = True
        return guessed_char

    def play_game(self):
        """
        Control the game play
        Loop asking player to guess a letter and displaying the updated phrase
        (guessed letters becoming visible) until either the phrase has been guessed
        or player is out of lives
        """
        print('Welcome to Phrase Hunter !')
        print('guess a letter in the phrase')
        print('5 guesses to get the phrase')
        while not self.won and self.lives > 0:
            print(f'You have {self.lives} guesses left')
            print('Current phrase is: ', end='')
            self.phrase.display_phrase()
            guessed_char = self.get_guess()
            self.letters_guessed.append(guessed_char.lower())
            good_guess = self.phrase.check_guess(guessed_char)
            if good_guess:
                print('Good guess')
                self.won = self.phrase.check_if_won()
            else:
                print('Sorry this letter not in phrase')
                self.lives -= 1
        if self.won:
            print("********************************")
            print(" Magnificent job, you got it !! ")
            print("********************************")
        else:
            print("Sorry you didn't get it this time.")
        print("Complete quote:\n\n " + self.phrase.show_full_quoted_phrase() +
              "\n")