简体   繁体   English

C#中的组合生成器

[英]Combination generator in C#

I'm creating a game in which fight is based on combination system. 我正在创建一个基于组合系统的战斗游戏。 You've got to pick 2 out of 5 randomly generated actions like weak attack, block or dodge etc. These 2 actions you picked generate combo with diffrent results. 您必须从5个随机生成的动作(例如弱攻击,格挡或躲闪等)中选择2个。您选择的这2个动作会生成具有不同结果的组合。

I'm working on algorythm that performs these actions and I'm wondering, if there is any better way to do so other than using switch cases. 我正在研究执行这些操作的算法,我想知道是否有比使用切换用例更好的方法了。

By now i got something like this: 现在,我得到了这样的东西:

void comboEffect(int firstAction, int secondAction) 
// weak attack = 1; strong attack = 2 etc
{
    switch (firstAction)
    {
        case 1:
             switch (secondAction)
             {
                   case 1: 
                   // execute 11 combo (weak attack + weak attack)
                   break;

                   case 2:
                   // execute 12 combo (weak attack + strong attack)
                   break;

                   ... etc
            }
        break;

        case 2:
             switch (second action)
             {
                   case 1:
                   // execute 21 combo
                   ... etc
}

You could do something like this 你可以做这样的事情

class ActionGen
{
    private readonly Dictionary<Tuple<int,int>, Action> _actionDictionary = new Dictionary<Tuple<int, int>, Action>();

    public ActionGen()
    {
        _actionDictionary.Add(Tuple.Create(1, 1), () => Console.WriteLine("Action 1, 1"));
        _actionDictionary.Add(Tuple.Create(1, 2), () => Console.WriteLine("Action 1, 2"));
        _actionDictionary.Add(Tuple.Create(2, 1), () => Console.WriteLine("Action 2, 1"));
        _actionDictionary.Add(Tuple.Create(2, 2), () => Console.WriteLine("Action 2, 2"));
    }

    public void ExecuteAction(Tuple<int,int> inputForAction)
    {
        if (_actionDictionary.ContainsKey(inputForAction))
            _actionDictionary[inputForAction]();
        else Console.WriteLine("Invalid action");
    }
}

And to test it 并进行测试

static void Main(string[] args)
    {
        var actionGen = new ActionGen();
        actionGen.ExecuteAction(Tuple.Create(1, 1));
        actionGen.ExecuteAction(Tuple.Create(1, 2));
        actionGen.ExecuteAction(Tuple.Create(2, 1));
        actionGen.ExecuteAction(Tuple.Create(2, 2));
        actionGen.ExecuteAction(Tuple.Create(3, 1));
        Console.ReadLine();
    }

EDIT> The output is 编辑>输出是

Action 1,1 Action 1,2 Action 2,1 Action 2,2 Invalid Action 行动1,1行动1,2行动2,1行动2,2无效行动

This way save some code and avoid all those switch. 这样可以节省一些代码并避免所有这些切换。 You even could have your actions in other classes 您甚至可以在其他课程中进行动作

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM