官术网_书友最值得收藏!

Saving a high score using LocalStorage

For a game like this where users are constantly driven to improve their score, it goes without saying that you need to store the user's best score persistently. Even though this game is running in a browser, we can still store data persistently. To accomplish this, we make use of HTML5 LocalStorage. Cocos2d-html5 provides a wrapper, although it is just as easy accessing LocalStorage with the window.localStorage.setItem or window.localStorage.getItem command.

HTML5 LocalStorage stores data in key/value pairs and a web page can only access data stored by itself. Thus our game's data is safe with the browser. This data has no expiry date and will not be destroyed even if the browser is closed. The only exception is if the user chooses to clear the browser's cache. Data is not persistent if the user chooses to browse in private or incognito mode.

We shall store our high-score data with a key specified by the HIGHSCORE_KEY variable defined at the top of gameworld.js. When the main menu is displayed, we check to see whether data exists for HIGHSCORE_KEY. The code is as follows:

// set default value for high score
// this will be executed only the first time the game is launched
// local storage stores data persistently
if(sys.localStorage.getItem(HIGHSCORE_KEY) == null)
sys.localStorage.setItem(HIGHSCORE_KEY, "0");

The getItem function returns null if no such data is available. Thus, we store a default high-score value of 0. Subsequently, if a new high score is achieved, it must be stored in a similar fashion. This is done in the showGameOverPopup function in GameWorld:

// fetch old high score from browser's local storage
var oldHighScore = parseInt(sys.localStorage.getItem(HIGHSCORE_KEY));

var highScoreLabel = cc.LabelTTF.create("Your Best:" + oldHighScore, "Comic Sans MS", 60);
highScoreLabel.setPosition(cc.p(this.screenSize.width*0.5, this.screenSize.height*0.5));
this.popup.addChild(highScoreLabel);

// check if new high score has been achieved
if(this.score > oldHighScore)
{
  // save the new high score
  sys.localStorage.setItem(HIGHSCORE_KEY, this.score+"");

  // animate the button suggesting that a new high score has been achieved
  highScoreLabel.runAction(cc.Sequence.create(cc.DelayTime.create(1),
  cc.EaseSineIn.create(cc.ScaleTo.create(0.25, 1.1)),
  cc.CallFunc.create( function(nodeExecutingAction, data){ nodeExecutingAction.setString("Your Best:" + this.score); }, this ),
  cc.EaseSineOut.create(cc.ScaleTo.create(0.25, 1))));
}
主站蜘蛛池模板: 威宁| 高尔夫| 长丰县| 长泰县| 承德市| 汶上县| 镇巴县| 苏尼特左旗| 延安市| 新干县| 张家界市| 杂多县| 哈巴河县| 汾西县| 甘孜| 南丰县| 恩施市| 望城县| 潍坊市| 南安市| 巨鹿县| 根河市| 石河子市| 壤塘县| 封丘县| 托克托县| 林芝县| 年辖:市辖区| 连山| 庄浪县| 扶沟县| 呼伦贝尔市| 尼勒克县| 琼中| 岳阳县| 乌拉特前旗| 龙胜| 惠来县| 北川| 夏邑县| 丰县|