-2

I am new to ruby and creating a hangman game. Soo far I have my code comparing the words to the correct word. But I want it to compare letters. So basically, if the secrect word is glue, the user enters G it would come inncorrect, but if the user enters glue it would be correct. I need it to compare letter by letter just like hangman.

Having a bit of trouble with that. I have attached my code below.

secret_word = []
puts "enter a word to be guessed"
secret_word = gets.chomp



guess_letters = []
guess = ""
guess_limit = 3
guess_count = 0
out_of_guesses = false

while guess != secret_word and !out_of_guesses
    if guess_count < guess_limit
    puts "enter your guess: "
    guess = gets.chomp()
    guess_letters << guess
    guess_count +=1
    puts "you have used these letters thus far #{guess_letters.join(", ")}"
else
    out_of_guesses = true
end
end
if out_of_guesses
    puts "you Lose, the word was #{secret_word}"
else
    puts "you win"
end
1
  • 1
    "Having a bit of trouble with that." is not a precise enough error description for us to help you. What doesn't work? How doesn't it work? What trouble do you have with your code? Do you get an error message? What is the error message? Is the result you are getting not the result you are expecting? What result do you expect and why, what is the result you are getting and how do the two differ? Is the behavior you are observing not the desired behavior? What is the desired behavior and why, what is the observed behavior, and in what way do they differ? Oct 8, 2019 at 21:27

2 Answers 2

0

I'm not sure which hangman rules you are using but here's a rough draft that allows three failed attempts and works with lowercase characters

def guess_word(word, tries)

    if tries < 1
        puts "You are hanged!"
    elsif word.empty?
        puts "You guessed it! You are saved from the gallows!"
    else
        print "Enter character: "
        c = STDIN.getc.downcase
        STDIN.getc # get rid of newline
        if word.index(c).nil?
            puts "Ooops, #{c} was wrong!"
            guess_word(word, tries - 1)
        else
            puts "#{c} was correct!"
            guess_word(word.sub(/["#{c}"]/, ''), tries)
        end
    end

end

if __FILE__ == $0

    TRIES = 3

    print "Enter word to guess: "
    word = gets.chomp

    guess_word(word.downcase, 3)    

end

This is untested..

0

The rules of the game hangman are given at its Wiki. I've assumed the player trying to guess the word loses when all seven parts of the man on the gallows have been drawn (head, neck, left arm, body, right arm, left leg, right leg).

Helper methods

Draw the man being hanged

First create a hash that can be used to draw the partial or full hangman:

MAN = [" O\n", " |\n", "\\", "|", "/\n", " |\n/", " \\"].
  map.each_with_object([""]) { |s,arr| arr << (arr.last + s) }.
      each.with_index.with_object({}) { |(s,i),h| h[i] = s }

The keys are the number of incorrect guesses. For example:

puts MAN[2]
 O
 |
puts MAN[6]
 O
 |
\|/
 |
/

Keep track of the positions of the letters of the word

Next create a hash whose keys are unique letters of the secret word and whose values are arrays of indices of the keys location(s) in the word.

def construct_unknown(word)
  word.each_char.with_index.with_object({}) { |(c,i),h| (h[c] ||= []) << i }
end

For example,

unknown = construct_unknown("beetle")
  #=> {"b"=>[0], "e"=>[1, 2, 5], "t"=>[3], "l"=>[4]}

We will also create an empty hash for letters whose positions are known:

known = {}

Move guessed letters from the hash unknown to the hash known

If a letter that is guessed is a key of unknown that key and value are moved to known.

def move_unknown_to_known(letter, unknown, known)
  known.update(letter=>unknown[letter])
  unknown.delete(letter)
end

For example (for unknown and known above),

move_unknown_to_known("e", unknown, known)
unknown #=> {"b"=>[0], "t"=>[3], "l"=>[4]} 
known   #=> {"e"=>[1, 2, 5]} 

See if the guesser has won or lost

We to determine when, after guessing a letter, the player has won or lost, or is to continue:

def win?(word_size, known)
  known.values.flatten.sum == word_size
end

def lose?(wrong_guess_count)
  wrong_guess_count == HANGMAN.size
end

For example,

win?(word.size, known)
  #=> false

lose?(6) #=> false
lose?(7) #=> true

Display the known letters

def display_known(word_size, known)
  known.each_with_object('_' * word_size) { |(k,a),s| a.each { |i| s[i] = k } }
end

For example (recall word #=> "beetle"),

puts display_known(word.size, known)
_ee__e

Main method

We are now ready to write the main method.

def hangman
  puts "Player 2, please avert your eyes for a moment."
  print "Player 1: enter a secret word with at least two letters: "
  word = gets.chomp.downcase
  unknown = construct_unknown(word)
  known = {}
  wrong_guess_count = 0
  loop do
    puts display_known(word.size, known)
    puts MAN[wrong_guess_count] if wrong_guess_count > 0
    if win?(word.size, known)
      puts "You win! You win! Congratulations!"
      break  
    end
    if lose?(wrong_guess_count)
      puts "Sorry, but you've run out of guesses"
      break
    end 
    print "Player 2: enter a letter or your guess of the word: "
    guess = gets.chomp.downcase
    if guess.size > 1
      if guess == word
        puts word
        puts "You win! You win! Congratulations!"
        break
      else
        puts "Sorry, that's not the word"
        wrong_guess_count += 1
      end
    elsif unknown.key?(guess)
      nbr = unknown[guess].size
      puts nbr == 1 ? "There is 1 #{guess}" : "There are #{nbr} #{guess}'s"
      move_unknown_to_known(guess, unknown, known)                   
    else
      puts "Sorry, the word contains no #{guess}'s"
      wrong_guess_count += 1
    end
  end
end  

Example

After explaining the rules to the two players and to the audience, the guest host ends by saying, "And don't forget, when guessing a letter or the word it must be expressed as a question...one moment...hold that...I've been told it is not necessary to frame that as a question".

Suppose the word is beetle and the letter guesses are 't', 'i', 'a', 'l', 'r', 's', 't', 'u', 'e', 'beetle'.

hangman

Player 2, please avert your eyes for a moment.

Player 1: enter a secret word with at least two letters: beetle
______

Player 2: enter a letter or your guess of the word: t
There is 1 t
___t__

Player 2: enter a letter or your guess of the word: i
Sorry, the word contains no i's
___t__
 O

Player 2: enter a letter or your guess of the word: a
Sorry, the word contains no a's
___t__
 O
 |

Player 2: enter a letter or your guess of the word: l
There is 1 l
___tl_
 O
 |

Player 2: enter a letter or your guess of the word: r
Sorry, the word contains no r's
___tl_
 O
 |
\

Player 2: enter a letter or your guess of the word: s
Sorry, the word contains no s's
___tl_
 O
 |
\|

Player 2: enter a letter or your guess of the word: t
Sorry, the word contains no t's
___tl_
 O
 |
\|/

Player 2: enter a letter or your guess of the word: u
Sorry, the word contains no u's
___tl_
 O
 |
\|/
 |
/

Player 2: enter a letter or your guess of the word: e
There are 3 e's
_eetle
 O
 |
\|/
 |
/

Player 2: enter a letter or your guess of the word: beetle
beetle
You win! You win! Congratulations!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.