← Back to All Parts
🎲
Part 610 min

Mini-Project 3 - Random Player Picker

In Chamber of Secrets, we need to secretly pick one player to be the Parseltongue speaker. Let's learn how to pick random players!

How Random Works in Lua

First, let's understand how to pick random things:

-- Pick a random number between 1 and 10
local randomNumber = math.random(1, 10)
print(randomNumber)

-- Pick a random item from a list
local fruits = {"apple", "banana", "orange", "grape"}
local randomIndex = math.random(1, #fruits)
local randomFruit = fruits[randomIndex]
print("You got: " .. randomFruit)
The # symbol counts how many items are in a list. So #fruits = 4 (there are 4 fruits in our list)

Pick a Random Player Script

Add this Script to ServerScriptService:

-- Random Player Picker
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

-- Store who the chosen one is
local chosenPlayer = Instance.new("StringValue")
chosenPlayer.Name = "ParseltonguePlayer"
chosenPlayer.Value = ""
chosenPlayer.Parent = ReplicatedStorage

local function pickRandomPlayer()
    local allPlayers = Players:GetPlayers()

    -- Need at least 2 players!
    if #allPlayers < 2 then
        print("Need more players!")
        return nil
    end

    -- Pick randomly
    local randomIndex = math.random(1, #allPlayers)
    local chosen = allPlayers[randomIndex]

    chosenPlayer.Value = chosen.Name
    print("The secret Parseltongue speaker is: " .. chosen.Name)
    return chosen
end

-- Wait for players to join, then pick
wait(10)
pickRandomPlayer()

Tell Only the Chosen Player

This is the SECRET part! We need to show a message only to the chosen player. Add a LocalScript to StarterGui:

-- Secret Message (LocalScript in StarterGui)
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local player = Players.LocalPlayer

local chosenPlayer = ReplicatedStorage:WaitForChild("ParseltonguePlayer")

chosenPlayer.Changed:Connect(function(newName)
    if newName == player.Name then
        -- This player is the Parseltongue!
        -- Create a secret message
        local gui = Instance.new("ScreenGui")
        gui.Parent = player.PlayerGui

        local label = Instance.new("TextLabel")
        label.Size = UDim2.new(0.5, 0, 0.2, 0)
        label.Position = UDim2.new(0.25, 0, 0.4, 0)
        label.Text = "🐍 YOU are the Parseltongue speaker! 🐍"
        label.TextScaled = true
        label.BackgroundColor3 = Color3.fromRGB(26, 71, 42)
        label.TextColor3 = Color3.fromRGB(212, 175, 55)
        label.Parent = gui

        wait(3)
        gui:Destroy()
    end
end)

The Magic Part!

LocalScripts only run on ONE player's computer. So when we check "if newName == player.Name", only the chosen player's screen shows the message! Everyone else's screen shows nothing!

✅ Checklist - Check them off!

Random selection! The game secretly picks someone and only THEY know!