我將遊戲項目的代碼從Python移植到C#。現在我無法翻譯一段特定的代碼,遊戲會檢查兩艘太空飛船是友好的還是敵對的。派系通過整數進行識別。使用敵對或友好派系號碼列表。將列表創建的字典從Python轉換爲C#
用於檢查敵意或friendlyness功能是(Python)的:分別
def is_hostile_faction(ownF, oppF):
hostile_factions = { 1:[5], 2:[4,5], 3:[5], 4:[2,5], 5:[1,2,3,4], 6:[5], 7:[8,9,10], 8:[5,7,9,10], 9:[7,8,10], 10:[7,8,9]}
if oppF in hostile_factions[ownF]:
return True
else:
return False
和
def is_allied_faction(ownF, oppF):
allied_factions = { 1:[1,2], 2:[1,2,3], 3:[3], 4:[4], 5:[5], 6:[1,2,3,6], 7:[7], 8:[8], 9:[9], 10:[10] }
if oppF in allied_factions[ownF]:
return True
else:
return False
。到目前爲止,這麼容易。我將如何重新在C#中相同的功能,而無需編寫像醜陋的代碼:
List<int> faction1hostiles = new List<int> {5};
List<int> faction2hostiles = new List<int> {4,5};
// etc
Dictionary<int,List<int>> hostileFactions = new Dictionary<int,List<int>();
hostileFactions.Add(faction1hostiles);
hostileFactions.Add(faction2hostiles);
// etc
public void isHostile(int ownF, int oppF) {
if (hostileFactions[ownF].Contains(oppF)) {
return true; }
else { return false; }
}
// same for friendly factions
原代碼的Python(Panda3D的框架),目標代碼是C#(Unity3D框架)。考慮到Python代碼的簡單性,在數據結構的即時創建中,C#必須有一個同樣簡單的解決方案?
試圖* *轉換代碼通常是一個可怕的想法 - 適合一種語言並不一定適合其他的解決方案。最好簡單地用其他語言重新實現。 –
完全同意@Lattyware –