游戏结束
Coddy Roblox 游戏:塔防 课程的第 22 课,共 22 课。
你的游戏快完成了。设置中最后登场的是首领:它有 200 点生命值,速度很慢,但会对基地造成 20 点伤害,所以如果防御无法拦住它,你就会在最后一波失败。
失败是最后一条规则。基地生命值降到 0 时,游戏就结束了:服务器会将 Status 设为 "Lost",清除路径上的所有敌人,并且不再开始新一波。变量 gameOver 会把这个状态传递给所有需要它的循环:
if gameOver then
break
end只有基地守住了,最后的胜利才算数:if not gameOver then。
然后按“开始”,建造防御并击败全部 5 波敌人。调整 Settings,打造你自己的平衡方案。
挑战
困难基地被摧毁时,游戏失败。
- 添加
local gameOver = false。当damageBase首次将生命值降到 0 时:将它设为 true,将Status设为"Lost",并执行enemies:ClearAllChildren()。 - 在
runWave的生成循环中添加if gameOver then return end,在波次循环开头添加if gameOver then break end。 - 只有在
if not gameOver时才设置"Won"。 - 当状态为
"Lost"时,showEnd显示The base has fallen。
按下“开始”,什么都不建:基地会被摧毁。然后点击“检查”。
亲手试试
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local Debris = game:GetService("Debris")
local Settings = require(game.ReplicatedStorage.Settings)
local remotes = game.ReplicatedStorage.Remotes
local enemies = workspace.Enemies
local towers = workspace.Towers
local towerPad = {} -- 每座塔对应它所在的平台
local skipped = false
print("The base can take " .. Settings.BaseHealth .. " hits")
-- 按顺序排列的路径点(名称依次为 1、2、3……)
local waypoints = workspace.Path.Waypoints:GetChildren()
table.sort(waypoints, function(a, b)
return tonumber(a.Name) < tonumber(b.Name)
end)
-- 基地的生命值作为 workspace 的属性保存,每个客户端都能读取
workspace:SetAttribute("BaseHealth", Settings.BaseHealth)
-- 每位玩家的排行榜上都有 Money
Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local money = Instance.new("IntValue")
money.Name = "Money"
money.Value = Settings.StartMoney
money.Parent = leaderstats
end)
-- 一个敌人到达了基地
local function damageBase(amount)
local health = math.max(0, workspace:GetAttribute("BaseHealth") - amount)
workspace:SetAttribute("BaseHealth", health)
print("Base: " .. health)
-- 第 22 课:在这里处理 Game Over
end
-- 让敌人沿路径行走。MoveTo 会在 8 秒后放弃,并发出信号
-- (MoveToFinished 返回 false),所以会再次让移动缓慢的敌人前进,直到它到达。
local function walkPath(enemy)
local humanoid = enemy.Humanoid
for i = 2, #waypoints do
repeat
humanoid:MoveTo(waypoints[i].Position)
until humanoid.MoveToFinished:Wait() or not enemy.Parent
if not enemy.Parent then
return
end
end
-- 它到达了基地
damageBase(Settings.Enemies[enemy.Name].Damage)
enemy:Destroy()
end
-- 一个新敌人出现在入口,开始沿路径行走
local function spawnEnemy(kind)
local enemy = ServerStorage.Enemies[kind]:Clone()
-- 放在第一个路径点的正上方
enemy:PivotTo(waypoints[1].CFrame + Vector3.new(0, 5, 0))
local info = Settings.Enemies[kind]
enemy.Humanoid.MaxHealth = info.Health
enemy.Humanoid.Health = info.Health
enemy.Humanoid.WalkSpeed = info.Speed
enemy.Parent = enemies
-- 它的生命值条会随生命值变化
enemy.Humanoid.HealthChanged:Connect(function(health)
enemy.HealthBar.Back.Fill.Size = UDim2.fromScale(health / enemy.Humanoid.MaxHealth, 1)
end)
enemy.Humanoid.Died:Connect(function()
-- 每位玩家都会获得奖励
for _, player in Players:GetPlayers() do
player.leaderstats.Money.Value += info.Reward
end
enemy:Destroy()
end)
task.spawn(walkPath, enemy)
return enemy
end
-- 指定位置范围内最近的存活敌人,如果没有则返回 nil
local function nearestEnemy(position, range)
local best, bestDistance = nil, range
for _, enemy in enemies:GetChildren() do
local root = enemy:FindFirstChild("HumanoidRootPart")
if root and enemy.Humanoid.Health > 0 then
local distance = (root.Position - position).Magnitude
if distance <= bestDistance then
best, bestDistance = enemy, distance
end
end
end
return best
end
-- 从防御塔射向目标的一道闪光
local function beam(from, to)
local ray = Instance.new("Part")
ray.Anchored = true
ray.CanCollide = false
ray.CanTouch = false
ray.Material = Enum.Material.Neon
ray.Color = Color3.fromRGB(255, 240, 150)
ray.Size = Vector3.new(0.2, 0.2, (to - from).Magnitude)
ray.CFrame = CFrame.lookAt((from + to) / 2, to)
ray.Parent = workspace
Debris:AddItem(ray, 0.1)
end
-- Frost:敌人会以原速度的一部分行走 2 秒
local function slow(enemy, factor)
if enemy:GetAttribute("Slowed") then
return
end
enemy:SetAttribute("Slowed", true)
local speed = Settings.Enemies[enemy.Name].Speed
enemy.Humanoid.WalkSpeed = speed * factor
task.delay(2, function()
if enemy.Parent then
enemy.Humanoid.WalkSpeed = speed
enemy:SetAttribute("Slowed", nil)
end
end)
end
-- 射击:对目标造成伤害(如果是 Cannon,还会伤害附近的所有敌人)
local function shoot(tower, target, info)
local damage = info.Damage * tower:GetAttribute("Level")
local at = target.HumanoidRootPart.Position
if info.Splash then
for _, enemy in enemies:GetChildren() do
local root = enemy:FindFirstChild("HumanoidRootPart")
if root and (root.Position - at).Magnitude <= info.Splash then
enemy.Humanoid:TakeDamage(damage)
end
end
else
target.Humanoid:TakeDamage(damage)
end
if info.Slow and target.Parent then
slow(target, info.Slow)
end
beam(tower.Head.Position, at)
end
-- 防御塔的行动:瞄准范围内最近的敌人,射击,然后等待冷却结束
local function runTower(tower)
local info = Settings.Towers[tower.Name]
while tower.Parent do
local target = nearestEnemy(tower.Head.Position, info.Range)
if target then
tower.Head.CFrame = CFrame.lookAt(tower.Head.Position, target.HumanoidRootPart.Position)
shoot(tower, target, info)
task.wait(info.Cooldown)
else
task.wait(0.1)
end
end
end
-- 在底座上建造防御塔
local function placeTower(pad, kind)
local tower = ServerStorage.Towers[kind]:Clone()
tower:PivotTo(pad.CFrame + Vector3.new(0, pad.Size.Y / 2 + 1, 0))
tower:SetAttribute("Level", 1)
tower.Parent = towers
pad:SetAttribute("Used", true)
towerPad[tower] = pad
task.spawn(runTower, tower)
end
-- 客户端请求在底座上建造防御塔。检查所有条件:底座确实存在且未被占用,
-- 防御塔确实存在,而且玩家有足够的钱支付。
remotes.Place.OnServerEvent:Connect(function(player, pad, kind)
if typeof(pad) ~= "Instance" or pad.Parent ~= workspace.Pads or pad:GetAttribute("Used") then
return
end
local info = typeof(kind) == "string" and Settings.Towers[kind]
if not info then
return
end
local money = player.leaderstats.Money
if money.Value < info.Price then
return
end
money.Value -= info.Price
placeTower(pad, kind)
end)
-- 升级:每次升到下一级的花费都会增加,每升一级都会再次增加
-- 防御塔的伤害
remotes.Upgrade.OnServerEvent:Connect(function(player, tower)
if typeof(tower) ~= "Instance" or tower.Parent ~= towers then
return
end
local level = tower:GetAttribute("Level")
local cost = math.floor(Settings.Towers[tower.Name].Price * Settings.UpgradeCost * level)
local money = player.leaderstats.Money
if money.Value < cost then
return
end
money.Value -= cost
tower:SetAttribute("Level", level + 1)
end)
-- 出售:返还一半价格,底座也会重新空出来
remotes.Sell.OnServerEvent:Connect(function(player, tower)
if typeof(tower) ~= "Instance" or tower.Parent ~= towers then
return
end
player.leaderstats.Money.Value += math.floor(Settings.Towers[tower.Name].Price / 2)
towerPad[tower]:SetAttribute("Used", nil)
towerPad[tower] = nil
tower:Destroy()
end)
-- 跳过等待:提前开始下一波(仅限间歇期间)
remotes.Skip.OnServerEvent:Connect(function()
if workspace:GetAttribute("Break") then
skipped = true
end
end)
-- 一波敌人:逐个生成,然后等待它们全部消失
local function runWave(list)
for _, kind in list do
spawnEnemy(kind)
task.wait(Settings.SpawnGap)
end
while #enemies:GetChildren() > 0 do
task.wait(0.2)
end
end
-- 每波敌人都在间歇后出现
for i, list in Settings.Waves do
workspace:SetAttribute("Wave", i)
workspace:SetAttribute("Break", true)
skipped = false
local started = time()
while time() - started < Settings.WaveBreak and not skipped do
task.wait(0.1)
end
workspace:SetAttribute("Break", false)
runWave(list)
end
-- 所有波次结束:基地守住了
workspace:SetAttribute("Status", "Won")
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
Roblox 游戏:塔防中的所有课
自己练习: Roblox 在线编辑器