当前位置:  开发笔记 > IOS > 正文

请求GKStateMachine的简单示例?

如何解决《请求GKStateMachine的简单示例?》经验,为你挑选了1个好方法。

我一直在为Swift研究Apple的状态机,并找到了几个例子,但是没有一个真的死了.

有人可以在Swift中掀起一个超级简单的GKStateMachine,可能有两个状态,最好是在一个Swift文件中?谢谢!



1> vacawama..:

以下是在美国工作的交通灯状态机的示例.红绿灯从green -> yellow -> red -> green.

在应用程序中,您可能会让didEnter(from:)例程更新屏幕图形,或允许其他actor移动.

import UIKit
import GameKit

class Green: GKState {

    override func isValidNextState(_ stateClass: AnyClass) -> Bool {
        return stateClass is Yellow.Type
    }

    override func didEnter(from previousState: GKState?) {
        print("Traffic light is green")
    }
}

class Yellow: GKState {
    override func isValidNextState(_ stateClass: AnyClass) -> Bool {
        return stateClass is Red.Type
    }

    override func didEnter(from previousState: GKState?) {
        print("Traffic light is yellow")
    }

}

class Red: GKState {
    override func isValidNextState(_ stateClass: AnyClass) -> Bool {
        return stateClass is Green.Type
    }

    override func didEnter(from previousState: GKState?) {
        print("Traffic light is red")
    }
}

class ViewController: UIViewController {

    var stateMachine: GKStateMachine?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Create the states            
        let green = Green()
        let yellow = Yellow()
        let red = Red()

        // Initialize the state machine            
        stateMachine = GKStateMachine(states: [green, yellow, red])

        // Try entering various states...            
        if stateMachine?.enter(Green.self) == false {
            print("failed to move to green")
        }
        if stateMachine?.enter(Red.self) == false {
            print("failed to move to red")
        }
        if stateMachine?.enter(Yellow.self) == false {
            print("failed to move to yellow")
        }
        if stateMachine?.enter(Green.self) == false {
            print("failed to move to green")
        }
        if stateMachine?.enter(Red.self) == false {
            print("failed to move to red")
        }

    }

}

输出:

Traffic light is green
failed to move to red
Traffic light is yellow
failed to move to green
Traffic light is red

推荐阅读
php
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有