我目前正致力于构建猜词游戏。有一个单词,用户会猜到单词中的一个字符。如果用户猜测的角色实际上是在单词中,那么将给出反馈。例如,单词是" cookie"并且用户输入" o"那么反馈就是
_ o o _ _ _
在这种情况下,尝试次数等于单词的长度6.如果用户猜测不是单词的一部分的字符,例如" z"消息将显示错误。但是,我在访问if和else语句时遇到问题,它们仅适用于第一个输入。这是我的代码:
class Game
attr_reader :word
attr_accessor :guess_counts, :guesses, :user_input, :guess_array
def initialize(word)
@word = word
@guesses = ""
end
def tries
@tries = @word.length
end
def guesses(user_input)
@user_input = user_input
@guesses << @user_input
end
def underscored
return @word.tr('^' + @guesses, '_').chars.join(' ')
end
end
# user interface
puts "Please enter a word to initialize the Guessing The Word game"
secret_word = gets.chomp
game = Game.new(secret_word)
puts "you have #{game.tries} attemps left"
guesses = []
tries = secret_word.length
while tries > 0
puts "Plese enter a letter you believe is in the secret word"
letter = gets.chomp
game.guesses(letter)
guesses << letter
guess = guesses[0]
if !secret_word.include? guess
puts "Letter not in word"
tries -= 1
puts "you have #{tries} left "
next
elsif secret_word.include? guess
p game.underscored
else
puts "you lost"
end
end
&#13;
当我输入&#34; o&#34;时,您会在此图片中看到
答案 0 :(得分:1)
问题是你写的时候总是抓住guesses
数组中的第一个元素:
guess = guesses[0]
所以表达式!secret_word.include? guess
是:
true
,然后是false
要解决此问题,您可能需要抓住最后一个猜测;即
guess = guesses.last
# `.last` is convenience method for accessing last element of an array; like so
#
# guess = guesses[-1]
或letter
声明的当前if
:即
if !secret_word.include? letter
# [...]
elsif secret_word.include? letter
# [...]