Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

design the logic for the game Hangman, in which the user guesses letters in a hi

ID: 3627339 • Letter: D

Question

design the logic for the game Hangman, in which the user guesses letters in a hidden word. Store the letters of a word in an array of characters. Display a dash for each missing letter. Allow the user to continuously guess a letter until all the letters in a word are guessed correctly. As the user enters each guess, display the word again, filling in the guess if it was correct. For example, if the hidden word is "computer", first display "--------". After the user guesses "p", the display becomes "---P----". Make sure that when a user makes a correct guess, all the matching letters are filled in. For example, if the word is "banana" and the user guesses "a", all three "a" characters must be filled in.

Explanation / Answer

words = ['banana', 'computer', 'rocks', 'giraffe', 'science'] answer = '' while answer != 'no' #init try_count to 6 == number of body parts for hangman try_count = 6 random = rand(words.count) game_word = words[random] game_word = game_word.split(//) guessed_word = ['-'] * game_word.count puts 'This is HangMan: Limited Edition' while guessed_word != game_word && try_count !=0 puts guessed_word.to_s puts 'Guess a letter: ' letter = gets.chomp matches = [] counter = 0 game_word.each_index do |i| if letter == game_word[i] matches 1 puts( "You have #{try_count} tries left") elsif try_count == 1 puts( "You have #{try_count} try left") else puts( "You have no tries left") end end puts try_count.to_s + 'try count' if try_count == 0 puts 'You lose the game.' end end if try_count > 0 puts guessed_word.to_s puts( "You completed the word, congratulations!") end begin puts 'Would you like to play again? Yes or No?' answer = gets.chomp.downcase end while answer != 'yes' && answer != 'no' end