如何在Hangman(Ruby)中显示用户的正确猜测

时间:2015-08-12 12:52:27

标签: ruby

如果用户猜到了正确的字母,我希望它能显示确切的位置。像这样:字香蕉。用户写“a”并显示_a__a_a

word = nil      #no word or letters yet
tries = 0       #setting the tries to zero
letter = nil    #no word or letters yet

puts "This is a game for 2. Player 1 writes which word they want player 2 to guess."
puts "Player 1, write a word: "
word = gets.chomp
letters = []
letters = word.split(//)
progress = ["_ " * letters.length]
puts progress
puts "Player 2, guess a letter: "

while tries < 10 || letters.length == 0
    letter = gets.chomp
    if letters.include? letter
        ind = letters.index(letter)
        progress.insert(ind, letter)
        progress.delete("_ ")
        letters.delete(letter)
        puts "You guessed one letter!"
        progress = "_ " * letters.length
        puts progress
    else
        puts "Nope, sorry."
        tries += 1
        puts "You have " + (10 - tries).to_s + " left"
    end
end

2 个答案:

答案 0 :(得分:1)

可能是这样的:

def show_progress(word,guessed_letters)
  display_string = ''
  word.chars.each do |char|
    if guessed_letters.include?(char)
      display_string << char
    else 
      display_string << '_'
    end
  end
  display_string
end

然后你只需用答案和猜到的字母来称呼它

show_progress('duck', ['u','k','f'])
# => "_u_k"

答案 1 :(得分:1)

我对主循环做了一些修改,以便你可以检查玩家是否赢了:

def check_and_print(letters, guessed)
  won = true

  # Print letters accordingly
  letters.each do |l|
    if guessed.include? l
      print l
    else
      print '_ '
      won = false
    end
  end

  # Insert a line break
  puts ""

  return won
end

while tries < 10 || letters.length == 0
    letter = gets.chomp
    if letters.include? letter
        puts "You guessed one letter!"
        guessed << letter
        won = check_and_print(letters, guessed)

        # Check if the user won
        if won
          puts "You won!!"
          break
        end
    else
        puts "Nope, sorry."
        tries += 1
        puts "You have " + (10 - tries).to_s + " left"
    end
end