Example #1
0
 @Override
 public Weapon requestNextMove(Player player) {
   Scanner scanner = new Scanner(System.in);
   Weapon nextMove = null;
   System.out.println(player.getDescription() + ", select next move:");
   Weapon[] weapons = Weapon.values();
   for (Weapon weapon : weapons) {
     StringBuilder promptBuilder = new StringBuilder();
     promptBuilder.append(weapon.name()).append(" : ").append(weapon.ordinal());
     System.out.println(promptBuilder.toString());
   }
   while (nextMove == null) {
     if (scanner.hasNextInt()) {
       int ordinal = scanner.nextInt();
       if (ordinal >= 0 && ordinal < weapons.length) {
         nextMove = weapons[ordinal];
       } else {
         System.out.println("Error please re-enter [0-" + (weapons.length - 1) + "]");
       }
     } else {
       scanner.next();
       System.out.println("Error please re-enter [0-" + (weapons.length - 1) + "]");
     }
   }
   return nextMove;
 }
  @Override
  public WeaponJudgingResult judgeWinningWeapon(Weapon weaponOne, Weapon weaponTwo) {
    validateNumberOfWeaponsOrFail();

    if (weaponOne.equals(weaponTwo)) {
      return WeaponJudgingResult.tie();
    } else {
      int numWeapons = Weapon.values().length;
      int mod = (numWeapons + weaponOne.ordinal() - weaponTwo.ordinal()) % numWeapons;
      if (mod % 2 == 1) {
        return new WeaponJudgingResult(weaponOne);
      } else {
        return new WeaponJudgingResult(weaponTwo);
      }
    }
  }
 private void validateNumberOfWeaponsOrFail() {
   if (Weapon.values().length < 3 || Weapon.values().length % 2 == 0) {
     throw new UnsupportedOperationException(
         "ModuloArithmeticWeaponJudge is only a valid strategy when there are at least 3 weapons and the number of weapons is an odd number");
   }
 }