示例#1
0
  @Override
  public void execute(ScriptEntry scriptEntry) throws CommandExecutionException {
    // Fetch objects
    Script script = (Script) scriptEntry.getObject("script");
    Duration duration = (Duration) scriptEntry.getObject("duration");
    Type type = (Type) scriptEntry.getObject("type");

    // Report to dB
    dB.report(
        getName(),
        aH.debugObj("Type", type.toString())
            + script.debug()
            + (type == Type.PLAYER ? aH.debugObj("Player", scriptEntry.getPlayer().getName()) : "")
            + duration.debug());

    // Perform cooldown
    if (type == Type.PLAYER)
      setCooldown(
          ((OfflinePlayer) scriptEntry.getObject("player")).getName(),
          duration.getSecondsAsInt(),
          script.getName(),
          false);
    else if (type == Type.GLOBAL)
      setCooldown(null, duration.getSecondsAsInt(), script.getName(), true);
  }
  @Override
  public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException {

    dItem item = null;
    Action action = Action.PLACE;
    Duration duration = null;
    dLocation location = null;

    // Make sure NPC is available
    for (String arg : scriptEntry.getArguments()) {

      if (aH.matchesDuration(arg)) duration = aH.getDurationFrom(arg);
      else if (aH.matchesArg("REMOVE", arg)) action = Action.REMOVE;
      else if (aH.matchesLocation(arg)) location = aH.getLocationFrom(arg);
      else if (aH.getItemFrom(arg) != null) item = aH.getItemFrom(arg);
      else throw new InvalidArgumentsException(Messages.ERROR_UNKNOWN_ARGUMENT, arg);
    }

    // Check required args
    if (item == null) throw new InvalidArgumentsException("Must specify an item to display.");

    if (location == null) throw new InvalidArgumentsException(Messages.DEBUG_SET_LOCATION);

    // Add objects to ScriptEntry for execution
    scriptEntry
        .addObject("item", item)
        .addObject("action", action)
        .addObject("duration", duration)
        .addObject("location", location);
  }
示例#3
0
  @Override
  public void execute(ScriptEntry scriptEntry) throws CommandExecutionException {
    Element message = scriptEntry.getElement("message");
    Element fileName = scriptEntry.getElement("file");
    Element typeElement = scriptEntry.getElement("type");

    dB.report(scriptEntry, getName(), message.debug() + fileName.debug() + typeElement.debug());

    Type type = Type.valueOf(typeElement.asString().toUpperCase());

    String directory = URLDecoder.decode(System.getProperty("user.dir"));
    File file = new File(directory, fileName.asString());

    if (type == Type.NONE) {
      try {
        file.getParentFile().mkdirs();
        FileWriter fw = new FileWriter(file, true);
        fw.write(message + "\n");
        fw.close();
      } catch (IOException e) {
        dB.echoError("Error logging to file...");
        dB.echoError(e);
      }
      return;
    }

    DebugLog log = new DebugLog("Denizen-ScriptLog-" + fileName, file.getAbsolutePath());

    switch (type) {
      case SEVERE:
        log.severe(message.asString());
        break;

      case INFO:
        log.info(message.asString());
        break;

      case WARNING:
        log.warning(message.asString());
        break;

      case FINE:
        log.fine(message.asString());
        break;

      case FINER:
        log.finer(message.asString());
        break;

      case FINEST:
        log.finest(message.asString());
    }

    log.close();
  }
  @Override
  public void execute(ScriptEntry scriptEntry) throws CommandExecutionException {

    // Get objects from ScriptEntry
    dItem item = (dItem) scriptEntry.getObject("item");
    Duration duration = (Duration) scriptEntry.getObject("duration");
    dLocation location = (dLocation) scriptEntry.getObject("location");
    Action action = (Action) scriptEntry.getObject("action");

    // Report to dB
    dB.report(
        getName(),
        aH.debugObj("Action", action.toString())
            + item.debug()
            + (duration != null ? duration.debug() : "")
            + location.debug());

    if (action == Action.PLACE) {

      int ticks = Integer.MAX_VALUE;
      if (duration != null) ticks = duration.getTicksAsInt();

      // Display the item
      if (displayed.containsKey(location.dScriptArgValue())) {
        displayed.get(location.dScriptArgValue()).remove();
        displayed.remove(location.dScriptArgValue());
      }

      // Remember the item entity
      displayed.put(
          location.dScriptArgValue(),
          location
              .getBlock()
              .getLocation()
              .add(0, 1, 0)
              .getWorld()
              .dropItem(location, item.getItemStack()));
      displayed.get(location.dScriptArgValue()).setPickupDelay(Integer.MAX_VALUE);
      displayed.get(location.dScriptArgValue()).setTicksLived(ticks);
    }

    // Remove the item
    else if (action == Action.REMOVE) {
      if (displayed.containsKey(location.dScriptArgValue())) {
        displayed.get(location.dScriptArgValue()).remove();
        displayed.remove(location.dScriptArgValue());
      }
    }
  }
示例#5
0
  @Override
  public void execute(ScriptEntry scriptEntry) throws CommandExecutionException {

    // Report!
    dB.report(
        scriptEntry,
        getName(),
        scriptEntry.getElement("outcome").debug() + scriptEntry.getElement("passively").debug());

    // Fetch
    String outcome = scriptEntry.getElement("outcome").asString();
    Boolean passively = scriptEntry.getElement("passively").asBoolean();

    Long uniqueId = (Long) scriptEntry.getObject("reqId");
    if (uniqueId == null) {
      dB.echoError("Cannot use determine in this queue!");
      return;
    }

    if (outcomes.containsKey(uniqueId)) {
      dB.echoError("This queue already has a determination!");
      return;
    }

    outcomes.put(uniqueId, outcome);

    if (!passively)
      // Stop the queue by clearing the remainder of it.
      scriptEntry.getResidingQueue().clear();
  }
示例#6
0
  @Override
  public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException {

    // Define necessary fields
    Script script = scriptEntry.getScript();
    Duration duration = null;
    OfflinePlayer player = null;
    Type type = Type.PLAYER;

    // Set player in scriptEntry to the target
    if (scriptEntry.getPlayer() != null) player = scriptEntry.getPlayer();
    else if (scriptEntry.getOfflinePlayer() != null) player = scriptEntry.getOfflinePlayer();

    // Parse Arguments
    for (String arg : scriptEntry.getArguments()) {

      if (aH.matchesDuration(arg) || aH.matchesInteger(arg)) duration = aH.getDurationFrom(arg);

      // Default is PLAYER, but having both to choose from seems to be most straightforward
      else if (aH.matchesArg("GLOBAL, PLAYER", arg)) type = Type.valueOf(arg.toUpperCase());

      // Must be an actual script! If the script doesn't exist, matchesScript(...)
      // will echo an error.
      else if (aH.matchesScript(arg)) script = aH.getScriptFrom(arg);
      else throw new InvalidArgumentsException(Messages.ERROR_UNKNOWN_ARGUMENT, arg);
    }

    // Check to make sure required arguments have been filled
    if (type == Type.PLAYER && player == null)
      throw new InvalidArgumentsException(Messages.ERROR_NO_PLAYER);
    if (script == null) throw new InvalidArgumentsException(Messages.ERROR_NO_SCRIPT);

    // Store necessary items in the scriptEntry
    scriptEntry.addObject("script", script);
    scriptEntry.addObject("duration", duration);
    scriptEntry.addObject("type", type);
    // Store the player only when necessary
    if (type == Type.PLAYER) scriptEntry.addObject("player", player);
  }
示例#7
0
  @Override
  public void execute(ScriptEntry scriptEntry) throws CommandExecutionException {

    // Grab comparables from the ScriptEntry
    List<Comparable> comparables = (List<Comparable>) scriptEntry.getObject("comparables");

    int counter = 1;

    // Evaluate comparables
    for (Comparable com : comparables) {
      com.determineOutcome();

      // Show outcome of Comparable
      dB.echoDebug(
          scriptEntry,
          ChatColor.YELLOW + "Comparable " + counter + ": " + ChatColor.WHITE + com.toString());
      counter++;
    }

    // Compare outcomes

    int ormet = 0;
    for (Comparable comparable : comparables) {
      if (comparable.bridge == Comparable.Bridge.OR) if (comparable.outcome) ormet++;
    }

    int andcount = 0;
    int andmet = 0;
    for (Comparable comparable : comparables) {
      if (comparable.bridge == Comparable.Bridge.AND) {
        if (comparable.outcome) andmet++;
        andcount++;
      }
    }

    boolean do_then;

    if (comparables.size() > 1) {
      do_then = (ormet > 0) || (andcount == andmet && comparables.get(0).outcome == true);
    } else do_then = comparables.get(0).outcome;

    // Determine outcome -- then, or else?
    if (do_then) {
      // dB.log("then: " + scriptEntry.getObject("then-outcome").toString());
      doCommand(scriptEntry, "then-outcome");
    } else {
      // dB.log("else: " + scriptEntry.getObject("else-outcome").toString());
      doCommand(scriptEntry, "else-outcome");
    }
  }
示例#8
0
  @Override
  public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException {

    // Parse Arguments
    for (String arg : scriptEntry.getArguments()) {
      if (aH.matchesState(arg))
        scriptEntry.addObject("state", Action.valueOf(aH.getStringFrom(arg).toUpperCase()));
      else if (aH.matchesArg("NPC, PLAYER", arg))
        scriptEntry.addObject("target", Target.valueOf(aH.getStringFrom(arg).toUpperCase()));
      else throw new InvalidArgumentsException(dB.Messages.ERROR_UNKNOWN_ARGUMENT, arg);
    }

    if (scriptEntry.getObject("state") == null)
      throw new InvalidArgumentsException("Must specify a state action!");

    if (scriptEntry.getObject("target") == null)
      throw new InvalidArgumentsException("Must specify a target!");

    if ((scriptEntry.getObject("target") == Target.NPC && scriptEntry.getNPC() == null)
        || (scriptEntry.getObject("target") == Target.PLAYER && scriptEntry.getPlayer() == null))
      throw new InvalidArgumentsException("NPC not found!");
  }
示例#9
0
  private void doCommand(ScriptEntry scriptEntry, String mapName) {
    TreeMap<Integer, ArrayList<String>> commandMap =
        (TreeMap<Integer, ArrayList<String>>) scriptEntry.getObject(mapName);

    if (commandMap == null || commandMap.size() == 0) return;

    List<ScriptEntry> entries = new ArrayList<ScriptEntry>();

    for (Map.Entry<Integer, ArrayList<String>> pairs : commandMap.entrySet()) {
      ArrayList<String> commandArray = pairs.getValue();
      String command = commandArray.get(0);
      commandArray.remove(0);
      String[] arguments = commandArray.toArray(new String[commandArray.size()]);

      try {
        ScriptEntry entry =
            new ScriptEntry(
                    command,
                    arguments,
                    (scriptEntry.getScript() == null
                        ? null
                        : scriptEntry.getScript().getContainer()))
                .setPlayer(scriptEntry.getPlayer())
                .setNPC(scriptEntry.getNPC())
                .setInstant(true)
                .addObject("reqId", scriptEntry.getObject("reqId"));

        entries.add(entry);

      } catch (ScriptEntryCreationException e) {
        dB.echoError("There has been a problem running the Command. Check syntax.");
        dB.echoError(e);
      }
    }

    // Put tracked objects into new script entries.
    for (String tracked_object : scriptEntry.tracked_objects) {
      ScriptBuilder.addObjectToEntries(
          entries, tracked_object, scriptEntry.getObject(tracked_object));
    }

    scriptEntry.getResidingQueue().injectEntries(entries, 0);
  }
示例#10
0
  @Override
  public void execute(ScriptEntry scriptEntry) throws CommandExecutionException {

    // Get objects
    Action action = (Action) scriptEntry.getObject("action");
    dLocation location = (dLocation) scriptEntry.getObject("location");
    Element range = (Element) scriptEntry.getObject("range");
    Element id = (Element) scriptEntry.getObject("id");

    // Report to dB
    dB.report(
        scriptEntry,
        getName(),
        aH.debugObj("NPC", scriptEntry.getNPC().toString())
            + action.name()
            + id.debug()
            + (location != null ? location.debug() : "")
            + (range != null ? range.debug() : ""));

    dNPC npc = scriptEntry.getNPC();

    switch (action) {
      case ADD:
        npc.getCitizen().getTrait(Anchors.class).addAnchor(id.asString(), location);
        return;

      case ASSUME:
        npc.getEntity()
            .teleport(
                npc.getCitizen().getTrait(Anchors.class).getAnchor(id.asString()).getLocation());
        return;

      case WALKNEAR:
        npc.getNavigator()
            .setTarget(
                Utilities.getWalkableLocationNear(
                    npc.getCitizen().getTrait(Anchors.class).getAnchor(id.asString()).getLocation(),
                    range.asInt()));
        return;

      case WALKTO:
        npc.getNavigator()
            .setTarget(
                npc.getCitizen().getTrait(Anchors.class).getAnchor(id.asString()).getLocation());
        return;

      case REMOVE:
        npc.getCitizen()
            .getTrait(Anchors.class)
            .removeAnchor(npc.getCitizen().getTrait(Anchors.class).getAnchor(id.asString()));
    }
  }
示例#11
0
  @Override
  public void execute(ScriptEntry scriptEntry) throws CommandExecutionException {

    NPC npc = scriptEntry.getNPC().getCitizen();
    SittingTrait trait = npc.getTrait(SittingTrait.class);

    if (!npc.hasTrait(SittingTrait.class)) {
      npc.addTrait(SittingTrait.class);
      dB.echoDebug("...added sitting trait");
    }

    if (!trait.isSitting()) {
      dB.echoError("...NPC is already standing, removing trait");
      npc.removeTrait(SittingTrait.class);
      return;
    }

    trait.stand();
    npc.removeTrait(SittingTrait.class);
  }
示例#12
0
  @Override
  public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException {

    for (aH.Argument arg : aH.interpret(scriptEntry.getArguments())) {

      if (arg.matches("passive, passively")) scriptEntry.addObject("passively", new Element(true));
      else if (!scriptEntry.hasObject("outcome"))
        scriptEntry.addObject("outcome", new Element(arg.raw_value));
      else arg.reportUnhandled();
    }

    // Set defaults
    scriptEntry.defaultObject("passively", new Element(false));
    scriptEntry.defaultObject("outcome", new Element(false));
  }
示例#13
0
  @Override
  public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException {

    // Parse Arguments
    for (Argument arg : aH.interpret(scriptEntry.getArguments())) {

      if (!scriptEntry.hasObject("action") && arg.matchesEnum(Action.values()))
        scriptEntry.addObject("action", Action.valueOf(arg.getValue().toUpperCase()));
      else if (!scriptEntry.hasObject("range")
          && arg.matchesPrimitive(aH.PrimitiveType.Double)
          && arg.matchesPrefix("range, r")) scriptEntry.addObject("range", arg.asElement());
      else if (!scriptEntry.hasObject("id") && arg.matchesPrefix("id, i"))
        scriptEntry.addObject("id", arg.asElement());
      else if (!scriptEntry.hasObject("location") && arg.matchesArgumentType(dLocation.class))
        scriptEntry.addObject("location", arg.asType(dLocation.class));
      else arg.reportUnhandled();
    }

    // Check required arguments
    if (!scriptEntry.hasNPC())
      throw new InvalidArgumentsException("NPC linked was missing or invalid.");

    if (!scriptEntry.hasObject("action"))
      throw new InvalidArgumentsException(
          "Must specify an 'Anchor Action'. Valid: " + Action.values());
  }
示例#14
0
  public boolean execute(ScriptEntry scriptEntry) {
    Matcher m;
    StringBuffer sb;
    if (scriptEntry.getCommandName().indexOf('%') != -1) {
      m = definition_pattern.matcher(scriptEntry.getCommandName());
      sb = new StringBuffer();
      while (m.find()) {
        String definition = scriptEntry.getResidingQueue().getDefinition(m.group(1));
        if (definition == null) definition = "null";
        m.appendReplacement(sb, definition);
      }
      m.appendTail(sb);
      scriptEntry.setCommandName(sb.toString());
    }

    // Get the command instance ready for the execution of the scriptEntry
    AbstractCommand command = plugin.getCommandRegistry().get(scriptEntry.getCommandName());

    if (command == null) {
      dB.echoDebug(
          scriptEntry, DebugElement.Header, "Executing command: " + scriptEntry.getCommandName());
      dB.echoError(
          scriptEntry.getCommandName() + " is an invalid dCommand! Are you sure it loaded?");
      dB.echoDebug(scriptEntry, DebugElement.Footer);
      return false;
    }

    // Debugger information
    if (scriptEntry.getPlayer() != null)
      dB.echoDebug(
          scriptEntry,
          DebugElement.Header,
          "Executing dCommand: "
              + scriptEntry.getCommandName()
              + "/"
              + scriptEntry.getPlayer().getName());
    else
      dB.echoDebug(
          scriptEntry,
          DebugElement.Header,
          "Executing dCommand: "
              + scriptEntry.getCommandName()
              + (scriptEntry.getNPC() != null ? "/" + scriptEntry.getNPC().getName() : ""));

    // Don't execute() if problems arise in parseArgs()
    boolean keepGoing = true;

    try {

      // Throw exception if arguments are required for this command, but not supplied.
      if (command.getOptions().REQUIRED_ARGS > scriptEntry.getArguments().size())
        throw new InvalidArgumentsException("");

      if (scriptEntry.has_tags)
        scriptEntry.setArguments(
            TagManager.fillArguments(
                scriptEntry.getArguments(), scriptEntry, true)); // Replace tags

      /*  If using NPC:# or PLAYER:Name arguments, these need to be changed out immediately because...
       *  1) Denizen/Player flags need the desired NPC/PLAYER before parseArgs's getFilledArguments() so that
       *     the Player/Denizen flags will read from the correct Object. If using PLAYER or NPCID arguments,
       *     the desired Objects are obviously not the same objects that were sent with the ScriptEntry.
       *  2) These arguments should be valid for EVERY ScriptCommand, so why not just take care of it
       *     here, instead of requiring each command to take care of the argument.
       */

      List<String> newArgs = new ArrayList<String>();

      // Don't fill in tags if there were brackets detected..
      // This means we're probably in a nested if.
      int nested_depth = 0;
      // Watch for IF command to avoid filling player and npc arguments
      // prematurely
      boolean if_ignore = false;

      for (aH.Argument arg : aH.interpret(scriptEntry.getArguments())) {
        if (arg.getValue().equals("{")) nested_depth++;
        if (arg.getValue().equals("}")) nested_depth--;

        // If nested, continue.
        if (nested_depth > 0) {
          newArgs.add(arg.raw_value);
          continue;
        }

        if (arg.raw_value.indexOf('%') != -1) {
          m = definition_pattern.matcher(arg.raw_value);
          sb = new StringBuffer();
          while (m.find()) {
            String definition = scriptEntry.getResidingQueue().getDefinition(m.group(1));
            if (definition == null) definition = "null";
            m.appendReplacement(sb, definition);
          }
          m.appendTail(sb);
          arg = aH.Argument.valueOf(sb.toString());
        }

        // If using IF, check if we've reached the command + args
        // so that we don't fill player: or npc: prematurely
        if (command.getName().equalsIgnoreCase("if")
            && DenizenAPI.getCurrentInstance().getCommandRegistry().get(arg.getValue()) != null)
          if_ignore = true;

        // Fill player/off-line player
        if (arg.matchesPrefix("player") && !if_ignore) {
          dB.echoDebug(scriptEntry, "...replacing the linked player with " + arg.getValue());
          String value =
              TagManager.tag(
                  scriptEntry.getPlayer(),
                  scriptEntry.getNPC(),
                  arg.getValue(),
                  false,
                  scriptEntry);
          dPlayer player = dPlayer.valueOf(value);
          if (player == null || !player.isValid()) {
            dB.echoError(value + " is an invalid player!");
            return false;
          }
          scriptEntry.setPlayer(player);
        }

        // Fill NPCID/NPC argument
        else if (arg.matchesPrefix("npc, npcid") && !if_ignore) {
          dB.echoDebug(scriptEntry, "...replacing the linked NPC with " + arg.getValue());
          String value =
              TagManager.tag(
                  scriptEntry.getPlayer(),
                  scriptEntry.getNPC(),
                  arg.getValue(),
                  false,
                  scriptEntry);
          dNPC npc = dNPC.valueOf(value);
          if (npc == null || !npc.isValid()) {
            dB.echoError(value + " is an invalid NPC!");
            return false;
          }
          scriptEntry.setNPC(npc);
        }

        // Save the scriptentry if needed later for fetching scriptentry context
        else if (arg.matchesPrefix("save") && !if_ignore) {
          dB.echoDebug(scriptEntry, "...remembering this script entry!");
          scriptEntry.getResidingQueue().holdScriptEntry(arg.getValue(), scriptEntry);
        } else newArgs.add(arg.raw_value);
      }

      // Add the arguments back to the scriptEntry.
      scriptEntry.setArguments(newArgs);

      // Now process non-instant tags.
      if (scriptEntry.has_tags)
        scriptEntry.setArguments(
            TagManager.fillArguments(scriptEntry.getArguments(), scriptEntry, false));

      // Parse the rest of the arguments for execution.
      command.parseArgs(scriptEntry);

    } catch (InvalidArgumentsException e) {

      keepGoing = false;
      // Give usage hint if InvalidArgumentsException was called.
      dB.echoError("Woah! Invalid arguments were specified!");
      if (e.getMessage() != null && e.getMessage().length() > 0)
        dB.log(
            ChatColor.YELLOW
                + "+> MESSAGE follows: "
                + ChatColor.WHITE
                + "'"
                + e.getMessage()
                + "'");
      dB.log("Usage: " + command.getUsageHint());
      dB.echoDebug(scriptEntry, DebugElement.Footer);
      scriptEntry.setFinished(true);

    } catch (Exception e) {

      keepGoing = false;
      dB.echoError("Woah! An exception has been called with this command!");
      dB.echoError(e);
      dB.echoDebug(scriptEntry, DebugElement.Footer);
      scriptEntry.setFinished(true);

    } finally {

      if (keepGoing)
        try {
          // Run the execute method in the command
          command.execute(scriptEntry);
        } catch (Exception e) {
          dB.echoError("Woah!! An exception has been called with this command!");
          dB.echoError(e);
          scriptEntry.setFinished(true);
        }
    }

    return true;
  }
示例#15
0
  @Override
  public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException {

    // Comparables check the logic
    List<Comparable> comparables = new ArrayList<Comparable>();
    // Insert new comparable into the list
    comparables.add(new Comparable());

    // Indicate that comparables are building
    boolean buildingComparables = true;

    // What to do depending on the logic of the comparables
    // is stored in two tree maps
    TreeMap<Integer, ArrayList<String>> thenOutcome = new TreeMap<Integer, ArrayList<String>>();
    TreeMap<Integer, ArrayList<String>> elseOutcome = new TreeMap<Integer, ArrayList<String>>();

    // Keep tracking of whether we're inside the Else part of the statement or not
    boolean insideElse = false;

    // Keep track of this to avoid Denizen overlooking comparedTo when an operator is used
    // with a value that matches the name of a command. (Good find dimensionZ!)
    boolean usedOperator = false;

    // Track whether we are adding a new command or not
    boolean newCommand = false;

    // Track whether we are inside nested brackets whose contents
    // should be added as arguments to our current If, not as commands
    int bracketsEntered = 0;

    for (aH.Argument arg : aH.interpret(scriptEntry.getArguments())) {
      if (buildingComparables) {

        // Set logic to NEGATIVE
        if (arg.startsWith("!")) {
          comparables.get(comparables.size() - 1).setNegativeLogic();
          if (arg.getValue().length() == 1) continue;
          if (arg.startsWith("!=")) arg.replaceValue("==");
          else arg.replaceValue(arg.getValue().substring(1));
        }

        // Replace symbol-operators/bridges with ENUM value for matching
        if (arg.getValue().equals("==")) arg.replaceValue("EQUALS");
        else if (arg.getValue().equals(">=")) arg.replaceValue("OR_MORE");
        else if (arg.getValue().equals("<=")) arg.replaceValue("OR_LESS");
        else if (arg.getValue().equals("<")) arg.replaceValue("LESS");
        else if (arg.getValue().equals(">")) arg.replaceValue("MORE");
        else if (arg.getValue().equals("||")) arg.replaceValue("OR");
        else if (arg.getValue().equals("&&")) arg.replaceValue("AND");

        // Set bridge
        if (arg.matchesEnum(Comparable.Bridge.values())) {
          // new Comparable to add to the list
          comparables.add(new Comparable());
          comparables.get(comparables.size() - 1).bridge =
              Comparable.Bridge.valueOf(arg.getValue().toUpperCase());
        }

        // Set operator (Optional, default is EQUALS)
        else if (arg.matchesEnum(Comparable.Operator.values())) {
          comparables.get(comparables.size() - 1).operator =
              Comparable.Operator.valueOf(arg.getValue().toUpperCase());
          usedOperator = true;
        }

        // Set comparable
        else if (comparables.get(comparables.size() - 1).comparable == null) {
          // If using MATCHES operator, keep as string.
          comparables.get(comparables.size() - 1).setComparable(arg.getValue());
        } else if (!usedOperator && arg.matches("{")) {
          buildingComparables = false;
        }

        // Check if filling comparables are done by checking the command registry for valid
        // commands.
        // If using an operator though, skip on to compared-to!
        else if (!usedOperator
            && denizen.getCommandRegistry().get(arg.getValue().replace("^", "")) != null) {
          buildingComparables = false;
        }

        // Set compared-to
        else {
          comparables.get(comparables.size() - 1).setComparedto(arg.getValue());
          usedOperator = false;
        }
      }

      if (!buildingComparables) {

        // Read "-" as meaning we are moving to a new command, unless we
        // are inside nested brackets (i.e. bracketsEntered of at least 2)
        // in which case we just treat what follows as arguments
        if (arg.matches("-") && bracketsEntered < 2) {
          newCommand = true;
        } else if (!insideElse) {

          // Move to else commands if we read an "else" and we're not
          // currently going through nested arguments
          if (arg.matches("else") && bracketsEntered == 0) {
            insideElse = true;
          }

          // If we find a bracket, and we're already inside
          // nested brackets, add the bracket to the current
          // command's arguments
          else if (arg.matches("{")) {
            bracketsEntered++;

            if (bracketsEntered > 1) {
              thenOutcome.get(thenOutcome.lastKey()).add(arg.raw_value);
            }
          } else if (arg.matches("}")) {
            bracketsEntered--;

            if (bracketsEntered > 0) {
              thenOutcome.get(thenOutcome.lastKey()).add(arg.raw_value);
            }
          }

          // Add new outcome command if the last argument was a non-nested "-"
          // or if there are no outcome commands yet
          else if (newCommand || thenOutcome.size() == 0) {
            thenOutcome.put(thenOutcome.size(), new ArrayList<String>());
            thenOutcome.get(thenOutcome.lastKey()).add(arg.raw_value);
            newCommand = false;
          }

          // Add new outcome argument
          else {
            thenOutcome.get(thenOutcome.lastKey()).add(arg.raw_value);
          }
        } else if (insideElse) {

          // If we find a bracket, and we're already inside
          // nested brackets, add the bracket to the current
          // command's arguments
          if (arg.matches("{")) {
            bracketsEntered++;

            if (bracketsEntered > 1) {
              elseOutcome.get(elseOutcome.lastKey()).add(arg.raw_value);
            }
          } else if (arg.matches("}")) {
            bracketsEntered--;

            if (bracketsEntered > 0) {
              elseOutcome.get(elseOutcome.lastKey()).add(arg.raw_value);
            }
          }

          // Add new else command if the last argument was a non-nested "-"
          // or if it was "else" and we have no else commands yet
          else if (newCommand || elseOutcome.size() == 0) {
            newCommand = false;

            // Important!
            //
            // If we find an "else if", act like we entered a set of
            // brackets, so we treat the if's commands as arguments
            // and don't add them to our current else commands
            if (arg.matches("if") && elseOutcome.size() == 0) {
              bracketsEntered++;
            }

            // Add the new else command
            elseOutcome.put(elseOutcome.size(), new ArrayList<String>());
            elseOutcome.get(elseOutcome.lastKey()).add(arg.raw_value);
          }

          // Add new else argument
          else {
            elseOutcome.get(elseOutcome.lastKey()).add(arg.raw_value);
          }
        }
      }
    }

    // Stash objects required to execute() into the ScriptEntry
    scriptEntry
        .addObject("comparables", comparables)
        .addObject("then-outcome", thenOutcome)
        .addObject("else-outcome", elseOutcome);
  }
示例#16
0
  @Override
  public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException {

    for (aH.Argument arg : aH.interpret(scriptEntry.getArguments())) {
      if (!scriptEntry.hasObject("type")
          && arg.matchesPrefix("type")
          && arg.matchesEnum(Type.values())) scriptEntry.addObject("type", arg.asElement());
      else if (!scriptEntry.hasObject("file") && arg.matchesPrefix("file"))
        scriptEntry.addObject("file", arg.asElement());
      else if (!scriptEntry.hasObject("message")) scriptEntry.addObject("message", arg.asElement());
      else arg.reportUnhandled();
    }

    if (!scriptEntry.hasObject("message"))
      throw new InvalidArgumentsException("Must specify a message.");

    if (!scriptEntry.hasObject("file")) throw new InvalidArgumentsException("Must specify a file.");

    if (!scriptEntry.hasObject("type")) scriptEntry.addObject("type", new Element("INFO"));
  }
示例#17
0
  @Override
  public void execute(ScriptEntry scriptEntry) throws CommandExecutionException {
    // Get objects
    Action action = (Action) scriptEntry.getObject("state");
    Target target = (Target) scriptEntry.getObject("target");

    // Report to dB
    dB.report(
        getName(),
        aH.debugObj("Toggle", action.name())
            + aH.debugObj(
                "Target",
                target == Target.NPC
                    ? scriptEntry.getNPC().toString()
                    : scriptEntry.getPlayer().getName()));

    switch (target) {
      case NPC:
        if (!scriptEntry.getNPC().getCitizen().hasTrait(InvisibleTrait.class))
          scriptEntry.getNPC().getCitizen().addTrait(InvisibleTrait.class);
        InvisibleTrait trait = scriptEntry.getNPC().getCitizen().getTrait(InvisibleTrait.class);

        switch (action) {
          case FALSE:
            trait.setInvisible(false);
            break;

          case TRUE:
            trait.setInvisible(true);
            break;

          case TOGGLE:
            trait.toggle();
            break;
        }

        break;

      case PLAYER:
        if (scriptEntry.getPlayer() != null) {

          Player player = scriptEntry.getPlayer().getPlayerEntity();
          PotionEffect invis =
              new PotionEffect(PotionEffectType.INVISIBILITY, Integer.MAX_VALUE, 1);

          switch (action) {
            case FALSE:
              player.removePotionEffect(PotionEffectType.INVISIBILITY);
              break;

            case TRUE:
              invis.apply(player);
              break;

            case TOGGLE:
              if (player.hasPotionEffect(PotionEffectType.INVISIBILITY))
                player.removePotionEffect(PotionEffectType.INVISIBILITY);
              else invis.apply(player);

              break;
          }
        }
    }
  }
示例#18
0
 @Override
 public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException {
   // stand should have no additional arguments
   for (String arg : scriptEntry.getArguments())
     throw new InvalidArgumentsException(Messages.ERROR_UNKNOWN_ARGUMENT, arg);
 }