我想在Elixir中實現hang子手,我很困惑我應該如何用正確的猜到字母(相應的索引)替換佔位符字中的破折號。我曾嘗試使用slice/3
和replace/4
函數,但沒有多少運氣。下面是函數,我檢查,如果由用戶輸入的字母是在祕密字,並在那裏我試圖插入信成佔位符包含破折號:在Elixir的Hangman遊戲中用字母替換破折號
def check_match(word, guess) do
len = String.length(word)
str = String.duplicate("_ ", len)
if String.contains? word, guess do
{index, length} = :binary.match(word, guess)
#String.slice(str, index, len) <> guess <> String.slice(str, index+1, len)
IO.puts String.replace(str, " ", guess)
else
IO.puts str
end
end
我打電話check_match/2
內guess_word/2
(其中還包含我的遊戲邏輯):
def guess_word(word, duration) do
gs = IO.gets("enter letter: ")
guess = String.trim(gs)
put(duration, guess)
update_letters()
check_match(word, guess)
if duration > 0 && !check_win(word, guess) do
guess_word(word, duration - 1)
end
end
也許我試圖取代破折號在程序中的錯誤部分。我將如何去替換正確的索引破折號?
例如,加密詞是富:
_ _ _
用戶猜f
f _ _
全部代碼在這裏:http://pastebin.com/JkSefm1S