Menu
CoddyTech

A Random Tower

Lesson 3 of 18 in Coddy's Roblox Game: Endless Tower course.

A tower of the same stage five times is no fun. ServerStorage.Stages holds seven kinds: Steps, KillBricks, Conveyor, VanishingSteps, Bounce, Spinner and Lasers. Pick one at random for each floor:

local all = stages:GetChildren()
local stage = all[math.random(1, #all)]

math.random(1, #all) is a whole number from 1 to the number of stages, so every stage has the same chance. Most of them do nothing yet: their spinners, belts and lasers come to life in the next chapter.

On top of the last stage goes ServerStorage.Finish, a gold pad where the climb ends. stack already lifts any Model, so it lifts the Finish too.

challenge icon

Challenge

Easy
  1. Write pickStage(): return a random child of stages.
  2. In buildTower, stack pickStage() instead of stages.Steps.
  3. After the loop, stack ServerStorage.Finish on the top.

Press Play a few times: each tower is different. Then Check.

Try it yourself

local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local Settings = require(game.ReplicatedStorage.Settings)

local stages = ServerStorage.Stages
local tower = nil

print("Each tower has " .. Settings.StageCount .. " stages")

-- Every player gets Wins on the leaderboard
Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player

	local wins = Instance.new("IntValue")
	wins.Name = "Wins"
	wins.Parent = leaderstats
end)

-- Put a copy of a model on top of the tower; returns the copy and the new top
local function stack(template, bottom)
	local copy = template:Clone()
	local box, size = copy:GetBoundingBox()
	local lift = bottom - (box.Position.Y - size.Y / 2)
	copy:PivotTo(copy:GetPivot() + Vector3.new(0, lift, 0))
	copy.Parent = tower
	return copy, bottom + size.Y
end

-- Build a tower of the Steps stage
local function buildTower()
	tower = Instance.new("Model")
	tower.Name = "Tower"
	tower.Parent = workspace
	local top = 0
	for i = 1, Settings.StageCount do
		local stage, newTop = stack(stages.Steps, top)
		top = newTop
	end
end

buildTower()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Roblox Game: Endless Tower