Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 6.00 Problem Set 3
- #
- # Hangman
- #
- # -----------------------------------
- # Helper code
- # (you don't need to understand this helper code)
- import random
- import string
- WORDLIST_FILENAME = "words.txt"
- def load_words():
- """
- 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 choose_word(wordlist):
- """
- wordlist (list): list of words (strings)
- Returns a word from wordlist at random
- """
- return random.choice(wordlist)
- # end of helper code
- # -----------------------------------
- # actually load the dictionary of words and point to it with
- # the wordlist variable so that it can be accessed from anywhere
- # in the program
- wordlist = load_words()
- # your code begins here!
- # issues: 1)updates the letters available. 2) displaying the word in a string vs. list
- print "Welcome to the game, Hangman!"
- random_word = choose_word(wordlist)
- print random_word
- word = ''
- for e in range (0, len(random_word)):
- word = word + '-'
- print word
- string = 'abcdefghijklmnopqrstuvqxyz'
- print "I am thinking of a word that is ", len(word), " letters long."
- print"--------------------"
- guesses = 8
- while guesses > 0 and word != random_word:
- print 'You have', guesses, ' left.'
- print "Available letter: ", string
- attempt = raw_input("Please guess a letter: ")
- for a in range (0, len(string)):
- if attempt == string[a]:
- string = string[0:a] + string[a+1:len(string)]
- # Why do you need a break here????
- score = 0
- for a in range (0, len(random_word)):
- if random_word[a] == attempt:
- word = word[0:a] + str(attempt) + word[a+1: len(word)]
- score = score + 1
- if score > 0:
- print "Good guess:", word
- else:
- print "Oops! That letter is not in my word: ", word
- guesses = guesses - 1
- score = 0
- if word == random_word:
- print "You win", word
- else:
- print "Sorry champ not this time.", random_word
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement