I'm making a Hangman game, and I want to make sure that if there are multiple letters that are the same in the string, I want to input them in their desired locations. However, only the first found is inputted.
local words = {
"airplane", "vehicle", "house", "machine", "castle", "airport", "medieval", "recovery", "hospital", "police",
"animal",
}
local tries = 6 -- each body part
local slots = {}
local function chooseWord()
local word = words[math.random(1, #words)]
return word
end
local function generateSlots(length) -- based on word's length
for i = 1, length do
local slot = script.Slot:Clone()
slot.Name = "Slot"..i
table.insert(slots, slot)
slot.Parent = script.Parent.Slots
end
for x = 1, #slots do
slots[x].Position = UDim2.new(slots[x].Position.X.Scale + 0.05, 0, 0.68, 0)
end
end
local function inputLetter(word, letter)
print(string.match(word, letter))
local pos = lookForLetter(word, letter)
slots[pos].Letter.Text = string.upper(letter)
end
function lookForLetter(word, letter) -- this is the problem of my question
local position = string.find(word, letter, 0)
return position
end
play.TextButton.MouseButton1Down:Connect(function()
play.Visible = false
title.Visible = false
back.Visible = true
-- Tweening stuff
infinite:TweenPosition(UDim2.new(0.5, 0, 0.42, 0), "Out", "Sine", 0.5)
timed:TweenPosition(UDim2.new(0.5, 0, 0.3, 0), "Out", "Sine", 0.5)
timerImage:TweenPosition(UDim2.new(0.64, 0, 0.3, 0), "Out", "Sine", 0.5)
singleplayer:TweenPosition(UDim2.new(0.5, 0, 0.12, 0), "Out", "Sine", 0.5)
infinite.MouseButton1Click:Connect(function()
infinite.Position = UDim2.new(0.5, 0, 4, 0)
timed.Position = UDim2.new(0.5, 0, 4, 0)
timerImage.Position = UDim2.new(0.64, 0, 4, 0)
singleplayer.Position = UDim2.new(0.5, 0, -4, 0)
local pickedWord = chooseWord()
print("Word: "..pickedWord)
generateSlots(string.len(pickedWord))
letters:TweenPosition(UDim2.new(0, 0, 0, 0), "Out", "Sine", 0.5)
for _, letter in pairs(letters:GetChildren()) do
letter.MouseButton1Down:Connect(function()
print(string.match(pickedWord, string.lower(letter.Text)))
if string.lower(letter.Text) == string.match(pickedWord, string.lower(letter.Text)) then
inputLetter(pickedWord, string.lower(letter.Text))
end
end)
end
end)
end)
