Noticias sobre mascotas poco comunes
Lección 17 de 18 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.
Desafío
Difícil- En
PetServer, después de incubar, si la Rarity de la mascota esLegendary, activaremotes.Announcepara todos los clientes con el Name del jugador y el nombre de la mascota. - En
PetClient, enremotes.Announce.OnClientEvent, establece el texto de Banner enPlayer1 hatched a Dragon!, muéstralo, espera 4 segundos y ocúltalo.
Pulsa Jugar y luego Comprobar: las comprobaciones hacen que aparezca un Dragon al incubar.
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 está
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 fuera 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
-- Cada jugador recibe 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 posee
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 lugar de 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 cosa, 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 aleatoria ponderada: el Chance de cada mascota (de 100) es su proporción del total
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: el aviso 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()
-- sale de inmediato, si hay espacio
local pet = givePet(player, name, equippedCount(player) < Settings.MaxEquipped)
print(player.Name .. " hatched a " .. name)
end)
-- Las mascotas desplegadas siguen a su dueño: cada una tiene una pieza en el mundo, colocada en una
-- 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
model:Destroy()
petModels[pet] = nil
end
end
end
end)
-- El cliente pide desplegar o guardar una mascota. El servidor comprueba que la mascota
-- pertenece al jugador y que no hay más de MaxEquipped desplegadas.
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)
Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.
Todas las lecciones de Juego de Roblox: simulador de mascotas
4El mundo
La puerta del desierto