Map Voting Script not Working

I have a map voting script here. This is the server side code:



local maps = ReplicatedStorage:WaitForChild("Maps")

local NumberOfMapOptions = 3
local intermissionTime = 5
local voteTime = 10

local plrVotes = {}

function addVote(plr, mapName)
	plrVotes[plr.UserId] = mapName
	ReplicatedStorage:WaitForChild("Voted"):FireAllClients(plrVotes)
end

function removePlayerVote(plr)
	plrVotes[plr.UserId] = nil
	ReplicatedStorage:WaitForChild("Voted"):FireAllClients(plrVotes)
end

function loadMap(mapName)
	local mapmodels = maps:GetChildren()
	local Map = {}
	for i = 1, #mapmodels do
		if mapmodels[i]:FindFirstChild("MapInfo") and mapmodels[i].MapInfo:FindFirstChild("MapName") and mapmodels[i].MapInfo.MapName.Value == mapName then
			table.insert(Map, mapmodels[i])
		end
	end
	if #Map == 0 then
		warn("No map found with name: " .. tostring(mapName))
		return nil
	end
	local newMap = Map[1]:Clone()
	newMap.Parent = Workspace
	return newMap
end

function removeMap(map)
	if map and map.Parent then
		map:Destroy()
	end
	local playerList = Players:GetPlayers()
	for i = 1, #playerList do
		local plr = playerList[i]
		plr:LoadCharacter()
	end
end

ReplicatedStorage:WaitForChild("Voted").OnServerEvent:Connect(function(plr, mapName)
	addVote(plr, mapName)
end)
Players.PlayerRemoving:Connect(function(plr)
	removePlayerVote(plr)
end)

function MapVote()
	local mapsToVote = maps:GetChildren()
	while #mapsToVote > NumberOfMapOptions do
		table.remove(mapsToVote, math.random(1, #mapsToVote))
	end
	ReplicatedStorage:WaitForChild("VotingBegun"):FireAllClients(mapsToVote)
	task.wait(18)
	plrVotes = {}

	ReplicatedStorage:WaitForChild("MapVoteTimer"):FireAllClients("")

	if script:FindFirstChild("Sounds") and script.Sounds:FindFirstChild("MapVote") then
		script.Sounds.MapVote:Play()
	end

	task.wait(voteTime)

	for i = 1, 10 do
		ReplicatedStorage:WaitForChild("MapVoteTimer"):FireAllClients(11 - i)
		if script:FindFirstChild("Sounds") and script.Sounds:FindFirstChild("MapVoteTimer") then
			script.Sounds.MapVoteTimer:Play()
		end
		task.wait(1)
	end

	ReplicatedStorage:WaitForChild("MapVoteTimer"):FireAllClients("")

	if script:FindFirstChild("Sounds") and script.Sounds:FindFirstChild("MapVote") then
		script.Sounds.MapVote:Stop()
	end

	local highestVotedFor = nil
	local votes = {}
	for i = 1, #mapsToVote do
		local map = mapsToVote[i]
		votes[map.Name] = 0
		if i == 1 then
			highestVotedFor = map.Name
		end
	end

	for userId, vote in pairs(plrVotes) do
		if votes[vote] ~= nil then
			votes[vote] = votes[vote] + 1
			if votes[highestVotedFor] < votes[vote] then
				highestVotedFor = vote
			end
		end
	end

	ReplicatedStorage:WaitForChild("VotingEnded"):FireAllClients()

	local newMap = loadMap(highestVotedFor)
	return newMap
end
local currentMap = nil

And this is the client code


local rs = game.ReplicatedStorage
local frame = script.Parent
frame.Visible = false

-- Get the template frame for map options
local templateFrame = script:FindFirstChild("MapFrame")


local function getRandomUniqueMaps(maps, count)
    local selected = {}
    local used = {}
    local total = #maps
    if total == 0 then return selected end
    if total >= count then
        while #selected < count do
            local idx = math.random(1, total)
            if not used[idx] then
                table.insert(selected, maps[idx])
                used[idx] = true
            end
        end
    else
        for i = 1, total do
            table.insert(selected, maps[i])
        end
        while #selected < count do
            local idx = math.random(1, total)
            table.insert(selected, maps[idx])
        end
    end
    return selected
end

local votingBegunEvent = rs:FindFirstChild("VotingBegun")
if votingBegunEvent then
    votingBegunEvent.OnClientEvent:Connect(function(mapsToVote)
        task.wait(3)
        frame.Visible = true
        if frame:FindFirstChild("Vote for a map") then
            frame["Vote for a map"].Visible = false
        end
        task.wait(5)
        if frame:FindFirstChild("Vote for a map") then
            frame["Vote for a map"].Visible = true
        end
        local mapOptions = frame:FindFirstChild("MapOptions")
        if mapOptions and templateFrame then
            local children = mapOptions:GetChildren()
            for i = 1, #children do
                local child = children[i]
                if child.ClassName == templateFrame.ClassName then
                    child:Destroy()
                end
            end
            local mapFrames = {}
            local mapsToDisplay = getRandomUniqueMaps(mapsToVote, 3)
            for i = 1, #mapsToDisplay do
                local map = mapsToDisplay[i]
                local newMapFrame = templateFrame:Clone()
                newMapFrame.Name = map.MapInfo.MapName.Value
                newMapFrame.MapName.Text = map.MapInfo.MapName.Value
                newMapFrame.NumVotes.Text = "0"
                newMapFrame.MapImage.Image = "rbxassetid://" .. map.MapInfo.ImageId.Value

                newMapFrame.VoteButton.MouseButton1Click:Connect(function()
                    local votedEvent = rs:FindFirstChild("Voted")
                    if votedEvent then
                        votedEvent:FireServer(map.Name)
                    end
                end)
                table.insert(mapFrames, newMapFrame)
            end
            table.sort(mapFrames, function(a, b)
                return a.Name < b.Name
            end)
            for i = 1, #mapFrames do
                mapFrames[i].Parent = mapOptions
            end
        end
    end)
end

local votingEndedEvent = rs:FindFirstChild("VotingEnded")
if votingEndedEvent then
    votingEndedEvent.OnClientEvent:Connect(function()
        local mapOptions = frame:FindFirstChild("MapOptions")
        if mapOptions then
            local MapFrames = mapOptions:GetChildren()
            for i = 1, #MapFrames do
                MapFrames[i]:Destroy()
            end
        end
        task.wait(5)
        frame.Visible = false
    end)
end

local votedEvent = rs:FindFirstChild("Voted")
if votedEvent then
    votedEvent.OnClientEvent:Connect(function(plrVotes)
        if frame.Visible == true then
            local votes = {}
            for plr, vote in plrVotes do
                if not votes[vote] then
                    votes[vote] = 1
                else
                    votes[vote] = votes[vote] + 1
                    if script:FindFirstChild("Sound") then
                        script.Sound:Play()
                    end
                end
            end
            local mapOptions = frame:FindFirstChild("MapOptions")
            if mapOptions and templateFrame then
                local children = mapOptions:GetChildren()
                for i = 1, #children do
                    local mapFrame = children[i]
                    if mapFrame.ClassName == templateFrame.ClassName then
                        mapFrame.NumVotes.Text = tostring(votes[mapFrame.Name] or 0)
                    end
                end
            end
        end
    end)
end

local mapVoteTimerEvent = rs:FindFirstChild("MapVoteTimer")
if mapVoteTimerEvent then
    mapVoteTimerEvent.OnClientEvent:Connect(function(text)
        if frame:FindFirstChild("Timer") then
            frame.Timer.Text = text
        end
    end)
end


The problem I am facing is that on the next time the code runs, there is only one map option to vote for, even though there were three to begin with, which is the normal amount.

Where is the bug being caused and how could it be fixed? I could really use some help. Thanks!

There are a lot of things I don’t understand about this setup. Why does the getRandomUniqueMaps function even need to exist if the server is hardcoded to send an array of 3 map options to the clients, and the client script is hardcoded to display 3 options. I can’t really think of a case in a map voting system where you’d want each client to randomly pick a different subset of options to show either. Normally, you want all players to have the same options, which is not what your code would do if you sent the clients more than 3 maps, because you use math.random() without sending a seed from the server.

I don’t understand why your UI is creating and destroying these mapFrame entries from a template either. Just create the number you need at the start and re-use them. Destroying and recreating in response to remote events is unnecessary and possibly contributes to your problem as it makes the system more complicated than it needs to be.

It looks like your client script enables the voting buttons about 8 seconds after receiving the VotingBegun event. But then, about 10 seconds later, after the task.wait(18), the server clears out the plrVotes, throwing away any votes that happened in those first 10 seconds of voting? I don’t get what’s going on here.

Then there is this:

Player internet connections can have a considerable ping time, and unstable connection speed. This code is in no way guaranteed to display a timer on any client that ticks down once per second. Timers should be done with the client clock, using tick() or os.time(), or at least have the wait(1) loop in a client code coroutine. The remote events are not going to arrive and get processed exactly 1 second apart, so the clock will be wonky. Trigger the clock sound on the client too, in sync with the number change. As you have it, the sound is playing via server-to-client replication, so it’s not going to tick in time with the text label change of the seconds remaining. You won’t see any of this testing in Studio, but when you publish to a live game, the problems will be obvious.

I recommend having the server send the timestamp for when voting ends (with the VotingBegun event), and have the client code use Workspace:GetServerTimeNow() to calculate time remaining. Have a grace period of at least a few seconds on the server to make sure that any player who voted before they saw the clock hit 0 actually has their vote counted. It feels bad otherwise.

Use a UIListLayout or UIGridLayout to arrange frames in alphabetical order. The order you parent things to a container does not guarantee display order, so there’s no point in sorting the array.

You probably don’t understand it because I previously tried to use the AI assistant to try and solve the issue. A lot of the time it has helped out, but this issue was something it couldn’t resolve. Thanks for the info

Also, in regards to this, the reason I had that is because I had a tip that was displayed on screen before the voting began.

I managed to resolve the issue I was facing.