背景:使用一個類,我正在構建一個類似hang子手的遊戲,其中玩家1輸入一個要猜測的單詞,玩家2嘗試猜測它。分配給玩家2的猜測數與相關單詞有關,但重複的猜測不計入玩家。紅寶石 - 編寫一個猜測字母的程序
每個猜測應該通過顯示他們猜測單詞的進度來向玩家2提供連續的反饋,這應該在每個猜測階段結束時打印出來。例如)'代碼'一詞將顯示爲「_ _ _ _ 」,如果字母「o」被猜測,反饋將看起來像「 _ o _ _」等。一旦該單詞被猜測或者球員還剩0次,則宣佈獲勝者。
問題1:我無法讓程序在game_won時關閉?方法評估爲true。它繼續運行,直到嘗試== game_word.length + 2.關於如何用獲勝聲明結束程序的任何想法?
問題2:我嘗試添加一個game_lost方法,但一旦玩家2嘗試完成時嘗試創建一個實例變量(嘗試創建一個與接口中的嘗試綁定的實例變量,但每當它被外部調用問題3:每當輸入一個不正確的字母時,就會出現一個錯誤信息,說明它是一個零類,而不是一個整數。我怎樣才能創建一個函數方法來指明遊戲何時丟失?
問題3: 「不,再試一次...」的答覆打印出來的次數與單詞的長度一樣多,似乎是在guess_the_letter方法中打印出最後一次評估的次數x次。 ISSU e 4:如果輸入的單詞包含多個同一個字母,則單詞進度更新將出現與該單詞存在於遊戲單詞中的次數相同的次數。 (似乎是問題3的類似問題)任何想法,我在做什麼錯在這裏。
class GuessingGame
def initialize(word)
@word = word.downcase
@display_word = "_" * word.length
end
# Take a guess in the form of a letter and check to see if it is in the
# target word, update the word pattern to include the missing letter
def guess_the_letter(g_letter)
g_letter.downcase
@word.split("").each_with_index do |w_letter, index|
if g_letter == w_letter
@display_word[index] = g_letter
puts "Here is your progress towards guessing the word:"
p @display_word
end
if [email protected]? (g_letter)
puts "Nope, try again..."
end
end
end
# Determine winning conditions
def game_won?
if @word == @display_word
puts "Congratulations Player 2, you won!"
true
else
false
end
end
def game_lost?
#method body
end
end
puts "Welcome to the Word Guessing Game!"
puts "This game is for 2 players."
puts "Player 1, please enter a word for player 2 to guess..."
game_word = gets.chomp
game = GuessingGame.new(game_word)
attempts = 0
guessed_letters = []
#Create an interface for the users to play the game
until attempts == game_word.length + 2
puts "Player 2, please guess a letter..."
letter_guess = gets.chomp
if guessed_letters.include? letter_guess
puts "You already tried that letter, enter a new one."
letter_guess = gets.chomp
end
guessed_letters << letter_guess
game.guess_the_letter(letter_guess)
game.game_won?
attempts += 1
end
請在嘗試傳達複雜概念時養成使用段落的習慣。你的問題是一段難以理解的文字。另外,不要在你的問題中加入「編輯」之類的東西。我們不關心你的問題在過去是否被嚴重地表述過,只要它現在已經寫得很好*(編輯歷史也可以用幾種非常好的格式提供)。 –
謝謝,我對文本塊進行了一些編輯,使其更清晰。仍然習慣了網站@JörgWMittag – Dan