예제 #1
0
  /**
   * Returns the response to a non-internal input, using a Responder.
   *
   * @param input the "non-internal" (possibly multi-sentence, non-substituted) input
   * @param userid the userid for whom the response will be generated
   * @param botid the botid from which to get the response
   * @param responder the Responder who cares about this response
   */
  public static synchronized String getResponse(
      String input, String userid, String botid, Responder responder) {
    // Get the specified bot object.
    Bot bot = Bots.getBot(botid);

    // Split sentences (after performing substitutions and responder pre-processing).
    ArrayList sentenceList =
        bot.sentenceSplit(bot.applyInputSubstitutions(responder.preprocess(input, HOST_NAME)));

    // Get an iterator on the replies.
    Iterator replies = getReplies(sentenceList, userid, botid).iterator();

    // Start by assuming an empty response.
    String response = EMPTY_STRING;

    // Get an iterator over the input sentences.
    Iterator sentences = sentenceList.iterator();

    // For each input sentence...
    while (sentences.hasNext()) {
      // ...ask the responder to append the reply to the response, and accumulate the result.
      response = responder.append((String) sentences.next(), (String) replies.next(), response);
    }

    // Log the response.
    responder.log(input, response, HOST_NAME, userid, botid);

    // Finally, ask the responder to postprocess the response, and return the result.
    response = responder.postprocess(response);

    // Return the response (may be just EMPTY_STRING!)
    return response;
  }
예제 #2
0
 public void ChanHandler(String[] args, String sender, String c, Bot b) { // c = channel
   if (args[0].equals("!info")) {
     b.sendMessage(c, "Hi " + sender + ".");
   } else {
     b.sendMessage(c, "[ERROR] Invalid command. Try !help.");
   }
 }
예제 #3
0
  @Override
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.clearRect(-100, -100, getWidth() + 100, getHeight() + 100);
    if (board == null) return;

    for (Bot bot : board.getBots()) {
      g2d.drawString(
          board.getSymbol(bot), bot.getPosition().x * 38, -bot.getPosition().y * 38 + 400);
      g2d.drawString("G" + board.getSymbol(bot), bot.getGoal().x * 38, -bot.getGoal().y * 38 + 400);
    }
  }
예제 #4
0
  public void testBot() throws Exception {
    AttributesImpl attributes = new AttributesImpl();
    attributes.addAttribute(null, "name", null, "String", "bot.predicate1");
    handler.startElement(null, null, "bot", attributes);

    Bot expected = new Bot("bot.predicate1");
    Bot actual = (Bot) stack.peek();
    assertEquals(expected, actual);

    Bot bot2 = new Bot("bot.predicate2");
    assertFalse(bot2.equals(actual));
  }
 @Override
 public void run() {
   while (true) {
     try {
       CompareImages ci =
           new CompareImages(
               Bot.get_screen(),
               Variables.disconnect,
               Variables.disconnectStart,
               Variables.disconnectFinish,
               new ArrayList<>(),
               0.1f);
       ci.compare();
       if (ci.result() != null) {
         System.out.println("DISCONNECT");
         Variables.needToWait.set(true);
         try {
           Thread.sleep(Variables.sleepAfterDisconnect + 10000);
         } catch (InterruptedException e) {
         }
       }
     } catch (AWTException e) {
     }
     try {
       Thread.sleep(1000);
     } catch (InterruptedException e) {
     }
   }
 }
예제 #6
0
  @Override
  protected String getReply(Bot bot, JBotSender sender, String[] args) {
    if (args.length < 1) {
      throw new IllegalArgumentException();
    } else if (args.length == 1) {
      Map<String, AliasCommand> aliases = bot.getAliases();
      if (aliases.isEmpty()) {
        return "Defined aliases: none";
      } else {
        StringBuilder msg = new StringBuilder("Defined aliases:");
        for (Map.Entry<String, AliasCommand> entry : aliases.entrySet()) {
          msg.append("\n\t").append(entry.getKey()).append(entry.getValue().getHelp());
        }
        return msg.toString();
      }
    } else if (args.length < 3) {
      String alias = args[1];
      AliasCommand aliasCmd = bot.removeAlias(alias);
      if (aliasCmd != null) {
        return "deleted alias: " + alias + aliasCmd.getHelp();
      } else {
        return sender.getNickname() + ": don't know an alias called '" + alias + "'";
      }
    } else {
      String alias = args[1];
      String cmdName = args[2];
      JBotCommand cmd = bot.getCommand(cmdName);
      if (cmd == null) {
        return sender.getNickname()
            + ": sorry don't know a command or alias called '"
            + cmdName
            + "'";
      }
      String[] cmdArguments = ArrayUtils.EMPTY_STRING_ARRAY;
      if (args.length > 3) {
        cmdArguments = MessageHelper.copyOfRange(args, 3, args.length);
      }

      AliasCommand aliasCmd = new AliasCommand(cmd, cmdName, cmdArguments);
      try {
        bot.addAlias(alias, aliasCmd);
      } catch (IllegalArgumentException e) {
        return sender.getNickname() + ": " + e.getMessage();
      }
      return "created alias: " + alias + aliasCmd.getHelp();
    }
  }
예제 #7
0
 public static void run(RobotController _rc) throws GameActionException {
   Bot.init(_rc);
   init();
   while (true) {
     myLocation = rc.getLocation();
     Radio.process();
     action();
     Radio.clear();
     Clock.yield();
   }
 }
예제 #8
0
  /**
   * Produces a response to an &quot;internal&quot; input sentence -- i.e., an input that has been
   * produced by a <code>srai</code>.
   *
   * <p>The main differences between this and {@link
   * #getResponse(String,String,TemplateParser,boolean,Responder)} are that this method takes an
   * already-existing <code>TemplateParser</code>, <i>doesn't</i> take a <code>Responder</code>, and
   * assumes that the inputs have already been normalized.
   *
   * @see {@link #getResponse(String,String,TemplateParser,boolean,Responder)}
   * @param input the input sentence
   * @param userid the userid requesting the response
   * @param botid the botid from which to get the response
   * @param parser the parser object to update when generating the response
   */
  public static String getInternalResponse(
      String input, String userid, String botid, TemplateParser parser) {
    // Get the requested bot.
    Bot bot = Bots.getBot(botid);

    // Ready the that and topic predicates for constructing the match path.
    ArrayList thatSentences = bot.sentenceSplit(PredicateMaster.get(THAT, 1, userid, botid));
    String that =
        InputNormalizer.patternFitIgnoreCase((String) thatSentences.get(thatSentences.size() - 1));

    if (that.equals(EMPTY_STRING) || that.equals(PREDICATE_EMPTY_DEFAULT)) {
      that = ASTERISK;
    }

    String topic = InputNormalizer.patternFitIgnoreCase(PredicateMaster.get(TOPIC, userid, botid));
    if (topic.equals(EMPTY_STRING) || topic.equals(PREDICATE_EMPTY_DEFAULT)) {
      topic = ASTERISK;
    }

    return getMatchResult(input, that, topic, userid, botid, parser);
  }
예제 #9
0
 public static void loop(RobotController theRC) throws GameActionException {
   Clock.yield();
   Bot.init(theRC);
   init();
   while (true) {
     try {
       turn();
     } catch (Exception e) {
       e.printStackTrace();
     }
     Clock.yield();
   }
 }
예제 #10
0
  // HQ or pastr calls this function to spend spare bytecodes computing paths for soldiers
  public static void work(MapLocation dest, int priority, int bytecodeLimit)
      throws GameActionException {
    int page = findFreePage(dest, priority);
    Debug.indicate("path", 1, "BFS Pathing to " + dest.toString() + "; using page " + page);
    if (page == -1) return; // We can't do any work, or don't have to

    if (!dest.equals(previousDest)) {
      Debug.indicate("path", 0, "BFS initingQueue");
      initQueue(dest);
    } else {
      Debug.indicate("path", 0, "BFS queue already inited");
    }

    previousDest = dest;
    previousRoundWorked = Clock.getRoundNum();
    previousPage = page;

    int mapWidth = rc.getMapWidth();
    int mapHeight = rc.getMapHeight();
    MapLocation enemyHQ = rc.senseEnemyHQLocation();
    boolean destInSpawn = dest.distanceSquaredTo(enemyHQ) <= 25;

    while (locQueueHead != locQueueTail && Clock.getBytecodeNum() < bytecodeLimit) {
      // pop a location from the queue
      MapLocation loc = locQueue[locQueueHead];
      locQueueHead++;

      int locX = loc.x;
      int locY = loc.y;
      for (int i = 8; i-- > 0; ) {
        int x = locX + dirsX[i];
        int y = locY + dirsY[i];
        if (x >= 0 && y >= 0 && x < mapWidth && y < mapHeight && !wasQueued[x][y]) {
          MapLocation newLoc = new MapLocation(x, y);
          if (rc.senseTerrainTile(newLoc) != TerrainTile.VOID
              && (destInSpawn || !Bot.isInTheirHQAttackRange(newLoc))) {
            publishResult(page, newLoc, dest, dirs[i]);

            // push newLoc onto queue
            locQueue[locQueueTail] = newLoc;
            locQueueTail++;
            wasQueued[x][y] = true;
          }
        }
      }
    }

    boolean finished = locQueueHead == locQueueTail;
    Debug.indicate("path", 2, "BFS finished = " + finished + "; locQueueHead = " + locQueueHead);
    writePageMetadata(page, Clock.getRoundNum(), dest, priority, finished);
  }
예제 #11
0
 private static void startBots() {
   logger.info("Starting bots");
   List<YAMLNode> nodes = ChatBot.getSettingsManager().getMainConfig().getNodeList("bots", null);
   for (YAMLNode node : nodes) {
     final String botType = node.getString("type");
     logger.info("Starting {} bot", botType);
     try {
       BotClassInfo botClassInfo = BOT_INFO.get(botType);
       if (botClassInfo == null) {
         logger.error("Cannot start bot '{}': the specified bot doesn't exist!", botType);
         continue;
       }
       Bot bot = botClassInfo.getBotClass().newInstance();
       bot.info = botClassInfo;
       bot.start();
       BOTS.add(bot);
     } catch (Exception e) {
       logger.error("Failed to start bot '{}'", botType);
       e.printStackTrace();
     }
   }
   logger.info("Started {} bot(s)", BOTS.size());
 }
예제 #12
0
  protected static void init(RobotController theRC) throws GameActionException {
    Bot.init(theRC);
    //		Debug.init(theRC, "pages");

    // claim the assignment to build this pastr so others know not to build it
    int numPastrLocations = MessageBoard.NUM_PASTR_LOCATIONS.readInt();
    for (int i = 0; i < numPastrLocations; i++) {
      MapLocation pastrLoc = MessageBoard.BEST_PASTR_LOCATIONS.readFromMapLocationList(i);
      if (rc.getLocation().equals(pastrLoc)) {
        MessageBoard.PASTR_BUILDER_ROBOT_IDS.claimAssignment(i);
        break;
      }
    }
  }
예제 #13
0
 public void Handler(String[] args, String sender, Bot b) {
   if (args[0].equals("!register")) {
     r.Reg(args, sender, b);
     // b.sendMessage(sender, c() + "03,01 Connecting to: " + Colors.BOLD + c() + "04,01Uplink
     // Public Access Server... " + Colors.BOLD + c() + "00,01<- / -> ");
   } else if (args[0].equals("!help")) {
     b.sendMessage(sender, "~-~ UplinkRPG v0.1a by expertmac2 ~-~");
     b.sendMessage(sender, "!argstest [arg] [arg]: Testing of args");
     b.sendMessage(
         sender, "!register: Establishes a connection to the Uplink Public Access Server.");
   } else if (args[0].equals("!argstest")) {
     try {
       b.sendMessage(sender, "1: " + args[1] + " and 2: " + args[2]);
     } catch (ArrayIndexOutOfBoundsException e) {
       b.sendMessage(sender, "[ERROR] Syntax: !argstest [arg1] [arg2]");
     }
   } else {
     b.sendMessage(sender, "[ERROR] Invalid command. Try !help.");
   }
 }
예제 #14
0
 private double evaluate(RobotInfo info) {
   return bot.distanceSquaredTo(info.location);
 }
예제 #15
0
파일: Room.java 프로젝트: l3eta/Turntable
 public void saveUser(User user) {
   bot.getDatabase().saveUser(user);
 }
예제 #16
0
  protected static void init(RobotController theRC) throws GameActionException {
    Bot.init(theRC);
    // Debug.init(theRC, "herd");

    here = rc.getLocation();

    // claim the assignment to build this tower so others know not to build it
    int numPastrLocations = MessageBoard.NUM_PASTR_LOCATIONS.readInt();
    amSuppressor = true;
    for (int i = 0; i < numPastrLocations; i++) {
      MapLocation pastrLoc = MessageBoard.BEST_PASTR_LOCATIONS.readFromMapLocationList(i);
      if (rc.getLocation().isAdjacentTo(pastrLoc)) {
        amSuppressor = false;
        MessageBoard.TOWER_BUILDER_ROBOT_IDS.claimAssignment(i);
        break;
      }
    }

    if (amSuppressor) {
      int bestDistSq = 999999;
      int numSuppressors = MessageBoard.NUM_SUPPRESSORS.readInt();
      int suppressorIndex = -1;
      for (int i = 0; i < numSuppressors; i++) {
        MapLocation target = MessageBoard.SUPPRESSOR_TARGET_LOCATIONS.readFromMapLocationList(i);
        int distSq = here.distanceSquaredTo(target);
        if (distSq < bestDistSq) {
          bestDistSq = distSq;
          suppressionTarget = target;
          suppressorIndex = i;
        }
      }
      if (suppressorIndex != -1) {
        MessageBoard.SUPPRESSOR_BUILDER_ROBOT_IDS.claimAssignment(suppressorIndex);
      }
    } else {
      // Figure out the best direction to start herding in
      double[] freeCows = new double[8];
      double[][] cowGrowth = rc.senseCowGrowth();
      Direction[] dirs = Direction.values();
      for (int i = 0; i < 8; i++) {
        Direction dir = dirs[i];
        MapLocation probe = here.add(dir);
        while (Util.passable(rc.senseTerrainTile(probe))
            && here.distanceSquaredTo(probe) <= RobotType.NOISETOWER.attackRadiusMaxSquared) {
          freeCows[i] += cowGrowth[probe.x][probe.y];
          probe = probe.add(dir);
        }
      }

      double bestScore = -1;
      int bestDir = -1;
      for (int i = 0; i < 8; i++) {
        double score = freeCows[i] + freeCows[(i + 1) % 8] + freeCows[(i + 2) % 8];
        if (score > bestScore) {
          bestScore = score;
          bestDir = i;
        }
      }
      attackDir = dirs[bestDir];
    }
  }
 public void assertIsNotOpen(Openable openable, Object... arguments) throws AssertionError {
   Bot.assertIsNotOpen(openable, arguments);
 }
 public boolean isNotOpen(Openable openable, Object... arguments) {
   return Bot.isNotOpen(openable, arguments);
 }
 public void open(Openable openable, Object... arguments) {
   Bot.open(openable, arguments);
 }
 // WORKAROUND: Make Bot methods visible that are otherwise hidden when using static import
 public void open(String url) {
   Bot.open(url);
 }
예제 #21
0
  /**
   * Gets the list of replies to some input sentences. Assumes that the sentences have already had
   * all necessary pre-processing and substitutions performed.
   *
   * @param sentenceList the input sentences
   * @param userid the userid requesting the replies
   * @param botid
   * @return the list of replies to the input sentences
   */
  private static ArrayList getReplies(ArrayList sentenceList, String userid, String botid) {
    // All replies will be assembled in this ArrayList.
    ArrayList replies = new ArrayList(sentenceList.size());

    // Get the requested bot.
    Bot bot = Bots.getBot(botid);

    // Ready the that and topic predicates for constructing the match path.
    ArrayList thatSentences = bot.sentenceSplit(PredicateMaster.get(THAT, 1, userid, botid));
    String that =
        InputNormalizer.patternFitIgnoreCase((String) thatSentences.get(thatSentences.size() - 1));

    if (that.equals(EMPTY_STRING) || that.equals(PREDICATE_EMPTY_DEFAULT)) {
      that = ASTERISK;
    }

    String topic = InputNormalizer.patternFitIgnoreCase(PredicateMaster.get(TOPIC, userid, botid));
    if (topic.equals(EMPTY_STRING) || topic.equals(PREDICATE_EMPTY_DEFAULT)) {
      topic = ASTERISK;
    }

    Iterator sentences = sentenceList.iterator();

    // We might use this to track matching statistics.
    long time = 0;

    // If match trace info is on, mark the time just before matching starts.
    if (SHOW_MATCH_TRACE) {
      time = System.currentTimeMillis();
    }

    // Get a reply for each sentence.
    while (sentences.hasNext()) {
      replies.add(getReply((String) sentences.next(), that, topic, userid, botid));
    }

    // Increment the (static) response count.
    responseCount++;
    ;

    // If match trace info is on, produce statistics about the response time.
    if (SHOW_MATCH_TRACE) {
      // Mark the time that processing is finished.
      time = System.currentTimeMillis() - time;

      // Calculate the average response time.
      totalTime += time;
      avgResponseTime = (float) totalTime / (float) responseCount;
      Trace.userinfo(
          RESPONSE_SPACE
              + responseCount
              + SPACE_IN_SPACE
              + time
              + MS_AVERAGE
              + avgResponseTime
              + MS);
    }

    // Invoke targeting if appropriate.
    if (responseCount % TARGET_SKIP == 0) {
      if (USE_TARGETING) {
        Graphmaster.checkpoint();
      }
    }

    // If no replies, return an empty string.
    if (replies.size() == 0) {
      replies.add(EMPTY_STRING);
    }
    return replies;
  }
예제 #22
0
  /*
   * @pre Appeler majStatut() avant //
   * @warning ATTENTION CETTE METHODE EST A MODIFIER SI LE FORMAT CHANGE DANS LE PRACTICE //
   * @description : On suppose que le premier robot à jouer est le notre //
   */
  public void majRobots() throws IOException, InterruptedException {

    String[] tokens;
    tokens = Parser();

    System.out.println("\n \n Joueur : " + tokens[0]);
    Thread.sleep(1000);

    if (tokens[0].equals(nomEquipeServeur)) {

      System.out.println("\n \n Dans Joueur nous sommes J1 \n\n\n");
      // MAJ VALEURS DE NOTRE BOT  //
      botMiagic.setNumJoeur("Joueur 1");

      botMiagic.setNbVies(tokens[1]);
      botMiagic.setNbBombe(tokens[2]);
      botMiagic.setNbBullet(tokens[3]);

      botMiagic.setNbBouclier(tokens[4]);

      // MAJ VALEURS DE l'ADVERSAIRE PRACTICE //
      botAdverse.setNumJoeur("Joueur 2");

      botAdverse.setNbVies(tokens[6]);
      botAdverse.setNbBombe(tokens[7]);
      botAdverse.setNbBullet(tokens[8]);

      botAdverse.setNbBouclier(tokens[9]);

      this.coutRestant = Integer.parseInt(tokens[10]);
    } else if (tokens[5].equals(nomEquipeServeur)) {

      System.out.println("\n \n Dans Joueur nous sommes J2 \n\n\n");

      // MAJ VALEURS DE l'ADVERSAIRE PRACTICE //
      botAdverse.setNumJoeur("Joueur 1");

      botAdverse.setNbVies(tokens[1]);
      botAdverse.setNbBombe(tokens[2]);
      botAdverse.setNbBullet(tokens[3]);

      botAdverse.setNbBouclier(tokens[4]);

      // MAJ VALEURS DE l'ADVERSAIRE PRACTICE //
      botMiagic.setNumJoeur("Joueur 2");

      botMiagic.setNbVies(tokens[6]);
      botMiagic.setNbBombe(tokens[7]);
      botMiagic.setNbBullet(tokens[8]);

      botMiagic.setNbBouclier(tokens[9]);

      this.coutRestant = Integer.parseInt(tokens[10]);
    }
  }