Jump to content

Question

Posted (edited)

Hello MaxCheaters, i want to ask how can i make pages every 6 items on this NpcInstance.

RLtuC.png

 

 

  • Here Java Code

 

 

/* This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 *
 * http://www.gnu.org/copyleft/gpl.html
 */
package com.l2jfrozen.gameserver.model.actor.instance;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.StringTokenizer;

import com.l2jfrozen.gameserver.ai.CtrlIntention;
import com.l2jfrozen.gameserver.datatables.sql.ItemTable;
import com.l2jfrozen.gameserver.network.SystemMessageId;
import com.l2jfrozen.gameserver.network.serverpackets.ActionFailed;
import com.l2jfrozen.gameserver.network.serverpackets.CharInfo;
import com.l2jfrozen.gameserver.network.serverpackets.InventoryUpdate;
import com.l2jfrozen.gameserver.network.serverpackets.MyTargetSelected;
import com.l2jfrozen.gameserver.network.serverpackets.NpcHtmlMessage;
import com.l2jfrozen.gameserver.network.serverpackets.SystemMessage;
import com.l2jfrozen.gameserver.network.serverpackets.UserInfo;
import com.l2jfrozen.gameserver.network.serverpackets.ValidateLocation;
import com.l2jfrozen.gameserver.model.actor.instance.L2PcInstance;
import com.l2jfrozen.gameserver.templates.L2NpcTemplate;
import com.l2jfrozen.util.CloseUtil;
import com.l2jfrozen.util.database.L2DatabaseFactory;

import javolution.text.TextBuilder;

/**
 * 
 * @author Elfocrash
 *
 */

public class L2SmartMultisellInstance extends L2FolkInstance
{
  public L2SmartMultisellInstance(int objectId, L2NpcTemplate template)
  {
    super(objectId, template);
  }

  @Override
public void onBypassFeedback(L2PcInstance player, String command)
  {
         if(player == null)
         {
            return;
         }
         
         if(command.startsWith("buyItem "))
         {
        	String itemId = null;
        	StringTokenizer st = new StringTokenizer(command, " ");
        	 
        	while (st.hasMoreTokens())
        	{
        		itemId = st.nextToken();
        	}
        	
        	int id = Integer.parseInt(itemId);
        	
        	if(player.getInventory().getItemByItemId(getItemCostId(id)).getCount() >= getItemCostCount(id))
        	{
        		player.getInventory().destroyItemByItemId("delete", getItemCostId(id), getItemCostCount(id), player, null);
        		
			    L2ItemInstance item = null;		     
			    item = player.getInventory().addItem("Elfo", getItemId(id), 1, null, null);
			    item.setEnchantLevel(getItemEnchant(id));
			    
				// send packets
				InventoryUpdate iu = new InventoryUpdate();
				iu.addItem(item);
				player.sendPacket(iu);
				player.broadcastPacket(new CharInfo(player));
				player.sendPacket(new UserInfo(player));
			
				SystemMessage sm = new SystemMessage(SystemMessageId.YOU_PICKED_UP_S1_S2);
				sm.addItemName(item.getItemId());
				sm.addNumber(1);
				player.sendPacket(sm);
				iu = null;
        	}
        	else
        	{
        		player.sendMessage("You don't have enough items in order to buy this one");
        		return;
        	}
         }
        
  }

  @Override
	public void onAction(L2PcInstance player)
	  {
	    if (!canTarget(player)) {
	      return;
	    }
	
	    if (this != player.getTarget())
	    {
	      player.setTarget(this);
	
	      player.sendPacket(new MyTargetSelected(getObjectId(), 0));
	
	      player.sendPacket(new ValidateLocation(this));
	    }
	    else if (!canInteract(player))
	    {
	      player.getAI().setIntention(CtrlIntention.AI_INTENTION_INTERACT, this);
	    }
	    else
	    {
	    		showHtmlWindow(player);
	    }
	
	    player.sendPacket(new ActionFailed());
	  }

  private void showHtmlWindow(L2PcInstance activeChar)
  {
    NpcHtmlMessage nhm = new NpcHtmlMessage(5);
    TextBuilder tb = new TextBuilder("");
   
    tb.append("<html><head><title>Smart Shop</title></head><body>");
    tb.append("<center>");
    tb.append("<table width=\"250\" cellpadding=\"5\" bgcolor=\"000000\">");
    tb.append("<tr>");
    tb.append("<td width=\"45\" valign=\"top\" align=\"center\"><img src=\"L2ui_ch3.menubutton4\" width=\"38\" height=\"38\"></td>");
    tb.append("<td valign=\"top\"><font color=\"FF6600\">Smart Shop</font>"); 
    tb.append("<br1><font color=\"00FF00\">"+activeChar.getName()+"</font>, Here you can buy Enchanted Gear.</td>");
    tb.append("</tr>");
    tb.append("</table>");
    tb.append("</center>");
    tb.append("<center>");
    
    for(int i = 1; i<= getRowsCount(); i++)
    	tb.append("<br><a action=\"bypass -h npc_" + getObjectId() + "_buyItem " + i + "\">Item name: " + ItemTable.getInstance().getTemplate(getItemId(i)).getName() + " Enchant: +"+ getItemEnchant(i) + " Cost: " + getItemCostCount(i) + " " + ItemTable.getInstance().getTemplate(getItemCostId(i)).getName() + "</a>");
    
    tb.append("</center>");
    tb.append("<center>");
    tb.append("<img src=\"l2ui_ch3.herotower_deco\" width=256 height=32 align=center>");
    tb.append("<font color=\"FF6600\">By Elfocrash</font>"); 
    tb.append("</center>");
    tb.append("</body></html>");

    nhm.setHtml(tb.toString());
    activeChar.sendPacket(nhm);

    activeChar.sendPacket(new ActionFailed());
  }
  
  private int getRowsCount()
  {
      int rows = 0;
      Connection con = null;
      try
      {
              con = L2DatabaseFactory.getInstance().getConnection();
                 
              PreparedStatement statement = con.prepareStatement("SELECT * FROM smart_shop");
              
              ResultSet rset = statement.executeQuery();
              while (rset.next())
              {
                  rows++;
              }
  			rset.close();
  			statement.close();
                  
      }
		catch(Exception e)
		{
			e.printStackTrace();
		}finally{
			CloseUtil.close(con);
			con = null;
		}
      return rows;
      
  }
  
  private int getItemId(int itemId)
  {
      int itemIdd = 0;
      Connection con = null;
      try
      {
              con = L2DatabaseFactory.getInstance().getConnection();
                 
              PreparedStatement statement = con.prepareStatement("SELECT item_id FROM smart_shop WHERE id=?");
              statement.setInt(1, itemId);
              
              ResultSet rset = statement.executeQuery();
              while (rset.next())
              {
            	  itemIdd = rset.getInt("item_id");
              }
    			rset.close();
      			statement.close();
                  
      }
		catch(Exception e)
		{
			e.printStackTrace();
		}finally{
			CloseUtil.close(con);
			con = null;
		}
      return itemIdd;
      
  }
  
  private int getItemCostId(int costid)
  {
      int costIt = 0;
      Connection con = null;
      try
      {
              con = L2DatabaseFactory.getInstance().getConnection();
                 
              PreparedStatement statement = con.prepareStatement("SELECT cost_item_id FROM smart_shop WHERE id=?");
              statement.setInt(1, costid);
              
              ResultSet rset = statement.executeQuery();
              while (rset.next())
              {
            	  costIt = rset.getInt("cost_item_id");
              }
    			rset.close();
      			statement.close();
                  
      }
		catch(Exception e)
		{
			e.printStackTrace();
		}finally{
			CloseUtil.close(con);
			con = null;
		}
      return costIt;
      
  }
  
  private int getItemCostCount(int costid)
  {
      int costIt = 0;
      Connection con = null;
      try
      {
              con = L2DatabaseFactory.getInstance().getConnection();
                 
              PreparedStatement statement = con.prepareStatement("SELECT cost_item_count FROM smart_shop WHERE id=?");
              statement.setInt(1, costid);
              
              ResultSet rset = statement.executeQuery();
              while (rset.next())
              {
            	  costIt = rset.getInt("cost_item_count");
              }
    			rset.close();
      			statement.close();
                  
      }
		catch(Exception e)
		{
			e.printStackTrace();
		}finally{
			CloseUtil.close(con);
			con = null;
		}
      return costIt;
      
  }
  
  private int getItemEnchant(int id)
  {
      int itemEnch = 0;
      Connection con = null;
      PreparedStatement statement = null;
      try
      {
              con = L2DatabaseFactory.getInstance().getConnection();
                 
              statement = con.prepareStatement("SELECT item_enchant FROM smart_shop WHERE id=?");
              statement.setInt(1, id);
              
              ResultSet rset = statement.executeQuery();
              while (rset.next())
              {
            	  itemEnch = rset.getInt("item_enchant");
              }
    			rset.close();
      			statement.close();
                  
      }
		catch(Exception e)
		{
			e.printStackTrace();
		}finally{
			CloseUtil.close(con);
			con = null;
		}
      return itemEnch;
      
  }

} 

 

 

 

  • Here SQL

 

 

/*
Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 50519
Source Host           : localhost:3306
Source Database       : l2jfrozen

Target Server Type    : MYSQL
Target Server Version : 50519
File Encoding         : 65001

Date: 2013-01-17 18:22:51
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `smart_shop`
-- ----------------------------
DROP TABLE IF EXISTS `smart_shop`;
CREATE TABLE `smart_shop` (
  `id` int(1) NOT NULL DEFAULT '0',
  `item_id` int(5) DEFAULT NULL,
  `item_enchant` int(5) DEFAULT NULL,
  `cost_item_id` int(5) DEFAULT NULL,
  `cost_item_count` bigint(16) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

 

 

 

 

//Edit

I want to make it like this (at the moment pages not working)

 

Vik3Rzz.png

Edited by activeChar.getAdena()

9 answers to this question

Recommended Posts

  • 0
Posted (edited)

You can inspire yourself about admincommands. Some of them got a page system.
 

On aCis, I use a specific method to calculate number of page, then I sublist the ArrayList holding infos. It's shorter/easier writing style than "old" stuff you find on L2JFrozen and L2J.

	/**
	 * @param numberOfObjects : The overall elements size.
	 * @param pageSize : The number of elements per page.
	 * @return The number of pages, based on the number of elements and the number of elements we want per page.
	 */
	public static int countNumberOfPages(int numberOfObjects, int pageSize)
	{
		return numberOfObjects / pageSize + (numberOfObjects % pageSize == 0 ? 0 : 1);
	}

Used for example like :

		final int objId = activeChar.getObjectId();
		List<L2Bookmark> bookmarks = BookmarkTable.getInstance().getBookmarks(objId);
		
		// Load static Htm.
		final NpcHtmlMessage html = new NpcHtmlMessage(0);
		html.setFile("data/html/admin/bk.htm");
		
		if (bookmarks.isEmpty())
		{
			html.replace("%locs%", "<tr><td>No bookmarks are currently registered.</td></tr>");
			activeChar.sendPacket(html);
			return;
		}
		
		final int max = MathUtil.countNumberOfPages(bookmarks.size(), PAGE_LIMIT);
		
		bookmarks = bookmarks.subList((page - 1) * PAGE_LIMIT, Math.min(page * PAGE_LIMIT, bookmarks.size()));

"bookmarks" holds good info, and only the good info. You have to define PAGE_LIMIT under a static int aswell.

private static final int PAGE_LIMIT = 15;

The count of pages begins to 0 (page 0 = 0 to 14, etc).

Edited by Tryskell
  • 0
Posted

Tbh there is nothing to understand, the whole code is here.... The only things you need is the total size of the array (whatever.size()), the PAGE_LIMIT, and the actual page you're looking on.

 

I already posted what I use for page system for my bookmark system.

 

The complete method :

	/**
	 * Show the basic HTM fed with generated data.
	 * @param activeChar The player to make checks on.
	 * @param page The page id to show.
	 */
	private static void showBookmarks(L2PcInstance activeChar, int page)
	{
		final int objId = activeChar.getObjectId();
		List<L2Bookmark> bookmarks = BookmarkTable.getInstance().getBookmarks(objId);
		
		// Load static Htm.
		final NpcHtmlMessage html = new NpcHtmlMessage(0);
		html.setFile("data/html/admin/bk.htm");
		
		if (bookmarks.isEmpty())
		{
			html.replace("%locs%", "<tr><td>No bookmarks are currently registered.</td></tr>");
			activeChar.sendPacket(html);
			return;
		}
		
		final int max = MathUtil.countNumberOfPages(bookmarks.size(), PAGE_LIMIT);
		
		bookmarks = bookmarks.subList((page - 1) * PAGE_LIMIT, Math.min(page * PAGE_LIMIT, bookmarks.size()));
		
		// Generate data.
		final StringBuilder sb = new StringBuilder(2000);
		
		for (L2Bookmark bk : bookmarks)
		{
			final String name = bk.getName();
			final int x = bk.getX();
			final int y = bk.getY();
			final int z = bk.getZ();
			
			StringUtil.append(sb, "<tr><td><a action=\"bypass -h admin_move_to ", x, " ", y, " ", z, "\">", name, " (", x, " ", y, " ", z, ")", "</a></td><td><a action=\"bypass -h admin_delbk ", name, "\">Remove</a></td></tr>");
		}
		html.replace("%locs%", sb.toString());
		
		// Cleanup the sb.
		sb.setLength(0);
		
		// End of table, open a new table for pages system.
		for (int i = 0; i < max; i++)
		{
			final int pagenr = i + 1;
			if (page == pagenr)
				StringUtil.append(sb, pagenr, " ");
			else
				StringUtil.append(sb, "<a action=\"bypass -h admin_bkpage ", pagenr, "\">", pagenr, "</a> ");
		}
		
		html.replace("%pages%", sb.toString());
		activeChar.sendPacket(html);
	}
  • 0
Posted

So i can suggest you to start with some smaller modifications. If you will spend some time on learning how everything works, you will be able to do a lot better things than just pages inside html :)

  • 0
Posted

Well the method I put is way easier to understand than L2J one, so if you don't understand, you won't understand L2J way. I suggest you to take time to read it until you understand, all is correctly documented.

 

The idea is you got a list of elements, you retrieve size, you get page, you get page limit, so it calculates max page amount. Then you sublist the overall list to retrieve only elements for current page, and process result.

 

Got nothing more to say tbh, except doing it for you, which I won't do.

  • 0
Posted (edited)

emmmm guys... i know how to make page... but i cant stop page 1 (one) to stop on 6th item... and dont show me the other list... thats my problem on NPC.

Analyze what I wrote, the subList section does it for you.

Edited by Tryskell

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Posts

    • what pack you use  send me on discord for it
    • package custom.events.RandomZoneEvent; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.ScheduledFuture; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.l2jmobius.commons.threads.ThreadPool; import org.l2jmobius.commons.time.SchedulingPattern; import org.l2jmobius.commons.time.TimeUtil; import org.l2jmobius.commons.util.IXmlReader; import org.l2jmobius.gameserver.managers.ZoneManager; import org.l2jmobius.gameserver.model.StatSet; import org.l2jmobius.gameserver.model.actor.Creature; import org.l2jmobius.gameserver.model.actor.Npc; import org.l2jmobius.gameserver.model.actor.Player; import org.l2jmobius.gameserver.model.quest.Event; import org.l2jmobius.gameserver.model.zone.ZoneId; import org.l2jmobius.gameserver.model.zone.ZoneType; import org.l2jmobius.gameserver.model.zone.type.RandomZone; import org.l2jmobius.gameserver.util.Broadcast; /** * Random Zone Event - Activates one random PvP zone temporarily. No modifica la clase de la zona: usa flags PvP en runtime. * @author Juan */ public class RandomZoneEvent extends Event { private static final String CONFIG_FILE = "data/scripts/custom/events/RandomZoneEvent/config.xml"; private static int EVENT_DURATION_MINUTES = 15; private static boolean _isActive = false; private ScheduledFuture<?> _eventTask = null; private final List<ZoneType> _availableZones = new ArrayList<>(); private ZoneType _activeZone = null; public RandomZoneEvent() { loadConfig(); loadZones(); registerZoneListeners(); } /** * Registra listeners a TODAS LAS ZONAS random */ private void registerZoneListeners() { for (ZoneType zone : _availableZones) { addEnterZoneId(zone.getId()); addExitZoneId(zone.getId()); LOGGER.info("[RandomZoneEvent] Registered listener for zone: " + zone.getName()); } } private void loadConfig() { new IXmlReader() { @Override public void load() { parseDatapackFile(CONFIG_FILE); } @Override public void parseDocument(Document doc, File file) { forEach(doc, "event", eventNode -> { final StatSet att = new StatSet(parseAttributes(eventNode)); final String name = att.getString("name"); for (Node node = eventNode.getFirstChild(); node != null; node = node.getNextSibling()) { if ("schedule".equals(node.getNodeName())) { final StatSet attributes = new StatSet(parseAttributes(node)); final String pattern = attributes.getString("pattern"); final SchedulingPattern schedulingPattern = new SchedulingPattern(pattern); final StatSet params = new StatSet(); params.set("Name", name); params.set("SchedulingPattern", pattern); final long delay = schedulingPattern.getDelayToNextFromNow(); getTimers().addTimer("Schedule_" + name, params, delay + 5000, null, null); LOGGER.info("[RandomZoneEvent] Event " + name + " scheduled at " + TimeUtil.getDateTimeString(System.currentTimeMillis() + delay)); } } }); } }.load(); } private void loadZones() { for (ZoneType zone : ZoneManager.getInstance().getAllZones(RandomZone.class)) { if ((zone.getName() != null) && zone.getName().toLowerCase().startsWith("random_zone")) { _availableZones.add(zone); LOGGER.info("[RandomZoneEvent] Loaded zone: " + zone.getName() + " (id=" + zone.getId() + ")"); } } LOGGER.info("[RandomZoneEvent] Total random zones loaded: " + _availableZones.size()); } @Override public void onTimerEvent(String event, StatSet params, Npc npc, Player player) { if (event.startsWith("Schedule_")) { eventStart(null); final SchedulingPattern schedulingPattern = new SchedulingPattern(params.getString("SchedulingPattern")); final long delay = schedulingPattern.getDelayToNextFromNow(); getTimers().addTimer(event, params, delay + 5000, null, null); LOGGER.info("[RandomZoneEvent] Rescheduled for " + TimeUtil.getDateTimeString(System.currentTimeMillis() + delay)); } } @Override public boolean eventStart(Player eventMaker) { if (_isActive) { if (eventMaker != null) { eventMaker.sendMessage("RandomZoneEvent already active."); } return false; } if (_availableZones.isEmpty()) { Broadcast.toAllOnlinePlayers("[RandomZoneEvent] No zones configured."); return false; } _isActive = true; Broadcast.toAllOnlinePlayers("⚔️ Random Zone Event has started!"); _eventTask = ThreadPool.schedule(this::activateRandomZone, 5_000); return true; } private void activateRandomZone() { _activeZone = _availableZones.get(new Random().nextInt(_availableZones.size())); _activeZone.setEnabled(true); Broadcast.toAllOnlinePlayers("🔥 Random Zone Event: " + _activeZone.getName() + " is now PvP for " + EVENT_DURATION_MINUTES + " minutes!"); _eventTask = ThreadPool.schedule(this::eventStop, EVENT_DURATION_MINUTES * 60 * 1000L); } @Override public boolean eventStop() { if (!_isActive) { return false; } _isActive = false; if (_eventTask != null) { _eventTask.cancel(true); _eventTask = null; } if (_activeZone != null) { _activeZone.setEnabled(false); Broadcast.toAllOnlinePlayers("🏁 Random Zone Event ended. " + _activeZone.getName() + " is back to normal."); _activeZone = null; } else { Broadcast.toAllOnlinePlayers("🏁 Random Zone Event ended."); } return true; } @Override public void onEnterZone(Creature creature, ZoneType zone) { if (!_isActive || (_activeZone == null)) { return; } if ((zone == _activeZone) && creature.isPlayable()) { creature.setInsideZone(ZoneId.PVP, true); if (creature.isPlayer()) { creature.sendMessage("Esta zona está en modo PvP temporalmente."); } } } @Override public void onExitZone(Creature creature, ZoneType zone) { if (!_isActive || (_activeZone == null)) { return; } if ((zone == _activeZone) && creature.isPlayable()) { creature.setInsideZone(ZoneId.PVP, false); if (creature.isPlayer()) { creature.sendMessage("Abandonaste la zona PvP temporal."); } } } @Override public boolean eventBypass(Player player, String bypass) { return true; } @Override public String onEvent(String event, Npc npc, Player player) { return super.onEvent(event, npc, player); } @Override public String onFirstTalk(Npc npc, Player player) { return null; } public static void main(String[] args) { new RandomZoneEvent(); } } i have this but its not working
    • ZonePvPSpawnBossRadio=0 ZonePvPSpawnBossBarakiel=0 at the Customs.ini in L2Server folder. Im prety sure this is it because i had the same problem with you in cruma 1 floor for example and i couldn't fix it but i fixed it finally by changing these 2 lines
    • Siege Reward Start PM Msg Rework Config root BossDieAnnounce and BossDieSound in the L24Team.properties and Config.java files for global raid boss death notifications and sounds. Adds a new reward_list table to the DB.sql file to track castle rewards. Improves character creation logic for thread safety and validation. Adds extensive state checks to the RequestEnchantItem method to prevent enchantments during inappropriate player states. Fixed auto-attack animation bug (there was no attack animation, only damage animation) Clean Code Other fixes I forgot to list! Java 14 Fixed issue where deleting a character would prevent it from leaving the screen or being removed, or even after a delete CD (it would only exit when re-logging in or creating a new character). Added Premium System from the other C2 project (Needs testing and improvement). Added the "Improved" Community Board (incomplete).
  • Topics

×
×
  • Create New...

AdBlock Extension Detected!

Our website is made possible by displaying online advertisements to our members.

Please disable AdBlock browser extension first, to be able to use our community.

I've Disabled AdBlock