编辑scripts/Game.ts
,添加lblScoreNow
和lblScoreBest
这两个属性。
private rootNode: cc.Node = null
@property(cc.Label)
private lblScoreNow: cc.Label = null
@property(cc.Label)
private lblScoreBest: cc.Label = null
拖拽节点到对应属性上。
编辑scripts/Game.ts
,添加KEY_SCORE_BEST
常量用于储存最高分数的 key。
const MOVE_DISTANCE = 10
const KEY_SCORE_BEST = 'KEY_SCORE_BEST'
添加_scoreNow
和_scoreBest
这两个属性记录当前分数和最高分数。
private _canTouchMove = false
private _scoreNow: number = 0
private _scoreBest: number
添加addScore
和showScore
这两个方法。
private addScore(score: number) {
this._scoreNow += score
if (this._scoreNow > this._scoreBest) {
this._scoreBest = this._scoreNow
cc.sys.localStorage.setItem(KEY_SCORE_BEST, JSON.stringify(this._scoreBest))
}
this.showScore()
}
private showScore() {
this.lblScoreNow.string = this._scoreNow.toString()
this.lblScoreBest.string = this._scoreBest.toString()
}
修改init
方法,在尾部添加获取最高分数并显示相关分数的代码。
this._scoreBest = parseInt(cc.sys.localStorage.getItem(KEY_SCORE_BEST) ?? '0')
this.showScore()
修改move
方法,在数字合并的地方添加调用addScore
方法。
this.addScore(num * 2)
lastGrid.num = num * 2
grid.reset()
运行程序,在合并数字后会更新显示当前分数了,并且重新运行程序时也会显示历史最高分数。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。