Skip to content

Instantly share code, notes, and snippets.

@tmitzka
Last active April 15, 2018 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmitzka/2913b6edec332f023db002ef7d72624c to your computer and use it in GitHub Desktop.
Save tmitzka/2913b6edec332f023db002ef7d72624c to your computer and use it in GitHub Desktop.
A text-based game of Hangman.
"""A game of Hangman."""
import string
import random
import sys
# Define constants.
FILENAME = "words.txt"
WRONG_MAX = 10
class Hangman():
"""The Hangman class."""
def __init__(self):
"""Initalize attributes."""
self.word = ""
self.guessed_word = ""
self.wrong_letters = []
self.wrong_guesses = 0
self.allowed_letters = string.ascii_uppercase
self.reset_game()
def __repr__(self):
"""Return information about this class."""
return "A game of Hangman."
def reset_game(self):
"""Reset attributes to start a new game."""
# Choose a new word.
self.word = self.choose_word()
# Create a string to represent the guessed word.
characters = ["*" for letter in self.word]
self.guessed_word = "".join(characters)
self.wrong_letters = []
self.wrong_guesses = 0
@staticmethod
def choose_word():
"""Choose a word from the word file."""
words = []
try:
with open(FILENAME) as word_file:
for line in word_file:
words.append(line.strip())
except FileNotFoundError:
print(f"The word file {FILENAME} wasn't found.")
sys.exit()
else:
return random.choice(words).upper()
def update_guessed_word(self, letter):
"""Update the string to show the player's progress."""
new_string = ""
for i in range(len(self.word)):
if self.word[i] == letter:
new_string += letter
else:
new_string += self.guessed_word[i]
self.guessed_word = new_string
def get_input(self):
"""Get a letter from the player."""
player_input = ""
while (
len(player_input) != 1 or
player_input not in self.allowed_letters or
player_input in self.guessed_word or
player_input in self.wrong_letters
):
print()
# Show wrong letters.
if self.wrong_letters:
print("Wrong letters:", end=" ")
print(", ".join(self.wrong_letters), end=" ")
print(f"({self.wrong_guesses}/{WRONG_MAX})")
player_input = input("Enter a letter: ").strip().upper()
if (
len(player_input) != 1 or
player_input not in self.allowed_letters
):
print("Please enter only a single letter.")
elif player_input in self.guessed_word:
print(f"You already guessed the letter {player_input}.")
elif player_input in self.wrong_letters:
print(f"You already tried the letter {player_input}.")
return player_input
def play(self):
"""Play the game until the player guessed the word."""
print("Hi there! Let's play Hangman.")
while True:
print("Here is your word:")
while (
self.guessed_word != self.word and
self.wrong_guesses < WRONG_MAX
):
# Show the guessed word and get the next letter.
print(f"\n{self.guessed_word}")
letter = self.get_input()
# Tell the user whether the guess was right or wrong.
if letter in self.word:
print(f"\nYup, the letter {letter} is in that word.")
self.update_guessed_word(letter)
else:
print(f"\nNope, there's no letter {letter}.")
self.wrong_letters.append(letter)
self.wrong_letters.sort()
# Raise counter for wrong guesses.
self.wrong_guesses += 1
# The player has either won or lost this game.
if self.guessed_word == self.word:
print(f"\nAwesome, you guessed it!")
else:
print("\nSorry, you're dead.")
print(f"The word was: {self.word}")
# Play again?
answer = ""
while len(answer) != 1 or answer not in "yn":
answer = input("\nDo you want to play again? (y/n) ").lower()
if answer == "y":
self.reset_game()
else:
break
print("Bye, see ya!")
def main():
"""The main function."""
hman = Hangman()
hman.play()
if __name__ == "__main__":
main()
universe
space
planet
rocket
asteroid
astronaut
satellite
earth
moon
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment