Setting Up HighScore in Swift and Sprite Kit using NSuserdefaults

前端 未结 2 1932
闹比i
闹比i 2021-02-06 18:41

I am building a swift game and a need to set up a highscore , i have been trying to figure out how to do it for a while. So please can you tell me how to search this library to

2条回答
  •  隐瞒了意图╮
    2021-02-06 19:28

    Create a new iOS project in Xcode by using the Single View Application template. Then, replace the content of ViewController.swift with the following code:

    import UIKit
    
    class ViewController: UIViewController {
        
        var generator = [6, 12, 8].generate()
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            let button = UIButton(type: .System)
            button.setTitle("Button", forState: .Normal)
            button.addTarget(self, action: "newScore", forControlEvents: .TouchUpInside)
            button.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview(button)
            
            // Auto layout code using anchors (requires iOS9+)
            let horizontalConstraint = button.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor)
            let verticalConstraint = button.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor)
            NSLayoutConstraint.activateConstraints([horizontalConstraint, verticalConstraint])
            
            // Print NSUserDefaults's highscore value when app is launched
            print("highscore:", NSUserDefaults.standardUserDefaults().integerForKey("highscore"))
        }
        
        func newScore() {
            guard let score = generator.next() else { return }
            print("current score:", score)
    
            //Check if score is higher than NSUserDefaults stored value and change NSUserDefaults stored value if it's true
            if score > NSUserDefaults.standardUserDefaults().integerForKey("highscore") {
                NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "highscore")
                NSUserDefaults.standardUserDefaults().synchronize()
            }
            
            print("highscore:", NSUserDefaults.standardUserDefaults().integerForKey("highscore"))
        }
        
    }
    

    Build and run the project on your iPhone or on the simulator. The Xcode console will print 0, which is the current value for NSUserDefaults.standardUserDefaults().integerForKey("highscore").

    Now, click on the button. This will set the value of score to 6 and, because 6 > 0, NSUserDefaults.standardUserDefaults().integerForKey("highscore") will get this new value.

    Click once again on the button. This will set the value of score to 12. You will immediately see in the console that NSUserDefaults.standardUserDefaults().integerForKey("highscore") gets this new value.

    Now, if you change the value of score to 8 by clicking on the button, you will see that NSUserDefaults.standardUserDefaults().integerForKey("highscore") still has a value of 12 because 8 < 12.

    If you rebuild your project and relaunch it, you will see that NSUserDefaults.standardUserDefaults().integerForKey("highscore") is persistent (its value is still 12 and has not been reset). Therefore, NSUserDefaults can be a perfect tool in order to store your players highest scores.


    Extra tip

    NSUserDefaults.standardUserDefaults().integerForKey("highscore") always return an Int (if you haven't set it by yourself, it will return 0, not nil). Thus, you dont need to / can't use optional binding with it. If you really want to deal with an optional value return, you will prefer NSUserDefaults.standardUserDefaults().objectForKey("highscore") as? Int.

提交回复
热议问题