Created
February 9, 2013 01:06
-
-
Save alenbasic/4743309 to your computer and use it in GitHub Desktop.
A hangman game based on the words file in *nix systems.
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
import random | |
file = open("/usr/share/dict/words").read().splitlines() | |
dict = [] | |
for word in file: | |
dict.append(word) | |
guesses = [] | |
incorrect = 10 | |
word = (dict[random.randrange(0,len(dict)-1)]).lower() | |
blank = list('*' * len(word)) | |
print "##### THE HANGMAN GAME #####" | |
print "The word is %d letters long" % len(blank) | |
while True: | |
i = 0 | |
if incorrect == 0: | |
print "Sorry, you ran out of tries. The word was '%s'" % word | |
exit(0) | |
print ''.join(blank) | |
guess = raw_input("Please choose a letter: ") | |
if guess == word: | |
print "Congrats! You win! The word was '%s'" % word | |
exit(0) | |
elif len(guess) != len(word) and len(guess) > 1: | |
print "You can only choose one letter at a time, or guess the whole word" | |
continue | |
elif len(guess) == len(word) and guess != word: | |
incorrect -= 1 | |
print "Sorry, but your guess is incorrect. You have %d incorrect tries left" % incorrect | |
continue | |
if guess in guesses: | |
print "You have already chosen this letter, please try again." | |
print "Letters tried so far: %s" % guesses | |
continue | |
else: guesses.append(guess) | |
if guess in word: | |
while i < len(word): | |
if word[i] == guess: | |
blank[i] = guess | |
i += 1 | |
elif guess not in word: | |
print "Sorry, this letter is not in this word." | |
incorrect -= 1 | |
print "You have %d incorrect tries left." % incorrect | |
complete = ''.join(blank) | |
if complete == word: | |
print "Congrats! You win! The word was '%s'" % word | |
exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment