Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from random import choice
- from bs4 import BeautifulSoup
- from string import ascii_letters
- import requests
- class Hangman:
- def __init__(self, *words):
- """A text-based game of the all-time classic, Hangman. Can you save the man from the gallows?
- :param words:
- Word(s) to be used for the game. String(s) can be passed directly as parameter(s) or in a list or
- in a tuple. A word is chosen by random and assigned to 'self.word', which is then used for the
- player to guess in a game of a hangman.
- """
- while isinstance(words, list) or isinstance(words, tuple):
- words = choice(words)
- if not isinstance(words, str):
- raise TypeError(f"Expected 'str' type. Got {type(words)} instead.")
- self.word = words.lower()
- self.correct_guess = set(' ')
- self.incorrect_guess = set()
- self.attempts = 8
- self.center = num if (calc := len(self.word) * 2 - 1) < (num := 15 + len(self.word)) else calc
- def play(self):
- """Initiate a game of hangman.
- """
- self.draw_hangman()
- while not set(self.word).issubset(self.correct_guess):
- if (guess := self.get_letter()) in set(self.word):
- self.success_msg(guess)
- continue
- self.failed_msg(guess)
- if self.game_over():
- return
- print(f"{'YOU WIN':^{self.center}}\n{'You guessed ' + self.word.upper():^{self.center}}\n")
- def get_letter(self):
- """Return a single letter from the player's input. Also checks if the input is unique from previous inputs.
- """
- while True:
- if len(guess := input('Enter a letter: ').lower()) > 1 or not guess.isalpha():
- print("Please enter one letter.")
- continue
- if guess in self.correct_guess | self.incorrect_guess:
- print(f"You already entered '{guess}'. Please enter another letter.")
- continue
- return guess
- def success_msg(self, guess):
- """Display a success message along with the current progress of the game. Also updates set for correct guesses.
- """
- self.correct_guess.update(guess)
- print(f"\n{'SUCCESS!':^{self.center}}")
- self.draw_hangman()
- def failed_msg(self, guess):
- """Display a failed message along with the current progress of the game. Also updates set for incorrect guesses
- and subtracts one from attempts
- """
- self.attempts -= 1
- self.incorrect_guess.update(guess)
- print(f"\n{'FAILED!':^{self.center}}")
- self.draw_hangman()
- def game_over(self):
- """Returns a True if the user is out of attempts.
- """
- if self.attempts < 1:
- print(f"{'GAME OVER':^{self.center}}\n{'The answer was ' + self.word.upper():^{self.center}}.\n")
- self.attempts = 8
- return True
- return False
- def draw_hangman(self):
- """Displays the number of attempts remaining and draws the hangman based on the attempts the player has left.
- Also shows the player's progress on what letters they've guessed correctly.
- """
- print(f"{str(self.attempts) + ' Attempts left':^{self.center}}")
- # Displays hangman board when these strings are joined with a new line separator. i.e. '\n'.join(_hangman)
- _hangman = [' _____ ', ' | | ', ' | ', ' | ', ' | ', ' _|_']
- # Modifies the hangman board based on player attempts.
- if self.attempts < 8: _hangman[2] = _hangman[2][:2] + 'O' + _hangman[2][3:] # Draw head
- if self.attempts < 7: _hangman[3] = _hangman[3][:1] + '/' + _hangman[3][2:] # Draw left arm
- if self.attempts < 6: _hangman[3] = _hangman[3][:2] + '|' + _hangman[3][3:] # Draw torso
- if self.attempts < 5: _hangman[3] = _hangman[3][:3] + '\\' + _hangman[3][4:] # Draw right arm
- if self.attempts < 4: _hangman[4] = _hangman[4][:0] + '_' + _hangman[4][1:] # Draw left foot
- if self.attempts < 3: _hangman[4] = _hangman[4][:1] + '/' + _hangman[4][2:] # Draw left leg
- if self.attempts < 2: _hangman[4] = _hangman[4][:2] + "'\\" + _hangman[4][4:] # Draw right leg
- if self.attempts < 1: _hangman[4] = _hangman[4][:4] + '_' + _hangman[4][5:] # Draw right foot
- print(*[f"{section:^{self.center}}" for section in _hangman], sep='\n')
- print(f"{' '.join([x.upper() if x in self.correct_guess else '_' for x in self.word]):^{self.center}}", '\n')
- class CommentGetter:
- def __init__(self):
- """Module used for grabbing random comments from pornhub's comment section.
- """
- self.url = 'https://www.pornhub.com/'
- data = requests.get(self.url)
- self.soup = BeautifulSoup(data.text, 'lxml')
- def get_rand_video(self):
- """Returns url of a random video from the hot section
- """
- hot_section = self.soup.find('ul', id='hotVideosSection')
- return self.url[:-1] + choice([section.div.div.a['href'] for section in hot_section.find_all(
- 'li', class_='js-pop videoblock videoBox')])
- def get_rand_comment(self, url=None):
- """Returns a random comment from a random video.
- """
- if url is None:
- url = self.get_rand_video()
- data = requests.get(url)
- soup = BeautifulSoup(data.text, 'lxml')
- comments = [comment.span.text for comment in soup.find_all('div', class_='commentMessage')]
- while True:
- if len(comment := ''.join([char for char in choice(comments) if char in ascii_letters + ' '])) > 1:
- return comment
- def ask_play():
- """Ask the player if he/she would like to play.
- """
- while True:
- if (play := input("Would you like to play Hangman? [Y/N]: ").lower()) in ['yes', 'y', '1']:
- return True
- if play in ['no', 'n', '2']:
- raise SystemExit
- print('Invalid input. Please try again.')
- def main():
- while True:
- if ask_play():
- print('Fetching Comment...')
- rand_comment = CommentGetter().get_rand_comment()
- Hangman(rand_comment).play()
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement