TABLES for Multi Level Games

Below is part of the code from two modules from my game:

  1. score Module – the table I want to store the high score for each level
  2. Game Module – the module for game play

I have been able to set this up successfully for one level; however, I am having trouble when I try to add multiple levels to the table and then retrieve the scores and write scores for new levels.  I set them up so that I can pull the numbers to use for various things.  My questions are at the bottom after the Game Module.  I’m trying to wrap my brain around tables.   I appreciate any help. 


– Score Module

local highScoreT = { }  
 


–VARIABLE

highScoreT.scorelevel1 = 0


–INITIALIZE LEVEL 1 -------

function highScoreT.initL1( options )
   local customOptions = options or {}
   local opt = {}
   opt.fontSize = customOptions.fontSize or 50
   opt.font = customOptions.font or native.systemFontBold
   opt.x = customOptions.x or display.contentCenterX
   opt.y = customOptions.y or opt.fontSize * 0.5
   opt.maxDigits = customOptions.maxDigits or 6
   opt.leadingZeros = customOptions.leadingZeros or false
   highScoreT.filename = customOptions.filename or “score1file.txt”
   local prefix = “”
   if opt.leadingZeros then
   prefix = “0”
end
 

highScoreT.format = “%” … prefix … opt.maxDigits … “d”

highScoreT.scorelevel1Text = display.newText(string.format(highScoreT.format, 0), opt.x, opt.y, opt.font, opt.fontSize)
highScoreT.scorelevel1Text.isVisible = false
 

return highScoreT.scorelevel1Text
end


–SET FUNCTION

function highScoreT.setL1(value)
   highScoreT.scorelevel1 = value
   highScoreT.scorelevel1Text.text = string.format(highScoreT.format,highScoreT.scorelevel1)
end
 


–SAVE LEVEL1

function highScoreT.saveL1()
   local path = system.pathForFile( highScoreT.filename, system.DocumentsDirectory)
   local file = io.open(path, “w”) – io.open opens a file at path. returns nil if no file found
   if file then
       local contents = tostring( highScoreT.scorelevel1 )
       file:write( contents ) – write game score to the text file
       print (“the score has been written to the table”)
       io.close( file )
      return true
     else
     print("Error: could not read ", highScoreT.filename, “.”)
     return false
   end
end


–LOAD FUNCTION   

–LOAD LEVEL 1 SCORE–
function highScoreT.loadL1()
   local path = system.pathForFile( highScoreT.filename, system.DocumentsDirectory)
   local contents = “”
   local file = io.open( path, “r” )
   if file then
     – read all contents of file into a string
       local contents = file:read( “*a” )
        local scorelevel1 = tonumber(contents);
        io.close( file )
        return scorelevel1
  end
     print("Could not read scores from ", highScoreT.filename, “.”)
     return nil
end
 

return highScoreT

 

GAME MODULE:

local score = require (“score”)


–INITIALIZE SCORE TEXT  

local scorelevel1Text = score.initL1({
filename = “score1file.txt”,  

})


–SET AND SAVE SCORE  

scorelevel 1 = 1000

score.setL1(scorelevel1)  
score.saveL1(“score1file.txt”)   
 

QUESTIONS:

When I add multiple levels would I set the variables as follows?

highScoreT.scorelevel1 = 0

highScoreT.scorelevel2 = 0

highScoreT.scorelevel3 = 0
 

Would I save all the high scores in the same file name or in separate file names?

“scorefile.txt”    or “score1file.txt” and “score2file.txt” and “score3file.txt”
 

If I have to use a unique file name for each high score in the score module, would I set up a separate INITIALILE LEVEL for each unique file name in the score module?

Example:


–INITIALIZE LEVEL 1 -------

function highScoreT.initL1( options )
local customOptions = options or {}……….

