我正在构建一个刽子手游戏,我不知道如何用 player_input (Array) 中的匹配字母替换 hidden_word (String) 中的下划线。任何想法我应该做什么?提前谢谢你,我很感激!
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
这里有一些代码可以让你继续前进。将猜出的字母收集到一个数组中。然后,将单词的字符映射到字符(如果猜到的话)或下划线。
word = "RHUBARB"
guessed_letters = ['A', 'R', 'U']
hidden_word = word.chars.map { |c| guessed_letters.include?(c) ? c : '_' }.join
# => "R_U_AR_"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句