Question

In: Computer Science

Looking to see how to figure this out. So far when I break apart the coding...

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:

  • the computer will choose a word. (For this version, a word is selected from a static list encoded into the program -- so the words are pretty limited). Let's say the word is "cocoa".
  • the computer shows the user how many letters are in the word by displaying a "space" for each letter.   For our example, "cocoa" would be shown as:   _ _ _ _ _
  • the user guesses a letter
  • if the guessed letter is in the secret word, the computer updates the "_ _ _ _ _" representation to show where the chosen letter resides. So, for instance, if the user chose "o", the representation would be updated to be "_o_o_"
  • the user guesses another letter ... and the game continues until the user fills in all the letters.

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()

Solutions

Expert Solution


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:


Related Solutions

This is what I have so far. The out print I am looking for is Date...
This is what I have so far. The out print I am looking for is Date is 7/22/2020 New month: 9 New day: 5 New Year: 2020 Date is 9/5/2020 #include    class Date {    public:        Date::Date(int dateMonth, int dateDay, int dateYear)        month{dateMonth}, day{dateDay}, int dateYear}{}               //void displayDate();         //set month        void Date::setMonth(std::int dateMonth){            month = dateMonth;        }        //retrieve month   ...
So I was looking out the sky one day and I wondered how I would go...
So I was looking out the sky one day and I wondered how I would go about calculating how much water was contained in a cloud. I figured the following simple outline 1) We need to roughly know how big it is. We'll also be figuring out how high the cloud is. Use some sort of geometric method? Triangles? 2) We need to relate its color to its density. (Darker clouds more dense) (White fluffy clouds less dense) 3) Correction...
I am so desperate to know how to figure out if the industry is increasing, decreasing...
I am so desperate to know how to figure out if the industry is increasing, decreasing or constant cost industry by using given supply function, for example, S(p)= 200p - 3000. Please explain in detail Thanks
Coding: Use MATLAB to figure out the following problem, if you do not know how to...
Coding: Use MATLAB to figure out the following problem, if you do not know how to use MATLAB then please do not answer. Coding is required for the exercise. For f(x) = arctan(x), find its zeros by implimenting Newtons method and the Secant method in Matlab. (Hint: Use Newtons method to calculate x1 for Secant method) Comment all code please since I would like to learn how to do this correctly in MATLAB. Thank you.
Looking for assistance on these three quick questions as I can't seem to figure them out....
Looking for assistance on these three quick questions as I can't seem to figure them out. Thanks in advance for your help! 1. Which of the following would decrease the depth of breathing? A. Increased arterial PCO2 B. Exercising C. Increased action potential frequency in neurons from the ventral respiratory group D. Acidic plasma pH E. Decreased action potential frequency in neurons from the dorsal respiratory group F. Overactivation of the respiratory center in the medulla 2. Which of the...
How to schematize a diagnostic argument? This is what i have so far not sure if...
How to schematize a diagnostic argument? This is what i have so far not sure if its right, need help with this one in order to figure out rest of homework. ----------- IQ: Is drinking milk healthy? (5 items of Support TD or NTD) S1: S2: S3: S4: S5: C1: More than half of the population in north America are lactose intolerant meaning they cannot digest milk properly. C2: Article: https://milk.procon.org/
I am supposed to map out the following and can't figure out how to do it!...
I am supposed to map out the following and can't figure out how to do it! Can somebody help? The experiment has to do with determining the simplest formula of potassium chlorate and to determine the original amount of potassium chlorate in a potassium chlorate-potassium chloride mixture by measuring the oxygen lost from decomposition. The chemical reaction is 2KClO3(s) ------> 2KCL(s) + 3 O2(g) I am supposed to map out 1. Mass of oxygen lost in the first part 2....
Suppose we have two galaxies that are sufficiently far apart so that the distance between them...
Suppose we have two galaxies that are sufficiently far apart so that the distance between them increases due to Hubble's expansion. If I were to connect these two galaxies with a rope, would there be tension in the rope? Would the tension increase with time? Is the origin of the tension some sort of drag between the expanding space and matter?
PYTHON CODING: In this problem, we will figure out if two balls are colliding. We will...
PYTHON CODING: In this problem, we will figure out if two balls are colliding. We will think in 2D to simplify things, though 3D isn’t different conceptually. For calculating collision, we only care about a ball’s position in space, as well as its size. We can store a ball’s position with the (x, y) coordinates of its center point, and we can calculate its size if we know its radius. Thus, we represent a ball in 2D space as a...
This is a nice question when you find it out, and I am really looking for...
This is a nice question when you find it out, and I am really looking for a proper answer. Take quicksilver (Hg) in the periodic table. It has one proton more than Gold (melting point 1337.33 K), and one less than Thallium (melting point 577 K). It belongs to the same group as Zinc (692.68 K) and Cadmium (594.22 K). All not very high melting points, but still dramatically higher than quicksilver (234.32 K). When his neighbors melt, quicksilver vaporizes...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT