Skip to content

Instantly share code, notes, and snippets.

@zntfdr zntfdr/gamekitPath.swift Secret
Last active Mar 16, 2019

Embed
What would you like to do?
import GameplayKit
let myGraph = GKGraph()
class MyNode: GKGraphNode {
let name: String
var travelCost: [GKGraphNode: Float] = [:]
init(name: String) {
self.name = name
super.init()
}
required init?(coder aDecoder: NSCoder) {
self.name = ""
super.init()
}
override func cost(to node: GKGraphNode) -> Float {
return travelCost[node] ?? 0
}
func addConnection(to node: GKGraphNode, bidirectional: Bool = true, weight: Float) {
self.addConnections(to: [node], bidirectional: bidirectional)
travelCost[node] = weight
guard bidirectional else { return }
(node as? MyNode)?.travelCost[self] = weight
}
}
func print(_ path: [GKGraphNode]) {
path.flatMap({ $0 as? MyNode}).forEach { node in
print(node.name)
}
}
func printCost(for path: [GKGraphNode]) {
var total: Float = 0
for i in 0..<(path.count-1) {
total += path[i].cost(to: path[i+1])
}
print(total)
}
let nodeA = MyNode(name: "A")
let nodeB = MyNode(name: "B")
let nodeC = MyNode(name: "C")
let nodeD = MyNode(name: "D")
myGraph.add([nodeA, nodeB, nodeC, nodeD])
nodeA.addConnection(to: nodeB, weight: 1.1)
nodeB.addConnection(to: nodeC, weight: 0.1)
nodeC.addConnection(to: nodeD, weight: 1.3)
var path = myGraph.findPath(from: nodeA, to: nodeD)
print(path)
printCost(for: path)
let nodeS = MyNode(name: "S")
nodeS.addConnection(to: nodeA, weight: 0)
nodeS.addConnection(to: nodeD, weight: 1.5)
path = myGraph.findPath(from: nodeA, to: nodeD)
print(path)
printCost(for: path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.