我正在构建一个hang子手游戏,我不知道如何用player_input(数组)中的匹配字母替换hidden_word(字符串)中的下划线。有什么想法我应该做什么?预先谢谢您,谢谢!
def update
if @the_word.chars.any? do |letter|
@player_input.include?(letter.downcase)
end
puts "updated hidden word" #how to replace underscores?
end
puts @hidden_word
puts "You have #{@attempts_left-1} attempts left."
end
我有两个字符串,the_word和hidden_word,还有一个数组,player_input。每当玩家选择与the_word匹配的字母时,hidden_word就会更新。
例如
the_word =“红宝石”
hidden_word =“ _ _ _ _”
玩家选择“ g”,hidden_word仍为“ _ _ _ _”
玩家选择“ r”,hidden_word更新“ R _ _ _”
这是其余的代码:
class Game
attr_reader :the_word
def initialize
@the_word = random_word.upcase
@player_input = Array.new
@attempts_left = 10
end
def random_word
@the_word = File.readlines("../5desk.txt").sample.strip()
end
def hide_the_word
@hidden_word = "_" * @the_word.size
puts "Can you find out this word? #{@hidden_word}"
puts "You have #{@attempts_left} attempts left."
puts @the_word #delete this
end
def update
if @the_word.chars.any? do |letter|
@player_input.include?(letter.downcase)
end
puts "updated hidden word" #how to replace underscores?
end
puts @hidden_word
puts "You have #{@attempts_left-1} attempts left."
end
def guess_a_letter
@player_input << gets.chomp
puts "All the letters you have guessed: #{@player_input}"
end
def has_won?
if !@hidden_word.include?("_") || @player_input.include?(@the_word.downcase)
puts "You won!"
elsif @attempts_left == 0
puts "You lost..."
end
end
def game_round #the loop need fixin
puts "Let's play hangman!"
hide_the_word
while @attempts_left > 0
guess_a_letter
update
@attempts_left -= 1 #fix this
has_won?
break if @player_input.include?("q") #delete this
end
end
end
new_game = Game.new
new_game.game_round
答案 0 :(得分:1)
这里有一些代码可以帮助您入门。将猜测的字母收集在一个数组中。然后,将单词的字符映射到猜出的字符或下划线。
word = "RHUBARB"
guessed_letters = ['A', 'R', 'U']
hidden_word = word.chars.map { |c| guessed_letters.include?(c) ? c : '_' }.join
# => "R_U_AR_"
答案 1 :(得分:0)
我不确定downcase
,因为您也使用过uppercase
。
只选择一个字母大小写。
但这对您有用:
def update
@the_word.each_char.with_index do |letter, index|
@hidden_word[index] = letter if @player_input.include?(letter.downcase)
end
puts @hidden_word
puts "You have #{@attempts_left-1} attempts left."
end
它将秘密单词的每个字母与用户的输入进行比较,并通过巧合更改隐藏单词中的下划线。
答案 2 :(得分:0)
一种选择是使用正则表达式:
@hidden_word = @the_word.gsub(/[^#{@player_input.join('')}\s]/i, '_')