high-order functions my beloved
This commit is contained in:
parent
3f694ccec9
commit
93a4961419
@ -6,5 +6,6 @@
|
|||||||
"love.filesystem.load": "loadfile"
|
"love.filesystem.load": "loadfile"
|
||||||
},
|
},
|
||||||
"workspace.ignoreDir": ["dev_utils"],
|
"workspace.ignoreDir": ["dev_utils"],
|
||||||
"diagnostics.ignoredFiles": "Disable"
|
"diagnostics.ignoredFiles": "Disable",
|
||||||
|
"completion.autoRequire": false
|
||||||
}
|
}
|
||||||
|
|||||||
@ -23,6 +23,7 @@ local easing = require "lib.utils.easing"
|
|||||||
--- }
|
--- }
|
||||||
--- }:run()
|
--- }:run()
|
||||||
--- ```
|
--- ```
|
||||||
|
--- @deprecated
|
||||||
--- @class AnimationNode
|
--- @class AnimationNode
|
||||||
--- @field count integer
|
--- @field count integer
|
||||||
--- @field run animationRunner
|
--- @field run animationRunner
|
||||||
@ -73,6 +74,7 @@ function animation:update(dt)
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
--- @deprecated
|
||||||
--- @param data {[1]: animationRunner?, onEnd?: voidCallback, duration: number?, easing: ease?, children?: AnimationNode[]}
|
--- @param data {[1]: animationRunner?, onEnd?: voidCallback, duration: number?, easing: ease?, children?: AnimationNode[]}
|
||||||
--- @return AnimationNode
|
--- @return AnimationNode
|
||||||
local function new(data)
|
local function new(data)
|
||||||
|
|||||||
@ -1,4 +1,5 @@
|
|||||||
local AnimationNode = require "lib.animation_node"
|
local AnimationNode = require "lib.animation_node"
|
||||||
|
local easing = require "lib.utils.easing"
|
||||||
|
|
||||||
local function closestCharacter(char)
|
local function closestCharacter(char)
|
||||||
local caster = Vec3 {}
|
local caster = Vec3 {}
|
||||||
@ -31,76 +32,28 @@ function behavior.new()
|
|||||||
return setmetatable({}, behavior)
|
return setmetatable({}, behavior)
|
||||||
end
|
end
|
||||||
|
|
||||||
function behavior:update(dt)
|
--- @return Task<nil>
|
||||||
self.owner:try(Tree.behaviors.spellcaster, function(b)
|
function behavior:makeTurn()
|
||||||
if b.state == "casting" then
|
return function(callback) -- почему так, описано в Task
|
||||||
b.cast:update(self.owner, dt)
|
self.owner:try(Tree.behaviors.spellcaster, function(spellB)
|
||||||
end
|
local charTarget = closestCharacter(self.owner)
|
||||||
end)
|
charTarget:try(Tree.behaviors.positioned, function(b)
|
||||||
if self.animationNode and self.animationNode.state == "running" then
|
self.target = Vec3 { b.position.x, b.position.y + 1 } --- @todo тут захардкожено + 1, но мы должны как-то хитро определять с какой стороны обойти
|
||||||
self.animationNode:update(dt)
|
end)
|
||||||
-- print(self.animationNode.t)
|
|
||||||
|
spellB.spellbook[1]:cast(self.owner, self.target)(function()
|
||||||
|
-- здесь мы оказываемся после того, как сходили в первый раз
|
||||||
|
print("[AI]: finished move 1")
|
||||||
|
local newTarget = Vec3 { 1, 1 }
|
||||||
|
-- поэтому позиция персонажа для нового каста пересчитается динамически
|
||||||
|
spellB.spellbook[1]:cast(self.owner, newTarget)(function()
|
||||||
|
print("[AI]: finished move 2")
|
||||||
|
-- дергаем функцию после завершения хода
|
||||||
|
callback()
|
||||||
|
end)
|
||||||
|
end)
|
||||||
|
end)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
function behavior:draw()
|
|
||||||
self.owner:try(Tree.behaviors.spellcaster, function(b)
|
|
||||||
if b.state == "casting" then
|
|
||||||
b.cast:draw()
|
|
||||||
end
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
|
|
||||||
function behavior:makeMove()
|
|
||||||
self.owner:try(Tree.behaviors.spellcaster, function(spellB)
|
|
||||||
local charTarget = closestCharacter(self.owner)
|
|
||||||
charTarget:try(Tree.behaviors.positioned, function(b)
|
|
||||||
self.target = Vec3 { b.position.x, b.position.y + 1 } --- @todo тут захардкожено + 1, но мы должны как-то хитро определять с какой стороны обойти
|
|
||||||
end)
|
|
||||||
|
|
||||||
spellB.spellbook[1]:cast(self.owner, self.target):chain {
|
|
||||||
spellB.spellbook[1]:cast(self.owner, Vec3 { 10, 10 }):chain {
|
|
||||||
AnimationNode {
|
|
||||||
onEnd = function()
|
|
||||||
Tree.level.turnOrder:next()
|
|
||||||
end
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}:run()
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
-- -- print('какещке')
|
|
||||||
-- self.animationNode = AnimationNode { -- кринж
|
|
||||||
-- function(node) end,
|
|
||||||
-- onEnd = function()
|
|
||||||
-- -- print('kakeshke')
|
|
||||||
-- end,
|
|
||||||
-- children = {
|
|
||||||
-- AnimationNode {
|
|
||||||
-- function(node) --тяжело
|
|
||||||
-- local charTarget = closestCharacter(self.owner)
|
|
||||||
-- charTarget:try(Tree.behaviors.positioned, function(b)
|
|
||||||
-- self.target = Vec3 { b.position.x, b.position.y + 1 } --- @todo тут захардкожено + 1, но мы должны как-то хитро определять с какой стороны обойти
|
|
||||||
-- end)
|
|
||||||
-- spellB.spellbook[1]:cast(self.owner, self.target)
|
|
||||||
-- end,
|
|
||||||
-- onEnd = function() --база
|
|
||||||
-- end,
|
|
||||||
-- children = {
|
|
||||||
-- AnimationNode {
|
|
||||||
-- function(node)
|
|
||||||
-- -- if not self.target then return end
|
|
||||||
-- print("пупупупупупупупупупуупупуууууу")
|
|
||||||
-- print(spellB.spellbook[3]:cast(self.owner, self.target))
|
|
||||||
-- end
|
|
||||||
-- }
|
|
||||||
-- }
|
|
||||||
-- }
|
|
||||||
-- }
|
|
||||||
-- }
|
|
||||||
-- self.animationNode:run()
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
|
|
||||||
return behavior
|
return behavior
|
||||||
|
|||||||
@ -1,13 +1,17 @@
|
|||||||
|
local AnimationNode = require "lib.animation_node"
|
||||||
|
local easing = require "lib.utils.easing"
|
||||||
|
|
||||||
--- @class LightBehavior : Behavior
|
--- @class LightBehavior : Behavior
|
||||||
--- @field intensity number
|
--- @field intensity number
|
||||||
--- @field color Vec3
|
--- @field color Vec3
|
||||||
--- @field seed integer
|
--- @field seed integer
|
||||||
--- @field colorAnimationNode? AnimationNode
|
--- @field colorAnimationNode? AnimationNode
|
||||||
|
--- @field private animateColorCallback? fun(): nil
|
||||||
--- @field targetColor? Vec3
|
--- @field targetColor? Vec3
|
||||||
--- @field sourceColor? Vec3
|
--- @field sourceColor? Vec3
|
||||||
local behavior = {}
|
local behavior = {}
|
||||||
behavior.__index = behavior
|
behavior.__index = behavior
|
||||||
behavior.id = "light"
|
behavior.id = "light"
|
||||||
|
|
||||||
---@param values {intensity: number?, color: Vec3?, seed: integer?}
|
---@param values {intensity: number?, color: Vec3?, seed: integer?}
|
||||||
---@return LightBehavior
|
---@return LightBehavior
|
||||||
@ -26,11 +30,24 @@ function behavior:update(dt)
|
|||||||
self.colorAnimationNode:update(dt)
|
self.colorAnimationNode:update(dt)
|
||||||
end
|
end
|
||||||
|
|
||||||
function behavior:animateColor(targetColor, animationNode)
|
--- @TODO: refactor
|
||||||
|
function behavior:animateColor(targetColor)
|
||||||
if self.colorAnimationNode then self.colorAnimationNode:finish() end
|
if self.colorAnimationNode then self.colorAnimationNode:finish() end
|
||||||
self.colorAnimationNode = animationNode
|
self.colorAnimationNode = AnimationNode {
|
||||||
|
function(_) end,
|
||||||
|
easing = easing.easeInQuad,
|
||||||
|
duration = 800,
|
||||||
|
onEnd = function()
|
||||||
|
if self.animateColorCallback then self.animateColorCallback() end
|
||||||
|
end
|
||||||
|
}
|
||||||
|
self.colorAnimationNode:run()
|
||||||
self.sourceColor = self.color
|
self.sourceColor = self.color
|
||||||
self.targetColor = targetColor
|
self.targetColor = targetColor
|
||||||
|
|
||||||
|
return function(callback)
|
||||||
|
self.animateColorCallback = callback
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
function behavior:draw()
|
function behavior:draw()
|
||||||
|
|||||||
@ -5,7 +5,7 @@ local utils = require "lib.utils.utils"
|
|||||||
--- @field private runSource? Vec3 точка, из которой бежит персонаж
|
--- @field private runSource? Vec3 точка, из которой бежит персонаж
|
||||||
--- @field private runTarget? Vec3 точка, в которую в данный момент бежит персонаж
|
--- @field private runTarget? Vec3 точка, в которую в данный момент бежит персонаж
|
||||||
--- @field private path? Deque путь, по которому сейчас бежит персонаж
|
--- @field private path? Deque путь, по которому сейчас бежит персонаж
|
||||||
--- @field private animationNode? AnimationNode AnimationNode, с которым связана анимация перемещения
|
--- @field private followPathCallback? fun()
|
||||||
--- @field private t0 number время начала движения
|
--- @field private t0 number время начала движения
|
||||||
--- @field size Vec3
|
--- @field size Vec3
|
||||||
local behavior = {}
|
local behavior = {}
|
||||||
@ -20,10 +20,8 @@ function behavior.new(size)
|
|||||||
end
|
end
|
||||||
|
|
||||||
--- @param path Deque
|
--- @param path Deque
|
||||||
--- @param animationNode AnimationNode
|
--- @return Task<nil>
|
||||||
function behavior:followPath(path, animationNode)
|
function behavior:followPath(path)
|
||||||
if path:is_empty() then return animationNode:finish() end
|
|
||||||
self.animationNode = animationNode
|
|
||||||
self.owner:try(Tree.behaviors.sprite, function(sprite)
|
self.owner:try(Tree.behaviors.sprite, function(sprite)
|
||||||
sprite:loop("run")
|
sprite:loop("run")
|
||||||
end)
|
end)
|
||||||
@ -32,6 +30,10 @@ function behavior:followPath(path, animationNode)
|
|||||||
local nextCell = path:peek_front()
|
local nextCell = path:peek_front()
|
||||||
self:runTo(nextCell)
|
self:runTo(nextCell)
|
||||||
path:pop_front()
|
path:pop_front()
|
||||||
|
|
||||||
|
return function(callback)
|
||||||
|
self.followPathCallback = callback
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
--- @param target Vec3
|
--- @param target Vec3
|
||||||
@ -72,7 +74,10 @@ function behavior:update(dt)
|
|||||||
sprite:loop("idle")
|
sprite:loop("idle")
|
||||||
end)
|
end)
|
||||||
self.runTarget = nil
|
self.runTarget = nil
|
||||||
if self.animationNode then self.animationNode:finish() end
|
|
||||||
|
if self.followPathCallback then
|
||||||
|
self.followPathCallback()
|
||||||
|
end
|
||||||
end
|
end
|
||||||
else -- анимация перемещения не завершена
|
else -- анимация перемещения не завершена
|
||||||
positioned.position = utils.lerp(self.runSource, self.runTarget, fraction) -- линейный интерполятор
|
positioned.position = utils.lerp(self.runSource, self.runTarget, fraction) -- линейный интерполятор
|
||||||
|
|||||||
@ -37,11 +37,16 @@ function selector:update(dt)
|
|||||||
if not selectedId then self:select(nil) end
|
if not selectedId then self:select(nil) end
|
||||||
return
|
return
|
||||||
end
|
end
|
||||||
local task = b.cast:cast(char, mousePosition)
|
local task = b.cast:cast(char, mousePosition) -- в task функция, которая запускает анимацию спелла
|
||||||
if task then
|
if task then
|
||||||
task:run()
|
|
||||||
self:lock()
|
self:lock()
|
||||||
b.state = "running"
|
b.state = "running"
|
||||||
|
|
||||||
|
task(
|
||||||
|
function(_) -- это коллбэк, который сработает по окончании анимации спелла
|
||||||
|
b:endCast()
|
||||||
|
end
|
||||||
|
)
|
||||||
end
|
end
|
||||||
end)
|
end)
|
||||||
end
|
end
|
||||||
|
|||||||
@ -37,7 +37,9 @@ function turnOrder:next()
|
|||||||
|
|
||||||
local char = Tree.level.characters[self.current]
|
local char = Tree.level.characters[self.current]
|
||||||
char:try(Tree.behaviors.ai, function(ai)
|
char:try(Tree.behaviors.ai, function(ai)
|
||||||
ai:makeMove()
|
ai:makeTurn()(function()
|
||||||
|
self:next()
|
||||||
|
end)
|
||||||
end)
|
end)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
@ -57,7 +57,7 @@ function endTurnButton:onClick()
|
|||||||
end,
|
end,
|
||||||
duration = 1500,
|
duration = 1500,
|
||||||
easing = easing.easeInOutCubic,
|
easing = easing.easeInOutCubic,
|
||||||
onEnd = function() Tree.level.selector:select(cid) end
|
onEnd = function() if not playing:has(Tree.behaviors.ai) then Tree.level.selector:select(cid) end end
|
||||||
}:run()
|
}:run()
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
@ -14,7 +14,7 @@ local easing = require "lib.utils.easing"
|
|||||||
--- @field tag string
|
--- @field tag string
|
||||||
--- @field update fun(self: Spell, caster: Character, dt: number): nil Изменяет состояние спелла
|
--- @field update fun(self: Spell, caster: Character, dt: number): nil Изменяет состояние спелла
|
||||||
--- @field draw fun(self: Spell): nil Рисует превью каста, ничего не должна изменять в идеальном мире
|
--- @field draw fun(self: Spell): nil Рисует превью каста, ничего не должна изменять в идеальном мире
|
||||||
--- @field cast fun(self: Spell, caster: Character, target: Vec3): AnimationNode | nil Вызывается в момент каста, изменяет мир.
|
--- @field cast fun(self: Spell, caster: Character, target: Vec3): Task<nil> | nil Вызывается в момент каста, изменяет мир.
|
||||||
local spell = {}
|
local spell = {}
|
||||||
spell.__index = spell
|
spell.__index = spell
|
||||||
spell.tag = "base"
|
spell.tag = "base"
|
||||||
@ -38,25 +38,25 @@ function walk:cast(caster, target)
|
|||||||
return
|
return
|
||||||
end
|
end
|
||||||
|
|
||||||
local path = require "lib.pathfinder" (caster:has(Tree.behaviors.positioned).position:floor(), target)
|
local initialPos = caster:has(Tree.behaviors.positioned).position:floor()
|
||||||
|
local path = require "lib.pathfinder" (initialPos, target)
|
||||||
path:pop_front()
|
path:pop_front()
|
||||||
if path:is_empty() then return end
|
if path:is_empty() then
|
||||||
|
print("[Walk]: the path is empty", initialPos, target)
|
||||||
for p in path:values() do print(p) end
|
return
|
||||||
|
end
|
||||||
|
|
||||||
caster:try(Tree.behaviors.stats, function(stats)
|
caster:try(Tree.behaviors.stats, function(stats)
|
||||||
stats.mana = stats.mana - 2
|
stats.mana = stats.mana - 2
|
||||||
print(stats.mana)
|
|
||||||
end)
|
end)
|
||||||
|
|
||||||
local sprite = caster:has(Tree.behaviors.sprite)
|
local sprite = caster:has(Tree.behaviors.sprite)
|
||||||
if not sprite then return end
|
assert(sprite, "[Walk]", "WTF DUDE WHERE'S YOUR SPRITE")
|
||||||
return AnimationNode {
|
if not sprite then
|
||||||
function(node)
|
return
|
||||||
caster:has(Tree.behaviors.tiled):followPath(path, node)
|
end
|
||||||
end,
|
|
||||||
onEnd = function() caster:has(Tree.behaviors.spellcaster):endCast() end,
|
return caster:has(Tree.behaviors.tiled):followPath(path)
|
||||||
}
|
|
||||||
end
|
end
|
||||||
|
|
||||||
function walk:update(caster, dt)
|
function walk:update(caster, dt)
|
||||||
@ -90,7 +90,7 @@ function regenerateMana:cast(caster, target)
|
|||||||
end)
|
end)
|
||||||
print(caster.id, "has regenerated mana and gained initiative")
|
print(caster.id, "has regenerated mana and gained initiative")
|
||||||
local sprite = caster:has(Tree.behaviors.sprite)
|
local sprite = caster:has(Tree.behaviors.sprite)
|
||||||
if not sprite then return true end
|
if not sprite then return nil end
|
||||||
|
|
||||||
local light = require "lib/character/character".spawn("Light Effect")
|
local light = require "lib/character/character".spawn("Light Effect")
|
||||||
light:addBehavior {
|
light:addBehavior {
|
||||||
@ -98,29 +98,14 @@ function regenerateMana:cast(caster, target)
|
|||||||
Tree.behaviors.residentsleeper.new(),
|
Tree.behaviors.residentsleeper.new(),
|
||||||
Tree.behaviors.positioned.new(caster:has(Tree.behaviors.positioned).position + Vec3 { 0.5, 0.5 }),
|
Tree.behaviors.positioned.new(caster:has(Tree.behaviors.positioned).position + Vec3 { 0.5, 0.5 }),
|
||||||
}
|
}
|
||||||
AnimationNode {
|
|
||||||
function(node)
|
|
||||||
local audioPath = Tree.assets.files.audio
|
|
||||||
sprite:animate("hurt", node)
|
|
||||||
Tree.audio:crossfade(audioPath.music.level1.battle,
|
|
||||||
audioPath.music.level1.choral, 5000)
|
|
||||||
caster:try(Tree.behaviors.ai, function(b)
|
|
||||||
b:makeMove()
|
|
||||||
end)
|
|
||||||
end,
|
|
||||||
onEnd = function() caster:has(Tree.behaviors.spellcaster):endCast() end
|
|
||||||
}:run()
|
|
||||||
|
|
||||||
AnimationNode {
|
return function(callback)
|
||||||
function(node)
|
print(light:has(Tree.behaviors.light).animateColor)
|
||||||
light:has(Tree.behaviors.light):animateColor(Vec3 {}, node)
|
light:has(Tree.behaviors.light):animateColor(Vec3 {})(function()
|
||||||
end,
|
light:die()
|
||||||
easing = easing.easeInQuad,
|
callback()
|
||||||
duration = 800,
|
end)
|
||||||
onEnd = function() light:die() end
|
end
|
||||||
}:run()
|
|
||||||
|
|
||||||
return true
|
|
||||||
end
|
end
|
||||||
|
|
||||||
local attack = setmetatable({}, spell)
|
local attack = setmetatable({}, spell)
|
||||||
|
|||||||
0
lib/task.lua
Normal file
0
lib/task.lua
Normal file
36
lib/utils/task.lua
Normal file
36
lib/utils/task.lua
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
--- Обобщенная асинхронная функция
|
||||||
|
---
|
||||||
|
--- Использование в общих чертах выглядит так:
|
||||||
|
--- ```lua
|
||||||
|
--- local multiplyByTwoCallback = nil
|
||||||
|
--- local n = nil
|
||||||
|
--- local function multiplyByTwoAsync(number)
|
||||||
|
--- -- императивно сохраняем/обрабатываем параметр
|
||||||
|
--- n = number
|
||||||
|
--- return function(callback) -- это функция, которая запускает задачу
|
||||||
|
--- multiplyByTwoCallback = callback
|
||||||
|
--- end
|
||||||
|
--- end
|
||||||
|
---
|
||||||
|
--- local function update(dt)
|
||||||
|
--- --- ждем нужного момента времени...
|
||||||
|
---
|
||||||
|
--- if multiplyByTwoCallback then -- завершаем вычисление
|
||||||
|
--- local result = n * 2
|
||||||
|
--- multiplyByTwoCallback(result) -- результат асинхронного вычисления идет в параметр коллбека!
|
||||||
|
--- multiplyByTwoCallback = nil
|
||||||
|
--- end
|
||||||
|
--- end
|
||||||
|
---
|
||||||
|
---
|
||||||
|
--- --- потом это можно вызывать так:
|
||||||
|
--- local task = multiplyByTwoAsync(21)
|
||||||
|
--- -- это ленивое вычисление, так что в этот момент ничего не произойдет
|
||||||
|
--- -- запускаем
|
||||||
|
--- task(
|
||||||
|
--- function(result) print(result) end -- выведет 42 после завершения вычисления, т.е. аналогично `task.then((res) => print(res))` на JS
|
||||||
|
--- )
|
||||||
|
---
|
||||||
|
--- ```
|
||||||
|
--- @generic T
|
||||||
|
--- @alias Task<T> fun(callback: fun(value: T): nil): nil
|
||||||
Loading…
x
Reference in New Issue
Block a user