Menu
CoddyTech

나갈 때 저장하기

Coddy의 Roblox 게임: 끝없는 타워 코스 레슨. 21개 중 20번째.

승리 횟수와 최고 기록은 다음에 돌아왔을 때도 그대로 있어야 합니다. Roblox는 방문 사이에 데이터를 DataStore에 보관합니다. 이는 게임이 종료된 뒤에도 유지되는 Roblox 서버의 테이블입니다. 플레이어가 나갈 때 저장하고, 서버가 종료될 때 계속 플레이 중인 모든 플레이어의 데이터도 저장하세요.

local coinStore = DataStoreService:GetDataStore("Coins")

local function save(player)
	pcall(function()
		coinStore:SetAsync(player.UserId, { Coins = player.leaderstats.Coins.Value })
	end)
end

Players.PlayerRemoving:Connect(save)
game:BindToClose(function()
	for _, player in Players:GetPlayers() do
		save(player)
	end
end)

Roblox 측에서 저장에 실패할 수 있으며, 실패하면 스크립트가 중단될 수 있으므로 pcall 안에 넣습니다. 키는 플레이어의 UserId이며, 플레이어 이름과 달리 절대 바뀌지 않습니다.

challenge icon

챌린지

어려움

각 플레이어가 떠날 때 Wins와 BestTime을 저장하세요.

  1. 위쪽에: local DataStoreService = game:GetService("DataStoreService") 및 local towerStore = DataStoreService:GetDataStore("Tower").
  2. saveProgress(player)를 작성하세요. pcall 안에서 플레이어의 leaderstats 값을 사용해 towerStore:SetAsync(player.UserId, { Wins = ..., BestTime = ... })를 호출하세요.
  3. Players.PlayerRemoving에서 호출하고, game:BindToClose에서는 모든 플레이어에 대해 호출하세요.

‘플레이’를 누르고, 승리한 다음 ‘중지’를 누르세요. 그러면 다음 수업에서 불러올 수 있도록 Wins가 저장됩니다. 그런 다음 ‘확인’을 누르세요.

직접 해보기

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

local stages = ServerStorage.Stages
local lobbySpawn = workspace.Lobby.SpawnLocation
local tower = nil
local towerStages = {}
local lava = nil
local roundStart = 0
local finished = {}

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

-- 모든 플레이어의 리더보드에 Wins, Stage, BestTime이 추가됩니다
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

	local stage = Instance.new("IntValue")
	stage.Name = "Stage"
	stage.Parent = leaderstats

	local best = Instance.new("NumberValue")
	best.Name = "BestTime"
	best.Parent = leaderstats

	-- 떨어진 플레이어는 마지막으로 도달한 스테이지에서 다시 시작합니다.
	-- 단, 용암이 그곳을 덮었다면 로비에서 기다립니다
	player.CharacterAdded:Connect(function(character)
		task.wait()
		local checkpoint = towerStages[stage.Value]
		local covered = checkpoint and lava and checkpoint.Start.Position.Y < lava.Position.Y + lava.Size.Y / 2
		if checkpoint and not covered and not finished[player] then
			character:PivotTo(checkpoint.Start.CFrame + Vector3.new(0, 4, 0))
		end
	end)
end)

-- 로비의 게시판
local gui = Instance.new("SurfaceGui")
gui.Parent = workspace.Lobby.Board

local boardLabel = Instance.new("TextLabel")
boardLabel.Name = "Status"
boardLabel.Size = UDim2.fromScale(1, 1)
boardLabel.BackgroundColor3 = Color3.fromRGB(25, 25, 35)
boardLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
boardLabel.TextScaled = true
boardLabel.Text = "Endless Tower"
boardLabel.Parent = gui

local function setBoard(text)
	boardLabel.Text = text
end

-- Kill 태그가 붙은 것에 닿으면 목숨을 잃습니다
local function killOnTouch(hit)
	local humanoid = hit.Parent:FindFirstChild("Humanoid")
	if humanoid then
		humanoid.Health = 0
	end
end

-- 사라지는 발판은 누군가 착지한 직후 희미해졌다가 다시 나타납니다
local function makeVanish(part)
	part.Touched:Connect(function(hit)
		if part:GetAttribute("Gone") or not hit.Parent:FindFirstChild("Humanoid") then
			return
		end
		part:SetAttribute("Gone", true)
		task.wait(Settings.VanishDelay)
		part.Transparency = 0.8
		part.CanCollide = false
		task.wait(Settings.VanishTime)
		part.Transparency = 0
		part.CanCollide = true
		part:SetAttribute("Gone", nil)
	end)
end

-- 레이저는 Slide 오프셋까지 이동했다가 돌아오기를 무한히 반복합니다
local function makeSlide(part)
	local info = TweenInfo.new(Settings.SlideTime, Enum.EasingStyle.Linear, Enum.EasingDirection.InOut, -1, true)
	local goal = { Position = part.Position + part:GetAttribute("Slide") }
	TweenService:Create(part, info, goal):Play()
end

-- 점프 패드는 착지한 사람을 공중으로 튕겨 올립니다
local function bounce(hit)
	local root = hit.Parent:FindFirstChild("HumanoidRootPart")
	if root then
		root.AssemblyLinearVelocity = Vector3.new(0, Settings.BouncePower, 0)
	end
end

