c# - 将列表创建的字典从 Python 转换为 C#

标签 c# python list dictionary

我正在将游戏项目的代码从 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/

相关文章:

c# - 使用 Facebook C# SDK 在登陆页面上获取 AccessToken

c# - 将单个对象插入 json 文件而不重写整个文件

c# - 使用聚合连接 linq 将结果放入 POCO

python - python脚本中的多处理函数

list - 仅删除唯一元素

java - 具有抽象泛型和集合的 JPA 单表继承

c# - 我必须在终结器中删除 eventHandlers 吗?

python - 如何使用 Python 2.7(可能还有 pyserial)在 Linux 中检查串口是否已经打开(由另一个进程打开)?

python - 为什么 tSNE 学习率这么大?

python - 您将如何对路由器接口(interface)列表进行排序?