In: Computer Science
Looking to see how to figure this out. So far when I break apart the coding it works but when it is all together it doesn't,
Hangman
We're going to write a game of hangman. Don't worry, this assignment is not nearly as difficult as it may appear.
The way hangman works (for this assignment - we are doing a simplified game) is as follows:
I have provided you with skeleton code below. You must use this code. You will fill in the code for the places where you see comments that start with "TODO". Do NOT modify any of the rest of the code. No further modifications are necessary. You simply need to add the code that is specified and the program will work.
Most of the work is adding code to fill in the functions. How can you test that you have done this correctly? Each function (except for main()) is independent -- it does only one job and does not call any other functions. Therefore, you can test each function independently. Think of each as a separate question on an assignment. If you wish, you can cut and paste the skeleton of the function into another python file and isolate it from the rest of the code. To test if the function works the way you want it to, call the function with some made-up parameter values and print the result. So, for instance, to test the function updateUsedLetters(), you could do the following:
uLetters = "abcd" #this fabricated string represents the letters the user has already chosen guess = "z" #this is a user guess (no input required ..... just make up a letter) uLetters = updateUsedLetters(uLetters, guess) print(uLetters) #I expect to see "abcdz" returned
Testing this function doesn't depend at all on the rest of the program. Once I know that it works, I can continue on and work on the other functions.
The program is not going to run until you have all the functions complete and working -- so you really need to test each one individually. I will go over this process in the class on Tuesday.
Here is the skeleton code. Take some time to look at the structure
and understand how it works. Notice the way the functions are
structured --- each function does one task and each receives the
information that it needs to do the job and returns the answer.
This answer is used in the calling function.
You can cut and paste this into a new python file. It is easier to read when you put it into a Python window. When you hand in your code, remove all the instructional #TODO comments. You do not have to add to the docstrings but you should read them to understand more about how each function works.
here is my code thus far:
import random
def getSecretWord():
"""
This function chooses a word from the list of potential
secret
words.
Parameters: None
Return Value: a string representing the secret word
"""
potentialWords = ["tiger", "lion", "elephant", "snake",
"zebra"]
#random.randint(0, 4) will generate an integer between 0 and
4
#this is then used to select a value from potentialWords
return potentialWords[random.randint(0,4)]
def printStringWithSpaces(word):
"""
This function prints the blank representation ("___") of the
secret word on the screen with spaces between each underscore
so that the user can better see how many letters there are.
Parameter: string
Return Value: None
"""
#loop that places a space between each letter
for ch in word:
print(ch, ' ', end = '')
print()
print()
def convertWordToBlanks(word):
"""
Creates a string consisting of len(word) underscores.
For example, if word = "cat", function returns "___"
Parameter: string
Return Value: string
"""
#TODO -- complete this function so that it produces a string
with
#underscores representing the parameter "word" (which is a
string).
#eg: word = "watch", the function returns "_____" (5
underscores)
#You will need a loop for this. Also, a return statement.
#leave this line (and use the variable newString in your
code
newString = "" #start with an empty string and add onto it
#PUT YOUR CODE HERE
for ch in word:
empty = print(('_' + newString), end = '')
return empty
def updateRepresentation(blank, secret, letter):
"""
This function replaces the appropriate underscores with the
guessed
letter.
Eg. letter = 't', secret = "tiger", blank = "_i_er" --> returns
"ti_er"
Paramters: blank, secret are strings
letter is a string, but a single letter.
Returns: a string
"""
#TODO -- complete this function so that it produces a new
string
#from blank with letter inserted into the appropriate
locations.
#For example:
# letter = 't', secret = "tiger", blank = "_i_er" --> newString
"ti_er"
#newString should be returned.
#hint:
#iterate through each character of secret by index position
# check to see if letter = current character at index
position
# if yes, add this letter to newString
# if no, add the letter from blank found at index position
#leave this line (and use the variable newString in your
code
newString = ""
countIndex = 0
while countIndex<len(secret):
for ch in secret:
if ch == letter:
newString = blank[:countIndex] + letter +
blank[countIndex+1:]
countIndex +=1
else:
countIndex += 1
return newString
def updateUsedLetters(usedLetters, letter):
"""
This function concatenates the guessed letter onto the list of
letters
that have been guessed, returning the result.
Parameters: string representing the used letters
string respresenting the current user guess
Return Value: string
"""
usedLetters = "" + letter
return usedLetters
def main():
"""
This implements the user interface for the program.
"""
usedLetters = "" #no letters guessed yet
secret = getSecretWord()
print("The secret word is ", secret)
#convert the secret word to a string of underscores.
blank = convertWordToBlanks(secret)
printStringWithSpaces(secret)
while blank != secret:
userGuess = input("Please enter a single letter guess: ")
#check for valid input
while not(userGuess.isalpha()) or len(userGuess) != 1:
userGuess = input("Please enter valid input(a single letter
guess):")
#TODO: Add one line of code here (at the same level of
indentation of
#this comment) to check that userGuess is NOT in the string
usedLetters.
#ADD YOUR CODE HERE
if userGuess not in usedLetters:
print("You have guessed ", userGuess)
if userGuess in secret:
#letter is in the secret word so update the blank
representation
blank = updateRepresentation(blank, secret, userGuess)
printStringWithSpaces(blank)
#add the letter to the string of used letters
usedLetters = updateUsedLetters(usedLetters, userGuess)
else:
#letter has been guessed already -- update the user
print("You have already guessed that letter!!!")
print("Here are the letters you have guessed so far: ")
printStringWithSpaces(usedLetters)
print("You got it!! The word was", secret)
main()
import random
def getSecretWord():
"""
This function chooses a word from the list of
potential secret
words.
Parameters: None
Return Value: a string representing the secret
word
"""
potentialWords = ["tiger", "lion", "elephant",
"snake", "zebra"]
#random.randint(0, 4) will generate an integer between
0 and 4
#this is then used to select a value from
potentialWords
return potentialWords[random.randint(0,4)]
def printStringWithSpaces(word):
"""
This function prints the blank representation ("___")
of the
secret word on the screen with spaces between each
underscore
so that the user can better see how many letters there
are.
Parameter: string
Return Value: None
"""
#loop that places a space between each letter
for ch in word:
print(ch, ' ', end = '')
print()
print()
def convertWordToBlanks(word):
"""
Creates a string consisting of len(word)
underscores.
For example, if word = "cat", function returns
"___"
Parameter: string
Return Value: string
"""
#TODO -- complete this function so that it produces a
string with
#underscores representing the parameter "word" (which
is a string).
#eg: word = "watch", the function returns "_____" (5
underscores)
#You will need a loop for this. Also, a return
statement.
#leave this line (and use the variable newString in
your code
newString = "" #start with an empty string and add
onto it
# loop over the word appending '_' to newString
for ch in word:
newString = newString + '_'
return newString
def updateRepresentation(blank, secret, letter):
"""
This function replaces the appropriate underscores
with the guessed
letter.
Eg. letter = 't', secret = "tiger", blank = "_i_er"
--> returns "ti_er"
Paramters: blank, secret are strings
letter is a string, but a single letter.
Returns: a strings
"""
#TODO -- complete this function so that it produces
a new string
#from blank with letter inserted into the appropriate
locations.
#For example:
# letter = 't', secret = "tiger", blank = "_i_er"
--> newString "ti_er"
#newString should be returned.
#hint:
#iterate through each character of secret by index
position
# check to see if letter = current character at index
position
# if yes, add this letter to newString
# if no, add the letter from blank found at index
position
#leave this line (and use the variable newString in
your code
newString = ""
# loop over secret word
for i in range(len(secret)):
# ith letter of secret = letter,
append letter to newString
if secret[i] == letter:
newString =
newString + letter
else: # else append ith
character of blank to newString
newString =
newString + blank[i]
return newString
def updateUsedLetters(usedLetters, letter):
"""
This function concatenates the guessed letter onto the
list of letters
that have been guessed, returning the result.
Parameters: string representing the used letters
string respresenting the current user guess
Return Value: string
"""
# append letter to usedLetters and return it
usedLetters += letter
return usedLetters
def main():
"""
This implements the user interface for the
program.
"""
usedLetters = "" #no letters guessed yet
secret = getSecretWord()
print("The secret word is ", secret)
#convert the secret word to a string of
underscores.
blank = convertWordToBlanks(secret)
printStringWithSpaces(secret)
while blank != secret:
userGuess = input("Please enter a
single letter guess: ")
#check for valid input
while not(userGuess.isalpha()) or
len(userGuess) != 1:
userGuess =
input("Please enter valid input(a single letter guess):")
#TODO: Add one line of code here
(at the same level of indentation of
#this comment) to check that
userGuess is NOT in the string usedLetters.
#ADD YOUR CODE HERE
if userGuess not in
usedLetters:
print("You have
guessed ", userGuess)
if userGuess in
secret:
#letter is in the secret word so update the
blank representation
blank = updateRepresentation(blank, secret,
userGuess)
printStringWithSpaces(blank)
#add the letter
to the string of used letters
usedLetters =
updateUsedLetters(usedLetters, userGuess)
else:
#letter has been
guessed already -- update the user
print("You have
already guessed that letter!!!")
print("Here are
the letters you have guessed so far: ")
printStringWithSpaces(usedLetters)
print("You got it!! The word was", secret)
main()
#end of program
Code Screenshot:
Output: