如何更新高分

How to update highscore

我的游戏在碰撞中有分数和高分 属性 所以每当我的对象在某个逻辑分数上碰撞时,高分会增加,因为我的游戏中还没有死亡阶段,所以当我重新启动我的游戏高分从零开始我希​​望高分应该从以前的高分开始,并且只有在得分>高分时才会更新。我已经为它写了代码但是当我的对象碰撞时它不起作用高分从 6 所​​以请告诉我解决它的方法

   local Highscore = 0
    score = 0
    local function updateText()
        HighscoreText.text = "Highscore: " .. Highscore
    end

-- collision Property --

 local function onCollision( event )
    if ( event.phase == "began" ) then
-- logic --

    -- score update--

-- highscore update--
if score > Highscore then
  Highscore = score 
end
updateText()


end
end
end

Runtime:addEventListener( "collision" , onCollision )

end

我使用 Corona SDK JSON 库创建了一个小模块来处理持久性以获得高分。

-- File name
local fileName = "highscore.json"
-- Path for File
-- The system.DocumentsDirectory will be backed up by synchronization in iOS
local pathForFile = system.pathForFile(fileName, system.DocumentsDirectory)

-- JSON library included in Corona SDK
local json = require( "json" )

-- This table holds two functions
-- persistHighscore, to save the highscore to file
-- fetchHighscore, to retrieve the saved highscore
local persistence = {}

-- Persists the highscore table
-- It receives only one parameter which must be a table
-- containing the highscore in a Key, Value pair
-- Example: {highscore = 10}
persistence.persistHighscore = function(highscoreTable)
    local encoded = json.encode( highscoreTable )
    local file, errorString = io.open( pathForFile, "w" )

    if not file then
        print("Opening file failed: " .. errorString)
    else
        file:write(encoded)
        file:flush()
        file:close()
    end
end

-- Returns the Highscore table
-- If there is a highscore file it will be read and a 
--table containing the highscore will be returned
persistence.fetchHighscore = function()
    local decoded, pos, msg = json.decodeFile( pathForFile )
    if not decoded then
        print( "Decode failed at "..tostring(pos)..": "..tostring(msg) )
    else
        print( "File successfully decoded!" )
        return decoded
    end
end

return persistence

在您的项目中:

local persistence = require("highscorePeristence")

如果您不熟悉使用 Lua 在 Corona SDK 中加载模块,请务必 检查这个: Corona SDK API Doc - require 在你的高分处理逻辑中,当你发现分数高于当前高分时:

if score > highscore then
    -- Container table to be stored in JSON
    local scoreTable = {
        highscore=score
        }
    persistence.persistHighscore(scoreTable)
end

当您加载项目并且想要加载存储的高分时:

local highscore
local scoreTable = persistence.fetchHighscore()
-- No highscore was stored
if not scoreTable then
    -- Initialize the highscore with 0 since there was no other value before
    highscore = 0
else
    -- Initialize the highscore with the value read from the JSON decoded table
    highscore = scoreTable.highscore
end