我是Ruby新手,正在和這個hang子手風格的猜字遊戲一起工作。我有兩個主要問題。這裏是我與現在的工作是什麼:紅寶石猜字遊戲
class Word_game
def initialize(word)
@word = word.downcase
@display_word = "_ " * word.length
end
def guess_the_word(word_guess)
word_guess.downcase
@word.split("").each_with_index do |word_letter, index|
if word_guess == word_letter
@display_word[index] = word_guess
p @display_word
puts "You're getting somewhere! Keep trying!"
end
end
if [email protected]? (word_guess)
puts "Nope, guess again..."
end
def win?
if @word == @display_word
puts "Congratulations you won!!! You are the word master!!!"
true
else
false
end
end
def lose?
if @attempts == 0
puts "You lose!!"
true
end
end
puts "Welcome to the Word Guessing Game! Let's see if YOU have what it TAKES!!!"
puts "This is a 2 player game. "
puts "Player 1... please enter a word for Player 2 to guess!"
puts ">>"
game_word = gets.chomp
game = Word_game.new(game_word)
attempts = 0
guessed_letters = []
until @attempts == game_word.length
puts "Ok Player 2, Guess a letter! GO!!!"
letter_guess = gets.chomp
if guessed_letters.include? letter_guess
puts "You already guessed that letter! Enter a new one."
letter_guess = gets.chomp
end
guessed_letters << letter_guess
game.guess_the_word(letter_guess)
if game.win?
attempts += 1
else game.lose?
end
end
end
首先,單詞進度應該是這樣的,如果這個詞是個招呼:
h _ e _ _ o
取而代之的是,這些空間不在正確的地方,看起來像這樣(運行我的代碼的實際結果):
。
Ok Player 2, Guess a letter! GO!!!
h
"h _ _ _ _ "
You're getting somewhere! Keep trying!
Ok Player 2, Guess a letter! GO!!!
o
"h _ o _ _ "
You're getting somewhere! Keep trying!
Ok Player 2, Guess a letter! GO!!!
e
"he_ o _ _ "
You're getting somewhere! Keep trying!
Ok Player 2, Guess a letter! GO!!!
l
"hel o _ _ "
You're getting somewhere! Keep trying!
"hello _ _ "
當用戶猜測這個單詞時,它不會放我的「恭喜」聲明並結束遊戲。
我也堅持我的'失敗'方法。我不確定如何修復該方法,以便在用戶用盡了所有嘗試並打印「丟失」語句時遊戲結束。
感謝您的幫助!
非常感謝!我確實獲得了win方法...但是,即使它結束了,我也會收到錯誤消息「意外返回」,代表您放置的最後一段代碼。 –
另外,在改變我目前的[email protected]?部分...當我運行代碼時,如果我輸入一個'不正確'的字母,「再次猜測」會打印出5次,並且它會立即以「你輸」結束遊戲。我不知道爲什麼會發生這種情況。 –
無視我最後的評論!我在do塊中定義了它,一旦我在它之外定義它,它會停止打印很多次,讓我繼續猜測。然而,第一條評論的問題仍然沒有解決。 –