Jan 132012
 

This plug and play code* demonstrates just how easy it is to save a high score in Corona.

*This code relies on Ego, which can be downloaded from here.

The code below will display a blue-gray background with a score in the top right. Clicking the background increases the score which will be automatically saved if greater than the highest score when you quit or restart the application.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
--Hide the status bar
display.setStatusBar(display.HiddenStatusBar)

--Saving/Loading Stuff
local ego = require "ego"
local saveFile = ego.saveFile
local loadFile = ego.loadFile
--------------------------------------------------------------------
--------------------------------------------------------------------

--Create the background and make it blue
local bg = display.newRect( 0, 0, 320, 480 )
bg:setFillColor( 150, 180, 200 )

--Start the score at 0
local score = 0

--Create score text and make it dark gray
local scoreText = display.newText(score, 200, 20, native.systemFont, 24)
scoreText:setTextColor( 80, 80, 80 )

--Function to add to score and update scoreText
local function addToScore()
score = score + 1
scoreText.text = score
end
bg:addEventListener("tap", addToScore)

--------------------------------------------------------------------
--------------------------------------------------------------------

--Load highscore value from file. (It will initally be a string.)
highscore = loadFile ("highscore.txt")

--If the file is empty (this means it is the first time you've run the app) save it as 0
local function checkForFile ()
if highscore == "empty" then
highscore = 0
saveFile("highscore.txt", highscore)
end
end
checkForFile()

--Print the current highscore
print ("Highscore is", highscore)

--------------------------------------------------------------------
--------------------------------------------------------------------

--When the app is quit (or simulator refreshed) save the new highscore
--(If score > highscore the data will not be changed)

local function onSystemEvent ()
if score > tonumber(highscore) then --We use tonumber as highscore is a string when loaded
saveFile("highscore.txt", score)
end
end
Runtime:addEventListener( "system", onSystemEvent )

Enjoy!

Peach Pellen :)

PS – If you want to get in on the early bird entry for the Techority 48 Hour Challenge  you should do so now, prices will be back to normal within a day or two.

 

Like this post? Subscribe to the monthly newsletter!

*Want to learn how to lock/unlock levels using Ego? See here.

  36 Responses to “Easy Saving of Highscore in Corona SDK Apps”

  1. I assume you are loading highscore outside of the code you posted?

    I think what is happening is something got messed up in sandbox during the update. click on your desktop, click “GO” in top bar, press ALT so “Library” appears in the dropdown, open that, find “Application Support”, “Corona Simulator”, find your project name and go in there, into documents, and delete the score file.

    Think that may do it.

  2. Hey Peach, I have been using this system for a while now with no flaws but that was on Snow Leopard with Xcode 4.2 and an older version of Corona. I finally upgraded to the newest build of Corona (Version 2011.704 (2011.12.8)), Xcode 4.3.2, and OS X 10.7.3 (Lion). Now I am getting and error in Corona with code that hasn’t been changed in a while. In my version of the onSystemEvent (), I have a variable named “score” which is a number. Now when my onSystemEvent function is called, Corona gives me an error in the terminal saying it is trying to compare a number with a nil.

    1
    2
    3
    4
    5
    6
    7
    local score = 0;

    local function onSystemEvent ()
    if score > tonumber(highscore) then --We use tonumber as highscore is a string when loaded
    saveFile("highscore.txt", score)
    end
    end

    This code has worked before the upgrade and once I upgraded I got these errors. Also, when I built the app using the Xcode simulator, it works fine and the scores save. It just causes errors in the Corona simulator. Do you know why this is doing this? Do I have to initialize my “score” variable differently in the new version?

  3. @Niles – I’m hoping tomorrow I can get to your email; will see what I can do.

    @Roy – Ah, great, OK. When compiled the files don’t exist, they get created just like the sandbox ones do. Is that what you are asking? I am not certain. (Need sleep.)

  4. Ahh, I found it. I was creating highscore.txt in my project folder.

    Will this have any effect on when the App is uploaded to the App store? or does the compiling include the Sandbox folder. I can program but when I click Compile, I am clueless lol

  5. No worries Peach!

    I am using a global variable, (a must for this kind of game), and the terminal definitely shows that the variable is correct. It’s just not working in the GUI.

    I’ll email you both versions, Peach, and maybe that will explain myself better.

    Thanks again!

  6. @Niles:

    I may have something for you to look at in your code, but it does not involve EGO. I was having trouble moving variables from scene to scene because I would forget to “insert” them into each scene. The variable you create here (highscore, score, or scoretext) that is being displayed, must be inserted into your scene whether by using a GUI:insert(scoretext) and Scene:insert(scoretext) or however you have it done.

    Then in each scene I have to create a new variable to store the information in. So therefore you are not using the same variable on multiple scenes. (I’m not sure if using the same variable on multiple scenes can work regardless)

    I know I didn’t answer your question but maybe provided a different way to look at it to come up with a solution.

    • Sorry guys, this week has been a bit insane.

      Niles, Roy has a point – your variables need to be loaded in each scene that you need them in, or be global. (Loading in each scene would be best if that is an option.) This would solve your issue. I see you emailed but have not yet had the time to read and reply though I hope I can soon.

      Roy, are you changing the correct file? Did you find the highscore.txt file on your computer, edit it and then save it? It is fairly tucked away in the sandbox folder. It should work fine if you edit and save it. Let me know. (Some people create highscore.txt or whatnot in their project folder which is not correct.)

  7. Hi Peach. This is exactly what I have been looking for. I am going to be releasing an app in the next coming weeks and would definitely like to credit you as a major help. I do have one question though. Once highscore.txt is created, is there a way to reset it back to 0 for testing purposes? If I try and change the value to a certain number in the txt file, it does nothing. I think I may be overlooking an easy fix though. Thanks in advance!

  8. It’s for a text adventure game I’m porting over from the desktop version. I’m not using this for high scores, but for variable saves, like is this door open or closed (0 or 1). If I put your code from here in main.lua, change it for my variable name, run the game, go to the room with the door, open the door and reset the simulator, it seems to save that variable (1) just fine, both in the text document and what the terminal says. However, when I go into that scene again (each room is a scene) it acts like the variable is neither 0 or 1!

    There is way too much code to post. Should I just email you my test for this? One with your code, one without?

    I appreciate any help, as I need to port this quickly before the baby arrives! :) I’ll be more than happy to donate!

    Niles

    P.S., I’m sure you’ll probably tell me to use ICE or something else, but I like the simplicity of ego. I don’t mind making a text file for each variable. There aren’t that many, maybe like 15.

  9. I was really hoping to get this to work, but it is doing very odd things in my program!

    It seems to save and load the variable just fine, even from the terminal’s standpoint, but in practice, it’s acting like the right variables aren’t set as I play the game! Very weird!

    I’m placing this in Main. I have several scenes, not just one. Does this matter?

    • Hi Niles – what are you placing in main?

      If you load the highscore in menu (for example) but then try to display it on the gameover screen that wont work in director, you need to also load it in gameover. Does that make sense? :)

      If you have trouble make a forum thread and I will check it out when I’m about again tomorrow. (Be sure to post some code!)

  10. Ok ! Sweet dreams, I really appreciate the help!

  11. Email me the file, my address is on my contact page; http://techority.com/hire-me/

    Will look at it tomorrow if I can – about to sleep.

  12. Ok. Do you recommend any free website for uploading zip? Where do I send you the link privately?

  13. It’s hard to figure this out in comments; can you upload your project and give me a link? Can try to check it out tomorrow. (Not before then though, it’s after 6am here and I need sleep soon.)

  14. I’m sorry, please ignore the last post! Lol
    What I have is

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    ego = require "ego"
    saveFile = ego.saveFile
    loadFile = ego.loadFile
    counter = loadFile ("counter.txt")
    local function checkForFile ()
    if counter == "empty" then
    _G.counter = 1
    saveFile("counter.txt", _G.counter)
    end
    end
    checkForFile()
    print ("counter is", _G.counter)

    And then, in my specific scene where it should add 1:

    1
    2
    3
    _G.counter = _G.counter + 1
    print(_G.counter)
    saveFile("counter.txt", _G.counter)

    Now it is not saving properly, I think. It starts with 1, it adds normally to 2, but when I restart the simulator, it begins with counter = nil, and crashes in the specific scene, cause I can’t add to nil.
    Thoughts? Thanks!

  15. Hey Peach, it makes sense.

    I’m just having trouble with the code I think. Here’s what I have:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    ego = require "ego"
    saveFile = ego.saveFile
    loadFile = ego.loadFile
    --Load highscore value from file. (It will initally be a string.)
    highscore = loadFile ("counter.txt")
    local function checkForFile ()
    if counter == "empty" then
    _G.counter = 1
    saveFile("counter.txt", _G.counter)
    end
    end
    checkForFile()
    print ("Counter is", _G.counter)

    And then, in my scene that should add 1 to global counter:

    1
    2
    3
    _G.counter = _G.counter + 1
    print(_G.counter)
    saveFile("counter.txt", _G.counter)

    Is that right? Cause in terminal, my first counter is nil instead of 1. I’m not sure where I got it wrong!
    Thanks a lot

  16. The cave is getting more and more cave-like by the day ;)

  17. Peach is hiding in the FTW cave

  18. Thanks :)

    In the scene do the checkForFile I have in the sample and if it doesn’t exist save it with value of 1. (1 because if you’re doing it in the scene you know they have gotten there once already.)

    Then if you check and it DOES exist then save it with the value you loaded (using tonumber()) + 1.

    Make sense?

  19. Hey Peach, nice work!

    I’m trying to save the number of times the user reached one specific scene. When he reaches the third time, I’ll request an in-app for more. How do I save it without displaying the counter into a score?

  20. That’s a great game, Jetpack Joyride :)

    I do plan on sorting out more Ego tutes soon, I’ve just been a little swamped. (I really need to manage my time better – that’s a work in progress, heh.)

    Thanks for the kind words – really appreciate feedback. (All the better when it’s positive ;))

  21. Thanks Peach! You’re awesome! More tuts for Ego would be great; level unlock/lock; music on/off; missions (to replicate local achievements. I got completely mesmerized by Jetpack Joyride and having local achievements would be “killer” :P

    I know you had code posted on the corona forums, but your tutorials are so awesome. I recommend your site for it all the time. Thanks once more.

  22. Haha, awesome – love Deniro!

    Glad I was able to assist :)

  23. Ah, of course… as great robert deniro would say… “you… you…”

    http://www.youtube.com/watch?v=ravi4YtUTxo&t=0m13s

    … you saw that I was trying to do something, and you figured that out, that’s why you are who you are”

    :) :)

    PS. I wasn’t gonna include the other quote from 0:52

  24. Hey Max,

    That is because this is set to save on exit, so it doesn’t save until then. You could call the save function when the player dies or whatnot, that would mean it should show fine in the next scene/screen.

    Make sense?

  25. Thanks for the above. I got it 99% working. During the game play the score gets updated. I then save it against/to a highscore.txt file, but even though the score saves that value doesn’t show on the next screen – it shows previous highscore (or 0) if that’s a first game. Relaunching the simulator then updates the score and shows the correct high score.

  26. So, the full phrase is …. what? I just woke up, cut me some slack ;)

  27. Yep yep. I love to cross reference and compile information.

    MCMMFT9DM

    The CM is a new addition “Cyber Monkeys” they are the nemesis of the MM’s.

    good day.

    ng

  28. Haha, I wrote two – that one as you can was based on what I made for you. (Difference is that one is plug and play because it wasn’t via email.)

    Thanks for digging up that link, I didn’t have it to hand and may be useful for people who see the post until I turn it into a proper tutorial. :)

  29. You wrote a sample for someone? Hmmmmmmm I wonder who that could be :)

  30. I actually wrote a sample for someone on the forum for level locking/unlocking – I’ll try to clean it up a bit and post it in the next few days. (It’s easy though, you save the highest completed level to a file just like you do with the highscore, then when loading level icons base that on what is unlocked already.)

    Music on/off would be very easy, just save one value :)

  31. Very much appreciated! I’m going to play with it today after work. Thanks :)

    Would it be just as easy to implement unlocking/locking levels with ego, as well as have a music on/off type of scenario?

    Peach! Thanks again!

  32. Wow ! I never thought it would have been so easy to load a file. Thanks to this “ego” library ! Good Job! As Always !

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Notify me of followup comments via e-mail. You can also subscribe without commenting.