7
\$\begingroup\$

This code is for the game Hangman, I added a little bonus in it for cheating/debugging reasons, I thought it's worth sharing since it's the biggest code I've created yet.

Description:

Classic game of Hangman, that allows the user to cheat if they answer the riddle correctly

import time
import random

global fails, num, guessed, secretWord

fails = 0
num = 1
guessed = []


words = ["pizza", "fox", "apple", "carrot", "tree", "town", "house", "hangman", "cake", "dog", "cat", "elephant",\
              "building", "cop", "chicken", "parrot", "forest", "bird", "heist", "crime", "christmas", "death", "ripper"]
secretWord = list(random.choice(words))


print("\t\t----Welcome to Hangman!----\n")
print("=" * 60)

def main():

     confirm = input("\n\tAre you ready to start? y/n \nChoice: ")
     confirm = confirm.lower()

     if confirm == "y":
          print("\n\tGet ready to lose.")
          time.sleep(1)
          print("=" * 60)
          secretCode()
          wordFunc()

     elif confirm == "n":
          print("\n\tOk. Suit yourself.")
          time.sleep(1)
          exit()
     else:
          print("\n\tI didn't catch that. Let me ask you again..")
          time.sleep(1)
          main()

def secretCode():
     global secretWord

     print("\n----You meet a squirrel on your way to the noose.The squirrel gives you an offer that can save your life.----")
     print("\n\t\t----If you answer the squirrel's riddle you get to live.----")
     time.sleep(2)

     print("\n\t\t\t----The riddle is----")
     time.sleep(1)

     print("\n\t----'You can see me in water, but I never get wet. What am I?'----")
     answer = input("\n\tYour answer is: ")

     time.sleep(3)

     if answer.lower() == "a reflection":
          print("\n\tSquirrel: Well done. The word that they'll use is : ", "".join(secretWord))
          wordFunc()
     else:
          print("\n\tYou are not worthy of my help. Begone")
          wordFunc()

def wordFunc():          
     global secretWord, hiddenChar

     print("\n\t----Wait a bit until I think about the secret word...----")
     time.sleep(2)

     print("\n\t\t----Done. Get ready...----")
     time.sleep(1)

     print("=" * 60)

     print("____")
     print("|      |")
     print("|")
     print("|")                           
     print("|")
     print("|")
     print("|")
     print("====")

     print("\n\t----The word you are trying to guess is", len(secretWord), "letters.----")

     hiddenChar = ["_"] * len(secretWord)
     print ("\n\t\t\t"," ".join(hiddenChar))
     guess()

def guess():
     global secretWord, fails, num, hiddenChar 
     while fails < 9:
          c = input("\n\t\tChoose a letter: ")
          guessed.append(c)

          print("\n\t\t The letters you have guessed so far are: ", " ".join(guessed))

          if c in secretWord:
               itmIndx = secretWord.index(c)
               for i, x in enumerate(secretWord):
                        if x == c:
                             hiddenChar[i] = c;
                        else:
                             hiddenChar[itmIndx] = c
               num +=1

               if num > 2 and c in secretWord:
                    hiddenChar[itmIndx] = c
                    num +=1

                    print("\n\tOk, you're correct.")
                    print ("\n\t\t\t"," ".join(hiddenChar))
                    time.sleep(1)

               else:
                    print("\n\tYou are correct, but you're not going to win this, you know right?")
                    print ("\n\t\t\t"," ".join(hiddenChar))
                    time.sleep(1)

               winCheck(hiddenChar, fails)      
               guess()

          else:
               fails += 1
               print("Wrong letter!")
               time.sleep(1)

               hangmanFails()

def winCheck(hiddenChar, fails):
     global secretWord

     if "_" not in hiddenChar and fails < 8:
          print("\n\t\t----You win. Congrats!----")
          time.sleep(1)
          exit()
     else:
          return guess()

def hangmanFails():
     global fails, secretWord

     if fails == 1:
               print("There appears your head...")
               print("____")
               print("|      |")
               print("|    (_)")
               print("|")                           
               print("|")
               print("|")
               print("|")
               print("====")

     elif fails == 2:
               print("____")
               print("|      |")
               print("|    (_)")
               print("|      l")
               print("|")
               print("|")
               print("|")
               print("====")

     elif fails == 3:
               print("____")
               print("|      |")
               print("|    (_)")
               print("|      l")
               print("|     +")
               print("|")
               print("|")
               print("====")

     elif fails == 4:
               print("____")
               print("|      |")
               print("|    (_)")
               print("|      l")
               print("|    /+")
               print("|")
               print("|")
               print("====")

     elif fails == 5:
               print("____")
               print("|      |")
               print("|    (_)")
               print("|      l")
               print("|    /+\ ")
               print("|")
               print("|")
               print("====")

     elif fails == 6:
               print("____")
               print("|      |")
               print("|    (_)")
               print("|      l")
               print("|    /+\ ")
               print("|      |")
               print("|")
               print("====")

     elif fails == 7:
               print("____")
               print("|      |")
               print("|    (_)")
               print("|      l")
               print("|    /+\ ")
               print("|      |")
               print("|     /")
               print("====")

     elif fails == 8:
               print("____")
               print("|      |")
               print("|    (_)")
               print("|      l")
               print("|    /+\ ")
               print("|      |")
               print("|     / \ ")
               print("====")
               print("Well, at least you tried...")
               exit()
     time.sleep(1)          
     guess()

main()
\$\endgroup\$
  • \$\begingroup\$ Why do you have time.sleep(1) in a bunch of places? \$\endgroup\$ – Solomon Ucko Oct 28 '17 at 14:34
  • \$\begingroup\$ To create a delay between lines, I don't like instantaneous prints, and I believe it increases the program's quality \$\endgroup\$ – Marian Oct 29 '17 at 22:02
  • \$\begingroup\$ Ok. I probably wouldn't put it there, but that's your choice. \$\endgroup\$ – Solomon Ucko Oct 29 '17 at 22:06
  • \$\begingroup\$ Is there another way I could do it? I want to know more. \$\endgroup\$ – Marian Oct 30 '17 at 8:23
  • 2
    \$\begingroup\$ I would just not have pauses, and output immediately. I don't really like waiting for my computer. \$\endgroup\$ – Solomon Ucko Oct 30 '17 at 12:06
3
\$\begingroup\$
  1. The following are unnecessary global variables that could instead exist in the main funciton and be passed to the other functions:

    fails = 0
    num = 1
    guessed = []
    secretWord = list(random.choice(words))
    
  2. These are being run outside of main, even though they are logically part of it.

        print("\t\t----Welcome to Hangman!----\n")
        print("=" * 60)
    
  3. The structure of your program is unnecessarily recursive. this makes it less readable and places an upper limit on the number of times your game can be played, because python does not have Tail Call Optimization. This is by far the hardest thing to change.

  4. Your user interface and the model of your game are very intertwined. this will make it harder to change your game or your ui. Consider writing game methods that do no input and output and then printing the results.

  5. winCheck returns guess() even though guess() does not return anything

  6. in hangmanFails() instead of having the whole if-else block, you could create a dictionary or list that maps the value of fails directly to the corresponding hangman string.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.