Menu
CoddyTech

반려동물을 구하세요

Coddy의 Roblox 게임: 펫 시뮬레이터 코스 레슨. 18개 중 18번째.

코인, Desert, 그리고 모든 펫은 플레이어가 다음에 접속할 때도 그대로 남아 있어야 합니다. DataStore는 플레이어마다 UserId를 기준으로 테이블을 저장합니다. 펫은 인스턴스이므로 DataStore에 저장할 수 없습니다. 따라서 각 펫의 이름과 장착 여부를 일반 테이블에 저장하고, 접속할 때 이를 바탕으로 펫을 다시 생성하세요:

{ Coins = 120, Desert = true, Pets = { { Name = "Fox", Equipped = true } } }

플레이어가 나갈 때(PlayerRemoving)와 서버가 종료될 때(game:BindToClose) 저장하고, PlayerAdded에서 불러오세요. 두 호출 모두 Roblox 측에서 실패할 수 있으므로 pcall로 감싸세요. Roblox Studio에서는 장소를 게시하고 Enable Studio Access to API Services를 켜면 DataStore를 사용할 수 있습니다.

challenge icon

챌린지

어려움
  1. DataStoreService를 가져오고 Pets라는 DataStore를 만듭니다.
  2. save(player)를 작성합니다. 모든 펫에 대해 Coins, Desert 및 { Name, Equipped } 목록을 플레이어의 UserId를 키로 하여 pcall 안에서 저장합니다. PlayerRemoving에서 그리고 game:BindToClose에서 각 플레이어에 대해 이 함수를 호출합니다.
  3. PlayerAdded에서 폴더를 만든 다음 저장된 데이터를 불러와(pcall 안에서) 코인, Desert 특성 및 펫을 복원합니다(petInfo에 없는 이름은 건너뜁니다).

Play를 누르고, 알을 부화시킨 다음, Stop을 누르고 다시 Play를 누릅니다. 펫이 돌아와 있습니다. 그런 다음 Check를 누릅니다.

직접 해보기

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

local remotes = game.ReplicatedStorage.Remotes
local piles = workspace.Piles
local petParts = workspace.PetParts
local pileSpot = {} -- 각 pile -> 그 pile이 놓인 spot
local lastHit = {} -- 각 player -> 마지막으로 때린 시각

print("A Meadow pile gives " .. Settings.PileValue .. " coins")

-- 이름별로 정리한 Settings.Pets
local petInfo = {}
for _, info in Settings.Pets do
	petInfo[info.Name] = info
end

-- 펫: 플레이어의 Pets 폴더에 있는 StringValue로, 펫의 이름을 담고 있으며
-- 희귀도와 힘은 속성으로 저장됨
local function givePet(player, name, equipped)
	local info = petInfo[name]
	local pet = Instance.new("StringValue")
	pet.Name = "Pet"
	pet.Value = name
	pet:SetAttribute("Rarity", info.Rarity)
	pet:SetAttribute("Power", info.Power)
	pet:SetAttribute("Equipped", equipped)
	pet.Parent = player.Pets
	return pet
end

-- 플레이어가 꺼내 놓은 펫의 수
local function equippedCount(player)
	local count = 0
	for _, pet in player.Pets:GetChildren() do
		if pet:GetAttribute("Equipped") then
			count += 1
		end
	end
	return count
end

-- 플레이어의 펫이 타격마다 추가하는 힘
local function petPower(player)
	local power = 0
	for _, pet in player.Pets:GetChildren() do
		if pet:GetAttribute("Equipped") then
			power += pet:GetAttribute("Power")
		end
	end
	return power
end

-- 모든 플레이어는 리더보드에 Coins를 받음
Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player

	local coins = Instance.new("IntValue")
	coins.Name = "Coins"
	coins.Parent = leaderstats

	-- 플레이어가 소유한 펫
	local pets = Instance.new("Folder")
	pets.Name = "Pets"
	pets.Parent = player
end)

-- spot에 놓인 코인 더미: ServerStorage.CoinPile의 복사본으로, 체력
-- 과 가치를 속성으로 저장함
local function spawnPile(spot)
	local desert = spot.Parent.Parent.Name == "Desert"
	local health = desert and Settings.DesertHealth or Settings.PileHealth
	local pile = ServerStorage.CoinPile:Clone()
	pile.Position = spot.Position
	pile:SetAttribute("MaxHealth", health)
	pile:SetAttribute("Health", health)
	pile:SetAttribute("Value", desert and Settings.DesertValue or Settings.PileValue)
	pile:SetAttribute("Zone", spot.Parent.Parent.Name)
	pile.HealthGui.Label.Text = pile:GetAttribute("Health") .. "/" .. pile:GetAttribute("MaxHealth")
	pileSpot[pile] = spot
	pile.Parent = piles
	return pile
end

