-
-
Save zntfdr/c93fc2863ac0a847a90865564ca22121 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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