Question

In: Computer Science

Hangman We're going to write a game of hangman. Don't worry, this assignment is not nearly...

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.

'''
This is a simplified version of a hangman game. The computer chooses a word
from a pre-defined list of words and the user guesses letters until they have
filled in all the letters in the word.

Author:  
Student Number:  
Date:  Oct, 2020
'''
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
    """

    #DO NOT MODIFY THIS FUNCTION
    
    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
    """

    #TODO -- complete this function so that it prints "word" (a string)
    #so that there are spaces between each letter.
    #eg:  word = "watch", the function prints w a t c h
    #you will need a loop to do this.
    #recall that print() can be given a parameter end=' ' to keep all output
    #on the same line.

    #PUT YOUR CODE HERE

    #leave the following two lines at the end of your function for nicer output
    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
    

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 = ""

    
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
    """

    #TODO -- complete this function so that it returns the concatentation
    #of the string usedLetters with the letter. 
 
    pass #remove this line -- pass is a "do nothing" keyword

    

def main():
    """
    This implements the user interface for the program.
    """
    usedLetters = "" #no letters guessed yet
    secret = getSecretWord()
    print("The secret word is ", secret)

    #TODO - add one line of code here to call the function
    #convertWordToBlanks to convert the secret word
    #to a string of underscores.  Assign the result to
    #the variable blank as shown below.
    blank = #ADD YOUR FUNCTION CALL HERE.  

    
    printStringWithSpaces(blank)

    
    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

            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

Explanation:-

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:

O/P:-

If you have any dought about this answer dont give dislike ,tell us your dought in the comment then i can explain, Please rate me by giving me a like or thumb because it motivates me to do more work,Thank you.


Related Solutions

For this assignment we're going to make another calculator. This one will be a simple four...
For this assignment we're going to make another calculator. This one will be a simple four function (add, subtract, multiply, and divide) calculator, but it will have state. Specifically, the calculator will keep track of the result of the most recent operation and use that value as the first operand for the next operation. Take a look at the sample output below if this doesn't quite make sense. Your new calculator class should have the following fields and methods: fields:...
Write a program to allow a user to play the game Hangman. DO NOT USE AN...
Write a program to allow a user to play the game Hangman. DO NOT USE AN ARRAY The program will generate a random number (between 1 and 4581) to pick a word from the file - this is the word you then have to guess. Note: if the random number you generate is 42, you need the 42nd word - so loop 41 times picking up the word from the file and not doing anything with it, it is the...
For this assignment, you will create a command-line version of the game ​Hangman. You should work...
For this assignment, you will create a command-line version of the game ​Hangman. You should work in a group of two on the project and not view Hangman code of other students or found on-line. Submit this project-- your .java file-- here on Canvas. For this assignment you will research on StringBuilder Class (​Use this link​) and use it in your code. Functional requirements (rubric) ● Your game should have a list of at least ten phrases of your choosing...
How would I create a Hangman game that chooses  a random word and the player needs to...
How would I create a Hangman game that chooses  a random word and the player needs to guess it, letter by letter using  JavaScript and jQuery to allow user interaction. The content and the style of the page must be updated based on user’s input.
This week, we're going to be discussing Amazon and it's ascent to become one of the...
This week, we're going to be discussing Amazon and it's ascent to become one of the largest global online retailers. Get ready for another great set of conversations! https://www.youtube.com/watch?v=YlgkfOr_GLY Why do you think has Amazon succeeded when so many other companies have failed? How did their First Mover's Advantage factor into their ubiquity? How long did it take for Amazon to become profitable? What’s next for Amazon... Cloud computing? Deliveries by drone? Travel? Retail? You should research the company and...
Do it in python please This lesson's Group Activities are: We're going to take the Group...
Do it in python please This lesson's Group Activities are: We're going to take the Group Activity from last week and tweak it. Instead of storing the random numbers in a list, we're going to store them in a file. Write a program using functions and mainline logic which prompts the user to enter a number, then generates that number of random integers and stores them in a file. It should then display the following data to back to the...
Overview For this assignment, write a program that uses functions to simulate a game of Craps....
Overview For this assignment, write a program that uses functions to simulate a game of Craps. Craps is a game of chance where a player (the shooter) will roll 2 six-sided dice. The sum of the dice will determine whether the player (and anyone that has placed a bet) wins immediately, loses immediately, or if the game continues. If the sum of the first roll of the dice (known as the come-out roll) is equal to 7 or 11, the...
For this assignment, write a program that uses functions to simulate a game of Craps. Craps...
For this assignment, write a program that uses functions to simulate a game of Craps. Craps is a game of chance where a player (the shooter) will roll 2 six-sided dice. The sum of the dice will determine whether the player (and anyone that has placed a bet) wins immediately, loses immediately, or if the game continues. If the sum of the first roll of the dice (known as the come-out roll) is equal to 7 or 11, the player...
Can you create a player vs computer Hangman game on MATLAB using nested loops, for loops,...
Can you create a player vs computer Hangman game on MATLAB using nested loops, for loops, if loops, while loops, arrays and conditional execution, as well as creating an image of the game board. The list below must be considered in the code. - Selecting a word from a dictionary (a text file) - Reading a single letter from the user - Building a character array showing the letters matched so far - Keeping count of the number of guessed...
n this problem, we're going get a rough estimate the amount of uranium fuel it would...
n this problem, we're going get a rough estimate the amount of uranium fuel it would take if the US recieved all its electrical power from nuclear power plants. The size of a power plant in normally given as the about of electrical power it can produce when running a full capacity. This electrical power produced can be very different than the mechanical or thermal power that was required to produce this electricity. For example, power plant might have a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT