如何更新最高分

我在我的游戏中有得分和最高分的碰撞属性,所以每当我的物体碰撞时得分和最高分增加,因为我还没有游戏中的死亡阶段,所以当我重新启动我的游戏时最高分从零开始,我希望最高分应该从先前的最高分开始,并且仅在得分>最高分时更新。我已经为此编写了代码,但当我的物体碰撞时,最高分从6开始,所以请告诉我解决方法

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

-- 碰撞属性 --

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

    -- 更新得分 --

-- 更新最高分 --
if score > Highscore then
  Highscore = score
end
updateText()

end
end
end

Runtime:addEventListener( "collision" , onCollision )

end
点赞
用户6293559
用户6293559

我创建了一个小模块,使用 Corona SDK JSON 库来处理高分数的持久化。

-- 文件名
local fileName = "highscore.json"
-- 文件路径
-- 在 iOS 上,system.DocumentsDirectory 将在同步中被备份
local pathForFile = system.pathForFile(fileName, system.DocumentsDirectory)

-- Corona SDK 中包含的 JSON 库
local json = require( "json" )

-- 这个表包含两个函数
-- persistHighscore,用于保存高分数到文件中
-- fetchHighscore,用于检索保存的高分数
local persistence = {}

-- 持久化高分数表
-- 它只接收一个参数,必须是一个包含高分数键值对的表
-- 例如:{highscore = 10}
persistence.persistHighscore = function(highscoreTable)
    local encoded = json.encode( highscoreTable )
    local file, errorString = io.open( pathForFile, "w" )

    if not file then
        print("打开文件失败:" .. errorString)
    else
        file:write(encoded)
        file:flush()
        file:close()
    end
end

-- 返回高分数表
-- 如果有高分数文件,它将被读取,并返回一个包含高分数的表
persistence.fetchHighscore = function()
    local decoded, pos, msg = json.decodeFile( pathForFile )
    if not decoded then
        print( "解码失败:"..tostring(pos)..": "..tostring(msg) )
    else
        print( "文件解码成功!" )
        return decoded
    end
end

return persistence

在你的项目中:

local persistence = require("highscorePeristence")

如果你不熟悉使用 Lua 在 Corona SDK 中加载模块,请务必查看: Corona SDK API 文件 - require

当你发现得分比当前高分数更高时,你的高分数处理逻辑如下:

if score > highscore then
    -- 要存储到 JSON 中的容器表
    local scoreTable = {
        highscore=score
        }
    persistence.persistHighscore(scoreTable)
end

当你加载项目并想要加载存储的高分数时:

local highscore
local scoreTable = persistence.fetchHighscore()
-- 没有存储高分数
if not scoreTable then
    -- 由于以前不存在其他值,因此将高分数初始化为 0
    highscore = 0
else
    -- 使用从 JSON 解码表中读取的值初始化高分数
    highscore = scoreTable.highscore
end
2017-05-07 19:26:43