swift - 请求 GKStateMachine 的简单示例?

标签 swift state-machine gamekit

我一直在研究 Apple 的 Swift 状态机并找到了几个示例,但没有一个真正简单到死。

有人可以在 Swift 中创建一个 super 简单的 GKStateMachine,也许有两个状态,最好是全部在一个 Swift 文件中吗?谢谢!

最佳答案

这是在美国工作的交通信号灯状态机示例。交通灯从 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

关于swift - 请求 GKStateMachine 的简单示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41656742/

相关文章:

iphone - iPhone上有蓝牙功能是否可以实现比P2P更多的功能

swift - 简单的 SpriteKit 游戏性能问题 - Swift

ios - 使用 "po"从控制台日志中的服务器响应中获取数据

uml - UML 状态机图中的线程?

c# - ValueTask<TResult> 和异步状态机

MacOS GameKit 排行榜无法加载,并出现 App "does not support leaderboards"错误

swift - Swift 中条件一致性的解决方法(原为 : Adding protocol to a constrained generic types)

ios - 即使正确设置,也隐藏在 ViewController 中的大标题

scala - 有限状态机和 FSM 间信令

iphone - GKSession 分配/释放/分配 = 泄漏和崩溃