Menu
CoddyTech

Новости о редких питомцах

Урок 17 из 18 курса Игра в Roblox: симулятор питомцев на Coddy.

Когда кто-то вылупляет легендарного питомца, об этом должен узнать весь сервер. FireAllClients одновременно запускает RemoteEvent на клиенте каждого игрока:

-- сервер
remotes.Announce:FireAllClients(player.Name, name)
-- клиент
remotes.Announce.OnClientEvent:Connect(function(who, pet)
end)

Каждый клиент на несколько секунд показывает новость на Banner в своём HUD. OnClientEvent получает именно то, что отправил сервер: игрок с этой стороны не добавляется.

challenge icon

Задание

Сложно
  1. В PetServer после вылупления, если редкость питомца — Legendary, отправь remotes.Announce всем клиентам с именем игрока и именем питомца.
  2. В PetClient при событии remotes.Announce.OnClientEvent задай текст Banner: Player1 hatched a Dragon!, покажи его, подожди 4 секунды и скрой.

Нажми Play, затем Check: проверки заставят вылупиться Dragon.

Попробуйте сами

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 = {} -- каждая куча -> место, на котором она стоит
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

-- Питомец: StringValue в папке Pets игрока, содержащий его имя, а также
-- редкость и силу в виде атрибутов
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)

-- Куча монет на месте: копия 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)
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: симулятор питомцев