Advertisement
Inksaver

Hangman Python 3.4 OOP console version

Sep 24th, 2014
506
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.75 KB | None | 0 0
  1. # Hangman console version Python 3.4
  2. # http://pastebin.com/B9E5UEkg
  3. # get dictionary.txt from github or elsewhere call it "dictionary.txt" in same folder as script
  4. # https://github.com/dmcguinness/Hangman/blob/master/dictionary.txt
  5.  
  6. import random
  7. import os
  8.  
  9. version = "1.1"
  10.    
  11. class clsDictionary:
  12.     def __init__(self):
  13.         if os.path.exists("dictionary.txt"): # check if dictionary file in place      
  14.             fso = open("dictionary.txt", "r")
  15.             self.wordLength = [] # define list
  16.             for i in range(26):  # create 25 lists within the wordLength[] list
  17.                 self.wordLength.append([])
  18.    
  19.             for line in fso:   # read each line in dictionary and put into correct list    
  20.                 if len(line) > 0: # ignore empty lines
  21.                     if "-" not in line: # ignore hyphenated words
  22.                         self.wordLength[len(line)].append(line)
  23.                    
  24.             fso.close() # close text file
  25.             self.report = "" # no error so nothing to report
  26.         else: # file missing
  27.             self.report = "File 'dictionary.txt' not found"
  28.    
  29.     def getError(self): # property get: error text
  30.         return self.report
  31.                
  32.     def getWord(self, length): # method: get a word from the dictionary
  33.         returnValue = ""
  34.         if length > 0 and length < 26: # word must be between 1 and 26 characters
  35.             listLength = len(self.wordLength[length])
  36.             if listLength > 0:          
  37.                 return self.wordLength[length][random.randrange(listLength)].upper() # get word in uppercase
  38.         else:
  39.             self.report = "Error: word length requested == 0 or > 24"
  40.         return returnValue
  41.        
  42. class clsHangman:
  43.     #0_________________
  44.     #1|    _________  |
  45.     #2|    | /     |  |
  46.     #3|    |/      O  |
  47.     #4|    |      /|\ |
  48.     #5|    |       |  |
  49.     #6|    |      / \ |
  50.     #7| ___|___       |
  51.     #8|_______________|
  52.    
  53.     def __init__(self):
  54.         self.stage = 0
  55.         self.lettersAvailable = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  56.         self.lettersChosen = ""
  57.         self.completed = False
  58.         self.progress = ""
  59.         self.fail = False
  60.         self.word = ""
  61.        
  62.         self.row = [[],[],[],[],[],[],[],[],[]] # setup array elements for graphics
  63.         for i in range(9):
  64.             for j in range(12):
  65.                 self.row[i].append([])
  66.         #stage 0 - new game    
  67.         self.row[0][0] = "_________________"
  68.         self.row[1][0] = "|               |"
  69.         self.row[2][0] = "|               |"
  70.         self.row[3][0] = "|               |"
  71.         self.row[4][0] = "|               |"
  72.         self.row[5][0] = "|               |"
  73.         self.row[6][0] = "|               |"
  74.         self.row[7][0] = "|               |"
  75.         self.row[8][0] = "|_______________|"
  76.         # stage 1 - 1 mistake
  77.         self.row[0][1] = "_________________"
  78.         self.row[1][1] = "|               |"
  79.         self.row[2][1] = "|               |"
  80.         self.row[3][1] = "|               |"
  81.         self.row[4][1] = "|               |"
  82.         self.row[5][1] = "|               |"
  83.         self.row[6][1] = "|               |"
  84.         self.row[7][1] = "| _______       |"
  85.         self.row[8][1] = "|_______________|"
  86.         # stage 2 - 2 mistakes
  87.         self.row[0][2] = "_________________"
  88.         self.row[1][2] = "|               |"
  89.         self.row[2][2] = "|    |          |"
  90.         self.row[3][2] = "|    |          |"
  91.         self.row[4][2] = "|    |          |"
  92.         self.row[5][2] = "|    |          |"
  93.         self.row[6][2] = "|    |          |"
  94.         self.row[7][2] = "| ___|___       |"
  95.         self.row[8][2] = "|_______________|"        
  96.        
  97.         self.row[0][3] = "_________________"
  98.         self.row[1][3] = "|    _________  |"
  99.         self.row[2][3] = "|    | /        |"
  100.         self.row[3][3] = "|    |/         |"
  101.         self.row[4][3] = "|    |          |"
  102.         self.row[5][3] = "|    |          |"
  103.         self.row[6][3] = "|    |          |"
  104.         self.row[7][3] = "| ___|___       |"
  105.         self.row[8][3] = "|_______________|"
  106.        
  107.         self.row[0][4] = "_________________"
  108.         self.row[1][4] = "|    _________  |"
  109.         self.row[2][4] = "|    | /     |  |"
  110.         self.row[3][4] = "|    |/         |"
  111.         self.row[4][4] = "|    |          |"
  112.         self.row[5][4] = "|    |          |"
  113.         self.row[6][4] = "|    |          |"
  114.         self.row[7][4] = "| ___|___       |"
  115.         self.row[8][4] = "|_______________|"        
  116.  
  117.         self.row[0][5] = "_________________"
  118.         self.row[1][5] = "|    _________  |"
  119.         self.row[2][5] = "|    | /     |  |"
  120.         self.row[3][5] = "|    |/      O  |"
  121.         self.row[4][5] = "|    |          |"
  122.         self.row[5][5] = "|    |          |"
  123.         self.row[6][5] = "|    |          |"
  124.         self.row[7][5] = "| ___|___       |"
  125.         self.row[8][5] = "|_______________|"        
  126.        
  127.         self.row[0][6] = "_________________"
  128.         self.row[1][6] = "|    _________  |"
  129.         self.row[2][6] = "|    | /     |  |"
  130.         self.row[3][6] = "|    |/      O  |"
  131.         self.row[4][6] = "|    |      /   |"
  132.         self.row[5][6] = "|    |          |"
  133.         self.row[6][6] = "|    |          |"
  134.         self.row[7][6] = "| ___|___       |"
  135.         self.row[8][6] = "|_______________|"        
  136.        
  137.         self.row[0][7] = "_________________"
  138.         self.row[1][7] = "|    _________  |"
  139.         self.row[2][7] = "|    | /     |  |"
  140.         self.row[3][7] = "|    |/      O  |"
  141.         self.row[4][7] = "|    |      /|  |"
  142.         self.row[5][7] = "|    |          |"
  143.         self.row[6][7] = "|    |          |"
  144.         self.row[7][7] = "| ___|___       |"
  145.         self.row[8][7] = "|_______________|"
  146.                
  147.         self.row[0][8] = "_________________"
  148.         self.row[1][8] = "|    _________  |"
  149.         self.row[2][8] = "|    | /     |  |"
  150.         self.row[3][8] = "|    |/      O  |"
  151.         self.row[4][8] = "|    |      /|" + chr(92) + " |" # backspace causes printing errors so use ascii code
  152.         self.row[5][8] = "|    |          |"
  153.         self.row[6][8] = "|    |          |"
  154.         self.row[7][8] = "| ___|___       |"
  155.         self.row[8][8] = "|_______________|"
  156.            
  157.         self.row[0][9] = "_________________"
  158.         self.row[1][9] = "|    _________  |"
  159.         self.row[2][9] = "|    | /     |  |"
  160.         self.row[3][9] = "|    |/      O  |"
  161.         self.row[4][9] = "|    |      /|" + chr(92) + " |"
  162.         self.row[5][9] = "|    |       |  |"
  163.         self.row[6][9] = "|    |          |"
  164.         self.row[7][9] = "| ___|___       |"
  165.         self.row[8][9] = "|_______________|"      
  166.        
  167.         self.row[0][10] = "_________________"
  168.         self.row[1][10] = "|    _________  |"
  169.         self.row[2][10] = "|    | /     |  |"
  170.         self.row[3][10] = "|    |/      O  |"
  171.         self.row[4][10] = "|    |      /|" + chr(92) + " |"
  172.         self.row[5][10] = "|    |       |  |"
  173.         self.row[6][10] = "|    |      /   |"
  174.         self.row[7][10] = "| ___|___       |"
  175.         self.row[8][10] = "|_______________|"  
  176.         # stage 11 - 11 mistakes - end of game      
  177.         self.row[0][11] = "_________________"
  178.         self.row[1][11] = "|    _________  |"
  179.         self.row[2][11] = "|    | /     |  |"
  180.         self.row[3][11] = "|    |/      O  |"
  181.         self.row[4][11] = "|    |      /|" + chr(92) + " |"
  182.         self.row[5][11] = "|    |       |  |"
  183.         self.row[6][11] = "|    |      / " + chr(92) + " |"
  184.         self.row[7][11] = "| ___|___       |"
  185.         self.row[8][11] = "|_______________|"  
  186.                
  187.     def printStage(self): # method: print graphics for current stage
  188.         for i in range(9):
  189.             print(self.row[i][self.stage])
  190.         wordOut = ""
  191.         for i in range(len(self.progress)):
  192.             wordOut = wordOut + " " + self.progress[i]
  193.         print(wordOut)
  194.    
  195.     def setWord(self, newWord): # property set: use word from clsDictionary object
  196.         self.word = newWord
  197.         self.progress = ""
  198.         for i in range(len(newWord) - 1): # create a string of underscores as placeholders for letters
  199.             self.progress = self.progress + '_'
  200.        
  201.     def getWord(self): # property get: current word used in game
  202.         return self.word
  203.        
  204.     def getLettersAvailable(self): # property get: list of letters mot yet tried
  205.         return self.lettersAvailable
  206.      
  207.     def getLettersChosen(self): # property get: list of letters already tried
  208.         return self.lettersChosen
  209.      
  210.     def getCompleted(self): # property get: game complete, either pass or fail
  211.         return self.completed
  212.    
  213.     def checkGuess(self, guess): # method: check letter entered by user
  214.         if guess not in self.lettersChosen: # letter not used before
  215.             if guess in self.word: # letter is in game word!
  216.                 #add letter to self.progress (replace underscore characters with letters)
  217.                 position = self.word.find(guess) # -1 = not found, 0 = beginning
  218.                 while position >= 0: # found in game word
  219.                     if position == 0: # first letter of word, so substitute letter for first underscore
  220.                         front = guess
  221.                         middle = ""
  222.                         end = self.progress[1:]
  223.                     else: # not first letter, calculate new string with letter in place of underscore
  224.                         front = self.progress[:position]
  225.                         middle = guess
  226.                         if position == len(self.word) - 1: # last letter. len() is larger by 1, and position starts at 0, so -2 needed
  227.                             end = ""
  228.                         else:
  229.                             end = self.progress[position + 1:]
  230.                     self.progress = front + middle + end
  231.                     position = self.word.find(guess, position + 1)
  232.                
  233.                 if '_' not in self.progress: # game completed as all underscores are gone
  234.                     self.completed = True
  235.             else:
  236.                 #draw next stage of hangman
  237.                 if self.stage == 10: # game over, word not found
  238.                     self.fail = True
  239.                     self.completed = True
  240.  
  241.                 self.stage = self.stage + 1 # make sure next / final graphic is drawn
  242.             self.lettersChosen = ''.join(sorted(self.lettersChosen + guess)) # add last letter to list, sort list and return
  243.             position = self.lettersAvailable.find(guess) # remove last letter from list of available letters
  244.             self.lettersAvailable = self.lettersAvailable[:position] + self.lettersAvailable[position + 1:]            
  245.            
  246.     def getFail(self): # property get: game over with fail :(
  247.         return self.fail
  248.        
  249. def printMenu(wordlist, game):
  250.     os.system('cls') # clear screen
  251.     print("Welcome to Hangman version " + version)
  252.     game.setWord(wordlist.getWord(random.randrange(5,15))) # get a word from the dictionary
  253.     print("Guess the " + str(len(game.getWord()) - 1) + " letter word I have chosen")
  254.    
  255. def play(game):
  256.     while True:
  257.         game.printStage()
  258.         print("Letters Used:" + game.getLettersChosen())
  259.         print("Letters Available: " + game.getLettersAvailable())    
  260.         print
  261.         while True:
  262.             guess = input("Choose a letter: ")
  263.             if len(guess) > 0:
  264.                 if (ord(guess) > 64 and ord(guess) < 91) or (ord(guess) > 96 and ord(guess) < 123):
  265.                     guess = guess.upper()
  266.                     break
  267.            
  268.         game.checkGuess(guess)
  269.         if game.getCompleted():
  270.             break
  271.  
  272. def main():  
  273.     wordlist = clsDictionary() # create instance of clsDictionary, which will read text file and sort into lists by word length
  274.     if wordlist.getError() == "": # no errors opening dictionary
  275.         while True:
  276.             game = clsHangman() # create instance of clsHangman as a game object
  277.             printMenu(wordlist, game) # print introduction and get word from dictionary object
  278.             play(game) # play the game
  279.             game.printStage() # print final stage
  280.             if game.getFail():
  281.                 print ("Sorry you did not guess the word")
  282.                 print("it was: ", game.getWord())
  283.             else:
  284.                 print("Well Done!")
  285.            
  286.             answer = input("Do you want to play again? Y/N >")
  287.             if answer.upper() != "Y": # any key to quit, Y to continue
  288.                 os.system('cls')
  289.                 break
  290.     else: # error opening dictionary. ? deleted/moved/renamed
  291.         print(wordlist.getError())
  292.    
  293. # program runs from here
  294. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement