# Lesson 18 - Hangman computer player

Post date: Mar 8, 2018 6:03:29 PM

import word_dict, random

def drawhangman(missedGuesses):

if missedGuesses <= 0: return

print(" _____________")

if missedGuesses > 1:

print(" | |")

else: print(" |")

if missedGuesses > 2:

print(" | O")

else: print(" |")

if missedGuesses > 3:

print(" | /|\\")

else: print(" |")

if missedGuesses > 4:

print(" | |")

else: print(" |")

if missedGuesses > 5 :

print(" | / \\")

else: print(" |")

print(" |")

print(" |")

print(" |_____________")

def lengthwords(searchspace, length):

returnspace = []

for w in searchspace:

if len(w) == length:

returnspace.append(w.lower())

return returnspace

def match(searchspace, pattern):

returnspace = []

for w in searchspace:

for x in range(0, len(w)):

if pattern[x] != "_" and w[x] != pattern[x]:

break

returnspace.append(w)

return returnspace

def eliminatemissed(searchspace, missedletters):

returnspace = []

for w in searchspace:

for l in w:

if missedletters.find(l) != -1:

break

returnspace.append(w)

return returnspace

def stat(searchspace, pattern):

abc = "abcdefghijklmnopqrstuvwxyz"

lstat = {}

for c in abc:

lstat[c] = 0

for w in searchspace:

letters = ""

for c in w:

if letters.find(c) == -1:

letters += c

for c in letters:

lstat[c] += 1

count = 0

letter = ""

for c in abc:

if pattern.find(c) == -1:

if lstat[c] > count:

count = lstat[c]

letter = c

return letter

def guess(wordlength, pattern, eliminatedletters):

space = lengthwords(word_dict.db, wordlength)

space = match(space, pattern)

space = eliminatemissed(space, eliminatedletters)

lstat = stat(space, pattern)

return lstat

def play(word):

good_letters = ""

eliminated_letters =""

word_dash = ""

for x in range(0, len(word)):

word_dash += "_ "

print (word_dash)

missed_guesses = 0

while missed_guesses < 7 and word_dash.find("_") != -1:

automatedguess = guess(len(word), word_dash.replace(' ',''), eliminated_letters)

print("Let me guess:", automatedguess)

if word.find(automatedguess) > -1:

print("Correct guess!")

good_letters += automatedguess

else:

eliminated_letters += automatedguess

print("Wrong guess!")

missed_guesses = missed_guesses + 1

drawhangman(missed_guesses)

word_dash = ""

for x in range(0, len(word)):

if good_letters.find(word[x]) > -1:

word_dash += word[x] + " "

else:

word_dash += "_ "

print(word_dash)

print("The word is", word)

#This is the main program

size = len(word_dict.db)

print("Let's play Hangman")

wordindex = random.randint(0, size)

randomword = word_dict.db[wordindex]

randomword = randomword.lower()

play(randomword)