如何在我的游戏中保存用户的等级?

How do I save the user's level on my game?

我有一个用 swift 编码的迷宫游戏,它不保存关卡。目前,当用户关闭应用程序时,不会保存任何内容,用户必须重新从关卡 1 开始玩游戏。每个关卡都有不同的 .swift 和 .sks 文件,所以我不确定如何在 classes/files 中保存关卡数据。

我曾尝试使用 UserDefaults,但是,我不确定如何将 "file path" 保存到我的级别。我知道我需要在我的 AppDelegate 中实现一些东西(使用 applicationWillTerminate 或 applicationDidEnterBackground 函数),但是,我不确定我需要在场景中放置什么代码(如果有的话)来保存这些数据。我以前没有处理过保存用户数据,所以非常感谢帮助!

import SpriteKit
import GameplayKit
import CoreMotion
import SceneKit
import UIKit

class GameScene: SKScene, SKPhysicsContactDelegate {

let gameScene = SKScene()

var button: SKNode! = nil
var playerSprite = SKSpriteNode()
var nextNode = SKSpriteNode()

lazy var countdownLabel: SKLabelNode = {
    var label = SKLabelNode(fontNamed: "Helvetica")
    label.horizontalAlignmentMode = .center
    label.verticalAlignmentMode = .center
    label.color = UIColor.red
    label.text = "\(counter)"
    return label
}()

var counter = 30
var counterTimer = Timer()
var counterStartValue = 30

let motionManager = CMMotionManager()

override func didMove(to view: SKView) {

    self.scene?.scaleMode = SKSceneScaleMode.aspectFit

    button = SKSpriteNode(imageNamed: "redoButton")
    button.position = CGPoint(x: 350, y: 585);
    self.addChild(button)

    countdownLabel.position = CGPoint(x: 0.5, y: 0.5)
    addChild(countdownLabel)

    counter = counterStartValue
    runTimer()

    self.physicsWorld.contactDelegate = self

    playerSprite = self.childNode(withName: "playerSprite") as! SKSpriteNode
    nextNode = self.childNode(withName: "nextNode") as! SKSpriteNode

    motionManager.startAccelerometerUpdates()
    motionManager.accelerometerUpdateInterval = 0.1
    motionManager.startAccelerometerUpdates(to: OperationQueue.main) {
        (data,error) in

        self.physicsWorld.gravity = CGVector(dx: CGFloat((data?.acceleration.x)!) * 10, dy: CGFloat((data?.acceleration.y)!) * 10)
    }
}

func didBegin(_ contact: SKPhysicsContact) {
    let bodyA = contact.bodyA
    let bodyB = contact.bodyB

    if bodyA.categoryBitMask == 1 && bodyB.categoryBitMask == 2 || bodyA.categoryBitMask == 2 && bodyB.categoryBitMask == 1{

        playerSprite.removeFromParent()
        nextNode.removeFromParent()
        self.removeFromParent()
        let transition = SKTransition.fade(withDuration: 0.5)
        let gameScene2 = GameScene2(fileNamed: "GameScene2")
        gameScene2!.scaleMode = SKSceneScaleMode.aspectFit
        self.view?.presentScene(gameScene2!, transition: transition)

    }
}


func runTimer() {
    counterTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(decrementCounter), userInfo: nil, repeats: true)
    }


@objc func decrementCounter() {
    counter -= 1
    countdownLabel.text = "\(counter)"

    if countdownLabel.text! < "0" as String {
        countdownLabel.text = "Game Over"
        playerSprite.removeFromParent()
        nextNode.removeFromParent()


    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

    if let touch = touches.first {
        if touch.view == self.button {
            print("Yay!!!")

        } else {

            playerSprite.isHidden = false
            nextNode.isHidden = false

            let gameScene = GameScene(fileNamed: "GameScene")
            gameScene!.scaleMode = SKSceneScaleMode.aspectFit
            let transition = SKTransition.fade(withDuration: 0.5)
            self.view?.presentScene(gameScene!, transition: transition)
        }

    }
}

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered

}

}

用字符串保存

UserDefaults.standard.set(StateOftheGame, forKey: "levelPass")

然后在应用程序委托上检查用户是否在游戏开始时 'passLevel' 在

didFinishLaunchingWithOptions -> add function passLevel()

func passLevel() {
        if UserDefaults.standard.value(forKey: "levelPass") != nil
        {
            let VC = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "YOURVIEWCONTROLLERWITHSAVESTATE")
            let navVC = UINavigationController(rootViewController: VC)
            let share = UIApplication.shared.delegate as? AppDelegate
            share?.window?.rootViewController = navVC
            share?.window?.makeKeyAndVisible()
        }


    }