Hangman

Programming Hangman was on of my first computing projects. This was an excellent experience when first starting to program as the hangman game implements many key elements of procedural programming such as the uses of selection and repetition also requiring the use of functions and procedures. In order to simulate the hangman being drawn I used the Python Turtle graphics module.

Python code for Hangman Game

#Word bank to choose from animalWords=("ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebra".split()) fruitWords=("apple orange pear peach grapefruit passionfruit cherry grape plum mandarin guava watermelon melon pineapple lychee fig banana strawberry papaya carambola raspberry lemon pomelo cranberry blueberry coconut pomegrante kiwi mango".split()) countryWords=("malawi kenya somalia tanzania yemen burundi afghanistan ethiopia niger liberia madagascar zambia eritrea".split()) waterWords=("arroyo basin bay bayou bend bight billibong bog brook canal cataract channel cove creek dam delta estuary falls fen firth fjord fork geyser glacier gulch gulf gully harbour headland iceberg inlet island islet kettle kill lagoon lake loch arsh meander millpond moat mouth narrows neck oasis ocean playa pond pool prt prairie puddle rapids reef reservoir ria river rivulet run scarp scree sea seashore shallows shoal shore shoreline slough sound source spring strait stream surf swamp tributary wash waterfall watershed waterway wetland".split()) computerWords=("algorithm analog app application array backup bandwidth binary bit bitmap bite blog blogger bookmark boot broadband browser buffer bug bus byte cache captcha client command compile compress computer configure cookie copy cpu cd cybercrime cyberspace dashboard data debug decompress delete desktop development digital disk document domain dot download drag dvd dynamic email emoticon encryption enter exabyte faq file find firewall firmware flaming flash flashdrive floppy disk flowchart folder font format frame freeware gigabyte graphics hack hacker hardware host html hyperlink hypertext icon integer interface internet iteration java joystick kernel key keyboard keyword laptop link login logic lurking mainframe macro malware media memory mirror modem monitor motherboard mouse multimedia net network node offline online option output page password paste path phishing piracy pirate platform podcast portal printer privacy process program programmer protocol queue ram reboot resolution restore rom root router runtime save scan scanner screen screenshot script scroll security server shareware shell shift snapshot software spam spammer spreadsheet storage spyware supercomputer surf syntax table tag template terabyte terminal thread toolbar trash typeface undo unix username url user utility version virtual virus web webmaster website widget window wireless wiki workstation worm www xml zip".split()) #Imports functions to be used later on import sys import turtle import random #Subroutines for drawing Hangman def drawer(): if lives == 9: turtle.forward(250) if lives == 8: turtle.left(180) turtle.forward(150) turtle.right(90) turtle.forward(250) if lives ==7: turtle.right(90) turtle.forward(150) if lives ==6: turtle.speed(75) turtle.right(180) turtle.forward(20) if lives==5: turtle.left(90) turtle.forward(20) turtle.right(90) i=0 while i<270: turtle.forward(1) turtle.left(2) i=i+1 if lives==4: turtle.right(90) turtle.forward(25) turtle.right(90) turtle.forward(65) if lives==3: turtle.left(180) turtle.forward(130) if lives==2: turtle.left(180) turtle.forward(65) turtle.left(90) turtle.forward(35) if lives==1: turtle.right(45) turtle.forward(70) if lives==0: turtle.right(180) turtle.forward(70) turtle.right(90) turtle.forward(70) #Subroutine for choosing a random word def wordGenerator(wordlist): getWord=random.randint(0,len(wordlist)-1) return wordlist[getWord] #Subroutine for taking in a letter from user def validLetter(guess): while True: if len(guess)!= 1: guess=input("Please enter a single letter:") elif guess not in ("abcdefghijklmnopqrstuvwxyz"): guess=input("That is not a valid letter, Please re-enter:") elif guess in guessedLetters: guess=input("You have already selected that letter previously. Please try again:") else: return guess #Subroutine for if the word is blank def appendBlank(): blankword="*"*len(randomWord) for i in range(len(randomWord)): if randomWord[i] in correctLetters: blankword=blankword[:i]+randomWord[i]+blankword[i+1:] print (blankword) if blankword==randomWord: print("Congratulations! You successfully guessed all the letters!") sys.exit() #Subroutine for choosing which category of words def validCategory(category): while True: if category not in ("abcde"): category=input("Please select your category by entering either a, b, c, d or e") else: return category #--------Main Program-------- #Initiating lists and assigning values to variables lives=10 guessedLetters=[] correctLetters=[] wrongLetters=[] print("Hangman V.2...(Minimise all screens!)") #Lets the user choose what category they would like to choose from category=input("Which category would you like to choose a word from?\na)Animals\nb)Fruits\nc)Countries\nd)Bodies of Water\ne)Computers\nType the lowercase letter here:") validCategory(category) if category==("a"): randomWord=wordGenerator(animalWords) if category==("b"): randomWord=wordGenerator(fruitWords) if category==("c"): randomWord=wordGenerator(countryWords) if category==("d"): randomWord=wordGenerator(waterWords) if category==("e"): randomWord=wordGenerator(computerWords) #Displays a starred version of the word. Then shows how many letters in it. blank="*"*len(randomWord) print ("\nYou must guess the letters to the following word >> ",blank) print("It has this many letters in it:") print(len(randomWord)) print("\nLET THE GAMES BEGIN!!") #While loop that inputs the letter and checks if it is correct or not while lives>0: guess=input("\nPlease enter a letter (in lowercase form):") guess=validLetter(guess) if guess in randomWord: guessedLetters.append(guess) correctLetters.append(guess) appendBlank() else: wrongLetters.append(guess) guessedLetters.append(guess) lives=lives-1 print("List of incorrect letters:",wrongLetters) drawer() print("You have run out of lives. The secret word was:",randomWord)