我正在开发一款游戏并且有一些问题可以存储有史以来最好的分数。 我现在正在使用CoreData,但每次运行游戏时,分数都会与Int(17)进行比较并显示较高的分数。为此,数字17可能是我在运行游戏时获得的第一个分数。即当时不会存储最高分。
代码看起来像这样。 谢谢!
// Decide if the game ends
var actionArray: NSMutableArray = NSMutableArray()
actionArray.addObject(SKAction.runBlock({
var transition:SKTransition = SKTransition.flipHorizontalWithDuration(0.5)
//Use CoreData
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext
var request = NSFetchRequest(entityName:"Score")
request.returnsObjectsAsFaults=false
request.predicate = NSPredicate(format:"fetchScore = %@","fetchScore")
var results:NSArray = context.executeFetchRequest(request, error: nil)
if (results.count > 0) {
var compareBest:Int = 0
var res = results[0] as NSManagedObject
compareBest = res.valueForKey("bestScore") as Int
if compareBest < self.score {
var newBestScore = NSEntityDescription.insertNewObjectForEntityForName("Score", inManagedObjectContext: context) as NSManagedObject
newBestScore.setValue("fetchScore", forKey:"fetchScore")
newBestScore.setValue(Int(self.score), forKey: "bestScore")
context.save(nil)
self.bestScore = self.score
}else{
self.bestScore = compareBest
}
}else{
var newBestScore = NSEntityDescription.insertNewObjectForEntityForName("Score", inManagedObjectContext: context) as NSManagedObject
newBestScore.setValue(Int(self.score), forKey: "bestScore")
newBestScore.setValue("fetchScore", forKey:"fetchScore")
context.save(nil)
self.bestScore = self.score
}
var gameOverScene:SKScene = GameOverScene(size: self.size, won: false, scored: self.score, best: self.bestScore)
self.view.presentScene(gameOverScene,transition:transition)
}))