gpt4 book ai didi

swift - 请求 GKStateMachine 的简单示例?

转载 作者:搜寻专家 更新时间:2023-10-30 22:05:25 25 4
gpt4 key购买 nike

我一直在研究 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com