Hello At the moment I am working on a small Simon Says game and I have encountered a problem which I cannot seem to find a fix for.
Basically my code first gets all the colors available in the Simon Says color folder, then waits for the user to join and executes the initialize function which runs my main code. It then creates a stack and a game over variable set to false, and begins its loop. It starts by adding the first randomized color into the stack using my pickColor()
function above the main function. After that, it runs through all the items in the stack and lights up the color pads using my signalColor()
function.
Here is the problem that I found in that for loop that runs through the stack. The whole loop works but I am confused why it is running pickColor()
every time it goes through the second item in the stack. Why is this happening and how can I troubleshoot this?
Here is the following code (Note: There are some unfinished portions) :
local players = game:GetService("Players")
local colors = game.Workspace.Colors
local plrName = ""
local array = {}
local arrayStr = ""
-- Get all colors under folder into an array.
for i, item in pairs(colors:GetChildren()) do
array[i] = item.Name -- Get all color names in array.
arrayStr = arrayStr .. item.Name .. ", "
end
print("Colors Detected: " .. arrayStr)
-- Pick Randomized Color.
local function pickColor()
print("Picking color ...")
local num = math.random(0, 7)
local picked = array[num]
print("Picked " .. picked) -- Fails because 'picked' is nil sometimes, gotta fix.
return picked -- Returns string
end
-- Signaling the color plate to the player.
local function signalColor(color)
local object = colors:FindFirstChild(color)
object.Material = Enum.Material.Neon
wait(1)
object.Material = Enum.Material.Metal
end
-- Check for when player touches an object.
local function checkTouched(part)
end
-- Main sequence function.
local function initialize(plr)
plrName = plr.Name -- Getting plr name for plr model.
local player = players:FindFirstChild(plrName)
print("Player: " .. plrName)
local plrPart = game.Workspace:WaitForChild(plrName)
print("Player " .. plrName .. " Model Found.")
local stack = {}
local gameOver = false
local iteration = 0
print("Beginning new sequence ...")
wait(5)
while gameOver == false do
local clr = pickColor()
stack[iteration] = clr -- Stack on new Color
for index, item in pairs(stack) do
signalColor(item)
wait(1)
end
iteration += 1 -- Adds round finished
end
--player:Kick("Game Over! HighScore: " .. iteration .. "!")
end
-- When player joins, begin sequence.
players.PlayerAdded:connect(function(plr)
initialize(plr) -- Pass player added
end)