Example #1
0
  public static double getHammerRate(Town town) {
    ArrayList<SessionEntry> entries = CivGlobal.getSessionDB().lookup(HammerRate.getKey(town));
    double hammerrate = 1.0;

    ArrayList<SessionEntry> removed = new ArrayList<SessionEntry>();
    for (SessionEntry entry : entries) {
      String[] split = entry.value.split(":");
      double rate = Double.valueOf(split[0]);
      int duration = Integer.valueOf(split[1]);

      Date start = new Date(entry.time);
      Date now = new Date();

      if (now.getTime()
          > (start.getTime() + (duration * RandomEventSweeper.MILLISECONDS_PER_HOUR))) {
        /* Entry is expired, delete it and continue. */
        removed.add(entry);
        continue;
      }
      hammerrate *= rate;
    }

    /* Remove any expired entries */
    for (SessionEntry entry : removed) {
      CivGlobal.getSessionDB().delete(entry.request_id, entry.key);
    }
    return hammerrate;
  }
  public void conquered_cmd() throws CivException {
    Civilization civ = getNamedCiv(1);
    civ.setConquered(true);
    CivGlobal.removeCiv(civ);
    CivGlobal.addConqueredCiv(civ);
    civ.save();

    CivMessage.sendSuccess(
        sender, CivSettings.localize.localizedString("adcmd_civ_conqueredSuccess"));
  }
Example #3
0
  public void fancyDestroyStructureBlocks() {
    for (BlockCoord coord : this.structureBlocks.keySet()) {

      if (CivGlobal.getStructureChest(coord) != null) {
        continue;
      }

      if (CivGlobal.getStructureSign(coord) != null) {
        continue;
      }

      if (ItemManager.getId(coord.getBlock()) == CivData.BEDROCK
          || ItemManager.getId(coord.getBlock()) == CivData.AIR) {
        // Be a bit more careful not to destroy any of the item frames..
        continue;
      }

      Random rand = new Random();

      // Each block has a 10% chance to turn into gravel
      if (rand.nextInt(100) <= 10) {
        ItemManager.setTypeId(coord.getBlock(), CivData.GRAVEL);
        continue;
      }

      // Each block has a 50% chance of starting a fire
      if (rand.nextInt(100) <= 50) {
        ItemManager.setTypeId(coord.getBlock(), CivData.FIRE);
        continue;
      }

      // Each block has a 1% chance of launching an explosion effect
      if (rand.nextInt(100) <= 1) {
        FireworkEffect effect =
            FireworkEffect.builder()
                .with(org.bukkit.FireworkEffect.Type.BURST)
                .withColor(Color.ORANGE)
                .withColor(Color.RED)
                .withTrail()
                .withFlicker()
                .build();
        FireworkEffectPlayer fePlayer = new FireworkEffectPlayer();
        for (int i = 0; i < 3; i++) {
          try {
            fePlayer.playFirework(coord.getBlock().getWorld(), coord.getLocation(), effect);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    }
  }
Example #4
0
  public void onCannonDamage(int damage, CannonProjectile projectile) throws CivException {
    this.hitpoints -= damage;

    Resident resident = projectile.whoFired;
    if (hitpoints <= 0) {
      for (BlockCoord coord : this.controlPoints.keySet()) {
        ControlPoint cp = this.controlPoints.get(coord);
        if (cp != null) {
          if (cp.getHitpoints() > CannonProjectile.controlBlockHP) {
            cp.damage(cp.getHitpoints() - 1);
            this.hitpoints = this.getMaxHitPoints() / 2;
            StructureBlock hit = CivGlobal.getStructureBlock(coord);
            onControlBlockCannonDestroy(cp, CivGlobal.getPlayer(resident), hit);
            CivMessage.sendCiv(
                getCiv(),
                "Our "
                    + this.getDisplayName()
                    + " has been hit by a cannon and a control block was set to "
                    + CannonProjectile.controlBlockHP
                    + " HP!");
            CivMessage.sendCiv(
                getCiv(),
                "Our "
                    + this.getDisplayName()
                    + " has regenerated "
                    + this.getMaxHitPoints() / 2
                    + " HP! If it drops to zero, we will lose another Control Point.");
            return;
          }
        }
      }

      CivMessage.sendCiv(
          getCiv(),
          "Our "
              + this.getDisplayName()
              + " is out of hitpoints, walls can be destroyed by cannon and TNT blasts!");
      hitpoints = 0;
    }

    CivMessage.sendCiv(
        getCiv(),
        "Our "
            + this.getDisplayName()
            + " has been hit by a cannon! ("
            + this.hitpoints
            + "/"
            + this.getMaxHitPoints()
            + ")");
  }
Example #5
0
  @Override
  public void onPreBuild(Location loc) throws CivException {
    TownHall oldTownHall = this.getTown().getTownHall();
    if (oldTownHall != null) {
      ChunkCoord coord = new ChunkCoord(loc);
      TownChunk tc = CivGlobal.getTownChunk(coord);
      if (tc == null || tc.getTown() != this.getTown()) {
        throw new CivException("Cannot rebuild your town hall outside of your town borders.");
      }

      if (War.isWarTime()) {
        throw new CivException("Cannot rebuild your town hall during war time.");
      }

      this.getTown().clearBonusGoods();

      try {
        this.getTown().demolish(oldTownHall, true);
      } catch (CivException e) {
        e.printStackTrace();
      }
      CivMessage.sendTown(
          this.getTown(),
          "Your old town hall or capitol was demolished to make way for your new one.");
      this.autoClaim = false;
    } else {
      this.autoClaim = true;
    }
  }
Example #6
0
  @Override
  public void delete() throws SQLException {
    if (this.getTown() != null) {
      /* Remove any protected item frames. */
      for (ItemFrameStorage framestore : goodieFrames) {
        BonusGoodie goodie = CivGlobal.getBonusGoodie(framestore.getItem());
        if (goodie != null) {
          goodie.replenish();
        }

        CivGlobal.removeProtectedItemFrame(framestore.getFrameID());
      }
    }

    super.delete();
  }
  public void setgov_cmd() throws CivException {
    Civilization civ = getNamedCiv(1);

    if (args.length < 3) {
      throw new CivException(CivSettings.localize.localizedString("adcmd_civ_setgovPrompt"));
    }

    ConfigGovernment gov = CivSettings.governments.get(args[2]);
    if (gov == null) {
      throw new CivException(
          CivSettings.localize.localizedString("adcmd_civ_setGovInvalidGov")
              + " gov_monarchy, gov_depostism... etc");
    }
    // Remove any anarchy timers
    String key = "changegov_" + civ.getId();
    CivGlobal.getSessionDB().delete_all(key);

    civ.setGovernment(gov.id);
    CivMessage.global(
        CivSettings.localize.localizedString(
            "var_adcmd_civ_setGovSuccessBroadcast",
            civ.getName(),
            CivSettings.governments.get(gov.id).displayName));
    CivMessage.sendSuccess(sender, CivSettings.localize.localizedString("adcmd_civ_setGovSuccess"));
  }
  @Override
  public void respond(String message, Resident resident) {
    Player player;
    try {
      player = CivGlobal.getPlayer(resident);
    } catch (CivException e) {
      return;
    }
    resident.clearInteractiveMode();

    if (!message.equalsIgnoreCase("yes")) {
      CivMessage.sendError(player, "Mission Aborted.");
      return;
    }

    if (!TaskMaster.hasTask("missiondelay:" + playerName)) {
      TaskMaster.asyncTask(
          "missiondelay:" + playerName,
          (new EspionageMissionTask(mission, playerName, playerLocation, target, mission.length)),
          0);
    } else {
      CivMessage.sendError(player, "Waiting on countdown to start mission.");
      return;
    }
  }
Example #9
0
  private static void performPirate(Player player, ConfigMission mission) throws CivException {
    Resident resident = CivGlobal.getResident(player);
    if (resident == null || !resident.hasTown()) {
      throw new CivException("Only residents of towns can perform spy missions.");
    }
    // Must be within enemy town borders.
    ChunkCoord coord = new ChunkCoord(player.getLocation());
    CultureChunk cc = CivGlobal.getCultureChunk(coord);
    if (cc == null || cc.getCiv() == resident.getTown().getCiv()) {
      throw new CivException("Must be in another civilization's borders.");
    }

    // Check that the player is within range of the town hall.
    Structure tradeoutpost = cc.getCiv().getNearestStructureInTowns(player.getLocation());
    if (!(tradeoutpost instanceof TradeOutpost)) {
      throw new CivException("The closest structure to you must be a trade outpost.");
    }

    double distance =
        player
            .getLocation()
            .distance(((TradeOutpost) tradeoutpost).getTradeOutpostTower().getLocation());
    if (distance > mission.range) {
      throw new CivException("Too far away from the trade outpost to pirate it.");
    }

    TradeOutpost outpost = (TradeOutpost) tradeoutpost;
    ItemStack stack = outpost.getItemFrameStore().getItem();

    if (stack == null || ItemManager.getId(stack) == CivData.AIR) {
      throw new CivException("No trade goodie item at this location.");
    }

    if (processMissionResult(player, cc.getTown(), mission)) {
      outpost.getItemFrameStore().clearItem();
      player.getWorld().dropItem(player.getLocation(), stack);

      CivMessage.sendSuccess(player, "Arg! Got the booty!");
      CivMessage.sendTown(
          cc.getTown(),
          CivColor.Rose
              + "Avast! Someone stole our trade goodie "
              + outpost.getGood().getInfo().name
              + " at "
              + outpost.getCorner());
    }
  }
  public static ArrayList<String> getMissionLogs(Town town) {
    Connection context = null;
    ResultSet rs = null;
    PreparedStatement ps = null;

    try {
      ArrayList<String> out = new ArrayList<String>();
      try {
        context = SQL.getGameConnection();
        ps =
            context.prepareStatement(
                "SELECT * FROM " + SQL.tb_prefix + TABLE_NAME + " WHERE `town_id` = ?");
        ps.setInt(1, town.getId());
        rs = ps.executeQuery();

        SimpleDateFormat sdf = new SimpleDateFormat("M/dd h:mm:ss a z");
        while (rs.next()) {
          Date date = new Date(rs.getLong("time"));
          Town target = CivGlobal.getTownFromId(rs.getInt("target_id"));
          if (target == null) {
            continue;
          }

          String playerName = rs.getString("playerName");
          playerName = CivGlobal.getResidentViaUUID(UUID.fromString(playerName)).getName();

          String str =
              sdf.format(date)
                  + " - "
                  + rs.getString("playerName")
                  + ":"
                  + target.getName()
                  + ":"
                  + rs.getString("missionName")
                  + " -- "
                  + rs.getString("result");
          out.add(str);
        }
      } catch (SQLException e) {
        e.printStackTrace();
      }

      return out;
    } finally {
      SQL.close(rs, ps, context);
    }
  }
Example #11
0
  private static void performStealTreasury(Player player, ConfigMission mission)
      throws CivException {

    Resident resident = CivGlobal.getResident(player);
    if (resident == null || !resident.hasTown()) {
      throw new CivException("Only residents of towns can perform spy missions.");
    }

    // Must be within enemy town borders.
    ChunkCoord coord = new ChunkCoord(player.getLocation());
    TownChunk tc = CivGlobal.getTownChunk(coord);

    if (tc == null || tc.getTown().getCiv() == resident.getTown().getCiv()) {
      throw new CivException("Must be in another civilization's town's borders.");
    }

    // Check that the player is within range of the town hall.
    TownHall townhall = tc.getTown().getTownHall();
    if (townhall == null) {
      throw new CivException("This town doesnt have a town hall... that sucks.");
    }

    double distance = player.getLocation().distance(townhall.getCorner().getLocation());
    if (distance > mission.range) {
      throw new CivException("Too far away from town hall to steal treasury.");
    }

    double failMod = 1.0;
    if (resident.getTown().getBuffManager().hasBuff("buff_dirty_money")) {
      failMod = resident.getTown().getBuffManager().getEffectiveDouble("buff_dirty_money");
      CivMessage.send(
          player, CivColor.LightGray + "Your goodie buff 'Dirty Money' will come in handy here.");
    }

    if (processMissionResult(player, tc.getTown(), mission, failMod, 1.0)) {

      double amount = (int) (tc.getTown().getTreasury().getBalance() * 0.2);
      if (amount > 0) {
        tc.getTown().getTreasury().withdraw(amount);
        resident.getTown().getTreasury().deposit(amount);
      }

      CivMessage.sendSuccess(
          player, "Success! Stole " + amount + " coins from " + tc.getTown().getName());
    }
  }
Example #12
0
  public void build_trade_outpost_tower() throws CivException {
    /* Add trade good to town. */

    /* this.good is set by the good's load function or by the onBuild function. */
    TradeGood good = this.good;
    if (good == null) {
      throw new CivException("Couldn't find trade good at location:" + good);
    }

    /* Build the 'trade good tower' */
    /* This is always set on post build using the post build sync task. */
    if (tradeOutpostTower == null) {
      throw new CivException("Couldn't find trade outpost tower.");
    }

    Location centerLoc = tradeOutpostTower.getLocation();

    /* Build the bedrock tower. */
    for (int i = 0; i < 3; i++) {
      Block b = centerLoc.getBlock().getRelative(0, i, 0);
      ItemManager.setTypeId(b, CivData.BEDROCK);
      ItemManager.setData(b, 0);

      StructureBlock sb = new StructureBlock(new BlockCoord(b), this);
      this.addStructureBlock(sb.getCoord(), false);
      // CivGlobal.addStructureBlock(sb.getCoord(), this);
    }

    /* Place the sign. */
    Block b = centerLoc.getBlock().getRelative(1, 2, 0);
    ItemManager.setTypeId(b, CivData.WALL_SIGN);
    ItemManager.setData(b, CivData.DATA_SIGN_EAST);
    Sign s = (Sign) b.getState();
    s.setLine(0, good.getInfo().name);
    s.update();
    StructureBlock sb = new StructureBlock(new BlockCoord(b), this);
    // CivGlobal.addStructureBlock(sb.getCoord(), this);
    this.addStructureBlock(sb.getCoord(), false);

    /* Place the itemframe. */
    b = centerLoc.getBlock().getRelative(1, 1, 0);
    this.addStructureBlock(new BlockCoord(b), false);
    Block b2 = b.getRelative(0, 0, 0);
    Entity entity = CivGlobal.getEntityAtLocation(b2.getLocation());
    this.addStructureBlock(new BlockCoord(b2), false);

    if (entity == null || (!(entity instanceof ItemFrame))) {
      this.frameStore = new ItemFrameStorage(b.getLocation(), BlockFace.EAST);
    } else {
      this.frameStore = new ItemFrameStorage((ItemFrame) entity, b.getLocation());
    }

    this.frameStore.setBuildable(this);
  }
  public void unconquer_cmd() throws CivException {
    String conquerCiv = this.getNamedString(1, "conquered civ");

    Civilization civ = CivGlobal.getConqueredCiv(conquerCiv);
    if (civ == null) {
      civ = CivGlobal.getCiv(conquerCiv);
    }

    if (civ == null) {
      throw new CivException(
          CivSettings.localize.localizedString("var_adcmd_civ_NoCivByThatNane", conquerCiv));
    }

    civ.setConquered(false);
    CivGlobal.removeConqueredCiv(civ);
    CivGlobal.addCiv(civ);
    civ.save();

    CivMessage.sendSuccess(
        sender, CivSettings.localize.localizedString("adcmd_civ_unconquerSuccess"));
  }
Example #14
0
  public static void performMission(ConfigMission mission, String playerName) {
    Player player;
    try {
      player = CivGlobal.getPlayer(playerName);
    } catch (CivException e1) {
      return;
    }

    try {
      Resident resident = CivGlobal.getResident(playerName);
      if (!resident.getTown().getTreasury().hasEnough(mission.cost)) {
        throw new CivException(
            "Your town requires " + mission.cost + " coins to perform this mission.");
      }

      switch (mission.id) {
        case "spy_investigate_town":
          performInvestigateTown(player, mission);
          break;
        case "spy_steal_treasury":
          performStealTreasury(player, mission);
          break;
        case "spy_incite_riots":
          performInciteRiots(player, mission);
          break;
        case "spy_poison_granary":
          performPosionGranary(player, mission);
          break;
        case "spy_pirate":
          performPirate(player, mission);
          break;
        case "spy_sabotage":
          performSabotage(player, mission);
          break;
      }

    } catch (CivException e) {
      CivMessage.sendError(player, e.getMessage());
    }
  }
  public void setrelation_cmd() throws CivException {
    if (args.length < 4) {
      throw new CivException(
          CivSettings.localize.localizedString("Usage")
              + " [civ] [otherCiv] [NEUTRAL|HOSTILE|WAR|PEACE|ALLY]");
    }

    Civilization civ = getNamedCiv(1);
    Civilization otherCiv = getNamedCiv(2);

    Relation.Status status = Relation.Status.valueOf(args[3].toUpperCase());

    CivGlobal.setRelation(civ, otherCiv, status);
    if (status.equals(Status.WAR)) {
      CivGlobal.setAggressor(civ, otherCiv, civ);
      CivGlobal.setAggressor(otherCiv, civ, civ);
    }
    CivMessage.sendSuccess(
        sender,
        CivSettings.localize.localizedString(
            "var_adcmd_civ_setrelationSuccess", civ.getName(), otherCiv.getName(), status.name()));
  }
  public void liberate_cmd() throws CivException {
    Civilization motherCiv = getNamedCiv(1);

    /* Liberate the civ. */
    for (Town t : CivGlobal.getTowns()) {
      if (t.getMotherCiv() == motherCiv) {
        t.changeCiv(motherCiv);
        t.setMotherCiv(null);
        t.save();
      }
    }

    motherCiv.setConquered(false);
    CivGlobal.removeConqueredCiv(motherCiv);
    CivGlobal.addCiv(motherCiv);
    motherCiv.save();
    CivMessage.sendSuccess(
        sender,
        CivSettings.localize.localizedString("adcmd_civ_liberateSuccess")
            + " "
            + motherCiv.getName());
  }
      @Override
      public void run() {
        Player player;
        try {
          player = CivGlobal.getPlayer(playerName);
        } catch (CivException e) {
          return;
        }

        Resident resident = CivGlobal.getResident(playerName);
        if (resident == null) {
          return;
        }

        CivMessage.send(player, TownCommand.survey(player.getLocation()));
        CivMessage.send(player, "");
        CivMessage.send(
            player,
            CivColor.LightGreen
                + ChatColor.BOLD
                + CivSettings.localize.localizedString("interactive_capitol_confirmPrompt"));
        resident.setInteractiveMode(new InteractiveConfirmCivCreation());
      }
  @EventHandler(priority = EventPriority.MONITOR)
  public void onChannelChatEvent(ChannelChatEvent event) {
    Resident resident = CivGlobal.getResident(event.getSender().getName());
    if (resident == null) {
      event.setResult(Result.FAIL);
      return;
    }

    if (!resident.isInteractiveMode()) {
      if (resident.isMuted()) {
        event.setResult(Result.MUTED);
        return;
      }
    }

    if (event.getChannel().getDistance() > 0) {
      for (String name : Resident.allchatters) {
        Player player;
        try {
          player = CivGlobal.getPlayer(name);
        } catch (CivException e) {
          continue;
        }

        Chatter you = Herochat.getChatterManager().getChatter(player);
        if (!event.getSender().isInRange(you, event.getChannel().getDistance())) {
          player.sendMessage(
              CivColor.White
                  + event.getSender().getName()
                  + CivSettings.localize.localizedString("hc_prefix_far")
                  + " "
                  + event.getMessage());
        }
      }
    }
  }
Example #19
0
  public boolean isAvailable(Town town) {
    if (CivGlobal.testFileFlag("debug-norequire")) {
      CivMessage.global("Ignoring requirements! debug-norequire found.");
      return true;
    }

    if (town.hasUpgrade(this.require_upgrade)) {
      if (town.getCiv().hasTechnology(this.require_tech)) {
        if (town.hasStructure(require_structure)) {
          if (!town.hasUpgrade(this.id)) {
            return true;
          }
        }
      }
    }
    return false;
  }
  @EventHandler(priority = EventPriority.HIGHEST)
  public void onBlockBreak(BlockBreakEvent event) {
    if (event.isCancelled()) {
      return;
    }

    if (!War.isWarTime()) {
      return;
    }

    coord.setFromLocation(event.getBlock().getLocation());
    CultureChunk cc = CivGlobal.getCultureChunk(coord);

    if (cc == null) {
      return;
    }

    if (!cc.getCiv().getDiplomacyManager().isAtWar()) {
      return;
    }

    if (event.getBlock().getType().equals(Material.DIRT)
        || event.getBlock().getType().equals(Material.GRASS)
        || event.getBlock().getType().equals(Material.SAND)
        || event.getBlock().getType().equals(Material.GRAVEL)
        || event.getBlock().getType().equals(Material.TORCH)
        || event.getBlock().getType().equals(Material.REDSTONE_TORCH_OFF)
        || event.getBlock().getType().equals(Material.REDSTONE_TORCH_ON)
        || event.getBlock().getType().equals(Material.REDSTONE)
        || event.getBlock().getType().equals(Material.TNT)
        || event.getBlock().getType().equals(Material.LADDER)
        || event.getBlock().getType().equals(Material.VINE)
        || event.getBlock().getType().equals(Material.IRON_BLOCK)
        || event.getBlock().getType().equals(Material.GOLD_BLOCK)
        || event.getBlock().getType().equals(Material.DIAMOND_BLOCK)
        || event.getBlock().getType().equals(Material.EMERALD_BLOCK)
        || !event.getBlock().getType().isSolid()) {
      return;
    }

    CivMessage.sendError(event.getPlayer(), CivSettings.localize.localizedString("war_mustUseTNT"));
    event.setCancelled(true);
  }
Example #21
0
  @Override
  public void load(ResultSet rs)
      throws SQLException, InvalidNameException, InvalidObjectException, CivException {
    this.setId(rs.getInt("id"));
    this.configRandomEvent = CivSettings.randomEvents.get(rs.getString("config_id"));
    if (this.configRandomEvent == null) {
      /* Delete the random event. */
      this.delete();
      throw new CivException("Couldn't find random event config id:" + rs.getString("config_id"));
    }

    this.town = CivGlobal.getTownFromId(rs.getInt("town_id"));
    if (this.town == null) {
      this.delete();
      throw new CivException(
          "Couldn't find town id:" + rs.getInt("town_id") + " while loading random event.");
    }

    this.startDate = new Date(rs.getLong("start_date"));
    this.active = rs.getBoolean("active");

    loadComponentVars(rs.getString("component_vars"));
    loadSavedMessages(rs.getString("saved_messages"));

    /* Re-run the on start to re-enable any listeners. */
    /* Loop through all components for onStart() */
    buildComponents();
    for (RandomEventComponent comp : this.actions.values()) {
      comp.onStart();
    }
    for (RandomEventComponent comp : this.requirements.values()) {
      comp.onStart();
    }
    for (RandomEventComponent comp : this.success.values()) {
      comp.onStart();
    }
    for (RandomEventComponent comp : this.failure.values()) {
      comp.onStart();
    }

    RandomEventSweeper.register(this);
  }
Example #22
0
  @Override
  public void onDamage(
      int amount, World world, Player player, BlockCoord coord, BuildableDamageBlock hit) {

    ControlPoint cp = this.controlPoints.get(coord);
    Resident resident = CivGlobal.getResident(player);

    if (!resident.canDamageControlBlock()) {
      CivMessage.send(
          player,
          CivColor.Rose
              + "Cannot damage control blocks due to missing/invalid Town Hall or Capitol structure.");
      return;
    }

    if (cp != null) {
      if (!cp.isDestroyed()) {

        if (resident.isControlBlockInstantBreak()) {
          cp.damage(cp.getHitpoints());
        } else {
          cp.damage(amount);
        }

        if (cp.isDestroyed()) {
          onControlBlockDestroy(cp, world, player, (StructureBlock) hit);
        } else {
          onControlBlockHit(cp, world, player, (StructureBlock) hit);
        }
      } else {
        CivMessage.send(player, CivColor.Rose + "Control Block already destroyed.");
      }

    } else {
      CivMessage.send(
          player,
          CivColor.Rose
              + "Cannot Damage "
              + this.getDisplayName()
              + ", go after the control points!");
    }
  }
Example #23
0
  public void build_trade_outpost(Location centerLoc) throws CivException {

    /* Add trade good to town. */
    TradeGood good = CivGlobal.getTradeGood(tradeGoodCoord);
    if (good == null) {
      throw new CivException("Couldn't find trade good at location:" + good);
    }

    if (good.getInfo().water) {
      throw new CivException("Trade Outposts cannot be built on water goods.");
    }

    if (good.getTown() != null) {
      throw new CivException("Good is already claimed.");
    }

    good.setStruct(this);
    good.setTown(this.getTown());
    good.setCiv(this.getTown().getCiv());

    /* Save the good *afterwards* so the structure id is properly set. */
    this.setGood(good);
  }
Example #24
0
  @Override
  public void onDemolish() throws CivException {

    /*
     * If the trade goodie is not in our frame, we should not allow
     * the trade outpost to be demolished. As it may result in an inconsistent state.
     */
    if (this.frameStore == null) {
      return;
    }

    ItemStack frameItem = this.frameStore.getItem();
    if (frameItem != null) {
      BonusGoodie goodie = CivGlobal.getBonusGoodie(frameItem);
      if (goodie != null) {
        if (goodie.getOutpost() == this) {
          return;
        }
      }
    }

    throw new CivException("Cannot demolish when bonus goodie is not in item frame.");
  }
  @Override
  public void run() {

    for (Resident resident : CivGlobal.getResidents()) {
      if (!resident.isProtected()) {
        continue;
      }

      int mins;
      try {
        mins = CivSettings.getInteger(CivSettings.civConfig, "global.pvp_timer");
        if (DateUtil.isAfterMins(new Date(resident.getRegistered()), mins)) {
          // if (DateUtil.isAfterSeconds(new Date(resident.getRegistered()), mins)) {
          resident.setisProtected(false);
          CivMessage.send(
              resident, CivColor.LightGray + CivSettings.localize.localizedString("pvpTimerEnded"));
        }
      } catch (InvalidConfiguration e) {
        e.printStackTrace();
        return;
      }
    }
  }
  public void displayQuestion() {
    Player player;
    try {
      player = CivGlobal.getPlayer(playerName);
    } catch (CivException e) {
      return;
    }

    CivMessage.sendHeading(player, "Mission: " + mission.name);

    double failChance = MissionBook.getMissionFailChance(mission, target);
    double compChance = MissionBook.getMissionCompromiseChance(mission, target);
    DecimalFormat df = new DecimalFormat();

    String successChance = df.format((1 - failChance) * 100) + "%";
    String compromiseChance = df.format(compChance) + "%";
    String length = "";

    int mins = mission.length / 60;
    int seconds = mission.length % 60;
    if (mins > 0) {
      length += mins + " mins";
      if (seconds > 0) {
        length += " and ";
      }
    }

    if (seconds > 0) {
      length += seconds + " seconds";
    }

    CivMessage.send(
        player,
        CivColor.Green
            + CivColor.BOLD
            + "We have a "
            + CivColor.LightGreen
            + successChance
            + CivColor.Green
            + CivColor.BOLD
            + " chance of success.");
    CivMessage.send(
        player,
        CivColor.Green
            + CivColor.BOLD
            + "If we fail, the chance of being compromised is "
            + CivColor.LightGreen
            + compromiseChance);
    CivMessage.send(
        player,
        CivColor.Green
            + CivColor.BOLD
            + "It will cost our town "
            + CivColor.Yellow
            + mission.cost
            + CivColor.Green
            + CivColor.BOLD
            + " Coins to perform this mission.");
    CivMessage.send(
        player,
        CivColor.Green
            + CivColor.BOLD
            + "The mission will take "
            + CivColor.Yellow
            + length
            + CivColor.Green
            + CivColor.BOLD
            + " to complete.");
    CivMessage.send(
        player,
        CivColor.Green
            + CivColor.BOLD
            + "You must remain within the civ's borders during the mission, otherwise you'll fail the mission.");
    CivMessage.send(
        player,
        CivColor.Green
            + CivColor.BOLD
            + "If these conditions are acceptible, type "
            + CivColor.Yellow
            + "yes");
    CivMessage.send(player, CivColor.Green + ChatColor.BOLD + "Type anything else to abort.");
  }
Example #27
0
  @SuppressWarnings("deprecation")
  private static void performInvestigateTown(Player player, ConfigMission mission)
      throws CivException {

    Resident resident = CivGlobal.getResident(player);
    if (resident == null || !resident.hasTown()) {
      throw new CivException("Only residents of towns can perform spy missions.");
    }

    // Must be within enemy town borders.
    ChunkCoord coord = new ChunkCoord(player.getLocation());
    TownChunk tc = CivGlobal.getTownChunk(coord);

    if (tc == null || tc.getTown().getCiv() == resident.getTown().getCiv()) {
      throw new CivException("Must be in another civilization's town's borders.");
    }

    if (processMissionResult(player, tc.getTown(), mission)) {
      ItemStack book = new ItemStack(Material.WRITTEN_BOOK, 1);
      BookMeta meta = (BookMeta) book.getItemMeta();
      ArrayList<String> lore = new ArrayList<String>();
      lore.add("Mission Report");

      meta.setAuthor("Mission Reports");
      meta.setTitle("Investigate Town");

      //	ArrayList<String> out = new ArrayList<String>();
      String out = "";

      out += ChatColor.UNDERLINE + "Town:" + tc.getTown().getName() + "\n" + ChatColor.RESET;
      out +=
          ChatColor.UNDERLINE + "Civ:" + tc.getTown().getCiv().getName() + "\n\n" + ChatColor.RESET;

      SimpleDateFormat sdf = new SimpleDateFormat("M/dd h:mm:ss a z");
      out += "Time: " + sdf.format(new Date()) + "\n";
      out += ("Treasury: " + tc.getTown().getTreasury().getBalance() + "\n");
      out += ("Hammers: " + tc.getTown().getHammers().total + "\n");
      out += ("Culture: " + tc.getTown().getCulture().total + "\n");
      out += ("Growth: " + tc.getTown().getGrowth().total + "\n");
      out += ("Beakers(civ): " + tc.getTown().getBeakers().total + "\n");
      if (tc.getTown().getCiv().getResearchTech() != null) {
        out += ("Researching: " + tc.getTown().getCiv().getResearchTech().name + "\n");
      } else {
        out += ("Researching:Nothing" + "\n");
      }

      BookUtil.paginate(meta, out);

      out = ChatColor.UNDERLINE + "Upkeep Info\n\n" + ChatColor.RESET;
      try {
        out += "From Spread:" + tc.getTown().getSpreadUpkeep() + "\n";
        out += "From Structures:" + tc.getTown().getStructureUpkeep() + "\n";
        out += "Total:" + tc.getTown().getTotalUpkeep();
        BookUtil.paginate(meta, out);
      } catch (InvalidConfiguration e) {
        e.printStackTrace();
        throw new CivException("Internal configuration exception.");
      }

      meta.setLore(lore);
      book.setItemMeta(meta);

      HashMap<Integer, ItemStack> leftovers = player.getInventory().addItem(book);
      for (ItemStack stack : leftovers.values()) {
        player.getWorld().dropItem(player.getLocation(), stack);
      }

      player.updateInventory();

      CivMessage.sendSuccess(player, "Mission Accomplished");
    }
  }
Example #28
0
  private static void performPosionGranary(Player player, ConfigMission mission)
      throws CivException {
    Resident resident = CivGlobal.getResident(player);
    if (resident == null || !resident.hasTown()) {
      throw new CivException("Only residents of towns can perform spy missions.");
    }

    // Must be within enemy town borders.
    ChunkCoord coord = new ChunkCoord(player.getLocation());
    TownChunk tc = CivGlobal.getTownChunk(coord);

    if (tc == null || tc.getTown().getCiv() == resident.getTown().getCiv()) {
      throw new CivException("Must be in another civilization's town's borders.");
    }

    // Check that the player is within range of the town hall.
    Structure granary = tc.getTown().getNearestStrucutre(player.getLocation());
    if (!(granary instanceof Granary)) {
      throw new CivException("The closest structure to you must be a granary.");
    }

    double distance = player.getLocation().distance(granary.getCorner().getLocation());
    if (distance > mission.range) {
      throw new CivException("Too far away from the granary to poison it.");
    }

    ArrayList<SessionEntry> entries =
        CivGlobal.getSessionDB().lookup("posiongranary:" + tc.getTown().getName());
    if (entries != null && entries.size() != 0) {
      throw new CivException("Cannot poison granary, already posioned.");
    }

    double failMod = 1.0;
    if (resident.getTown().getBuffManager().hasBuff("buff_espionage")) {
      failMod = resident.getTown().getBuffManager().getEffectiveDouble("buff_espionage");
      CivMessage.send(
          player, CivColor.LightGray + "Your goodie buff 'Espionage' will come in handy here.");
    }

    if (processMissionResult(player, tc.getTown(), mission, failMod, 1.0)) {
      int min;
      int max;
      try {
        min =
            CivSettings.getInteger(
                CivSettings.espionageConfig, "espionage.poison_granary_min_ticks");
        max =
            CivSettings.getInteger(
                CivSettings.espionageConfig, "espionage.poison_granary_max_ticks");
      } catch (InvalidConfiguration e) {
        e.printStackTrace();
        throw new CivException("Invalid configuration error.");
      }

      Random rand = new Random();
      int posion_ticks = rand.nextInt((max - min)) + min;
      String value = "" + posion_ticks;

      CivGlobal.getSessionDB()
          .add(
              "posiongranary:" + tc.getTown().getName(),
              value,
              tc.getTown().getId(),
              tc.getTown().getId(),
              granary.getId());

      try {
        double famine_chance =
            CivSettings.getDouble(
                CivSettings.espionageConfig, "espionage.poison_granary_famine_chance");

        if (rand.nextInt(100) < (int) (famine_chance * 100)) {

          for (Structure struct : tc.getTown().getStructures()) {
            if (struct instanceof Cottage) {
              ((Cottage) struct).delevel();
            }
          }

          CivMessage.global(
              CivColor.Yellow
                  + "DISASTER!"
                  + CivColor.White
                  + " The cottages in "
                  + tc.getTown().getName()
                  + " have suffered a famine from poison grain! Each cottage loses 1 level.");
        }
      } catch (InvalidConfiguration e) {
        e.printStackTrace();
        throw new CivException("Invalid configuration.");
      }

      CivMessage.sendSuccess(player, "Poisoned the granary for " + posion_ticks + " hours!");
    }
  }
Example #29
0
  private static void performSabotage(Player player, ConfigMission mission) throws CivException {
    Resident resident = CivGlobal.getResident(player);

    // Must be within enemy town borders.
    ChunkCoord coord = new ChunkCoord(player.getLocation());
    CultureChunk cc = CivGlobal.getCultureChunk(coord);
    if (cc == null || cc.getCiv() == resident.getTown().getCiv()) {
      throw new CivException("Must be in another civilization's borders.");
    }

    // Check that the player is within range of the town hall.
    Buildable buildable = cc.getTown().getNearestBuildable(player.getLocation());
    if (buildable instanceof TownHall) {
      throw new CivException("Nearest structure is a town hall which cannot be destroyed.");
    }
    if (buildable instanceof Wonder) {
      if (buildable.isComplete()) {
        throw new CivException("Cannot sabotage completed wonders.");
      }
    }

    double distance = player.getLocation().distance(buildable.getCorner().getLocation());
    if (distance > mission.range) {
      throw new CivException("Too far away the " + buildable.getDisplayName() + " to sabotage it");
    }

    if (buildable instanceof Structure) {
      if (!buildable.isComplete()) {
        throw new CivException("Cannot sabotage incomplete structures.");
      }

      if (buildable.isDestroyed()) {
        throw new CivException(buildable.getDisplayName() + " is already destroyed.");
      }
    }

    if (buildable instanceof Wonder) {
      // Create a new mission and with the penalties.
      mission = CivSettings.missions.get("spy_sabotage_wonder");
    }

    double failMod = 1.0;
    if (resident.getTown().getBuffManager().hasBuff("buff_sabotage")) {
      failMod = resident.getTown().getBuffManager().getEffectiveDouble("buff_sabotage");
      CivMessage.send(
          player, CivColor.LightGray + "Your goodie buff 'Sabotage' will come in handy here.");
    }

    if (processMissionResult(player, cc.getTown(), mission, failMod, 1.0)) {
      CivMessage.global(
          CivColor.Yellow
              + "DISASTER!"
              + CivColor.White
              + " A "
              + buildable.getDisplayName()
              + " has been destroyed! Foul play is suspected.");
      buildable.setHitpoints(0);
      buildable.fancyDestroyStructureBlocks();
      buildable.save();

      if (buildable instanceof Wonder) {
        Wonder wonder = (Wonder) buildable;
        wonder.unbindStructureBlocks();
        try {
          wonder.delete();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
  }
Example #30
0
  private static boolean processMissionResult(
      Player player,
      Town target,
      ConfigMission mission,
      double failModifier,
      double compromiseModifier) {

    int fail_rate =
        (int) ((MissionBook.getMissionFailChance(mission, target) * failModifier) * 100);
    int compromise_rate =
        (int)
            ((MissionBook.getMissionCompromiseChance(mission, target) * compromiseModifier) * 100);
    Resident resident = CivGlobal.getResident(player);

    if (resident == null || !resident.hasTown()) {
      return false;
    }

    if (!resident.getTown().getTreasury().hasEnough(mission.cost)) {
      CivMessage.send(
          player,
          CivColor.Rose
              + "Suddenly, your town doesn't have enough cash to follow through with the mission.");
      return false;
    }

    resident.getTown().getTreasury().withdraw(mission.cost);

    Random rand = new Random();
    String result = "";
    int failnext = rand.nextInt(100);
    if (failnext < fail_rate) {
      int next = rand.nextInt(100);
      result += "Failed";

      if (next < compromise_rate) {
        CivMessage.global(
            CivColor.Yellow
                + "INTERNATIONAL INCIDENT!"
                + CivColor.White
                + " "
                + player.getName()
                + " was caught trying to perform a "
                + mission.name
                + " spy mission in "
                + target.getName()
                + "!");
        CivMessage.send(
            player,
            CivColor.Rose
                + "You've been compromised! (Rolled "
                + next
                + " vs "
                + compromise_rate
                + ") Spy unit was destroyed!");
        Unit.removeUnit(player);
        result += ", COMPROMISED";
      }

      MissionLogger.logMission(resident.getTown(), target, player.getName(), mission.name, result);
      CivMessage.send(
          player, CivColor.Rose + "Mission Failed! (Rolled " + failnext + " vs " + fail_rate + ")");
      return false;
    }

    MissionLogger.logMission(resident.getTown(), target, player.getName(), mission.name, "Success");
    return true;
  }