Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Created January 22, 2020 18:22
Show Gist options
  • Save shailrshah/b26ee8e8b44d2688616961d45f0dd2df to your computer and use it in GitHub Desktop.
Save shailrshah/b26ee8e8b44d2688616961d45f0dd2df to your computer and use it in GitHub Desktop.
Play hangman on the command line
from collections import defaultdict
from os import system
def clear():
_ = system('clear')
class Hangman:
def __init__(self):
self.word = input("Enter the word to guess: ").lower()
if not self.word.isalpha():
raise Error("The word should have only alphabets")
self.word_indices = defaultdict(set)
for i in range(len(self.word)):
self.word_indices[self.word[i]].add(i)
self.tries_left = int(input("Enter the number of tries: "))
if self.tries_left < 1:
raise Error("The player should have at least one try")
self.correct_guesses = 0
self.curr_state = [ '-' for i in range(0, len(self.word)) ]
clear()
print("Game initialized. Let's play Hangman!")
def guess(self, guessed_alphabet):
matched_indices = self.word_indices[guessed_alphabet]
matched_count = len(matched_indices)
self.correct_guesses += matched_count
if matched_count == 0:
self.tries_left -= 1
for i in matched_indices:
self.curr_state[i] = guessed_alphabet
return matched_count > 0
def get_curr_state(self):
return " ".join(self.curr_state)
def run(self):
while self.tries_left > 0 and self.correct_guesses < len(self.word):
print()
print("You have ", self.tries_left, " tries left")
print("The word is ", self.get_curr_state())
guessed_alphabet = input("Guess an alphabet: ")
if self.guess(guessed_alphabet):
print("Yay, it was a hit")
else:
print("Oh no! it was a miss.")
if self.correct_guesses == len(self.word):
print("You win!")
else:
print("You loose!")
print("Game over.")
Hangman().run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment