Salvataggio
Salvare e caricare

Salvataggio
Per qualche motivo non volevo lavorarci subito, anzi, temevo che sarebbe stato difficile. Ma visto che avevo già creato alcune scene di prova, era più comodo poter salvare il gioco. E ovviamente caricarlo.
Per questo ho creato in engine3 una classe, serialization.lua, che è un wrapper attorno a binser.
Così è possibile salvare correttamente i dati degli oggetti.
Nel gioco ho poi creato una classe state.lua che è più o meno così.
function State:saveEntities()
for _, entity in pairs(entityManager.entities) do
if entity.saveEntity then
entity:saveEntity()
end
end
end
---@param file string Where to save the data
function State:save(file, force)
-- Check if it is possible to save right now
if action:isProcessWorking() and force ~= true then
print("saving is not possible now, a action is still working")
return false
end
local data = {}
-- Create a save state for all entities that are needed
self:saveEntities()
-- We don't need all session data.
-- @warning keep this up to date if you want to add something
local sessionData = session:getData()
local validSessionKeyNamePatterns = {
"^actor-.*",
"^item-.*",
"^animation-.*",
"^scene-.*",
"action",
"^entity_delete",
"^entity_properties",
"^currentSceneUkey"
}
for sessionKeyName, sessionValue in pairs(sessionData) do
-- I don't know how to create multi patterns ... [x|y] don't work
local check = false
for _, pattern in pairs(validSessionKeyNamePatterns) do
if string.match(sessionKeyName, pattern) ~= nil then
if self.config.log.state then
print("[SESSION.SET." .. sessionKeyName .. "]")
end
data[sessionKeyName] = sessionValue
check = true
break
end
end
if check == false and self.config.log.state then
print("[SESSION.INFO." .. sessionKeyName .. "] don't match any save pattern")
end
end
local success, message = love.filesystem.write(file, Serialization.serialize(data))
if success == false then
error("Cannot save data, " .. message)
end
end
---@param file string What file data to load
function State:load(file)
local data = love.filesystem.read(file)
if data then
local results, len = Serialization.deserialize(data)
-- at the moment we only use one object in each file
if len == 1 then
-- set the session data
session:setData(results[1])
end
end
end
Uso
In ogni classe entity ora si possono creare (facoltativamente) due funzioni che vengono usate durante il salvataggio e il caricamento del gioco. Qui sotto vedi un esempio sintetico dell’entity dei personaggi. Il vantaggio di questo approccio è che in futuro puoi andare in ogni direzione, ma anche che i file restano molto piccoli.
-- special function that will execute when saving the game
function Actor:saveEntity()
-- maybe a extend class did create some data
local data = session:get("actor-" .. self.ukey) or {}
data.sceneUkey = self.sceneUkey
data.lastMove = self.lastMove
data.movableByUserInput = self.movableByUserInput
if self.activeFrameset then
data.startPositionX = self.activeFrameset:getX()
data.startPositionY = self.activeFrameset:getY()
end
-- maybe the actor did change the frameset (using a hat)
data.frameset = {}
for index, frameset in pairs(self.frameset) do
data.frameset[index] = frameset.name
end
session:set("actor-" .. self.ukey, data)
end
function Actor:loadEntity()
local restoreData = session:get("actor-" .. self.ukey)
if restoreData == nil then
return
end
if restoreData.sceneUkey ~= nil then
self:setSceneUkey(restoreData.sceneUkey)
end
if restoreData.movableByUserInput ~= nil then
self:setMovableByUserInput(restoreData.movableByUserInput)
end
-- maybe the actor did change the frameset (using a hat)
if restoreData.frameset then
for index, framesetName in pairs(restoreData.frameset) do
self:setFrameset(index, framesetName)
end
end
if restoreData.startPositionX and restoreData.startPositionY then
self.movable.vPosition.x = restoreData.startPositionX
self.movable.vPosition.y = restoreData.startPositionY
self:setXY(self.movable.vPosition.x, self.movable.vPosition.y)
end
if restoreData.lastMove then
-- what will be the new activeFrameset (index)
self:setActiveFrameset(restoreData.lastMove)
end
-- when load scene is used, we don't set the player position
-- @warning we do this after setXY, because that function will show the player
local currentSceneUkey = session:get("currentSceneUkey")
if currentSceneUkey and self.sceneUkey ~= currentSceneUkey then
self:hide()
end
end
Per finire
Come vedi, devi solo assicurarti di salvare i dati che ti servono davvero. Tutti gli altri dati sono superflui e rendono il debug quasi impossibile. Non aspettare troppo con un sistema del genere, perché prima o poi dovrai farlo comunque.
Il codice qui sopra al momento viene attivato con un pulsante, con uno screenshot del gioco, e il personaggio scelto dice che il salvataggio è riuscito.
self.buttonSave.callbackAfterMousePressedEvent["btnSave"] = function(button)
local currentTime = os.time()
local saveGameName = "savegame" .. currentTime .. ".data"
local saveGameScreenshot = "screenshot" .. currentTime .. ".png"
-- create a screenshot without the state menu (write it to the save directory (love default))
love.graphics.captureScreenshot(saveGameScreenshot)
-- save the game
State():save(saveGameName)
-- say that the save the game was correct
local activeActor = entityManager:find({ movableByUserInput = true }, "Player")
if #activeActor == 1 then
local actionSay = ActionSay()
actionSay:execute(
{
action = action.SAY,
initiator = activeActor[1]
},
{
text = i18n:s("Save game done!")
},
nil,
{},
{},
nil
)
end
self.buttonLoad:setIsVisible(true)
return { preventDefault = true }
end