Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

variables - Saving game currency in LOVE2D

So I'm making a new game using LOVE2D called PlayBall which is my variation of Pong, and I want to set up a currency in the game.

So I will set up a variable called money and set to 0 at the very beginning. Then, you gain currency by winning games: +10 for winning a match, +25 for winning a game, +5 for collecting a powerup.

If I leave the game (or close it), the value should be saved somewhere so I can reuse it again, but I don't know how to do so.

Is there a way to save a variable when you leave a LOVE2D game?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The love.filesystem library provides all means to manipulate files on your computer.

There are various ways to "serialize" your data so you can write the into a file. You could use existing libraries or write your own.

https://love2d.org/wiki/love.data.pack

https://love2d.org/wiki/Serializing

Simple example I found online (you can search the web too! try "love2d save game")

serialize = require("lib/ser")

function saveMaxScore()
    local data = { }-- Make a table to store variables in.
    data.maxScor = maxScor
    data.whatever = "Nick"
    -- Save the table to the "savegame.txt" file:
    love.filesystem.write("savegame.txt", serialize(data))
end

function loadMaxScore()    
    if not love.filesystem.exists("savegame.txt") then
        maxScor = 0
        saveMaxScore()
    end
    -- Load the data table:
    local data = love.filesystem.load("savegame.txt")()
    -- Copy the variables out of the table:
    maxScor = data.maxScor
    return maxScor
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...