AldenDavidson

PyHangman

Feb 17th, 2014
486
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.16 KB | None | 0 0
  1. #! /usr/bin/env python
  2. #
  3. ## PyHangman (ver. 1.0) - CLI-based Hangman game written in Python
  4. ## Β© 2014 Alden Davidson <[email protected]>
  5. ##
  6. ## This program is free software: you can redistribute it and/or modify
  7. ## it under the terms of the GNU General Public License as published by
  8. ## the Free Software Foundation, either version 3 of the License, or
  9. ## (at your option) any later version.
  10. ##
  11. ## This program is distributed in the hope that it will be useful,
  12. ## but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. ## GNU General Public License for more details.
  15. ##
  16. ## You should have received a copy of the GNU General Public License
  17. ## along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  
  19.  
  20. import sys, random, os
  21.  
  22. class Gallows:
  23.     def __init__(self):
  24.         '''Visual of the game.'''
  25.         self.state = [
  26.             [
  27.                 '\t  _______ ',
  28.                 '\t  |     | ',
  29.                 '\t        | ',
  30.                 '\t        | ',
  31.                 '\t        | ',
  32.                 '\t        | ',
  33.                 '\t________|_',
  34.             ],
  35.             [
  36.                 '\t  _______ ',
  37.                 '\t  |     | ',
  38.                 '\t  O     | ',
  39.                 '\t        | ',
  40.                 '\t        | ',
  41.                 '\t        | ',
  42.                 '\t________|_',
  43.             ],
  44.             [
  45.                 '\t  _______ ',
  46.                 '\t  |     | ',
  47.                 '\t  O     | ',
  48.                 '\t  |     | ',
  49.                 '\t  |     | ',
  50.                 '\t        | ',
  51.                 '\t________|_',
  52.             ],
  53.             [
  54.                 '\t  _______ ',
  55.                 '\t  |     | ',
  56.                 '\t  O     | ',
  57.                 '\t \|     | ',
  58.                 '\t  |     | ',
  59.                 '\t        | ',
  60.                 '\t________|_',
  61.             ],
  62.             [
  63.                 '\t  _______ ',
  64.                 '\t  |     | ',
  65.                 '\t  O     | ',
  66.                 '\t \|/    | ',
  67.                 '\t  |     | ',
  68.                 '\t        | ',
  69.                 '\t________|_',
  70.             ],
  71.             [
  72.                 '\t  _______ ',
  73.                 '\t  |     | ',
  74.                 '\t  O     | ',
  75.                 '\t \|/    | ',
  76.                 '\t  |     | ',
  77.                 '\t /      | ',
  78.                 '\t________|_',
  79.             ],
  80.             [
  81.                 '\t  _______ ',
  82.                 '\t  |     | ',
  83.                 '\t  O     | ',
  84.                 '\t \|/    | ',
  85.                 '\t  |     | ',
  86.                 '\t / \\    | ',
  87.                 '\t________|_',
  88.             ]
  89.         ]
  90.  
  91.     def set_state(self, misses):
  92.         '''Sets the current visual being used.'''
  93.         newState = ''
  94.        
  95.         state = self.state[misses] # set state to the list of desired gallows image
  96.         # construct gallows image into str from list
  97.         for piece in state:
  98.             newState += piece + '\n'
  99.         return newState
  100.  
  101.  
  102. class ChooseWord:
  103.     def __init__(self):
  104.         '''Set the length of the wordlist.'''
  105.         self.numLines = sum(1 for line in open('wordlist.txt'))
  106.    
  107.     def newWord(self):
  108.         '''Choose a new word to be guessed.'''
  109.         stopNum = random.randint(0, self.numLines-1) # establish random number to be picked from list
  110.         # extract word from file
  111.         with open("wordlist.txt") as file:
  112.             for x, line in enumerate(file):
  113.                 if x == stopNum:
  114.                     word = line.strip() # remove endline characters
  115.         return word
  116.  
  117.  
  118. class Letters:
  119.     def blanks(self, word, blanks):
  120.         '''Create blanks for each letter in the word.'''
  121.         for letter in word:
  122.             # Don't hide hyphens
  123.             if letter == '-':
  124.                 blanks += '-'
  125.             else:
  126.                 blanks += '_'
  127.         return blanks
  128.    
  129.     def check_letter(self, word, guess, blanks, used, missed):
  130.         '''Check if guessed letter is in the word.'''
  131.         newWord = word
  132.         # If the user presses enter without entering a letter
  133.         if guess == '':
  134.             raw_input("You have to guess something, silly!")
  135.         # replace the corresponding blank for each instance of guess in the word
  136.         elif guess in word and guess not in used:
  137.             for x in range(0, word.count(guess)):
  138.                 blanks[newWord.find(guess)] = guess
  139.                 newWord = newWord.replace(guess, '-', 1) # replace already checked letters with dashes
  140.             used += guess # add the guess to the used letter list
  141.         # If the user inputs a letter they've already used
  142.         elif guess in used:
  143.             raw_input("You already tried that letter, silly!")
  144.         # If the user inputs multiple letters at once
  145.         elif len(list(guess)) > 1:
  146.             raw_input("You can't guess more than one letter at a time, silly!")
  147.         #If the guess is wrong
  148.         else:
  149.             missed = True
  150.             used += guess
  151.         return blanks, used, missed
  152.  
  153.  
  154. class Engine:
  155.     def __init__(self):
  156.         '''Initialize all variables for the game'''
  157.         self.wrongGuesses = 0 # number of incorrect guesses
  158.         self.currentImg = "" # current state of the gallows
  159.         self.word = "" # word to be guessed
  160.         self.blanks = [] # blanks which hide each letter of the word until guessed
  161.         self.used =[] # list of used letters
  162.  
  163.     def setup(self, image, getWord, letters, finish):
  164.         self.__init__()
  165.         self.currentImg = image.set_state(self.wrongGuesses)
  166.         self.word = getWord.newWord()
  167.         self.blanks = letters.blanks(self.word, self.blanks)
  168.         self.play(image, getWord, letters, finish)
  169.        
  170.     def play(self, image, getWord, letters, finish):
  171.         missed = False
  172.        
  173.         newPage()
  174.         print self.currentImg
  175.         for x in self.blanks:
  176.             print x,
  177.         print '\n'
  178.         for x in self.used:
  179.             print x,
  180.         print '\n'
  181.        
  182.         guess = raw_input("Guess a letter: ")
  183.         blanks, self.used, missed = letters.check_letter(self.word, guess, self.blanks, self.used, missed)
  184.        
  185.         if missed == True and self.wrongGuesses < 6:
  186.             self.wrongGuesses += 1
  187.             self.currentImg = image.set_state(self.wrongGuesses)
  188.             self.play(image, getWord, letters, finish)
  189.         elif missed == False and blanks != list(self.word) and self.wrongGuesses != 6:
  190.             self.play(image, getWord, letters, finish)
  191.         elif blanks == list(self.word):
  192.             finish.victory(self, image, getWord, letters)
  193.         else:
  194.             finish.game_over(self, image, getWord, letters)
  195.        
  196.  
  197.  
  198. class EndGame:
  199.     def game_over(self, game, image, getWord, letters):
  200.         newPage()
  201.         print "Nice try! Your word was '%s'." % game.word
  202.         while True:
  203.             play_again = raw_input("Play again? [y/n]")
  204.             if 'y' in play_again:
  205.                 game.setup(image, getWord, letters, self)
  206.             elif 'n' in play_again:
  207.                 sys.exit(0)
  208.             else:
  209.                 print "Huh?"
  210.    
  211.     def victory(self, game, image, getWord, letters):
  212.         newPage()
  213.         print "Congratulations, you win!"
  214.         print "You correctly guessed the word '%s'!" % game.word
  215.         while True:
  216.             play_again = raw_input("Play again? [y/n]")
  217.             if 'y' in play_again:
  218.                 game.setup(image, getWord, letters, self)
  219.             elif 'n' in play_again:
  220.                 sys.exit(0)
  221.             else:
  222.                 print "Huh?"
  223.  
  224.  
  225.  
  226. def newPage():
  227.     '''Clears the window.'''
  228.     os.system('cls' if os.name == 'nt' else 'clear')
  229.  
  230. def main():
  231.     image = Gallows()
  232.     getWord = ChooseWord()
  233.     letters = Letters()
  234.     finish = EndGame()
  235.     game = Engine()
  236.    
  237.     newPage()
  238.     print("\nWelcome to Hangman!")
  239.     print("Guess the word before the man is hung and you win!")
  240.     raw_input("\n\t---Enter to Continue---\n")
  241.     newPage()
  242.    
  243.     game.setup(image, getWord, letters, finish)
  244.  
  245.  
  246.  
  247. if __name__ == '__main__':
  248.     main()
Advertisement
Add Comment
Please, Sign In to add comment