Question

can this code be provided? Project #3 Introduction As you wrap up with JavaScript, let's put...

can this code be provided?

Project #3

Introduction
As you wrap up with JavaScript, let's put together everything you've learned to make the classic game "Hangman" in a webpage.

If you are unfamiliar with the rules of Hangman, the game works like this:

A gallows is drawn on a surface, and Player 1 chooses a word that player 2 must guess.
Empty dashes for each letter in the word are drawn next to the gallows (so a 7-letter word means 7 dashes)
Each round, player 2 guesses a letter that might belong in the word
If the word contains one or more instances of the guessed letter, the dashes corresponding to the guessed letter are replaced with the guessed letter
If the word contains no instances of the guessed letter, a limb of a person is drawn on the gallows. This is a "strike", and the letter is recorded as such
When a complete stick-figure person is drawn on the gallows, player 2 loses and player 1 wins. If the word is guessed completely before that happens, player 2 wins.
The number of strikes allowed is typically 6, for each body part of the hanged man (1 head, 1 body, 2 arms, 2 legs)

Instructions
Instructor Note: you are stongly encouraged to work with your fellow students on this project. Don't be afraid to ask questions, and don't hesitate to give an answer if you know it!

Download the template for the project, Hangman.zip and extract it.
First, create an HTML page, "hangman.html" as follows:
The page should be divided into four sections:
A gallows section that will display a picture of the gallows and hanged man in stages
A strikes section that will display incorrect guesses
A word section that will show the word to guess as it is slowly revealed
A guess section that will contain a form where the player can type in their guess each round.
Note that the template comes with 7 images you can use for the gallows section, corresponding to the number of Strikes accrued
Make sure the elements in hangman.html have IDs that will make them easier to select with CSS and JavaScript later - this game will be driven by event management and DOM manipulation.
The logic for this game will be fairly complex compared to everything you've done so far, but all of it should be familiar.

The first thing you'll need to do in your JavaScript is create some variables that will track the game's state (and we can grab the word to guess at the same time!).

let word = prompt("Welcome to Hangman! Player 1, please enter a word for Player 2 to guess.").toUpperCase();
// note the switch toUpperCase(), we want to always work in upper case letters to avoid confusing 'a' and 'A' as unequal.

let revealedLetters = new Array(word.length); // creates an array with as many elements as word has characters. Each index of revealedLetters will correspond to a character in word, and if revealedLetters[n] is truthy, then word[n] has been correctly guessed.
revlealedLetters.fill(false);

const maxStrikes = 6;
let strikes = 0; // the number of incorrect guesses made so far

let strikeLetters = new Array(maxStrikes); // this will contain every letter that has been incorrectly guessed.

Now, it may seem like you're skipping ahead here, but it will be easiest to do this step now. Create the following functions:

drawWordProgress(); // run this now, to draw the empty word at the start of the game.

// Manipulates the DOM to write all the strike letters to the appropriate section in hangman.html
function drawStrikeLetters() {
// your DOM manipulation code here
// should create a String from strikeLetters and put that into the content of some element.
}

// Manipulates the DOM to write the successfully guessed letters of the word, replacing them with dashes if not yet guessed
function drawWordProgress() {
// your DOM manipulation code here
// should iterate over revealedLetters, and if the value at each index is truthy, print the corresponding letter from word. Otherwise, it should print a -.
}

// Manipulates the DOM to update the image of the gallows for the current game state.
function drawGallows() {
// your DOM manipulation code here
// should update an <img> element in the appropriate hangman.html section to point to "images/strike-"+strikes+".png"
}

Next you'll need to attach an event listener to the <form> element in hangman.html. When the form is submitted, you'll need to invoke a function named "processGuess()":

function processGuess() {
let guess = // the value of the <form>'s <input> element, toUpperCase()!

if (strikes < maxStrikes) {
// game logic goes here
} else
alert("The game is over!");
}
Now what should this game logic be?

First, you'll want to check to see if the word includes() the guessed letter.
If it does...
You'll need to loop over word. If the letter at a given index in word matches the guess, set the corresponding index of revealedLetters to a truthy value.
Then you'll need to invoke drawWordProgress() to show the updated word
If it doesn't...
Increment the number of strikes
Add the guessed letter to strikeLetters.
invoke drawGallows() and drawStrikeLetters()
Now you need to check if player 2 won. To do that, iterate over revealedLetters. If none of the values are false, player 2 wins!

These instructions are obviously not comprehensive, and you will of course have to fill in the gaps on your own (or with your peers). One of the things that makes programming fun and addictive is that you can always make improvements somewhere!

0 0
Add a comment Improve this question Transcribed image text
Answer #1
  

# Problem Set 2, hangman.py

# Name:

# Collaborators:

# Time spent:

# 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 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')

    # line: string

    line = inFile.readline()

    # wordlist: list of strings

    wordlist = line.split()

    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

# -----------------------------------

# Load the list of words into the variable wordlist

# so that it can be accessed from anywhere in the program

wordlist = load_words()

def is_word_guessed(secret_word, letters_guessed):

    '''

    secret_word: string, the word the user is guessing; assumes all letters are

      lowercase

    letters_guessed: list (of letters), which letters have been guessed so far;

      assumes that all letters are lowercase

    returns: boolean, True if all the letters of secret_word are in letters_guessed;

      False otherwise

    '''

    for i in secret_word:

        if i not in letters_guessed:

            return False

        else:

            return True

def get_guessed_word(secret_word, letters_guessed):

    '''

    secret_word: string, the word the user is guessing

    letters_guessed: list (of letters), which letters have been guessed so far

    returns: string, comprised of letters, underscores (_), and spaces that represents

      which letters in secret_word have been guessed so far.

    '''

    hangman_text = ""

    for wub in secret_word:

        if wub in letters_guessed:

            hangman_text += wub

        else:

            hangman_text += "_ "

    return hangman_text

    

def get_available_letters(letters_guessed):

    '''

    letters_guessed: list (of letters), which letters have been guessed so far

    returns: string (of letters), comprised of letters that represents which letters have not

      yet been guessed.

    '''

    alphabits = "abcdefghijklmnopqrstuvwxyz"

    unguessed = ""

    for i in alphabits:

        if i not in letters_guessed:

            unguessed += i

        else:

            continue

    print (unguessed)

    return unguessed

        

    

    

    

def hangman(secret_word):

    '''

    secret_word: string, the secret word to guess.

    

    Starts up an interactive game of Hangman.

    

    * At the start of the game, let the user know how many

      letters the secret_word contains and how many guesses s/he starts with.

      

    * The user should start with 6 guesses

    * Before each round, you should display to the user how many guesses

      s/he has left and the letters that the user has not yet guessed.

    

    * Ask the user to supply one guess per round. Remember to make

      sure that the user puts in a letter!

    

    * The user should receive feedback immediately after each guess

      about whether their guess appears in the computer's word.

    * After each guess, you should display to the user the

      partially guessed word so far.

    

    Follows the other limitations detailed in the problem write-up.

    '''

    letters_guessed = []

    alphabits = "abcdefghijklmnopqrstuvwxyz"

    vowel = "aeiou"

    warnings = 3

    guesses_left = 6

    print ("You have ", guesses_left, " guesses_left")

    print ("I am thinking of a word that is ", len(secret_word), " letters long.")

    while is_word_guessed(secret_word, letters_guessed) == False:

        print ("You have ", guesses_left, " guesses_left")

        get_available_letters(letters_guessed)

        guess = str(input("Guess a letter. "))

        if guess not in alphabits:

            warnings -= 1

            print ("Your guess should be a letter and lowercase. You have lost a warning.")

        letters_guessed = letters_guessed.append(guess)

        if guess in secret_word:

            print ("Good guess")

            print (get_guessed_word(secret_word, letters_guessed))

            return get_guessed_word(secret_word, letters_guessed)

        if guess in letters_guessed:

            print ("You already guessed that, silly buns. You lose 1 warning.")

            warnings -=1

        else:

            print ("That letter is not in the word. You lose 1 turn.")

            guesses_left -= 1

            if guess in vowel:

                print ("...and another")

                guesses_left -=1

        if warnings == 0:

            print ("You have lost a turn due to non compliance. ")

            guesses_left -= 1

            warnings = 3

        if guesses_left == 0:

            print ("Game Over ")

            print (secret_word)

            exit

        print ("-----------")

        

        

    

# When you've completed your hangman function, scroll down to the bottom

# of the file and uncomment the first two lines to test

#(hint: you might want to pick your own

# secret_word while you're doing your own testing)

# -----------------------------------

def match_with_gaps(my_word, other_word):

    '''

    my_word: string with _ characters, current guess of secret word

    other_word: string, regular English word

    returns: boolean, True if all the actual letters of my_word match the

        corresponding letters of other_word, or the letter is the special symbol

        _ , and my_word and other_word are of the same length;

        False otherwise:

    '''

    # FILL IN YOUR CODE HERE AND DELETE "pass"

    pass

def show_possible_matches(my_word):

    '''

    my_word: string with _ characters, current guess of secret word

    returns: nothing, but should print out every word in wordlist that matches my_word

             Keep in mind that in hangman when a letter is guessed, all the positions

             at which that letter occurs in the secret word are revealed.

             Therefore, the hidden letter(_ ) cannot be one of the letters in the word

             that has already been revealed.

    '''

    # FILL IN YOUR CODE HERE AND DELETE "pass"

    pass

def hangman_with_hints(secret_word):

    '''

    secret_word: string, the secret word to guess.

    

    Starts up an interactive game of Hangman.

    

    * At the start of the game, let the user know how many

      letters the secret_word contains and how many guesses s/he starts with.

      

    * The user should start with 6 guesses

    

    * Before each round, you should display to the user how many guesses

      s/he has left and the letters that the user has not yet guessed.

    

    * Ask the user to supply one guess per round. Make sure to check that the user guesses a letter

      

    * The user should receive feedback immediately after each guess

      about whether their guess appears in the computer's word.

    * After each guess, you should display to the user the

      partially guessed word so far.

      

    * If the guess is the symbol *, print out all words in wordlist that

      matches the current guessed word.

    

    Follows the other limitations detailed in the problem write-up.

    '''

    # FILL IN YOUR CODE HERE AND DELETE "pass"

    pass

# When you've completed your hangman_with_hint function, comment the two similar

# lines above that were used to run the hangman function, and then uncomment

# these two lines and run this file to test!

# Hint: You might want to pick your own secret_word while you're testing.

if __name__ == "__main__":

    #pass

    # To test part 2, comment out the pass line above and

    # uncomment the following two lines.

    

    secret_word = choose_word(wordlist)

    hangman(secret_word)

###############

    

    # To test part 3 re-comment out the above lines and

    # uncomment the following two lines.

    

    #secret_word = choose_word(wordlist)

    #hangman_with_hints(secret_word)

Add a comment
Know the answer?
Add Answer to:
can this code be provided? Project #3 Introduction As you wrap up with JavaScript, let's put...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • This is for C programming: You will be given files in the following format: n word1...

    This is for C programming: You will be given files in the following format: n word1 word2 word3 word4 The first line of the file will be a single integer value n. The integer n will denote the number of words contained within the file. Use this number to initialize an array. Each word will then appear on the next n lines. You can assume that no word is longer than 30 characters. The game will use these words as...

  • Simple JavaScript and HTML: You'll create a simple word guessing game where the user gets infinite...

    Simple JavaScript and HTML: You'll create a simple word guessing game where the user gets infinite tries to guess the word (like Hangman without the hangman, or like Wheel of Fortune without the wheel and fortune). Create two global arrays: one to hold the letters of the word (e.g. 'F', 'O', 'X'), and one to hold the current guessed letters (e.g. it would start with '_', '_', '_' and end with 'F', 'O', 'X'). Write a function called guessLetter that...

  • C++ Hangman (game) In this project, you are required to implement a program that can play...

    C++ Hangman (game) In this project, you are required to implement a program that can play the hangman game with the user. The hangman game is described in https://en.wikipedia.org/wiki/Hangman_(game) . Your program should support the following functionality: - Randomly select a word from a dictionary -- this dictionary should be stored in an ASCII text file (the format is up to you). The program then provides the information about the number of letters in this word for the user to...

  • I have to use java programs using netbeans. this course is introduction to java programming so...

    I have to use java programs using netbeans. this course is introduction to java programming so i have to write it in a simple way using till chapter 6 (arrays) you can use (loops , methods , arrays) You will implement a menu-based system for Hangman Game. Hangman is a popular game that allows one player to choose a word and another player to guess it one letter at a time. Implement your system to perform the following tasks: Design...

  • For a C program hangman game: Create the function int play_game [play_game ( Game *g )]...

    For a C program hangman game: Create the function int play_game [play_game ( Game *g )] for a C program hangman game. (The existing code for other functions and the program is below, along with what the function needs to do) (Also the link to program files (hangman.h and library file) is below the existing code section. You can use that to check if the code works) What int play_game needs to do mostly involves calling other functions you've already...

  • Overview In this exercise you are going to recreate the classic game of hangman. Your program...

    Overview In this exercise you are going to recreate the classic game of hangman. Your program will randomly pick from a pool of words for the user who will guess letters in order to figure out the word. The user will have a limited number of wrong guesses to complete the puzzle or lose the round. Though if the user answers before running out of wrong answers, they win. Requirements Rules The program will use 10 to 15 words as...

  • In PYTHON 3- Implement a subclass (described below) of "Word Guess", a variant of the game...

    In PYTHON 3- Implement a subclass (described below) of "Word Guess", a variant of the game Hangman. In this game, a word is first randomly chosen. Initially, the letters in the word are displayed represented by "_”.   For example, if the random word is "yellow”, the game initially displays "_ _ _ _ _ _”. Then, each turn, the player guesses a single letter that has yet to be guessed. If the letter is in the secret word, then the...

  • Do in Python please provide screenshots aswell. Here are the requirements for your game: 1. The...

    Do in Python please provide screenshots aswell. Here are the requirements for your game: 1. The computer must select a word at random from the list of avail- able words that was provided in words.txt. The functions for loading the word list and selecting a random word have already been provided for you in ps3 hangman.py. 2. The game must be interactive; the flow of the game should go as follows: • At the start of the game, let the...

  • PLEASE DO IN JAVA You can use any source for the dictionary or just a few...

    PLEASE DO IN JAVA You can use any source for the dictionary or just a few words are fine! description The purpose of this assignment is to practice with ArrayLists (and hopefully, you'll have some fun). As far as the user knows, play is exactly as it would be for a normal game of hangman, but behind the scenes, the computer cheats by delaying settling on a mystery word for as long as possible, which forces the user to use...

  • HEy GUYS PLZ I WROTE THIS CODE BUT I WAS ASKED TO ADD SOME ASSERTION TESTS AND I HAVE NEVER DONE SUCH THING. CAN YOU GUY...

    HEy GUYS PLZ I WROTE THIS CODE BUT I WAS ASKED TO ADD SOME ASSERTION TESTS AND I HAVE NEVER DONE SUCH THING. CAN YOU GUYS HELPS ME OUT ON HOW TO TEST A SIMPLE CODE SINCE ITS A GUESSING GAME! THANK YOU. PYTHON import random # here it allows us to use the benefits of the functions random #function 1 which is just a screen organized wordings def screen): screeninstructions () name input("Your Name : ") print('Welcome, name, 'This...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT