Menu
CoddyTech

Monedas del desierto

Lección 16 de 18 del curso Juego de Roblox: simulador de mascotas de Coddy.

El desierto tiene sus propios puntos y sus montones son más resistentes y valiosos: Settings.DesertHealth y Settings.DesertValue. Genera montones en cada zona y dale a cada uno un atributo Zone que indique dónde está. Un punto conoce su zona: está en Zones.Desert.Spawns, así que spot.Parent.Parent.Name es "Desert".

La puerta solo se abre en la pantalla del jugador, y alguien que haga trampas puede abrir cualquier muro en su pantalla. Así que la comprobación Hit del servidor añade una regla más: un montón del desierto ignora a los jugadores que no tienen el atributo Desert. El cliente abre las puertas; el servidor mantiene las reglas.

challenge icon

Desafío

Difícil
  1. En spawnPile, usa la salud y el valor del Desert para los puntos del Desert y establece el atributo Zone de cada pila con el nombre de su zona.
  2. Genera pilas en los puntos de todas las zonas de workspace.Zones.
  3. En el controlador de Hit, ignora una pila del Desert para un jugador cuyo atributo Desert no esté establecido.

Pulsa Play y después Check.

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 pila -> 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 guarda 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 activas 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

-- cuánto poder añaden las mascotas de un jugador 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)

-- Una pila de monedas en un lugar: una copia de ServerStorage.CoinPile con su salud
-- y valor como atributos
local function spawnPile(spot)
	local pile = ServerStorage.CoinPile:Clone()
	pile.Position = spot.Position
	pile:SetAttribute("MaxHealth", Settings.PileHealth)
	pile:SetAttribute("Health", Settings.PileHealth)
	pile:SetAttribute("Value", Settings.PileValue)
	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 una pila;
-- al llegar a 0, la pila se rompe y otorga 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 Meadow
for _, spot in workspace.Zones.Meadow.Spawns:GetChildren() do
	spawnPile(spot)
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
	hitPile(player, pile)
end)

-- Una selección aleatoria ponderada: la Chance de cada mascota (de 100) es su porció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 indicador de 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()
	-- sale de inmediato, si hay espacio
	local pet = givePet(player, name, equippedCount(player) < Settings.MaxEquipped)
	print(player.Name .. " hatched a " .. name)
end)

-- Las mascotas que están fuera siguen a su dueño: cada una tiene una pieza en el mundo, colocada en una
-- en fila detrás del jugador en cada fotograma
local petModels = {} -- cada mascota -> su parte 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 solicita sacar o guardar una mascota. El servidor comprueba que la mascota es
-- del propio jugador y que no hay más de MaxEquipped fuera.
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 del 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)
quiz iconPonte a prueba

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