highScoreT.filename = customOptions.filename or “score1file.txt”……
highScoreT.scorelevel1Text = display.newText(string.format(highScoreT.format, 0), opt.x, opt.y, opt.font, opt.fontSize)
highScoreT.scorelevel1Text.isVisible = false
return highScoreT.scorelevel1Text

 -------------------------------------------------
–INITIALIZE LEVEL 2 -------

function highScoreT.initL1( options )
local customOptions = options or {}
highScoreT.filename = customOptions.filename or “score2file.txt”……
highScoreT.scorelevel2Text = display.newText(string.format(highScoreT.format, 0), opt.x, opt.y, opt.font, opt.fontSize)
highScoreT.scorelevel2Text.isVisible = false
return highScoreT.scorelevel2Text
 

Would I have to set up a unique SET, SAVE and LOAD code for the high score for each level in the score module? Can I write a single level score to the table without messing up the other saved data?

When I’m looking at the table in my sandbox file - how can I see the score stored for each level if they are all stored in the same table?

You can do this without saving a separate score file for each level. Have you looked at Rob Miracle’s loadsave module? It allows you to easily save a Lua table into JSON format for persistent storage on the device.

Below is a very simple implementation for a highscore module to keep track of multiple levels:

local loadsave = require("loadsave") local ScoreModule = {} function ScoreModule:initialize( ) self.scores = loadsave.loadTable("highscores.json") or {} end function ScoreModule:getHighScore(levelID) return self.scores[levelID] or 0 end function ScoreModule:saveHighScore(levelID, score) self.scores[levelID] = score --This will insert the id if it doesnt exist or overwrite if it already does loadsave.saveTable(self.scores, "highscores.json") end return ScoreModule

Here is a very simple use case:

local scoreModule = require("ScoreModule") ----------------------------------------- -- Display the score ----------------------------------------- local currentLevelID --assuming you have a way of keeping track which level youre on local scoreText = display.newText(scoreModule:getHighScore(currentLevelID), 0,0 ...) ----------------------------------------- -- Save score when user completes level ----------------------------------------- local currentLevelID local currentScore --assuming this is the variable that keeps track of current score scoreModule:saveHighScore(currentLevelID, currentScore)

And to answer your last question about viewing the file in the sandbox, when you open up “highscores.json” it will look something like this:

{
    “level1” : 2000,
    “level2” : 1500,
    “level3” : 2350,
    etc…
}

Which is essentially a key/value pair similar to how tables are represented in Lua.

Thanks.  I will give this a try.

You can do this without saving a separate score file for each level. Have you looked at Rob Miracle’s loadsave module? It allows you to easily save a Lua table into JSON format for persistent storage on the device.

Below is a very simple implementation for a highscore module to keep track of multiple levels:

local loadsave = require("loadsave") local ScoreModule = {} function ScoreModule:initialize( ) self.scores = loadsave.loadTable("highscores.json") or {} end function ScoreModule:getHighScore(levelID) return self.scores[levelID] or 0 end function ScoreModule:saveHighScore(levelID, score) self.scores[levelID] = score --This will insert the id if it doesnt exist or overwrite if it already does loadsave.saveTable(self.scores, "highscores.json") end return ScoreModule

Here is a very simple use case:

local scoreModule = require("ScoreModule") ----------------------------------------- -- Display the score ----------------------------------------- local currentLevelID --assuming you have a way of keeping track which level youre on local scoreText = display.newText(scoreModule:getHighScore(currentLevelID), 0,0 ...) ----------------------------------------- -- Save score when user completes level ----------------------------------------- local currentLevelID local currentScore --assuming this is the variable that keeps track of current score scoreModule:saveHighScore(currentLevelID, currentScore)

And to answer your last question about viewing the file in the sandbox, when you open up “highscores.json” it will look something like this:

{
    “level1” : 2000,
    “level2” : 1500,
    “level3” : 2350,
    etc…
}

Which is essentially a key/value pair similar to how tables are represented in Lua.

Thanks.  I will give this a try.