Too many 'if' statements?

前端 未结 26 1147
天涯浪人
天涯浪人 2020-11-30 16:24

The following code does work how I need it to, but it\'s ugly, excessive or a number of other things. I\'ve looked at formulas and attempted to write a few solutions, but I

26条回答
  •  爱一瞬间的悲伤
    2020-11-30 16:48

    I don't like any of the solutions presented except for JAB's. None of the others make it easy to read the code and understand what is being computed.

    Here's how I would write this code -- I only know C#, not Java, but you get the picture:

    const bool t = true;
    const bool f = false;
    static readonly bool[,] attackResult = {
        { f, f, t, f }, 
        { f, f, f, t },
        { f, t, t, t },
        { t, f, t, t }
    };
    [Flags] enum HitResult 
    { 
        Neither = 0,
        PlayerOne = 1,
        PlayerTwo = 2,
        Both = PlayerOne | PlayerTwo
    }
    static HitResult ResolveAttack(int one, int two)
    {
        return 
            (attackResult[one, two] ? HitResult.PlayerOne : HitResult.Neither) | 
            (attackResult[two, one] ? HitResult.PlayerTwo : HitResult.Neither);
    }    
    

    Now it is much more clear what is being computed here: this emphasizes that we are computing who gets hit by what attack, and returning both results.

    However this could be even better; that Boolean array is somewhat opaque. I like the table lookup approach but I would be inclined to write it in such a way that made it clear what the intended game semantics were. That is, rather than "an attack of zero and a defense of one results in no hit", instead find a way to make the code more clearly imply "a low kick attack and a low block defense results in no hit". Make the code reflect the business logic of the game.

提交回复
热议问题