Menu
CoddyTech

参加時に読み込み

Coddyの「Robloxゲーム:ペットシミュレーター」コースのレッスン 20/20。

プレイヤーが参加したときに、保存データを読み込みます。GetAsyncは、キーに対してSetAsyncが保存した値を返します。まだ一度も保存したことがないプレイヤーの場合はnilを返します。失敗することもあるため、pcall内で呼び出します。pcallは、成功したかどうかと値を返します。

local ok, saved = pcall(function()
	return saveStore:GetAsync(player.UserId)
end)
if ok and saved then
	print(saved.Coins)
end

フォルダーを作成した後に読み込み、ペットを入れるためのPetsフォルダーがある状態にします。保存されている名前がpetInfoにない場合はスキップします。ゲームから削除されたペットが、プレイヤーの参加を妨げてはいけません。

challenge icon

チャレンジ

難しい

プレイヤーに保存したデータを戻します。

  1. Petsフォルダーを作成した後、PlayerAdded内で、local ok, saved = pcall(function() return saveStore:GetAsync(player.UserId) end)を実行します。
  2. ok and savedの場合、Coinsをsaved.Coinsに設定し、Desert属性をsaved.Desertに設定します。
  3. petInfo内の保存されたペットごとに、givePet(player, pet.Name, pet.Equipped == true)を実行します。

「プレイ」を押して孵化させ、Stopを押してから、もう一度「プレイ」を押します。コインとペットが戻っています。次に「確認」を押します。

自分で試してみよう

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

local remotes = game.ReplicatedStorage.Remotes
local piles = workspace.Piles
local petParts = workspace.PetParts
local saveStore = DataStoreService:GetDataStore("Pets")
local pileSpot = {} -- 各コインの山 -> その山が置かれている場所
local lastHit = {} -- 各プレイヤー -> 最後に攻撃した時刻

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
	-- レッスン20:参加時の読み込みはここに追加する
end)

-- スポット上のコインの山: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回につき、山の体力が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)

-- 保存:Coins、Desert、すべてのペット
local function save(player)
	local pets = {}
	for _, pet in player.Pets:GetChildren() do
		table.insert(pets, { Name = pet.Value, Equipped = pet:GetAttribute("Equipped") == true })
	end
	local data = {
		Coins = player.leaderstats.Coins.Value,
		Desert = player:GetAttribute("Desert") == true,
		Pets = pets,
	}
	pcall(function()
		saveStore:SetAsync(player.UserId, data)
	end)
end

Players.PlayerRemoving:Connect(save)

game:BindToClose(function()
	for _, player in Players:GetPlayers() do
		save(player)
	end
end)
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Robloxゲーム:ペットシミュレーターのすべてのレッスン

自分で練習してみよう: Robloxプレイグラウンド