0
我想在Swift中編碼A * Pathfinding。字典字符串等效問題
在這一點上,我在檢索我的封閉列表的G-Costs時遇到了一個問題。
此問題是,當我嘗試搜索詞典中的條目時,即使我相信我正在輸入正確的鍵,也會返回零。
這裏是相關的代碼(注意:字典是字符串:Int格式,因爲它不需要CGPoints)。
print("\(closedList["\(currentPos)"])")
print("\(currentPosString)")
print("\(closedList)")
GCost = GCost + (Int)(closedList["\(currentPosString)"]!)
CurrentPosString是一個字符串,CurrentPos是一個CGPoint(我都試過)。
這裏是從這段代碼中讀出的(我省略了很多代碼)。
零
4,4
[ 「4.0,4.0」:0]
(最後一行返回一個錯誤由於無)。
我的問題是我如何使'closedList [currentPosString]'具有正確的格式來成功訪問條目並返回0?
代碼生成closedPosString:
closedList["\(currentBest)"] = openList["\(currentBest)"]
openList["\(currentBest)"] = nil
openListOrder["\(currentBest)"] = nil
for i in 0 ..< mapTerrain.numberOfColumns{
for j in 0 ..< mapTerrain.numberOfRows{
if currentBest == "\(i), \(j)"{
currentPos = CGPoint(x: i, y: j)
currentPosString = "\(i), \(j)"
closedList["\(currentPos)"] = closedList[currentBest!]
print("\(closedList["\(currentPos)"])")
print("a") //not printing for some reason
foundNextNewPos = true
}
if foundNextNewPos == true{
break
}
}
if foundNextNewPos == true{
break
}
}
試圖用這個代碼重修,但仍打破了:currentBest的
currentPosString = currentBest!
currentBest = nil
代:
for key in openList.keys{
let tester = openList["\(key)"] //find way to not get a nil later
//print("\(openList["\(currentBest)"]!)") //gives nil
if key == "\(endPoint)"{
currentBest = key
foundEnd = true
break
}else if openList["\(currentBest)"] == nil{
currentBest = key
}else if tester! < openList["\(currentBest)"]!{
currentBest = key
} else if tester == openList["\(currentBest)"]{
if openListOrder["\(key)"]! > openListOrder["\(currentBest)"]!{
currentBest = key
}
}
}
你'currentPosString'的值爲 「4,4」,而你的字典使用字符串鍵是 「4.0,4.0」。顯然這兩個字符串是不相同的。你如何生成「currentPosString」。 –
使用[NSStringFromCGPoint](https://developer.apple.com/reference/uikit/1624504-nsstringfromcgpoint)將點轉換爲字符串作爲字典鍵使用 –
我現在沒有我的代碼,並且會得到回到你週一(因爲我想我知道我做了什麼,但我意識到可能有一個大問題,它不會選擇正確的座標,但不會導致此錯誤) –