我正在将游戏项目的代码从 Python 移植到 C#。现在我在翻译一段特定的代码时遇到了麻烦,其中游戏检查两艘 spaceship 是否彼此友好或敌对。派系通过整数来标识。使用敌对或友好派系编号列表。
检查敌意或友好的函数是(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# 一定有一个同样简单的解决方案吗?
最佳答案
我认为你可以做这样的事情:
Dictionary<int,int[]> hostileFactions = new Dictionary<int,int[]>(){
{1,new[]{5}}, {2,new[]{4,5}}
};
public void isHostile(int ownF, int oppF) {
return hostileFactions[ownF].Contains(oppF)
}
关于c# - 将列表创建的字典从 Python 转换为 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14149082/