Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How Can I Make it So That This Sword Fighting Script Selects 2 Random Fighters to Fight?

Asked by
8391ice 91
7 years ago

This simple script I made selects two players from the Players folder and just sends them to a battle script in a module script. But, how can I make it so that the players selected are always random instead of just the first two? This is my script so far.

while wait(10) do
    getPlayers = game.Players:GetChildren()
    local m = require(game.Workspace.Events) --Getting the Module Script

    p1 = getPlayers[1] --HOW CAN I MAKE IT SO THAT THE PLAYERS SELECTED ARE RANDOM? (The question I'm trying to ask)
    p2 = getPlayers[2]
    battle = m.Battle(p1, p2) --Battle will either return 1, 2, or 3 (1 = p1 won, 2 = p2 won, 3 = max time reached)
    if battle == 1 then
        print(p1.. " has won!")
    elseif battle == 2 then
        print(p2.. " has won!")
    else
        print("maximum duel time reached")
    end
end

1 answer

Log in to vote
0
Answered by
cabbler 1942 Moderation Voter
7 years ago

The table of players is a simple list of things, so you don't have to think of it specially. You know that you can get a certain player in the table by indexing with a certain number, ie getPlayers[2]. All you have to do is make that index a random number with a maximum of the number of players. This is easy by just doing math.random(#getPlayers). # tells you the length of the table.

So, getPlayers[math.random(#getPlayers)] will work for you.

Additionally, you also want to remove a selected player from the table so you get different players. It's barely more complicated.

local index

index = math.random(#getPlayers)
p1 = getPlayers[index]
table.remove(getPlayers,index)

index = math.random(#getPlayers)
p2 = getPlayers[index]
table.remove(getPlayers,index)

getPlayers = game.Players:GetPlayers() --do this if you want the original table again
Ad

Answer this question