2012-02-15 9 views
0

私が望むのは、ユーザー(プレーヤー)のハイスコアを保存することです。この情報は、アプリケーション(ゲーム)がコロナSDK(Lua)で起動されるまで維持されます。私はそれがiOSとAndroid上でうまく動作するようにしたい。私の最高記録データは実際には数字を含む2つのルアテーブルです。コロナで同等の "NSUserDefaults"機能を実装する方法は?

これを行うにはどのような方法が適切かつ簡単ですか?

答えて

3

スコアをテーブルに保存し、json形式のテキストファイルにシリアル化することができます。

local json=require("json") 
local savefile="scores.json" 

scores= 
    { 
     { 
      level=1, 
      status=0, 
      highscore=0, 
     }, 
     { 
      level=2, 
      status=0, 
      highscore=0, 
     }, 
    } 

function getScore(filename, base) 
    -- set default base dir if none specified 
    if not base then 
     base = system.DocumentsDirectory 
    end 

    -- create a file path for corona i/o 
    local path = system.pathForFile(filename, base) 

    -- will hold contents of file 
    local contents 

    -- io.open opens a file at path. returns nil if no file found 
    local file = io.open(path, "r") 
     local scores 
    if file then 
     -- read all contents of file into a string 
     contents = file:read("*a") 
      if content ~= nil then 
      scores=json.decode(content) 
      end 
     io.close(file) -- close the file after using it 
    end 

    return scores 
end 

function saveScore(filename, base) 
    -- set default base dir if none specified 
    if not base then 
     base = system.DocumentsDirectory 
    end 

    -- create a file path for corona i/o 
    local path = system.pathForFile(filename, base) 

    -- io.open opens a file at path. returns nil if no file found 
    local file = io.open(path, "wb") 
    if file then 
     -- write all contents of file into a string 
     file:write(json.encode(scores)) 
     io.close(file) -- close the file after using it 
    end 
end 

グローバルscores変数は、通常のテーブルのように操作することができ、あなたがscoresテーブルをロードまたは保存するときには、上記の機能を呼び出すことができます。

+2

ゲームセンターや他のオンラインリーダーボードサービスを使用する場合は、このデータベースを暗号化する必要があります。脱獄した携帯電話を使用しているユーザーは、テーブルを編集して任意のスコアを表示してからアプリを再度開き、彼らのオンラインスコア –

+0

cctan:すごく、ありがとう!私が探していたものとまったく同じもの。 ジャック:チップをありがとう、私はそれを知らなかった。私はゲームセンターを実装するときに行う。 – mindbomb

+1

@JackLawrence +1の暗号化について – cctan

関連する問題