Menu
CoddyTech

Noticias de mascotas raras

Lección 18 de 20 del curso Juego de Roblox: Simulador de mascotas de Coddy.

Cuando alguien obtiene una mascota legendaria de un huevo, todo el servidor debería enterarse. FireAllClients dispara un RemoteEvent en el cliente de cada jugador al mismo tiempo:

-- servidor
remotes.Announce:FireAllClients(player.Name, name)
-- cliente
remotes.Announce.OnClientEvent:Connect(function(who, pet)
end)

Cada cliente muestra la noticia en el Banner de su HUD durante unos segundos. OnClientEvent recibe exactamente lo que envió el servidor: no se añade ningún jugador en este lado.

challenge icon

Desafío

Difícil

Anuncia las mascotas legendarias a todos.

  1. En PetServer, conserva local pet = givePet(...); si su Rarity es Legendary, remotes.Announce:FireAllClients(player.Name, name).
  2. En PetClient, remotes.Announce.OnClientEvent recibe (who, pet): establece hud.Banner.Text en who .. " hatched a " .. pet .. "!", muéstralo, espera 4 segundos y ocúltalo.

Presiona «Jugar» y eclosiona un huevo: un Dragón, 1 huevo de cada 50, muestra un cartel amarillo en todas las pantallas. Después, «Comprobar».

Pruébalo tú mismo

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 = {} -- cada montón -> el lugar donde se encuentra
local lastHit = {} -- cada jugador -> cuándo golpeó por última vez

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

-- Settings.Pets por nombre
local petInfo = {}
for _, info in Settings.Pets do
	petInfo[info.Name] = info
end

-- Una mascota: un StringValue en la carpeta Pets del jugador que contiene su nombre, con
-- su rareza y poder como atributos
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

-- cuántas mascotas tiene desplegadas un jugador
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

-- lo que las mascotas de un jugador añaden a cada golpe
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

-- Todos los jugadores tienen Coins en la tabla de clasificación
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

	-- las mascotas que poseen
	local pets = Instance.new("Folder")
	pets.Name = "Pets"
	pets.Parent = player
end)

-- Un montón de monedas en un lugar: una copia de ServerStorage.CoinPile con su salud
-- y valor como atributos
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

-- Un golpe resta 1, más el poder de las mascotas del jugador, a la salud de un montón;
-- al llegar a 0, la pila se rompe y entrega su valor
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()
	-- una nueva pila en el mismo lugar, unos segundos después
	task.delay(Settings.RespawnTime, spawnPile, spot)
end

-- Una pila en cada punto de aparición, en cada zona
for _, zone in workspace.Zones:GetChildren() do
	for _, spot in zone.Spawns:GetChildren() do
		spawnPile(spot)
	end
end

-- El cliente solicita golpear una pila. Nunca confíes en el cliente: cualquiera puede activar
-- este evento remoto con cualquier dato, desde cualquier lugar y tan rápido como quiera.
remotes.Hit.OnServerEvent:Connect(function(player, pile)
	-- una pila real
	if typeof(pile) ~= "Instance" or pile.Parent ~= piles then
		return
	end
	-- al alcance
	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
	-- no demasiado rápido
	local now = time()
	if lastHit[player] and now - lastHit[player] < Settings.HitCooldown then
		return
	end
	lastHit[player] = now
	-- en una zona que el jugador ha desbloqueado
	if pile:GetAttribute("Zone") == "Desert" and not player:GetAttribute("Desert") then
		return
	end
	hitPile(player, pile)
end)

-- Una selección ponderada: el valor Chance de cada mascota (sobre 100) es su porción de la escala
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

-- Eclosión: la interacción del huevo, que se paga con monedas
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()
	-- equipada de inmediato, si hay espacio
	local pet = givePet(player, name, equippedCount(player) < Settings.MaxEquipped)
	print(player.Name .. " hatched a " .. name)
end)

-- Las mascotas activas siguen a su dueño: cada una tiene una pieza en el mundo, colocada
-- en fila detrás del jugador en cada fotograma
local petModels = {} -- cada mascota -> su pieza en el mundo
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
				-- al guardar la mascota, su pieza desaparece
				model:Destroy()
				petModels[pet] = nil
			end
		end
	end
end)

-- El cliente solicita sacar o guardar una mascota. El servidor comprueba que la mascota es
-- del propio jugador y que no hay más de MaxEquipped mascotas activas.
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)

-- La puerta de Desert: se paga una vez y se abre solo para ese jugador
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)

Todas las lecciones de Juego de Roblox: Simulador de mascotas

Practica por tu cuenta: Playground de Roblox