Lesson 13: Hangman searchspace

posted Jan 25, 2018, 8:03 AM by Attila Lengyel
import word_dict
import random

def drawHangman(missedGuess):
    if missedGuess > 0:
        print("       _________")
    else:
        print("")
    if missedGuess > 1:
        print("       |        |")
    else:
        print("       |        ")
    if missedGuess > 2:
        print("       |        0")
    else:
        print("       |        ")
    if missedGuess > 3:
        print("       |       /|\\")   
    else:
        print("       |        ")
    if missedGuess > 4:
        print("       |        |")
    else:
        print("       |        ")
       
    if missedGuess > 5:
        print("       |       / \\")
    else:
        print("       |        ")
   
    print("       _________")
    print("")

    if missedGuess > 6:
        return True
    else:
        return False

def wordlength(length):
  searchspace = []
  for w in word_dict.db:
    if len(w) == length:
      searchspace.append(w)
  return searchspace

def eliminateMissed(searchspace, missed_letters):
  searchspace2 = []
  for w in searchspace:
    add = True
    for y in missed_letters:
      if w.find(y) != -1:
        add = False
    if add:
      searchspace2.append(w)
  print(searchspace2)
  print(len(searchspace2))
  return searchspace2
 
eliminateMissed(wordlength(4), "aeiurso")

print("Let's play Hangman")

select = random.randint(0,len(word_dict.db))
word = word_dict.db[select]

word_dash = ""
for x in range(0, len(word)):
  word_dash += "_ "
 
print (word_dash)

cont = True
lost = False

good_letters = ""
missed_letters = ""
missedGuess = 0
 
while cont:

  guess = input("Guess a letter:")
 
  if word.find(guess) > -1 and good_letters.find(guess) == -1:
    print("Correct guess!")
    good_letters += guess
  else:
    print("Wrong guess!")
    missedGuess += 1
    missed_letters += guess
    lost = drawHangman(missedGuess)
   
   
 
  cont = False 
  word_dash = ""
  for x in range(0, len(word)):
    if good_letters.find(word[x]) > -1:
      word_dash += word[x] + " "
    else:
      word_dash += "_ "
      cont = True
  if lost:
    cont = False
  print(word_dash)
 
print("The correct word is ", word)
if lost:
  print("Sorry you are hanged...")
else:
  print("You are safe!!!")
Comments