Created
January 7, 2019 07:12
-
-
Save shailrshah/dd6b996108ff35225b6bbe387211ea0d to your computer and use it in GitHub Desktop.
Hangman
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from re import compile | |
class Hangman: | |
"""Play Hangman""" | |
def __init__(self, word="demo", chances=3): | |
"""Initialize the game with the correct word and number of chances""" | |
self.wordPattern = compile("^[a-z]+$") | |
self.guessPattern = compile("^[a-z]$") | |
if not self.wordPattern.match(word): | |
raise ValueError("The word should contain only alphabets.") | |
if chances < 1: | |
raise ValueError("At least 1 chance should be provided.") | |
self.word = list(word.lower()) | |
self.currWord = list('#' * len(word)) | |
self.chances = chances | |
self.history = set() | |
def guess(self, ch): | |
"""Guess an alphabet from the word""" | |
if not self.guessPattern.match(ch): | |
print("Please guess a single lowercase alphabet.") | |
return False | |
if ch in self.history: | |
print("Already guessed", ch) | |
return False | |
self.history.add(ch) | |
count = 0 | |
for i in range(len(self.word)): | |
if self.word[i] == ch: | |
self.currWord[i] = ch | |
count += 1 | |
if count == 0: | |
self.chances -= 1 | |
print("Sorry, wrong guess!") | |
else: | |
print("The guess is right!") | |
return count > 0 | |
def run(self): | |
"""driver for the game""" | |
print("Welcome to Hangman! You have", self.chances, | |
"to guess the correct word!") | |
while self.chances > 0: | |
print(self.chances, "left.", self.currWord) | |
alphabet = input("Guess an alphabet") | |
self.guess(alphabet) | |
if self.word == self.currWord: | |
print("You Win! The word was", "".join(self.currWord)) | |
return True | |
print("You lose!") | |
return False | |
Hangman("abracadabra", 3).run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment