--Server Script
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Red = require(ReplicatedStorage.Modules.Red)
local OnClickVote = Red.Server("OnClickVote")
print(PreviousVote)
if PreviousVote then
print("Player Has Previous vote")
Mapvotes[PreviousVote] -= 1
Mapvotes[NumericValue] += 1
else
print("Player never voted before ")
PlayerVotes[UserId] = NumericValue
print(PlayerVotes)
Mapvotes[PlayerVotes[UserId]] += 1
end
print(Mapvotes)
end)
--Module--
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Player = game.Players.LocalPlayer
local PlayerGUI = Player.PlayerGui
local Red = require(ReplicatedStorage.Modules.Red)
local OnClickVote = Red.Client("OnClickVote")
local Local = {}
local Shared = {}
local LiveConnections = {}
function Local:InitiateUI(MapName, MapNumber)
local Connection
if not PlayerGUI.Mapvote.Enabled then
PlayerGUI.Mapvote.Enabled = true
end
function Shared:ChangeVote()
OnClickVote:On("OnClickVote", function(Vote)
print(Vote)
end)
end
function Shared:ResetConnections()
for i, Connection in pairs(LiveConnections) do
Connection:Disconnect()
Connection = nil
end
table.clear(LiveConnections)
end
return Local
what do you think of this code I wrote for my roblox game's map voting system? im trying to handle whenever a player clicks on another map it remove their vote that they put on the previous vote
Assistant
Of course! This is a great start for a map voting system. You've correctly identified the core logic needed: storing each player's vote to ensure they can only vote once and can change their vote.
Let's break down the code, identify some key areas for improvement, and then look at a revised version.
Overall Impression
You have a solid foundation. The use of a module like "Red" for networking is a good, modern practice. The general structure of a server script for logic and a client script for UI is correct. The main issues are a critical logic bug, a major security vulnerability, and some areas where the code could be clearer.
Server Script Analysis
The Good:
Separation of Concerns: You're correctly handling the voting logic on the server, which is essential for security and authority.
Using UserID: Using player.UserId as a key in PlayerVotes is the right way to track votes. It's persistent and unique to the player.
Areas for Improvement:
Critical Logic Bug: When a player changes their vote, you don't update their new vote in the PlayerVotes table.
Trace the bug:
Player votes for Map 1. PlayerVotes[UserId] becomes 1. Mapvotes[1] becomes 1.
Player then votes for Map 2. The if PreviousVote then block runs. PreviousVote is 1.
Mapvotes[PreviousVote] (which is Mapvotes[1]) is decremented. Correct.
Mapvotes[NumericValue] (which is Mapvotes[2]) is incremented. Correct.
The problem:PlayerVotes[UserId] is never changed from 1 to 2.
If the player votes again for Map 3, PreviousVote will still be 1, and it will try to decrement Mapvotes[1] again, leading to incorrect counts.
Major Security Vulnerability (Trusting the Client):
You are sending an Instance (currentvote) from the client to the server. You should never trust the client with Instances or complex data. An exploiter could easily fire this remote event with a different instance, a fake one, or , which could cause your server script to error.
nil
The client should only send the minimal, necessary information. In this case, that's just the number of the map they are voting for (e.g., 1, 2, or 3).
Code Clarity:
Mapvotes[1] = math.min(0) is an unusual way to write Mapvotes[1] = 0. It works, but it's less readable.
In the else block, Mapvotes[PlayerVotes[UserId]] += 1 is also a bit redundant. You just set PlayerVotes[UserId], so you could use the new value directly.
Module/Client Script Analysis
The Good:
Connection Management: The ResetConnections function is excellent! Disconnecting events when they are no longer needed is crucial for preventing memory leaks.
Modular UI Setup: The InitiateUI function is a clean way to set up each map panel.
Areas for Improvement:
Sending Unnecessary Data:
In OnClickVote:Fire("OnClickVote", 1, MapUI), you're hardcoding the number 1 and also sending the MapUI instance. As discussed, you should only send the MapNumber.
Misunderstanding of Client/Server Events:
The Shared:ChangeVote function tries to listen to the same event that the client is firing (OnClickVote:On("OnClickVote", ...)). A client cannot listen to an event it is firing to the server. This function will never run.
If you want the server to send information back to the client (like updating vote counts for everyone), you need a separate remote event that the server fires and the clients listen to.
Revised and Improved Code
Here is how you could rewrite your scripts to be more secure, robust, and correct.
Server Script (Revised)
--Server Script
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local Red = require(ReplicatedStorage.Modules.Red)
-- Create two-way communication: one for client->server, one for server->client
local VoteHandler = Red.Server("VoteHandler")
-- Table to store vote counts for each map. Maps are identified by a number.
local mapVotes = {
[1] = 0,
[2] = 0,
[3] = 0,
}
-- Table to store which map each player has voted for. { [UserId] = MapNumber }
local playerVotes = {}
-- Function to update all clients with the latest vote counts
local function broadcastVoteCounts()
VoteHandler:FireAll("UpdateVoteCounts", mapVotes)
end
-- Listen for a player casting a vote
VoteHandler:On("CastVote", function(player, mapNumberVotedFor)
-- 1. VALIDATE THE INPUT
-- Ensure the mapNumber is a valid number and corresponds to a real map.
if type(mapNumberVotedFor) ~= "number" or not mapVotes[mapNumberVotedFor] then
warn("Player", player.Name, "sent an invalid vote:", mapNumberVotedFor)
return -- Stop execution if the data is bad
end
local userId = player.UserId
local previousVote = playerVotes[userId]
-- If the player is changing their vote to the same map, do nothing.
if previousVote == mapNumberVotedFor then
return
end
-- 2. UPDATE VOTE COUNTS
-- If the player has voted before, remove their previous vote
if previousVote then
mapVotes[previousVote] -= 1
end
-- Add the new vote
mapVotes[mapNumberVotedFor] += 1
-- 3. UPDATE THE PLAYER'S VOTE RECORD
-- This was the missing step in your original code!
playerVotes[userId] = mapNumberVotedFor
-- 4. BROADCAST CHANGES
-- Let all clients know the vote counts have changed so they can update their UI
broadcastVoteCounts()
print(player.Name, "voted for map", mapNumberVotedFor, ". Current votes:", mapVotes)
end)
-- Handle players leaving
Players.PlayerRemoving:Connect(function(player)
local userId = player.UserId
local playerVote = playerVotes[userId]
if playerVote then
-- Remove the player's vote from the counts
mapVotes[playerVote] -= 1
-- Remove the player's record
playerVotes[userId] = nil
-- Update everyone
broadcastVoteCounts()
end
end)
Module/Client Script (Revised)
--Module Script (Should be a LocalScript or required by one)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Player = game.Players.LocalPlayer
local PlayerGUI = Player.PlayerGui
local Red = require(ReplicatedStorage.Modules.Red)
-- Use the same event name as the server
local VoteHandler = Red.Client("VoteHandler")
local Local = {}
local LiveConnections = {}
-- Function to set up a single map voting UI element
function Local:InitiateUI(mapInfo, mapNumber)
-- mapInfo would be a table like { Name = "Factory", ImageId = "rbxassetid://..." }
if not PlayerGUI.Mapvote.Enabled then
PlayerGUI.Mapvote.Enabled = true
end
local mapUI = PlayerGUI.Mapvote:FindFirstChild("Map"..mapNumber)
if not mapUI then return end -- Guard clause
mapUI.Visible = true
mapUI.MapImage.Image = mapInfo.ImageId
mapUI.MapName.Text = mapInfo.Name
-- When the map is clicked, fire the simple map number to the server
local connection = mapUI.MapImage.MouseButton1Click:Connect(function()
print("Client firing vote for map:", mapNumber)
VoteHandler:Fire("CastVote", mapNumber)
-- Optional: Give immediate visual feedback by highlighting the selected frame
for i = 1, 3 do
local frame = PlayerGUI.Mapvote:FindFirstChild("Map"..i)
if frame then
-- Example: change border color to show selection
frame.UIStroke.Color = Color3.new(1, 1, 1) -- White (not selected)
end
end
mapUI.UIStroke.Color = Color3.new(0, 1, 0) -- Green (selected)
end)
table.insert(LiveConnections, connection)
end
-- This function now correctly listens for updates FROM the server
function Local:ListenForVoteUpdates()
VoteHandler:On("UpdateVoteCounts", function(voteCounts)
-- voteCounts will be a table like { [1] = 5, [2] = 2, [3] = 10 }
print("Client received vote counts:", voteCounts)
-- Update the vote count text on each map UI
for mapNumber, count in pairs(voteCounts) do
local mapUI = PlayerGUI.Mapvote:FindFirstChild("Map"..mapNumber)
if mapUI and mapUI:FindFirstChild("VoteCount") then
mapUI.VoteCount.Text = tostring(count) .. " Votes"
end
end
end)
end
function Local:ResetConnections()
for _, connection in ipairs(LiveConnections) do
connection:Disconnect()
end
table.clear(LiveConnections)
end
-- Call this when the voting starts
Local:ListenForVoteUpdates()
return Local
Summary of Changes & Key Takeaways
Security First: The client now only sends a mapNumber, which is a simple piece of data. The server validates this number before using it.
Correct Logic: The server now correctly updates the playerVotes table, ensuring that vote changes are handled properly.
Two-Way Communication: We now use two distinct event names within our VoteHandler "channel":
CastVote: For the client to tell the server it's voting.
UpdateVoteCounts: For the server to tell all clients about the new vote totals.
Robustness: The server code now handles players leaving, and the client code provides immediate visual feedback to the player who voted.
Clarity: Variable names are clearer (mapVotes, playerVotes, mapNumberVotedFor), and the logic is more straightforward.