public static void loadClasses(ConfigurationSection cs) {
   if (cs == null) {
     Log.info(BattleArena.getPName() + " has no classes");
     return;
   }
   StringBuilder sb = new StringBuilder();
   Set<String> keys = cs.getKeys(false);
   boolean first = true;
   for (String className : keys) {
     ArenaClass ac = parseArenaClass(cs.getConfigurationSection(className));
     if (ac == null) continue;
     if (first) first = false;
     else sb.append(", ");
     sb.append(ac.getName());
     ArenaClassController.addClass(ac);
   }
   if (first) {
     Log.info(
         BattleArena.getPName()
             + " no predefined classes found. inside of "
             + cs.getCurrentPath());
   } else {
     Log.info(BattleArena.getPName() + " registering classes: " + sb.toString());
   }
 }
Example #2
0
 // Battle Arena Anti-Cheat
 @EventHandler(priority = EventPriority.MONITOR)
 public void stopOutsideDamage(EntityDamageByEntityEvent e) {
   if (e.getEntity() instanceof Player) {
     Player damaged = (Player) e.getEntity();
     if (e.getDamager() instanceof Player) {
       Player damager = (Player) e.getDamager();
       if (!BattleArena.inArena(damager)) {
         if (BattleArena.inArena(damaged)) {
           e.setCancelled(true);
           Bukkit.broadcastMessage("CANCELLED!");
         }
       }
     }
   }
 }
  public Duel accept(ArenaPlayer player) {
    Duel d = getChallengedDuel(player);
    if (d != null) {
      d.accept(player);
      if (d.isReady()) {
        /// Do a final check to see if they have completed all the duel options
        if (!checkWager(d)) return null;

        ArenaTeam t = d.getChallengerTeam();
        ArenaTeam t2 = d.makeChallengedTeam();
        List<ArenaTeam> teams = new ArrayList<ArenaTeam>();
        teams.add(t);
        teams.add(t2);
        JoinOptions jo = new JoinOptions();
        jo.setMatchParams(d.getMatchParams());
        jo.setJoinLocation(player.getLocation());
        if (d.getOptions().hasOption(DuelOption.ARENA)) {
          jo.setArena((Arena) d.getOptions().getOptionValue(DuelOption.ARENA));
        }
        Matchup m = new Matchup(d.getMatchParams(), teams, jo);
        m.addArenaListener(this);
        formingDuels.remove(d);
        ongoingDuels.put(m, d);
        MatchTeamQObject mo = new MatchTeamQObject(m);
        BattleArena.getBAController().addMatchup(mo);
      }
    }
    return d;
  }
 public boolean startRound() {
   /// trying to start when we havent created anything yet
   /// or event was canceled/closed
   if (round < 0 || state == EventState.CLOSED) {
     return false;
   }
   announceRound();
   Plugin plugin = BattleArena.getSelf();
   /// Section to start the match
   curTimer =
       plugin
           .getServer()
           .getScheduler()
           .scheduleSyncDelayedTask(
               plugin,
               new Runnable() {
                 public void run() {
                   Round tr = rounds.get(round);
                   for (Matchup m : tr.getMatchups()) {
                     ac.addMatchup(m);
                   }
                 }
               },
               (long) (timeBetweenRounds * 20L * Defaults.TICK_MULT));
   return true;
 }
  public void start() {
    System.out.println("Arena::onStart " + timedSpawns);
    if (timedSpawns != null && !timedSpawns.isEmpty()) {
      Plugin plugin = BattleArena.getSelf();
      /// Create our Q, with a descending Comparator
      spawnQ =
          new PriorityQueue<NextSpawn>(
              timedSpawns.size(),
              new Comparator<NextSpawn>() {
                public int compare(NextSpawn o1, NextSpawn o2) {
                  return (o1.timeToNext.compareTo(o2.timeToNext));
                }
              });
      /// TeamJoinResult our items into the Q
      ArrayList<NextSpawn> nextspawns = new ArrayList<NextSpawn>();
      for (TimedSpawn is : timedSpawns.values()) {
        //				System.out.println("itemSpawns = " + timedSpawns.size() + " " +
        // is.getFirstSpawnTime()+ "  ts=" + is);
        long tts = is.getFirstSpawnTime();
        if (tts == 0) is.spawn();
        NextSpawn ns = new NextSpawn(is, tts);
        spawnQ.add(ns);
        nextspawns.add(ns);
      }

      timerId =
          plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new SpawnNextEvent(0L));
    }
  }
 private static BaseSerializer getSerializer(String name) {
   BaseSerializer bs = new BaseSerializer();
   File dir = new File(BattleArena.getSelf().getDataFolder() + "/inventories/");
   if (!dir.exists()) {
     dir.mkdirs();
   }
   return bs.setConfig(dir.getPath() + "/" + name + ".yml") ? bs : null;
 }
  public void testQueue() {
    MatchParams mp = loadParams("Arena");
    Player p1 = new TestBukkitPlayer("p1");
    Player p2 = new TestBukkitPlayer("p2");
    ArenaPlayer ap1 = BattleArena.toArenaPlayer(p1);
    ArenaPlayer ap2 = BattleArena.toArenaPlayer(p2);
    String[] args = new String[] {""};

    BAExecutor exec = new BAExecutor();
    exec.join(ap1, mp, args);
    exec.join(ap2, mp, args);
    for (MatchParams params : ParamController.getAllParams()) {
      System.out.println("param  =  " + params);
    }
    delay(50);
    assertTrue(bac.isInQue(ap1));
  }
Example #8
0
  public static ArenaTeam getTeam(Player player) {
    Hero hero = getHero(player);
    if (hero == null) return null;
    HeroParty party = hero.getParty();
    if (party == null) return null;
    ArenaTeam t = TeamFactory.createCompositeTeam();
    Hero leader = party.getLeader();
    if (leader != null) t.addPlayer(BattleArena.toArenaPlayer(leader.getPlayer()));

    Set<Hero> members = party.getMembers();
    if (members != null) {
      for (Hero h : members) {
        t.addPlayer(BattleArena.toArenaPlayer(h.getPlayer()));
      }
    }
    return t.size() > 0 ? t : null;
  }
Example #9
0
 public static void respawnClick(
     PlayerInteractEvent event, PlayerHolder am, Map<String, Integer> respawnTimer) {
   ArenaPlayer ap = BattleArena.toArenaPlayer(event.getPlayer());
   Integer id = respawnTimer.remove(ap.getName());
   Bukkit.getScheduler().cancelTask(id);
   Location loc =
       am.getSpawn(
           am.getTeam(ap).getIndex(),
           am.getParams().hasOptionAt(MatchState.ONSPAWN, TransitionOption.RANDOMRESPAWN));
   TeleportController.teleport(ap.getPlayer(), loc);
 }
Example #10
0
 @EventHandler
 public void openInventory(InventoryOpenEvent e) {
   if (BattleArena.inArena((Player) e.getPlayer())) {
     e.setCancelled(true);
   }
   List<Player> inProgress = ma.getArenaMaster().getAllPlayers();
   for (Player p2 : inProgress) {
     if (e.getPlayer() == p2) {
       e.setCancelled(true);
     }
   }
 }
  @ArenaEventHandler(suppressCastWarnings = true, priority = EventPriority.LOW)
  public void onEntityDamageEvent(EntityDamageEvent event) {
    if (!(event.getEntity() instanceof Player)) return;
    final TransitionOptions to = transitionOptions.getOptions(match.getMatchState());
    if (to == null) return;
    final PVPState pvp = to.getPVP();
    if (pvp == null) return;
    final ArenaPlayer target = BattleArena.toArenaPlayer((Player) event.getEntity());
    if (pvp == PVPState.INVINCIBLE) {
      /// all damage is cancelled
      target.setFireTicks(0);
      handler.setDamage(event, 0);
      event.setCancelled(true);
      return;
    }
    if (!(event instanceof EntityDamageByEntityEvent)) {
      return;
    }

    final Entity damagerEntity = ((EntityDamageByEntityEvent) event).getDamager();
    ArenaPlayer damager;
    switch (pvp) {
      case ON:
        ArenaTeam targetTeam = match.getTeam(target);
        if (targetTeam == null
            || !targetTeam.hasAliveMember(target)) // / We dont care about dead players
        return;
        damager = DmgDeathUtil.getPlayerCause(damagerEntity);
        if (damager == null) { // / damage from some source, its not pvp though. so we dont care
          return;
        }
        ArenaTeam t = match.getTeam(damager);
        if (t != null && t.hasMember(target)) { // / attacker is on the same team
          event.setCancelled(true);
        } else { /// different teams... lets make sure they can actually hit
          event.setCancelled(false);
        }
        break;
      case OFF:
        damager = DmgDeathUtil.getPlayerCause(damagerEntity);
        if (damager != null) { // / damage done from a player
          handler.setDamage(event, 0);
          event.setCancelled(true);
        }
        break;
      default:
        break;
    }
  }
Example #12
0
 @EventHandler
 public void stopArenaInteract(PlayerInteractEvent e) {
   if (e.getAction() == Action.RIGHT_CLICK_BLOCK) {
     Player p = e.getPlayer();
     if (BattleArena.inArena(p)) {
       e.setCancelled(true);
     }
     List<Player> inProgress = ma.getArenaMaster().getAllPlayers();
     for (Player p2 : inProgress) {
       if (p == p2) {
         e.setCancelled(true);
       }
     }
   }
 }
Example #13
0
  private void readyClick(PlayerInteractEvent event) {
    if (!Defaults.ENABLE_PLAYER_READY_BLOCK) return;
    final ArenaPlayer ap = BattleArena.toArenaPlayer(event.getPlayer());
    if (!isInWaitRoomState()) {
      return;
    }
    final Action action = event.getAction();
    if (action == Action.LEFT_CLICK_BLOCK) { // / Dont let them break the block
      event.setCancelled(true);
    }

    if (ap.isReady()) return;
    ap.setReady(true);
    MessageUtil.sendMessage(ap, "&2You ready yourself for the arena");
    callEvent(new ArenaPlayerReadyEvent(ap, true));
  }
 private void performMatchAction(ArenaPlayer player) {
   BAExecutor executor = BattleArena.getBAExecutor();
   String args[];
   switch (command) {
     case JOIN:
       args = new String[] {"join", options1};
       executor.join(player, mp, args, true);
       break;
     case LEAVE:
       args = new String[] {"leave", options1, options2};
       executor.leave(player, mp, true);
       break;
     case START:
       break;
   }
 }
Example #15
0
 public boolean matches(ArenaPlayer player, MatchParams mp) {
   if (mp.getTransitionOptions()
       .hasOptionAt(MatchState.PREREQS, TransitionOption.WITHINDISTANCE)) {
     Double distance =
         mp.getTransitionOptions().getOptions(MatchState.PREREQS).getWithinDistance();
     if (options.containsKey(DuelOption.ARENA)) {
       Arena arena = (Arena) options.get(DuelOption.ARENA);
       return arena.withinDistance(player.getLocation(), distance);
     } else {
       for (Arena arena : BattleArena.getBAController().getArenas(mp)) {
         if (arena.withinDistance(player.getLocation(), distance)) return true;
       }
       return false;
     }
   }
   return true;
 }
Example #16
0
 private void logInvocationError(Exception e, MethodWrapper mwrapper, Arguments newArgs) {
   System.err.println(
       "["
           + BattleArena.getNameAndVersion()
           + " Error] "
           + mwrapper.method
           + " : "
           + mwrapper.obj
           + "  : "
           + newArgs);
   if (newArgs != null && newArgs.args != null) {
     for (Object o : newArgs.args) System.err.println("[Error] object=" + o);
   }
   System.err.println("[Error] Cause=" + e.getCause());
   if (e.getCause() != null) {
     e.getCause().printStackTrace();
     Log.printStackTrace(e.getCause());
   }
   System.err.println("[Error] Trace Continued ");
   Log.printStackTrace(e);
 }
  public static void teleportOut(
      PlayerHolder am,
      ArenaTeam team,
      ArenaPlayer player,
      TransitionOptions mo,
      int teamIndex,
      boolean insideArena,
      boolean onlyInMatch,
      boolean wipeInventory) {
    MatchParams mp = am.getParams();
    Location loc = null;
    ArenaLocation src = player.getCurLocation();
    final LocationType type;
    if (mo.hasOption(TransitionOption.TELEPORTTO)) {
      loc = mo.getTeleportToLoc();
      type = LocationType.CUSTOM;
    } else {
      type = LocationType.HOME;
      loc = player.getOldLocation();
      /// TODO
      /// This is a bit of a kludge, sometimes we are "teleporting them out"
      /// when they are already out... so need to rethink how this can happen and should it
      if (loc == null && src.getType() == LocationType.HOME) {
        loc = src.getLocation();
      }
    }
    player.clearOldLocation();
    if (loc == null) {
      Log.err(
          BattleArena.getNameAndVersion()
              + " Teleporting to a null location!  teleportTo="
              + mo.hasOption(TransitionOption.TELEPORTTO));
    }

    ArenaLocation dest = new ArenaLocation(AbstractAreaContainer.HOMECONTAINER, loc, type);
    ArenaPlayerTeleportEvent apte =
        new ArenaPlayerTeleportEvent(
            am.getParams().getType(), player, team, src, dest, TeleportDirection.OUT);
    movePlayer(player, apte, mp);
  }
  @MCCommand(
      cmds = {"as", "addspawn"},
      selection = true,
      inGame = true,
      admin = true,
      min = 2,
      usage =
          "/aa addspawn <mob/item/block/spawnGroup> [buffs or effects] [number] [fs=first spawn time] [rt=respawn time] [trigger=<trigger type>]")
  public boolean arenaAddSpawn(Player sender, String[] args) {
    Long number = -1L;
    try {
      number = Long.parseLong(args[args.length - 1].toString());
    } catch (Exception e) {
      return MessageUtil.sendMessage(
          sender, "&cYou need to specify an index as the final value. &61-10000");
    }
    if (number == -1) {
      number = 1L;
    }
    if (number <= 0 || number > 10000) {
      return MessageUtil.sendMessage(
          sender, "&cYou need to specify an index within the range &61-10000");
    }

    Arena a = aac.getArena(sender);
    SpawnInstance spawn = parseSpawn(Arrays.copyOfRange(args, 0, args.length - 1));
    if (spawn == null) {
      return MessageUtil.sendMessage(sender, "Couldnt recognize spawn " + args[1]);
    }
    Location l = sender.getLocation();
    spawn.setLocation(l);
    TimedSpawn ts = new TimedSpawn(0, 30, 0, spawn);

    a.addTimedSpawn(number, ts);
    ac.updateArena(a);
    BattleArena.saveArenas();
    return MessageUtil.sendMessage(
        sender, "&6" + a.getName() + "&e now has spawn &6" + spawn + "&2  index=&4" + number);
  }
 @MCCommand(
     cmds = {"ds", "deletespawn"},
     selection = true,
     admin = true,
     usage = "/aa deleteSpawn <index>")
 public boolean arenaDeleteSpawn(CommandSender sender, Integer number) {
   if (number <= 0 || number > 10000) {
     return MessageUtil.sendMessage(
         sender, "&cYou need to specify an index within the range &61-10000");
   }
   Arena a = aac.getArena(sender);
   TimedSpawn ts = a.deleteTimedSpawn(new Long(number));
   if (ts != null) {
     ac.updateArena(a);
     BattleArena.saveArenas();
     return MessageUtil.sendMessage(
         sender,
         "&6" + a.getName() + "&e has deleted index=&4" + number + "&e that had spawn=" + ts);
   } else {
     return MessageUtil.sendMessage(sender, "&cThere was no spawn at that index");
   }
 }
  public static void saveInventory(final String name, final PInv pinv) {
    if (Defaults.NUM_INV_SAVES <= 0) {
      return;
    }
    Bukkit.getScheduler()
        .scheduleAsyncDelayedTask(
            BattleArena.getSelf(),
            new Runnable() {
              @Override
              public void run() {
                BaseSerializer serializer = getSerializer(name);
                if (serializer == null) return;
                Date now = new Date();
                String date =
                    DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(now);
                int curSection = serializer.config.getInt("curSection", 0);
                serializer.config.set("curSection", (curSection + 1) % Defaults.NUM_INV_SAVES);
                ConfigurationSection pcs = serializer.config.createSection(curSection + "");
                pcs.set("storedDate", date);
                List<String> stritems = new ArrayList<String>();
                for (ItemStack is : pinv.armor) {
                  if (is == null || is.getType() == Material.AIR) continue;
                  stritems.add(InventoryUtil.getItemString(is));
                }
                pcs.set("armor", stritems);

                stritems = new ArrayList<String>();
                for (ItemStack is : pinv.contents) {
                  if (is == null || is.getType() == Material.AIR) continue;
                  stritems.add(InventoryUtil.getItemString(is));
                }
                pcs.set("contents", stritems);
                serializer.save();
              }
            });
  }
Example #21
0
  @ArenaEventHandler(priority = EventPriority.HIGH)
  public void onPlayerRespawn(PlayerRespawnEvent event, final ArenaPlayer p) {
    if (Defaults.DEBUG_TRACE) MessageUtil.sendMessage(p, " -onPlayerRespawn  t=" + p.getTeam());

    if (isWon()) {
      return;
    }
    final TransitionOptions mo = tops.getOptions(MatchState.ONDEATH);

    if (mo == null) return;

    if (respawns) {
      final boolean randomRespawn = mo.randomRespawn();
      /// Lets cancel our death respawn timer
      Integer timer = deathTimer.get(p.getName());
      if (timer != null) {
        Bukkit.getScheduler().cancelTask(timer);
      }
      final Location loc;
      final ArenaTeam t = getTeam(p);
      if (mo.hasAnyOption(
          TransitionOption.TELEPORTLOBBY,
          TransitionOption.TELEPORTMAINLOBBY,
          TransitionOption.TELEPORTWAITROOM,
          TransitionOption.TELEPORTMAINWAITROOM)) {
        final int index = t.getIndex();
        if (mo.hasOption(TransitionOption.TELEPORTLOBBY)) {
          loc = RoomController.getLobbySpawn(index, getParams().getType(), randomRespawn);
        } else if (mo.hasOption(TransitionOption.TELEPORTMAINLOBBY)) {
          loc =
              RoomController.getLobbySpawn(
                  Defaults.MAIN_SPAWN, getParams().getType(), randomRespawn);
        } else if (mo.hasOption(TransitionOption.TELEPORTMAINWAITROOM)) {
          loc = this.getWaitRoomSpawn(Defaults.MAIN_SPAWN, randomRespawn);
        } else {
          loc = this.getWaitRoomSpawn(index, randomRespawn);
        }
        /// Should we respawn the player to the team spawn after a certain amount of time
        if (mo.hasOption(TransitionOption.RESPAWNTIME)) {
          int id =
              Bukkit.getScheduler()
                  .scheduleSyncDelayedTask(
                      BattleArena.getSelf(),
                      new Runnable() {
                        @Override
                        public void run() {
                          Integer id = respawnTimer.remove(p.getName());
                          Bukkit.getScheduler().cancelTask(id);
                          Location loc =
                              getTeamSpawn(
                                  index,
                                  tops.hasOptionAt(
                                      MatchState.ONSPAWN, TransitionOption.RANDOMRESPAWN));
                          TeleportController.teleport(p.getPlayer(), loc);
                        }
                      },
                      mo.getRespawnTime() * 20);
          respawnTimer.put(p.getName(), id);
        }
      } else {
        loc = getTeamSpawn(getTeam(p), randomRespawn);
      }

      event.setRespawnLocation(loc);
      /// For some reason, the player from onPlayerRespawn Event isnt the one in the main thread, so
      // we need to
      /// resync before doing any effects
      final Match am = this;
      Bukkit.getScheduler()
          .scheduleSyncDelayedTask(
              BattleArena.getSelf(),
              new Runnable() {
                public void run() {
                  ArenaTeam t = getTeam(p);
                  PerformTransition.transition(am, MatchState.ONDEATH, p, t, false);
                  PerformTransition.transition(am, MatchState.ONSPAWN, p, t, false);
                  if (respawnsWithClass) {
                    ArenaClass ac = null;
                    if (p.getPreferredClass() != null) {
                      ac = p.getPreferredClass();
                    } else if (p.getCurrentClass() != null) {
                      ac = p.getCurrentClass();
                    }
                    if (ac != null) {
                      ArenaClassController.giveClass(p, ac);
                    }
                  }
                  if (keepsInventory) {
                    psc.restoreMatchItems(p);
                  }
                  if (woolTeams) {
                    TeamUtil.setTeamHead(t.getIndex(), p);
                  }
                }
              });
    } else { /// This player is now out of the system now that we have given the ondeath effects
      Location l =
          tops.hasOptionAt(MatchState.ONLEAVE, TransitionOption.TELEPORTTO)
              ? tops.getOptions(MatchState.ONLEAVE).getTeleportToLoc()
              : oldlocs.get(p.getName());
      if (l != null) event.setRespawnLocation(l);
    }
  }
Example #22
0
  public static DuelOptions parseOptions(MatchParams params, ArenaPlayer challenger, String[] args)
      throws InvalidOptionException {
    DuelOptions dop = new DuelOptions();
    dop.options.putAll(defaultOptions.options);
    Map<DuelOption, Object> ops = dop.options;

    for (int i = 0; i < args.length; i++) {
      String op = args[i];
      Player p = ServerUtil.findPlayer(op);
      if (p != null) {
        if (!p.isOnline())
          throw new InvalidOptionException(
              "&cPlayer &6" + p.getDisplayName() + "&c is not online!");
        if (challenger != null && p.getName().equals(challenger.getName()))
          throw new InvalidOptionException("&cYou can't challenge yourself!");
        if (p.hasPermission(Permissions.DUEL_EXEMPT) && !Defaults.DUEL_CHALLENGE_ADMINS) {
          throw new InvalidOptionException("&cThis player can not be challenged!");
        }
        dop.challengedPlayers.add(BattleArena.toArenaPlayer(p));
        continue;
      }
      Object obj = null;

      DuelOption to = null;
      String val;
      if (op.contains("=")) {
        String[] split = op.split("=");
        op = split[0];
        val = split[1];
      } else {
        val = i + 1 < args.length ? args[i + 1] : null;
      }
      to = parseOp(op, val);
      switch (to) {
        case RATED:
          if (!Defaults.DUEL_ALLOW_RATED)
            throw new InvalidOptionException("&cRated formingDuels are not allowed!");
          break;
        default:
          break;
      }

      if (!to.needsValue) {
        ops.put(to, null);
        continue;
      }
      i++; /// another increment to get past the value
      switch (to) {
        case MONEY:
          Double money = null;
          try {
            money = Double.valueOf(val);
          } catch (Exception e) {
            throw new InvalidOptionException("&cmoney needs to be a number! Example: &6money=100");
          }
          if (!MoneyController.hasEconomy()) {
            if (challenger != null)
              MessageUtil.sendMessage(
                  challenger, "&cignoring duel option money as there is no economy!");
            Log.warn("[BA Error] ignoring duel option money as there is no economy!");
            continue;
          }
          obj = money;
          break;
        case ARENA:
          Arena a = BattleArena.getBAController().getArena(val);
          if (a == null) {
            throw new InvalidOptionException("&cCouldnt find the arena &6" + val);
          }
          if (params != null && !a.getArenaType().matches(params.getType())) {
            throw new InvalidOptionException("&cThe arena is used for a different type!");
          }
          obj = a;
        default:
          break;
      }
      ops.put(to, obj);
    }
    if (challenger != null && dop.challengedPlayers.isEmpty()) {
      throw new InvalidOptionException("&cYou need to challenge at least one player!");
    }
    return dop;
  }
Example #23
0
 public TournamentEvent(EventParams params) {
   super(params);
   oParms = params;
   Bukkit.getPluginManager().registerEvents(this, BattleArena.getSelf());
 }
  public static boolean alterArena(CommandSender sender, Arena arena, String[] args) {
    if (args.length < 3) {
      showAlterHelp(sender);
      //			sendMessage(sender,ChatColor.YELLOW+ "      or /arena alter MainArena spawnitem
      // <itemname>:<matchEndTime between spawn> ");
      return false;
    }
    BattleArenaController ac = BattleArena.getBAC();
    String arenaName = arena.getName();
    String changetype = args[2];
    String value = null;
    if (args.length > 3) value = args[3];
    String[] otherOptions = args.length > 4 ? Arrays.copyOfRange(args, 4, args.length) : null;
    if (Defaults.DEBUG)
      System.out.println("alterArena " + arenaName + ":" + changetype + ":" + value);

    boolean success = false;
    ChangeType ct = ChangeType.fromName(changetype);
    if (ct == null) {
      sendMessage(
          sender,
          ChatColor.RED
              + "Option: &6"
              + changetype
              + "&c does not exist. \n&cValid options are &6"
              + ChangeType.getValidList());
      showAlterHelp(sender);
      return false;
    }
    switch (ct) {
      case TEAMSIZE:
        success = changeTeamSize(sender, arena, ac, value);
        break;
      case NTEAMS:
        success = changeNTeams(sender, arena, ac, value);
        break;
      case TYPE:
        success = changeType(sender, arena, ac, value);
        break;
      case SPAWNLOC:
        success = changeSpawn(sender, arena, ac, changetype, value, otherOptions);
        break;
      case VLOC:
        success = changeVisitorSpawn(sender, arena, ac, changetype, value, otherOptions);
        break;
      case WAITROOM:
        success = changeWaitroomSpawn(sender, arena, ac, changetype, value, otherOptions);
        break;
      case ADDREGION:
        success = addWorldGuardRegion(sender, arena, ac, value);
        break;
      default:
        sendMessage(
            sender,
            ChatColor.RED
                + "Option: &6"
                + changetype
                + "&c does not exist. \n&cValid options are &6"
                + ChangeType.getValidList());
        break;
    }
    if (success) BattleArena.saveArenas();
    return success;
  }
 public SpawnController(Map<Long, TimedSpawn> spawnGroups) {
   this.timedSpawns = spawnGroups;
   plugin = BattleArena.getSelf();
 }
Example #26
0
  @ArenaEventHandler(bukkitPriority = org.bukkit.event.EventPriority.MONITOR)
  public void onPlayerDeath(ArenaPlayerDeathEvent event) {
    final ArenaPlayer target = event.getPlayer();
    if (state == MatchState.ONCANCEL || state == MatchState.ONCOMPLETE) {
      return;
    }
    final ArenaTeam t = event.getTeam();

    Integer nDeaths = t.addDeath(target);
    boolean exiting = event.isExiting() || !respawns || nDeaths >= nLivesPerPlayer;
    event.setExiting(exiting);
    final boolean trueDeath = event.getPlayerDeathEvent() != null;
    if (nLivesPerPlayer != ArenaSize.MAX) {
      int curLives = nLivesPerPlayer - nDeaths;
      SEntry e = scoreboard.getEntry(target.getPlayer());
      if (e != null) scoreboard.setEntryNameSuffix(e, curLives <= 1 ? "" : "&4(" + curLives + ")");
    }
    if (trueDeath) {
      PlayerDeathEvent pde = event.getPlayerDeathEvent();
      if (cancelExpLoss) pde.setKeepLevel(true);

      /// Handle Drops from bukkitEvent
      if (clearsInventoryOnDeath || keepsInventory) { // / clear the drops
        try {
          pde.getDrops().clear();
        } catch (Exception e) {
          if (!Defaults.DEBUG_VIRTUAL) Log.printStackTrace(e);
        }
      } else if (woolTeams) { /// Get rid of the wool from teams so it doesnt drop
        final int index = t.getIndex();
        ItemStack teamHead = TeamUtil.getTeamHead(index);
        List<ItemStack> items = pde.getDrops();
        for (ItemStack is : items) {
          if (is.getType() == teamHead.getType()
              && is.getDurability() == teamHead.getDurability()) {
            final int amt = is.getAmount();
            if (amt > 1) is.setAmount(amt - 1);
            else is.setType(Material.AIR);
            break;
          }
        }
      }
      /// If keepInventory is specified, but not restoreAll, then we have a case
      /// where we need to give them back the current Inventory they have on them
      /// even if they log out
      if (keepsInventory) {
        boolean restores =
            getParams().hasOptionAt(MatchState.ONLEAVE, TransitionOption.RESTOREITEMS);
        /// Restores and exiting, means clear their match inventory so they won't
        /// get their match and their already stored inventory
        if (restores && exiting) {
          psc.clearMatchItems(target);
        } else { /// keep their current inv
          psc.storeMatchItems(target);
        }
      }
      /// We can't let them just sit on the respawn screen... schedule them to lose
      /// We will cancel this onRespawn
      final ArenaMatch am = this;
      Integer timer = deathTimer.get(target.getName());
      if (timer != null) {
        Bukkit.getScheduler().cancelTask(timer);
      }
      timer =
          Bukkit.getScheduler()
              .scheduleSyncDelayedTask(
                  BattleArena.getSelf(),
                  new Runnable() {
                    @Override
                    public void run() {
                      PerformTransition.transition(am, MatchState.ONCOMPLETE, target, t, true);
                      checkAndHandleIfTeamDead(t);
                    }
                  },
                  15 * 20L);
      deathTimer.put(target.getName(), timer);
    }
    if (exiting) {
      PerformTransition.transition(this, MatchState.ONCOMPLETE, target, t, true);
      checkAndHandleIfTeamDead(t);
    }
  }
Example #27
0
  public void collect(Player player, List<ItemStack> itemDrops, EntityDeathEvent event) {
    if (itemDrops.isEmpty() && !levelAllow(player) && !expAllow(player)) {
      return;
    }

    if (plugin.config.dropOnPVPDeath() && player.getKiller() instanceof Player) {
      plugin.message(player, plugin.config.msgPVPDeath());
      return;
    }

    if (plugin.config.residence()) {
      ClaimedResidence res = Residence.getResidenceManager().getByLoc(player.getLocation());
      if (res != null) {
        ResidencePermissions perms = res.getPermissions();
        if (perms.playerHas(player.getName(), plugin.config.resFlag(), true)) {
          plugin.logDebug(
              "Player '"
                  + player.getName()
                  + "' is not allowed to use Scavenger in this residence. Items will be dropped.");
          plugin.message(player, plugin.config.msgInsideRes());
          return;
        } else {
          plugin.logDebug(
              "Player '" + player.getName() + "' is allowed to use Scavenger in this residence.");
        }
      }
    }

    if (plugin.config.factionEnemyDrops() && plugin.factionHook != null) {
      if (plugin.factionHook.isPlayerInEnemyFaction(player)) {
        return;
      }
    }

    if (plugin.config.dungeonMazeDrops() && plugin.dmHook != null) {
      plugin.logDebug("Checking if '" + player.getName() + "' is in DungeonMaze.");
      if (plugin.dmHook.isPlayerInDungeon(player)) {
        plugin.logDebug("Player '" + player.getName() + "' is in DungeonMaze.");
        plugin.message(player, plugin.config.msgInsideDungeonMaze());
        return;
      }
    }

    if (plugin.getWorldGuard() != null) {
      plugin.logDebug("Checking region support for '" + player.getWorld().getName() + "'");
      if (plugin.getWorldGuard().getRegionManager(player.getWorld()) != null) {
        try {
          RegionManager regionManager = plugin.getWorldGuard().getRegionManager(player.getWorld());
          ApplicableRegionSet set = regionManager.getApplicableRegions(player.getLocation());
          if (set.allows(DefaultFlag.PVP) && plugin.config.wgPVPIgnore()) {
            plugin.logDebug(
                "This is a WorldGuard PVP zone and WorldGuardPVPIgnore is "
                    + plugin.config.wgPVPIgnore());
            if (!plugin.config.msgInsideWGPVP().isEmpty()) {
              plugin.message(player, plugin.config.msgInsideWGPVP());
            }
            return;
          }
          if (!set.allows(DefaultFlag.PVP) && plugin.config.wgGuardPVPOnly()) {
            plugin.logDebug(
                "This is NOT a WorldGuard PVP zone and WorldGuardPVPOnly is "
                    + plugin.config.wgGuardPVPOnly());
            if (!plugin.config.msgInsideWGPVP().isEmpty()) {
              plugin.message(player, plugin.config.msgInsideWGPVPOnly());
            }
            return;
          }
        } catch (NullPointerException ex) {
          plugin.logDebug(ex.getMessage());
        }
      } else {
        plugin.logDebug("Region support disabled for '" + player.getWorld().getName() + "'");
      }
    }

    if (plugin.getUltimateArena() != null) {
      if (UltimateArenaAPI.hookIntoUA(plugin).isInArena(player)) {
        if (!plugin.config.msgInsideUA().isEmpty()) {
          plugin.message(player, plugin.config.msgInsideUA());
        }
        return;
      }
    }

    if (plugin.maHandler != null && plugin.maHandler.isPlayerInArena(player)) {
      if (!plugin.config.msgInsideMA().isEmpty()) {
        plugin.message(player, plugin.config.msgInsideMA());
      }
      return;
    }

    if (plugin.pvpHandler != null && !PVPArenaAPI.getArenaName(player).equals("")) {
      String x = plugin.config.msgInsidePA();
      if (!x.isEmpty()) {
        x = x.replace("%ARENA%", PVPArenaAPI.getArenaName(player));
        plugin.message(player, x);
      }
      return;
    }

    if (plugin.battleArena) {
      mc.alk.arena.objects.ArenaPlayer ap = mc.alk.arena.BattleArena.toArenaPlayer(player);
      if (ap != null) {
        Match match = BattleArena.getBAController().getMatch(ap);
        if (match != null) {
          if (match.isInMatch(ap)) {
            String x = plugin.config.msgInsideBA();
            if (!x.isEmpty()) {
              plugin.message(player, x);
            }
            return;
          }
        }
      }
    }

    if (plugin.minigames != null) {
      if (plugin.minigames.playerInMinigame(player)) {
        plugin.logDebug(
            "Player '" + player.getName() + "' is in a Minigame. Not recovering items.");
        return;
      }
    }

    if (hasRestoration(player)) {
      plugin.error(player, "Restoration already exists, ignoring.");
      return;
    }

    if (plugin.getEconomy() != null
        && !(player.hasPermission(PERM_FREE) || (player.isOp() && plugin.config.opsAllPerms()))
        && plugin.config.economyEnabled()) {
      NumberFormat formatter = NumberFormat.getInstance(new Locale(plugin.config.countryCode()));
      formatter.setMaximumFractionDigits(plugin.config.decimalPlaces());
      double restoreCost = plugin.config.restoreCost();
      double withdrawAmount;
      double playerBalance = plugin.getEconomy().getBalance(player);
      double percentCost = plugin.config.percentCost();
      double minCost = plugin.config.minCost();
      double maxCost = plugin.config.maxCost();
      EconomyResponse er;
      String currency;
      if (plugin.config.percent()) {
        if (playerBalance < 0) {
          withdrawAmount = 0;
        } else {
          withdrawAmount = playerBalance * (percentCost / 100.0);
        }
        plugin.logDebug("withdrawAmount: " + withdrawAmount);
        plugin.logDebug("playeBalance: " + playerBalance);
        plugin.logDebug("percentCost: " + percentCost + "(" + (percentCost / 100.0) + ")");
        if (plugin.config.addMin()) {
          withdrawAmount = withdrawAmount + minCost;
          plugin.logDebug("withdrawAmount (addMin): " + withdrawAmount);
        } else if (withdrawAmount < minCost) {
          withdrawAmount = minCost;
        }
        if (withdrawAmount > maxCost && maxCost > 0) {
          withdrawAmount = maxCost;
        }
      } else {
        withdrawAmount = restoreCost;
      }
      er = plugin.getEconomy().withdrawPlayer(player, withdrawAmount);
      if (er.transactionSuccess()) {
        plugin.logDebug("Withdraw success!");
        if (withdrawAmount == 1) {
          currency = plugin.getEconomy().currencyNameSingular();
        } else {
          currency = plugin.getEconomy().currencyNamePlural();
        }
        String x = plugin.config.msgSaveForFee();
        if (!x.isEmpty()) {
          x = x.replace("%COST%", formatter.format(withdrawAmount));
          x = x.replace("%CURRENCY%", currency);
          plugin.message(player, x);
        }
        if (!plugin.config.depositDestination().isEmpty()) {
          plugin.logDebug("DepositDesination: " + plugin.config.depositDestination());
          if (plugin.config.depositType().equalsIgnoreCase("bank")) {
            plugin.logDebug("DepositType: BANK");
            if (plugin.getEconomy().hasBankSupport()) {
              plugin.logDebug("Bank support is enabled");
              plugin.getEconomy().bankDeposit(plugin.config.depositDestination(), withdrawAmount);
            } else {
              plugin.logDebug("Bank support is NOT enabled");
            }
          } else if (plugin.config.depositType().equalsIgnoreCase("player")) {
            plugin.logDebug("DepositType: PLAYER");
            plugin.logDebug("DepositDestination: " + plugin.config.depositDestination());
            if (plugin.getEconomy().hasAccount(plugin.config.depositDestination())) {
              plugin.logDebug("DepositDestination: VALID");
              plugin.getEconomy().depositPlayer(plugin.config.depositDestination(), withdrawAmount);
            } else {
              plugin.logDebug("DepositDestination: INVALID");
            }
          } else {
            plugin.logDebug("DepositType: INVALID");
          }
        } else {
          plugin.logDebug("No deposit destination!");
        }
      } else {
        plugin.logDebug("Withdraw fail! " + er.errorMessage);
        if (playerBalance == 1) {
          currency = plugin.getEconomy().currencyNameSingular();
        } else {
          currency = plugin.getEconomy().currencyNamePlural();
        }
        String x = plugin.config.msgNotEnoughMoney();
        if (!x.isEmpty()) {
          x = x.replace("%BALANCE%", formatter.format(playerBalance));
          x = x.replace("%COST%", formatter.format(withdrawAmount));
          x = x.replace("%CURRENCY%", currency);
          x = x.replace("%ERRORMESSAGE%", er.errorMessage);
          plugin.message(player, x);
        }
        return;
      }
    } else {
      plugin.message(player, plugin.config.msgSaving());
    }

    Restoration restoration = new Restoration();
    restoration.enabled = false;

    // temporary fix for 1.9
    restoration.inventory = Arrays.copyOfRange(player.getInventory().getContents(), 0, 36);
    restoration.armour = player.getInventory().getArmorContents();
    if (plugin.isMc19or110()) {
      restoration.offHand = player.getInventory().getItemInOffHand();
    }
    restoration.playerName = player.getDisplayName();
    itemDrops.clear();

    if (levelAllow(player)) {
      plugin.logDebug("Collecting level " + player.getLevel() + " for " + player.getName());
      restoration.level = player.getLevel();
    }
    if (expAllow(player)) {
      plugin.logDebug("Collecting exp " + player.getExp() + " for " + player.getName());
      restoration.exp = player.getExp();
      event.setDroppedExp(0);
    }

    String deathCause = "NULL";
    if (player.getLastDamageCause() != null) {
      if (player.getLastDamageCause().getCause() != null) {
        deathCause = player.getLastDamageCause().getCause().toString();
      }
    }
    String deathCausePermission = PERM_SCAVENGE_PREFIX + deathCause;
    plugin.logDebug(
        "[p:"
            + player.getName()
            + "] ["
            + PERM_SCAVENGE
            + ":"
            + player.hasPermission(PERM_SCAVENGE)
            + "]"
            + " ["
            + deathCausePermission
            + ":"
            + player.hasPermission(deathCausePermission)
            + "]");
    if (player.hasPermission(PERM_SCAVENGE) || player.hasPermission(deathCausePermission)) {
      plugin.logDebug("Permissions are okay. Time to scavenge...");
      if (plugin.config.chanceToDrop() > 0 && !player.hasPermission(PERM_NO_CHANCE)) {
        checkChanceToDropItems(restoration.armour, itemDrops);
        checkChanceToDropItems(restoration.inventory, itemDrops);
        if (plugin.isMc19or110()) {
          checkChanceToDropItems(restoration.offHand, itemDrops);
        }
      }
      if (plugin.config.singleItemDrops()) {
        checkSingleItemDrops(player, restoration.armour, itemDrops);
        checkSingleItemDrops(player, restoration.inventory, itemDrops);
        checkSingleItemDrops(player, restoration.offHand, itemDrops);
      } else if (plugin.config.singleItemKeeps()) {
        checkSingleItemKeeps(player, "armour", restoration.armour, itemDrops);
        checkSingleItemKeeps(player, "inv", restoration.inventory, itemDrops);
        if (plugin.isMc19or110()) {
          checkSingleItemKeeps(player, "offhand", restoration.offHand, itemDrops, 1);
        }
      } else if (plugin.config.slotBasedRecovery()) {
        checkSlots(player, "armour", restoration.armour, itemDrops);
        checkSlots(player, "inv", restoration.inventory, itemDrops);
        if (plugin.isMc19or110()) {
          checkSlots(player, "offhand", restoration.offHand, itemDrops, 1);
        }
      }
    } else {
      plugin.logDebug("Permissions are NOT okay. Dropping items...");
      dropItems(restoration.armour, itemDrops);
      dropItems(restoration.inventory, itemDrops);
      dropItem(restoration.offHand, itemDrops);
    }
    addRestoration(player, restoration);
  }
 public ArenaEditorExecutor() {
   super();
   this.aac = BattleArena.getArenaEditor();
 }