-- 회전 장애물은 매 프레임 조금씩 회전합니다
RunService.Heartbeat:Connect(function(dt)
	for _, spinner in CollectionService:GetTagged("Spinner") do
		if spinner:IsDescendantOf(workspace) then
			spinner:PivotTo(spinner:GetPivot() * CFrame.Angles(0, math.rad(Settings.SpinSpeed) * dt, 0))
		end
	end
end)

-- 태그에 따라 스테이지의 모든 장애물을 활성화합니다
local function setupStage(stage, index)
	for _, part in stage:GetDescendants() do
		if part:HasTag("Kill") then
			part.Touched:Connect(killOnTouch)
		end
		if part:HasTag("Vanish") then
			makeVanish(part)
		end
		if part:HasTag("Conveyor") then
			part.AssemblyLinearVelocity = part.CFrame.LookVector * Settings.BeltSpeed
		end
		if part:HasTag("Slider") then
			makeSlide(part)
		end
		if part:HasTag("Bounce") then
			part.Touched:Connect(bounce)
		end
	end
	-- 스테이지의 Start에 도달하면 리더보드에 반영됩니다
	stage.Start.Touched:Connect(function(hit)
		local player = Players:GetPlayerFromCharacter(hit.Parent)
		if player and player.leaderstats.Stage.Value < index then
			player.leaderstats.Stage.Value = index
		end
	end)
end

-- 위로 갈수록 스테이지가 어려워집니다. 아래쪽 3분의 1은 쉽고, 위쪽 3분의 1은 어렵습니다
local function pickStage(index)
	local difficulty = math.ceil(index / Settings.StageCount * 3)
	local choices = {}
	for _, stage in stages:GetChildren() do
		if stage:GetAttribute("Difficulty") == difficulty then
			table.insert(choices, stage)
		end
	end
	return choices[math.random(1, #choices)]
end

-- 모델의 복사본을 타워 맨 위에 배치하고, 복사본과 새로운 맨 위 높이를 반환합니다
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

-- 타워 정상: 승리한 뒤 로비로 돌아갑니다
local function reachTop(hit)
	local player = Players:GetPlayerFromCharacter(hit.Parent)
	if not player or finished[player] then
		return
	end
	finished[player] = true
	player.leaderstats.Wins.Value += 1
	local seconds = math.floor((time() - roundStart) * 10) / 10
	local best = player.leaderstats.BestTime
	if best.Value == 0 or seconds < best.Value then
		best.Value = seconds
	end
	print(player.Name .. " reached the top in " .. seconds .. " seconds")
	hit.Parent:PivotTo(lobbySpawn.CFrame + Vector3.new(0, 4, 0))
end

-- 아래에서 위로 새로운 무작위 타워를 만듭니다
local function buildTower()
	tower = Instance.new("Model")
	tower.Name = "Tower"
	tower.Parent = workspace
	towerStages = {}
	local top = 0
	for i = 1, Settings.StageCount do
		local stage, newTop = stack(pickStage(i), top)
		top = newTop
		setupStage(stage, i)
		towerStages[i] = stage
	end
	local finish = stack(ServerStorage.Finish, top)
	finish.FinishPad.Touched:Connect(reachTop)
	return top
end

-- 용암이 지면에서 타워 정상 바로 아래까지 차오릅니다
local function startLava(top)
	lava = Instance.new("Part")
	lava.Name = "Lava"
	lava.Anchored = true
	lava.CanCollide = false
	lava.Size = Vector3.new(30, 2, 30)
	lava.Position = Vector3.new(0, -2, 0)
	lava.Color = Color3.fromRGB(255, 90, 20)
	lava.Material = Enum.Material.Neon
	lava.Parent = workspace
	lava.Touched:Connect(killOnTouch)
	local info = TweenInfo.new(top / Settings.LavaSpeed, Enum.EasingStyle.Linear, Enum.EasingDirection.InOut, 0, false, Settings.LavaDelay)
	TweenService:Create(lava, info, { Position = Vector3.new(0, top - 2, 0) }):Play()
end

local function startRound()
	finished = {}
	for _, player in Players:GetPlayers() do
		player.leaderstats.Stage.Value = 0
	end
	local top = buildTower()
	startLava(top)
	roundStart = time()
	for _, player in Players:GetPlayers() do
		if player.Character then
			player.Character:PivotTo(towerStages[1].Start.CFrame + Vector3.new(0, 4, 0))
		end
	end
end

local function endRound()
	for _, player in Players:GetPlayers() do
		if player.Character and not finished[player] then
			player.Character:PivotTo(lobbySpawn.CFrame + Vector3.new(0, 4, 0))
		end
		player.leaderstats.Stage.Value = 0
	end
	tower:Destroy()
	lava:Destroy()
	towerStages = {}
end

-- Lesson 20: Save on Leave가 여기에 들어갑니다

-- 라운드 반복문
while true do
	for i = Settings.Intermission, 1, -1 do
		setBoard("Next tower in " .. i)
		task.wait(1)
	end
	startRound()
	for i = Settings.RoundLength, 1, -1 do
		setBoard("Climb! " .. i .. " seconds left")
		task.wait(1)
	end
	endRound()
end

Roblox 게임: 끝없는 타워의 모든 레슨

직접 연습해 보세요: Roblox 플레이그라운드