This is an interactive game between the computer and the player, where the computer chooses a word and the user has to guess the letters in that word.
The computer provides certain number of guesses to the user.
Below is my code:
import random
import string
def load_words():
print "Loading word list from file..."
inFile = open("words.txt", 'r', 0)
line = inFile.readline()
wordlist = line.split()
print " ", len(wordlist), "words loaded."
return wordlist
wordlist = load_words()
def choose_word(wordlist):
return random.choice(wordlist)
def avail_letters(guesses,guess):
return guesses.replace(guess,'')
def fill_blank(random_word,blank,guess):
blank_new=''
for i,l in enumerate(random_word):
if l==guess:
blank_new+=guess
else:
blank_new+=blank[i]
#print blank_new
return blank_new
def hangman():
random_word=choose_word(wordlist)
## print random_word
len_word=len(random_word)
print "I am thinking of a word that is ",len_word," letters long."
print "-------------"
no_of_guesses=len_word*2
guesses=string.ascii_lowercase
guess=''
blank="_"*len_word
while no_of_guesses:
print "You have ",no_of_guesses," guesses left."
guesses=avail_letters(guesses,guess)
print "Available letters: ",guesses
guess=raw_input("Please guess a letter: ")
if guess in random_word and guesses:
blank=fill_blank(random_word,blank,guess)
print "Good guess: ",blank
else:
print "Oops! That letter is not in my word: ",blank
no_of_guesses-=1
print "-------------"
if blank==random_word:
print "Congratulations, you won!"
break;
else:
print "Sorry, you lose!"