Too many 'if' statements?

前端 未结 26 1180
天涯浪人
天涯浪人 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:44

    Here's a fairly concise version, similar to JAB's response. This utilises a map to store which moves triumph over others.

    public enum Result {
      P1Win, P2Win, BothWin, NeitherWin;
    }
    
    public enum Move {
      BLOCK_HIGH, BLOCK_LOW, ATTACK_HIGH, ATTACK_LOW;
    
      static final Map> beats = new EnumMap>(
          Move.class);
    
      static {
        beats.put(BLOCK_HIGH, new ArrayList());
        beats.put(BLOCK_LOW, new ArrayList());
        beats.put(ATTACK_HIGH, Arrays.asList(ATTACK_LOW, BLOCK_LOW));
        beats.put(ATTACK_LOW, Arrays.asList(ATTACK_HIGH, BLOCK_HIGH));
      }
    
      public static Result compare(Move p1Move, Move p2Move) {
        boolean p1Wins = beats.get(p1Move).contains(p2Move);
        boolean p2Wins = beats.get(p2Move).contains(p1Move);
    
        if (p1Wins) {
          return (p2Wins) ? Result.BothWin : Result.P1Win;
        }
        if (p2Wins) {
          return (p1Wins) ? Result.BothWin : Result.P2Win;
        }
    
        return Result.NeitherWin;
      }
    } 
    

    Example:

    System.out.println(Move.compare(Move.ATTACK_HIGH, Move.BLOCK_LOW));
    

    Prints:

    P1Win
    

提交回复
热议问题