MITx 6.00 Problem Set 3 hangma

A WORDGAME: HANGMAN

这是MITx 6.00的作业,Hangman游戏。

Note: Do not be intimidated by this problem! It’s actually easier than it looks. We will ‘scaffold’ this problem, guiding you through the creation of helper functions before you implement the actual game.

For this problem, you will implement a variation of the classic wordgame Hangman. For those of you who are unfamiliar with the rules, you may read all about it here. In this problem, the second player will always be the computer, who will be picking a word at random.

In this problem, you will implement afunction, calledhangman, that will start up and carry out an interactive Hangman game between a player and the computer. Before we get to this function, we’ll first implement a few helper functions to get you going.

Go to Canopy. From the File menu, choose "Open".Find the fileps3_hangman.pyand choose it.The templateps3_hangman.pyfile should now be open in Canopy. Click on it. From the Run menu, choose "Run File" (or simply hit Ctrl + R).

The code we have given you loads in a list of words from a file. If everything is working okay, after a small delay, you should see the following printed out:

Loading word list from file…55909 words loaded.

If you see anIOErrorinstead (e.g., "No such file or directory"), you should change the value of theWORDLIST_FILENAMEconstant (defined near the top of the file) to thecompletepathname for the filewords.txt(This will vary based on where you saved the file). Windows users, change the backslashes to forward slashes, like below.

For example, if you savedps3_hangman.pyandwords.txtin the directory "C:/Users/Ana/" change the line:

WORDLIST_FILENAME = "words.txt" to something like

WORDLIST_FILENAME = "C:/Users/Ana/words.txt"

This folder will vary depending on where you saved the files.

The fileps3_hangman.pyhas a number of already implemented functions you can use while writing up your solution. You can ignore the code between the following comments, though you should read and understand how to use each helper function by reading the docstrings:

# ———————————–# 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!)…# (end of helper code)# ———————————–

You will want to do all of your coding for this problem within this file as well because you will be writing a program that depends on each function you write.

Requirements

Here are the requirements for your game:

The computer must select a word at random from the list of available words that was provided inwords.txt. The functions for loading the word list and selecting a random word have already been provided for you inps3_hangman.py.

The game must be interactive; the flow of the game should go as follows:

At the start of the game, let the user know how many letters the computer’s word 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 computer’s 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.

Some additional rules of the game:

A user is allowed 8 guesses. Make sure to remind the user of how many guesses s/he has left after each round. Assume that players will only ever submit one character at a time (A-Z).

A user loses a guessonlywhen s/he guesses incorrectly.

If the user guesses the same letter twice, do not take away a guess – instead, print a message letting them know they’ve already guessed that letter and ask them to try again.

The game should end when the user constructs the full word or runs out of guesses. If the player runs out of guesses (s/he "loses"), reveal the word to the user when the game ends.

On the next page, we’ll break down the problem into logical subtasks, creating helper functions you will need to have in order for this game to work.

# 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 randomimport stringWORDLIST_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 maytake a while to finish."""print "Loading word list from file…"# inFile: fileinFile = open(WORDLIST_FILENAME, 'r', 0)# line: stringline = inFile.readline()# wordlist: list of stringswordlist = string.split(line)print " ", len(wordlist), "words loaded."return wordlistdef 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 programwordlist = loadWords()def isWordGuessed(secretWord, lettersGuessed):'''secretWord: string, the word the user is guessinglettersGuessed: list, what letters have been guessed so farreturns: boolean, True if all the letters of secretWord are in lettersGuessed;False otherwise'''# FILL IN YOUR CODE HERE…for x in secretWord:if x not in lettersGuessed:return Falsereturn Truedef getGuessedWord(secretWord, lettersGuessed):'''secretWord: string, the word the user is guessinglettersGuessed: list, what letters have been guessed so farreturns: string, comprised of letters and underscores that representswhat letters in secretWord have been guessed so far.'''# FILL IN YOUR CODE HERE…string = ""for x in secretWord:if x in lettersGuessed:string += xelse:string +='_'return stringdef getAvailableLetters(lettersGuessed):'''lettersGuessed: list, what letters have been guessed so farreturns: string, comprised of letters that represents what letters have notyet been guessed.'''# FILL IN YOUR CODE HERE…notGuessed = []# notGuessed = string.ascii_lowercasefor x in range(26):notGuessed += chr(x + ord('a'))for y in lettersGuessed:notGuessed.remove(y)string = ""for z in notGuessed:string += zreturn stringdef 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 manyletters the secretWord contains.* Ask the user to supply one guess (i.e. letter) per round.* The user should receive feedback immediately after each guessabout whether their guess appears in the computers word.* After each round, you should also display to the user thepartially guessed word so far, as well as letters that theuser has not yet guessed.Follows the other limitations detailed in the problem write-up.'''# FILL IN YOUR CODE HERE…print("Welcome to the game Hangman!")print("I am thinking of a word that is " + str(len(secretWord)) +" letters long")print("———–")lettersGuessed = []Guess = 8while not isWordGuessed(secretWord,lettersGuessed) and Guess>0:print ("You have "+str(len(Guess))+" guesses left.")print ("Available letters: "+getAvailableLetters(lettersGuessed))while True:guessValue = raw_input("Please guess a letter: ").lower()if guessValue in lettersGuessed:print("Oops! You've already guessed that letter: " + getGuessedWord(secretWord, lettersGuessed))print("———–")print("You have " + str(guesses) +" guesses left")print("Available Letters: " + getAvailableLetters(lettersGuessed))else:breaklettersGuessed += guessValueif isWordGuessed(secretWord, lettersGuessed):print("Good guess: " + getGuessedWord(secretWord, lettersGuessed))print("———–")print("Congratulations, you won!")breakelif guessValue in secretWord:print ("Good guess: "+ getGuessedWord(secretWord,lettersGuessed))print("———–")else:print("Oops! That letter is not in my word: " + getGuessedWord(secretWord, lettersGuessed))print("———–")guess -= 1if guess == 0:print ("Sorry, you ran out of guesses. The word was " +secretWord+ ".")secretWord = chooseWord(wordlist).lowerhangman(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)

,因为在路上你就已经收获了自由自在的好心情。

MITx 6.00 Problem Set 3 hangma

相关文章:

你感兴趣的文章:

标签云: