скрипт аугментации

6yka

Повелитель тьмы
Проверенный
Веселый флудер
Мастер реакций
Любитель реакций
Знаток письма высшего ранга
Знаток великого письма
Знаток письма
Знаток Lineage2
Старожил I степени
Победитель в номинации 2018
Победитель в номинации 2017
Медаль за активность на Форуме
За веру и верность форуму
Сообщения
1 730
Розыгрыши
0
Репутация
1 616
Реакции
1 212
Баллы
1 758
Код:
package services;


import javolution.util.FastMap;
import org.mmocore.commons.dao.JdbcEntityState;
import org.mmocore.commons.util.Rnd;
import org.mmocore.gameserver.data.htm.HtmCache;
import org.mmocore.gameserver.data.xml.holder.ItemHolder;
import org.mmocore.gameserver.database.DatabaseFactory;
import org.mmocore.gameserver.model.Player;
import org.mmocore.gameserver.model.actor.instances.player.ShortCut;
import org.mmocore.gameserver.model.items.Inventory;
import org.mmocore.gameserver.model.items.ItemInstance;
import org.mmocore.gameserver.scripts.Functions;
import org.mmocore.gameserver.scripts.ScriptFile;
import org.mmocore.gameserver.serverpackets.ExShowScreenMessage;
import org.mmocore.gameserver.serverpackets.InventoryUpdate;
import org.mmocore.gameserver.serverpackets.ShortCutRegister;
import org.mmocore.gameserver.serverpackets.SocialAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
* AugmentShop - allow sell augments on equipment weapon, armor or jawel.
*
* @author Masterio
*/

public class AugmentShop extends Functions implements ScriptFile {

  public static final int NPC_ID = 93000;
  public static final boolean CONSUME_ITEMS_ENABLED = true;
  private static final Logger _log = LoggerFactory.getLogger(AugmentShop.class);
  /**
  * <augmentation_id, Augment>
  */
  public static FastMap<Integer, Augment> AUGMENTS = new FastMap<Integer, Augment>();

  public void onLoad() {

  loadAugments();

  _log.info("Loaded Service: AugmentShop [activated]");
  }

  public void onReload() {
  }

  public void onShutdown() {
  }

  /**
  * param here is a page number.
  */
  public void page(String[] param) {
  Player player = getSelf();

  if (player == null) {
  return;
  }

  String html = null;
  String page = "0";

  if (param.length == 1) {
  page = param[0];
  }

  if (!page.equals("0")) {

  html = HtmCache.getInstance().getNotNull("scripts/services/AugmentShop/page-" + page + ".htm", player);

  }
  else {

  html = HtmCache.getInstance().getNotNull("default/" + NPC_ID + ".htm", player);

  }

  if (html != null) {

  html = prepareListPage(html, page);

  show(html, player, null);

  }
  else {
  System.out.println("AugmentShop: page == null. Player id=" + player.getObjectId());
  }


  }

  /**
  * Get as argument the augment ID and shows detailed informations.
  *
  * @param param
  */
  public void finalPage(String[] param) {
  Player player = getSelf();
  int augmentId = 0;
  String prevPage = "0";
  String html = null;

  if (player == null) {
  return;
  }

  if (param.length != 2) {
  return;
  }

  try {

  augmentId = Integer.parseInt(param[0]);
  prevPage = param[1];

  } catch (Exception e) {
  e.printStackTrace();
  return;
  }

  if (AUGMENTS.containsKey(augmentId)) {

  html = HtmCache.getInstance().getNotNull("scripts/services/AugmentShop/final_page.htm", player);

  }
  else {
  return;
  }

  if (html != null) {

  html = prepareFinalPage(html, augmentId, prevPage);

  show(html, player, null);

  }
  else {
  System.out.println("AugmentShop: page == null. Player id=" + player.getObjectId());
  }


  }

  private String prepareFinalPage(String html, int augId, String prevPage) {

  Augment a = AUGMENTS.get(augId);

  if (a == null) {
  System.out.println("AugmentShop: Final page not found the augment id in AUGMENTS!");
  return null;
  }
  else {

  html = html.replace("%aug_id%", String.valueOf(a.augmentId));
  html = html.replace("%aug_name%", a.augmentName);
  html = html.replace("%aug_desc%", a.augmentDescribe);
  html = html.replace("%aug_type%", a.augmentType);

  if (a.itemConsumeCount > 0) {

  html = html.replace("%aug_item_name%", a.itemConsumeName);
  html = html.replace("%aug_item_count%", Long.toString(a.itemConsumeCount));

  }
  else {
  // if no item count defined it replace this tags with empty value:

  html = html.replace("%aug_item_name%", "&nbsp;");
  html = html.replace("%aug_item_count%", "&nbsp;");

  }

  html = html.replace("%prev_page%", prevPage);

  }


  return html;
  }

  /**
  * Replace all %aug_name% tags in htm file with augmentation name defined in database.
  *
  * @param html
  * @return
  */
  private String prepareListPage(String html, String page) {

  for (FastMap.Entry<Integer, Augment> e = AUGMENTS.head(), end = AUGMENTS.tail(); (e = e.getNext()) != end; ) {

  html = html.replace("%aug_name_" + e.getValue().augmentId + "%", e.getValue().augmentName); // it will be harder for code but its possible.

  }
  html = html.replace("%this_page%", page); // it will be harder for code but its possible.


  return html;
  }

  public void addAugment(String[] param) {
  Player player = getSelf();

  if (player == null) {
  return;
  }

  int augId = 0;

  if (param.length == 2) {
  try {
  augId = Integer.parseInt(param[0]);
  } catch (Exception e) {
  e.printStackTrace();
  return;
  }
  }
  else {
  System.out.println("Too much parameters in: addAugment, executed by Player id=" + player.getObjectId());
  return;
  }


  // augment item:
  overrideAugument(player, augId); // used override method of augmentation the item. Cancel augment not required.

  // show npc dialog:
  page(new String[]{param[1]});
  }

  public void dialogConfirm(String[] param) {

  Player player = getSelf();

  if (player == null) {
  return;
  }

  player.scriptRequest("Вы уверены что хотите выбрать данный аугумент?", "scripts_services.AugmentShop:addAugment", param);

  // show npc dialog:
  page(new String[]{param[1]}); // TODO add checkers
  }

  private void overrideAugument(Player player, int augId) {

  // get weapon:
  ItemInstance targetItem = player.getInventory().getPaperdollItem(Inventory.PAPERDOLL_RHAND);

  if (!checkAugmentConditions(player, targetItem, augId)) {
  return;
  }

  if (!AUGMENTS.containsKey(augId)) {
  System.out.println("AugmentShop: wrong augmentation id not defined. Player id:" + player.getObjectId());
  return;
  }

  if (CONSUME_ITEMS_ENABLED && AUGMENTS.get(augId).itemConsumeCount > 0) {
  Functions.removeItem(player, AUGMENTS.get(augId).itemConsumeId, AUGMENTS.get(augId).itemConsumeCount);
  // player.getInventory().removeItemByItemId(AUGMENTS.get(augId).itemConsumeId, AUGMENTS.get(augId).itemConsumeCount);

  }

  boolean equipped = false;
  if (equipped = targetItem.isEquipped()) {
  player.getInventory().unEquipItem(targetItem);
  }

  targetItem.setAugmentationId((augId << 16) + Rnd.get(2800, 3200)); // 2800 - glow effect require additional values in slots 1 & 2.
  targetItem.setJdbcState(JdbcEntityState.UPDATED);
  targetItem.update();

  if (equipped) {
  player.getInventory().equipItem(targetItem);
  }

  player.sendPacket(new InventoryUpdate().addModifiedItem(targetItem));

  for (ShortCut sc : player.getAllShortCuts()) {
  if (sc.getId() == targetItem.getObjectId() && sc.getType() == ShortCut.TYPE_ITEM) {
  player.sendPacket(new ShortCutRegister(player, sc));
  }
  }

  player.sendChanges();
  player.broadcastPacket(new SocialAction(player.getObjectId(), 3));
  player.sendPacket(new ExShowScreenMessage("Вы успешно аугументировали ваше оружие!", 3000, ExShowScreenMessage.ScreenMessageAlign.BOTTOM_RIGHT, true));
  player.sendMessage("Вы успешно аугументировали ваше оружие!");

  }

  private boolean checkAugmentConditions(Player player, ItemInstance item, int augId) {

  if (player == null) {
  return false;
  }

  if (player.isActionsDisabled()) {
  return false;
  }

  if (player.isInStoreMode()) {
  return false;
  }

  if (player.isInTrade()) {
  return false;
  }

  if (item.isHeroWeapon()) {
  return false;
  }
  if (item == null) {
  player.sendPacket(new ExShowScreenMessage("Вы должны надеть оружие!", 3000, ExShowScreenMessage.ScreenMessageAlign.BOTTOM_RIGHT, true));
  player.sendMessage("Вы должны надеть оружие!");
  return false;
  }

  if (CONSUME_ITEMS_ENABLED && AUGMENTS.get(augId).itemConsumeCount > 0) {

  ItemInstance cItem = player.getInventory().getItemByItemId(AUGMENTS.get(augId).itemConsumeId);

  if (cItem == null || cItem.getCount() < AUGMENTS.get(augId).itemConsumeCount) {

  player.sendMessage("Простите но для аугументации вам нужно : " + AUGMENTS.get(augId).itemConsumeCount + " x " + AUGMENTS.get(augId).itemConsumeName);
  return false;

  }

  }

  return true;

  }

  private void loadAugments() {

  Connection con = null;
  try {
  con = DatabaseFactory.getInstance().getConnection();
  final PreparedStatement statement = con.prepareStatement("SELECT aug_id, item_consume_id, item_consume_count, aug_name, aug_describe, aug_type FROM augmentnpc");
  final ResultSet rset = statement.executeQuery();

  while (rset.next()) {
  Augment a = new Augment();

  a.augmentId = rset.getInt("aug_id");
  a.itemConsumeId = rset.getInt("item_consume_id");
  a.itemConsumeCount = rset.getLong("item_consume_count");
  a.augmentName = rset.getString("aug_name");
  a.augmentDescribe = rset.getString("aug_describe");
  a.augmentType = rset.getString("aug_type");

  a.itemConsumeName = ItemHolder.getInstance().getTemplate(a.itemConsumeId).getName();

  AUGMENTS.put(a.augmentId, a);

  }

  statement.close();
  rset.close();

  } catch (Exception e) {
  e.printStackTrace();
  } finally {
  try {
  if (con != null) {
  con.close();
  }
  } catch (SQLException e) {
  e.printStackTrace();
  }
  }

  }

  private class Augment {

  public int augmentId = 0;
  public String augmentName = null;
  public String augmentDescribe = null;
  public String augmentType = null;
  public int itemConsumeId = 0;
  public long itemConsumeCount = 0;
  public String itemConsumeName = null;

  }

}

проблема заключается в том, что не показывается финальная хтмлка с покупкой ЛСа. выбор и т.п. все работает. помогите кто может)
 
Последнее редактирование:

    Psycho

    Баллов: 0
    Искать помощи и требовать лайки, как минимум глупо. Жаль нет дизлайка.

    ArtToKill

    Баллов: 0
    наглость...
забыл написать что у меня сборка l2j-dev.ru приватка, т.е. как то допилить для овероподобных сборок)
 
upload_2016-2-1_15-34-44.png

Увидел, и сразу закрыл.
 
а че там? я непонимэ
 
я мб и понял о чем вы ведете речь, но я еще раз скажу, я именно ПОТРЕБИТЕЛЬ, я не шарю и только по етой причине ищу помощи на подобных порталах)
 
Действительно, если бы лайк не просили бы помог бы, а так вообще не вижу смысла в этом, т.к. за спасибо итак просите помощь, так еще и лайка просите.
 
Последнее редактирование:
  • Мне нравится
Реакции: Psycho и kick

    kick

    Баллов: 35
    За сообщение

    Floran

    Баллов: 5
    За сообщение
Действительно, если бы лайк не просили бы помог бы, а так вообще не вижу смысла в этом, т.к. за спасибо итак просите помощь, так еще и лайка просите.
ага тоже возмутило...прям ппц какой крутой скрипт аж нужен позарез всем.
 
столько пафоса в ваших словах... нельзя было просто попросить убрать этот хайд и всё?
 
столько пафоса в ваших словах... нельзя было просто попросить убрать этот хайд и всё?
долго думал над постом и решил так, а вас совесть как не мучает?выкладывать не свой труд, просить о помощи, да еще и за спасибо вам же?)
 
Отрубите руки тому кто это писал
 
public static FastMap<Integer, Augment> AUGMENTS = new FastMap<Integer, Augment>(); заменить на public static Map<Integer, Augment> AUGMENTS = new HashMap<Integer, Augment>();

import javolution.util.FastMap;

заменить на

import java.util.Map;
import java.util.HashMap;

 
  • Мне нравится
Реакции: 6yka
PHP:
[03.02.16 01:09:55:969] ERROR compiler.Compiler: /home/user87/gameserver2/data/scripts/services/AugmentShop.java:197,14: FastMap cannot be resolved to a type
[03.02.16 01:09:55:971] ERROR compiler.Compiler: /home/user87/gameserver2/data/scripts/services/AugmentShop.java:197,59: The method head() is undefined for the type java.util.Map<java.lang.Integer,services.AugmentShop.Augment>
[03.02.16 01:09:55:971] ERROR compiler.Compiler: /home/user87/gameserver2/data/scripts/services/AugmentShop.java:197,82: The method tail() is undefined for the type java.util.Map<java.lang.Integer,services.AugmentShop.Augment>
[03.02.16 01:09:56:907] ERROR scripts.Scripts: Scripts: Failed loading scripts!

теперь вот такие вещи)
 
заменил в 197 строчке
это
PHP:
  for (FastMap.Entry<Integer, Augment> e = AUGMENTS.head(), end = AUGMENTS.tail(); (e = e.getNext()) != end; ) {
на это
PHP:
  for (Map.Entry<Integer, Augment> e = AUGMENTS.head(), end = AUGMENTS.tail(); (e = e.getNext()) != end; ) {

и стало выкидывать вот такое)
PHP:
[03.02.16 01:15:04:962] ERROR compiler.Compiler: /home/user87/gameserver2/data/scripts/services/AugmentShop.java:197,55: The method head() is undefined for the type java.util.Map<java.lang.Integer,services.AugmentShop.Augment>
[03.02.16 01:15:04:963] ERROR compiler.Compiler: /home/user87/gameserver2/data/scripts/services/AugmentShop.java:197,78: The method tail() is undefined for the type java.util.Map<java.lang.Integer,services.AugmentShop.Augment>
[03.02.16 01:15:04:963] ERROR compiler.Compiler: /home/user87/gameserver2/data/scripts/services/AugmentShop.java:197,93: The method getNext() is undefined for the type java.util.Map.Entry<java.lang.Integer,services.AugmentShop.Augment>
[03.02.16 01:15:05:859] ERROR scripts.Scripts: Scripts: Failed loading scripts!
 
вроде решилась проблема) скрипт заработал. только никак не пойму почму он требует за аугментацию ФА??? во всех файлах крч по айди искал и нет ничего по етому поводу.
 
вернул всё как было. оказывется нужно было сделать табличку в БД. сделал, там же в табличке сменил итем за который аугментирует. почему то выпала вот такая ошибка

PHP:
[03.02.16 04:50:56:464] ERROR scripts.Scripts: Scripts: Error while calling services.AugmentShop.addAugment()
java.lang.NullPointerException
   at services.AugmentShop.checkAugmentConditions(AugmentShop.java:317)
   at services.AugmentShop.overrideAugument(AugmentShop.java:256)
   at services.AugmentShop.addAugment(AugmentShop.java:231)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
   at java.lang.reflect.Method.invoke(Method.java:601)
   at org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(MethodUtils.java:133)
   at org.mmocore.gameserver.scripts.Scripts.callScripts(Scripts.java:438)
   at org.mmocore.gameserver.clientpackets.RequestBypassToServer.runImpl(RequestBypassToServer.java:85)
   at org.mmocore.gameserver.clientpackets.L2GameClientPacket.run(L2GameClientPacket.java:44)
   at org.mmocore.commons.net.nio.impl.MMOExecutableQueue.run(MMOExecutableQueue.java:129)
   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
   at java.lang.Thread.run(Thread.java:722)
 
PHP:
[03.02.16 01:09:55:969] ERROR compiler.Compiler: /home/user87/gameserver2/data/scripts/services/AugmentShop.java:197,14: FastMap cannot be resolved to a type
[03.02.16 01:09:55:971] ERROR compiler.Compiler: /home/user87/gameserver2/data/scripts/services/AugmentShop.java:197,59: The method head() is undefined for the type java.util.Map<java.lang.Integer,services.AugmentShop.Augment>
[03.02.16 01:09:55:971] ERROR compiler.Compiler: /home/user87/gameserver2/data/scripts/services/AugmentShop.java:197,82: The method tail() is undefined for the type java.util.Map<java.lang.Integer,services.AugmentShop.Augment>
[03.02.16 01:09:56:907] ERROR scripts.Scripts: Scripts: Failed loading scripts!

теперь вот такие вещи)

заменил в 197 строчке
это
PHP:
  for (FastMap.Entry<Integer, Augment> e = AUGMENTS.head(), end = AUGMENTS.tail(); (e = e.getNext()) != end; ) {
на это
PHP:
  for (Map.Entry<Integer, Augment> e = AUGMENTS.head(), end = AUGMENTS.tail(); (e = e.getNext()) != end; ) {

и стало выкидывать вот такое)
PHP:
[03.02.16 01:15:04:962] ERROR compiler.Compiler: /home/user87/gameserver2/data/scripts/services/AugmentShop.java:197,55: The method head() is undefined for the type java.util.Map<java.lang.Integer,services.AugmentShop.Augment>
[03.02.16 01:15:04:963] ERROR compiler.Compiler: /home/user87/gameserver2/data/scripts/services/AugmentShop.java:197,78: The method tail() is undefined for the type java.util.Map<java.lang.Integer,services.AugmentShop.Augment>
[03.02.16 01:15:04:963] ERROR compiler.Compiler: /home/user87/gameserver2/data/scripts/services/AugmentShop.java:197,93: The method getNext() is undefined for the type java.util.Map.Entry<java.lang.Integer,services.AugmentShop.Augment>
[03.02.16 01:15:05:859] ERROR scripts.Scripts: Scripts: Failed loading scripts!
Не правильно, надо было заменить вот так for (Map.Entry<Integer, Augment> e : AUGMENTS.entrySet()) {
 
  • Мне нравится
Реакции: 6yka

    6yka

    Баллов: 2
    За помощь в исправлении ошибки в скрипте
Назад
Сверху Снизу