简体   繁体   中英

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.

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

This way save some code and avoid all those switch. You even could have your actions in other classes

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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