I’ve implemented some of this functionality into the explanation below. If you want the voting system to be easier to manage, store the votes in an object-oriented system where each pad represents a voteCasting
object and players can cast their votes to that object. You can then add up the votes for each object to see which one has the most.
Double-casted votes are accounted for on player-join, and they are validated with the userCanDoubleVote
function.
local playersService = game:GetService('Players')
local marketplaceService = game:GetService('MarketplaceService')
local playersWithDoubleVote = {}
playersService.PlayerAdded:Connect(function(player: Player)
local userOwnsGamepass = select(2, pcall(marketplaceService.UserOwnsGamePassAsync, marketplaceService, player.UserId, 166803693))
if userOwnsGamepass == true then
table.insert(playersWithDoubleVote, player.UserId)
end
end)
local function userCanDoubleVote(player: Player)
return table.find(playersWithDoubleVote, player.UserId) and true or false
end
local voteCasting = {}
function voteCasting.new()
local self = {}
local votesCasted = {}
function self:CastVote(player: Player)
if not votesCasted[player.UserId] then
votesCasted[player.UserId] = userCanDoubleVote(player) and 2 or 1
end
end
function self:RevokeVote(player: Player)
if votesCasted[player.UserId] then
votesCasted[player.UserId] = nil
end
end
function self:GatherVotes()
local totalVotes = 0
for _, votes in pairs(votesCasted) do
totalVotes = totalVotes + votes
end
return totalVotes
end
function self:ClearVotes()
votesCasted = {}
end
return self
end
Now I’ll show you how you can use this code. I generated the next block of code with ChatGPT to provide you this example, I believe it is an okay example.
-- Create three different voting instances
local voteOne = voteCasting.new()
local voteTwo = voteCasting.new()
local voteThree = voteCasting.new()
-- Players cast different numbers of votes for each instance
voteOne:CastVote(player1)
voteOne:CastVote(player2)
voteTwo:CastVote(player3)
voteTwo:CastVote(player4)
voteTwo:CastVote(player5)
voteThree:CastVote(player6)
voteThree:CastVote(player7)
voteThree:CastVote(player8)
voteThree:CastVote(player9)
-- Gather and print the total votes for each voting instance
local totalVotesOne = voteOne:GatherVotes() -- Total votes for VoteOne: 2
local totalVotesTwo = voteTwo:GatherVotes() -- Total votes for VoteTwo: 3
local totalVotesThree = voteThree:GatherVotes() -- Total votes for VoteThree: 4
I made a post thanks to you and to my motivation to make something useful, you can find it here.