-- 한 번 때리면 더미의 체력이 1에 플레이어 펫의 힘을 더한 만큼 줄어듦;
-- 0이 되면 더미가 부서지고 그 가치만큼 코인을 지급한다
local function hitPile(player, pile)
	local health = pile:GetAttribute("Health") - (1 + petPower(player))
	if health > 0 then
		pile:SetAttribute("Health", health)
		pile.HealthGui.Label.Text = health .. "/" .. pile:GetAttribute("MaxHealth")
		return
	end
	player.leaderstats.Coins.Value += pile:GetAttribute("Value")
	local spot = pileSpot[pile]
	pileSpot[pile] = nil
	pile:Destroy()
	-- 몇 초 후 같은 자리에 새로운 더미가 생긴다
	task.delay(Settings.RespawnTime, spawnPile, spot)
end

-- 모든 구역의 모든 지점에 더미를 하나씩 생성한다
for _, zone in workspace.Zones:GetChildren() do
	for _, spot in zone.Spawns:GetChildren() do
		spawnPile(spot)
	end
end

-- 클라이언트가 더미를 치겠다고 요청한다. 클라이언트를 절대 신뢰하지 말 것: 누구나
-- 어디서든 어떤 값으로든 원하는 만큼 빠르게 이 원격 이벤트를 호출할 수 있다.
remotes.Hit.OnServerEvent:Connect(function(player, pile)
	-- 실제 더미인지
	if typeof(pile) ~= "Instance" or pile.Parent ~= piles then
		return
	end
	-- 사정거리 안인지
	local character = player.Character
	local root = character and character:FindFirstChild("HumanoidRootPart")
	if not root or (root.Position - pile.Position).Magnitude > Settings.Reach then
		return
	end
	-- 너무 빠르지 않은지
	local now = time()
	if lastHit[player] and now - lastHit[player] < Settings.HitCooldown then
		return
	end
	lastHit[player] = now
	-- 플레이어가 개방한 구역에 있는지
	if pile:GetAttribute("Zone") == "Desert" and not player:GetAttribute("Desert") then
		return
	end
	hitPile(player, pile)
end)

-- 가중치 추첨: 각 펫의 Chance(100을 기준으로 한 값)가 전체에서 차지하는 몫이다
local function rollPet()
	local roll = math.random() * 100
	for _, info in Settings.Pets do
		roll -= info.Chance
		if roll <= 0 then
			return info.Name
		end
	end
	return Settings.Pets[1].Name
end

-- 부화: 알의 프롬프트를 통해 코인을 지불한다
workspace.Egg.ProximityPrompt.Triggered:Connect(function(player)
	local coins = player.leaderstats.Coins
	if coins.Value < Settings.EggPrice then
		return
	end
	coins.Value -= Settings.EggPrice
	local name = rollPet()
	-- 자리가 있으면 즉시 꺼내 놓는다
	local pet = givePet(player, name, equippedCount(player) < Settings.MaxEquipped)
	print(player.Name .. " hatched a " .. name)
	-- 가장 희귀한 펫에 대한 소식이 모두에게 전해진다
	if pet:GetAttribute("Rarity") == "Legendary" then
		remotes.Announce:FireAllClients(player.Name, name)
	end
end)

-- 밖에 나온 펫은 주인을 따라간다. 각 펫에는 게임 월드에 해당 파트가 있으며,
-- 매 프레임 플레이어 뒤에 한 줄로 배치된다
local petModels = {} -- 각 펫 -> 게임 월드에서 해당 펫의 파트
RunService.Heartbeat:Connect(function()
	for _, player in Players:GetPlayers() do
		local root = player.Character and player.Character:FindFirstChild("HumanoidRootPart")
		local pets = player:FindFirstChild("Pets")
		local slot = 0
		for _, pet in pets and pets:GetChildren() or {} do
			local model = petModels[pet]
			if pet:GetAttribute("Equipped") and root then
				slot += 1
				if not model then
					model = ServerStorage.PetModels[pet.Value]:Clone()
					model.Parent = petParts
					petModels[pet] = model
				end
				model.CFrame = root.CFrame * CFrame.new((slot - 2) * 3, -1.5, 4)
			elseif model then
				model:Destroy()
				petModels[pet] = nil
			end
		end
	end
end)

-- 클라이언트가 펫을 꺼내거나 들여보내도록 요청한다. 서버는 해당 펫이
-- 플레이어 자신의 것이며, 꺼낸 펫의 수가 MaxEquipped를 넘지 않는지 확인한다.
remotes.Equip.OnServerEvent:Connect(function(player, pet)
	if typeof(pet) ~= "Instance" or pet.Parent ~= player.Pets then
		return
	end
	if pet:GetAttribute("Equipped") then
		pet:SetAttribute("Equipped", false)
	elseif equippedCount(player) < Settings.MaxEquipped then
		pet:SetAttribute("Equipped", true)
	end
end)

-- Desert 게이트: 한 번 비용을 내면 해당 플레이어에게만 열린다
workspace.Gate.ProximityPrompt.Triggered:Connect(function(player)
	local coins = player.leaderstats.Coins
	if player:GetAttribute("Desert") or coins.Value < Settings.GatePrice then
		return
	end
	coins.Value -= Settings.GatePrice
	player:SetAttribute("Desert", true)
end)
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Roblox 게임: 펫 시뮬레이터의 모든 레슨