Skip to content

Instantly share code, notes, and snippets.

@saltavenger
Created October 23, 2012 14:45
Show Gist options
  • Save saltavenger/3939185 to your computer and use it in GitHub Desktop.
Save saltavenger/3939185 to your computer and use it in GitHub Desktop.
python hangman
# 6.00 Problem Set 3
#
# Hangman game
#
# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)
import random
import string
WORDLIST_FILENAME = "words.txt"
def loadWords():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = string.split(line)
print " ", len(wordlist), "words loaded."
return wordlist
def chooseWord(wordlist):
"""
wordlist (list): list of words (strings)
Returns a word from wordlist at random
"""
return random.choice(wordlist)
# end of helper code
# -----------------------------------
# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = loadWords()
def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
count = 0
for i, c in enumerate(secretWord):
if c in lettersGuessed:
count += 1
if count == len(secretWord):
return True
else:
return False
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
'''
count = 0
blank = ['_ '] * len(secretWord)
for i, c in enumerate(secretWord):
if c in lettersGuessed:
count += 1
blank.insert(count-1,c)
blank.pop(count)
if count == len(secretWord):
return ''.join(str(e) for e in blank)
else:
count += 1
blank.insert(count-1,'_')
blank.pop(count)
if count == len(secretWord):
return ''.join(str(e) for e in blank)
def getAvailableLetters(lettersGuessed):
'''
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters that represents what letters have not
yet been guessed.
'''
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
alphabet2 = alphabet[:]
def removeDupsBetter(L1, L2):
L1Start = L1[:]
for e in L1:
if e in L1Start:
L2.remove(e)
return ''.join(str(e) for e in L2)
return removeDupsBetter(lettersGuessed, alphabet2)
def hangman(secretWord):
'''
secretWord: string, the secret word to guess.
Starts up an interactive game of Hangman.
* At the start of the game, let the user know how many
letters the secretWord contains.
* Ask the user to supply one guess (i.e. letter) per round.
* The user should receive feedback immediately after each guess
about whether their guess appears in the computers word.
* After each round, you should also display to the user the
partially guessed word so far, as well as letters that the
user has not yet guessed.
Follows the other limitations detailed in the problem write-up.
'''
intro = str(len(secretWord))
lettersGuessed = []
guess = str
mistakesMade = 8
wordGuessed = False
print 'Welcome to the game, Hangman!'
print ('I am thinking of a word that is ') + intro + (' letters long.')
print ('------------')
while mistakesMade > 0 and mistakesMade <= 8 and wordGuessed is False:
if secretWord == getGuessedWord(secretWord, lettersGuessed):
wordGuessed = True
break
print ('You have ') + str(mistakesMade) + (' guesses left.')
print ('Available letters: ') + getAvailableLetters(lettersGuessed)
guess = raw_input('Please guess a letter: ').lower()
if guess in secretWord:
if guess in lettersGuessed:
print ("Oops! You've already guessed that letter: ") + getGuessedWord(secretWord, lettersGuessed)
print ('------------')
else:
lettersGuessed.append(guess)
print ('Good guess: ') + getGuessedWord(secretWord, lettersGuessed)
print ('------------')
else:
if guess in lettersGuessed:
print ("Oops! You've already guessed that letter: ") + getGuessedWord(secretWord, lettersGuessed)
print ('------------')
else:
lettersGuessed.append(guess)
mistakesMade -= 1
print ('Oops! That letter is not in my word: ') + getGuessedWord(secretWord, lettersGuessed)
print ('------------')
if wordGuessed == True:
return 'Congratulations, you won!'
elif mistakesMade == 0:
print ('Sorry, you ran out of guesses. The word was ') + secretWord
# When you've completed your hangman function, uncomment these two lines
# and run this file to test! (hint: you might want to pick your own
# secretWord while you're testing)
secretWord = chooseWord(wordlist).lower()
hangman(secretWord)
@Itz-Ayesha
Copy link

Does this genuinely work? When I do the code, it doesn't for me.

@tuohuang-li
Copy link

Does this genuinely work? When I do the code, it doesn't for me.

Worked for me, note that this was written in python2, you might want to adjust the format for a few lines so that it runs on python 3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment