Skip to content
La2Base
Home
DownloadsWikiForumFAQ
Search
ruen
Sign up Login
HomeFilesWikiLogin
  • Home
  • Downloads
  • Wiki
  • FAQ
  • Contact Us
  • About
  • Rules
  • Privacy
  • Terms of Service

© 2026 la2base.com · All rights reserved

ruen
Forum/Дополнения от наших пользователей/Расширение функций статус сервера (telnet)
Search

Расширение функций статус сервера (telnet)

1 replies205 viewsCurrently viewing: 1
filmotechnic
filmotechnic

User

Бывалый

Posts: 140

На форуме с: 01/01/2008

Репутация: +66

Рейтинг: 0

· 10/04/2009, 06:03 PM

Вот, хочу поделиться своими наработками по усовершенствованию функций статус сервера:

1. Реализация бана/разбана чата (включая offline персонажей):

Раскрывающийся текст
Код
else if (_usrCommand.startsWith("banchat"))
                {
                    StringTokenizer st = new StringTokenizer(_usrCommand.substring(8));
                    try
                    {
                        String player = st.nextToken();
                        L2PcInstance playerObj = L2World.getInstance().getPlayer(player);
                        int delay = 0;
                        try
                        {
                            delay = Integer.parseInt(st.nextToken());
                        } catch (NumberFormatException nfe) {}
                        catch (NoSuchElementException nsee) {}
                        if (playerObj != null)
                        {
                            playerObj.setChatBanned(true, delay);
                            _print.println("Character id: "+playerObj+" ("+ playerObj.getName() +") banchat!!! For "+ delay +" minutes.");
                        } else {
                        _print.println("Player is Offline!!!");
                        Connection con = null;
                            try
                            {
                            con = L2DatabaseFactory.getInstance().getConnection();
                            PreparedStatement statement = con.prepareStatement("UPDATE characters SET chatban_timer=? WHERE char_name=?");
                            statement.setLong(1, (long)delay * 60000L);
                            statement.setString(2,player);
                            statement.execute();
                            int count = statement.getUpdateCount();
                            statement.close();
                                if(count == 0)
                                    _print.println("Character not found!");
                                else
                                    _print.println("Character "+player+" banchat!!! For  "+(delay>0 ? delay+" minutes." : "ever!"));
            
                            }
                            catch (SQLException se)
                            {
                            _print.println("SQLException while banchating player");
                                if (Config.DEBUG) se.printStackTrace();
                                }
                            catch (NoSuchElementException nsee)
                            {
                            }
                                finally
                            {
                            try { con.close(); } catch (Exception e) {}
                            }
                        }
                        
                    } catch (NoSuchElementException nsee)
                    {
                        _print.println("Specify a character name.");
                    } catch(Exception e)
                    {
                        if (Config.DEBUG) e.printStackTrace();
                    }
                }
            

                else if (_usrCommand.startsWith("unbanchat"))
                {
                    StringTokenizer st = new StringTokenizer(_usrCommand.substring(10));
                    try
                    {
                        L2PcInstance playerObj = L2World.getInstance().getPlayer(st.nextToken());

                        if (playerObj != null)
                        {
                            playerObj.setChatBanned(false, 0);
                            _print.println("Character "+playerObj.getName()+" chat unbanned");
                        }
                    } catch (NoSuchElementException nsee)
                    {
                        _print.println("Specify a character name.");
                    } catch(Exception e)
                    {
                        if (Config.DEBUG) e.printStackTrace();
                    }
                }



2. Заточка вещей одетых на персонаже:
Раскрывающийся текст
Код
                else if (_usrCommand.startsWith("ench"))
                {
                    StringTokenizer st = new StringTokenizer(_usrCommand.substring(5));
                    int armorType = -1;
                    try
                    {
                        String player = st.nextToken();
                        L2PcInstance playerObj = L2World.getInstance().getPlayer(player);
                        String atype = st.nextToken();
                        int value = Integer.parseInt(st.nextToken());

                        if(playerObj != null)
                        {
                            if (atype !=null & (value >= 0 & value <= 65535))
                            {
                                if (atype.equals("eh"))
                                armorType = 6;
                                else if (atype.equals("ec"))
                                armorType = 10;
                                else if (atype.equals("eg"))
                                armorType = 9;
                                else if (atype.equals("eb"))
                                armorType = 12;
                                else if (atype.equals("el"))
                                armorType = 11;
                                else if (atype.equals("ew"))
                                armorType = 7;
                                else if (atype.equals("es"))
                                armorType = 8;
                                else if (atype.equals("le"))
                                armorType = 1;
                                else if (atype.equals("re"))
                                armorType = 2;
                                else if (atype.equals("lf"))
                                armorType = 4;
                                else if (atype.equals("rf"))
                                armorType = 5;
                                else if (atype.equals("en"))
                                armorType = 3;
                                else if (atype.equals("un"))
                                armorType = 0;
                                else if (atype.equals("ba"))
                                armorType = 13;
                            
                            
                            if (armorType != -1)
                            {
                                try
                                    {
                                    setEnchant(player, value, armorType);
                                    }
                                    catch (StringIndexOutOfBoundsException e)
                                    {
                                    if (Config.DEVELOPER) System.out.println("Set enchant error: " + e);
                                    }
                                    catch (NumberFormatException e)
                                    {
                                    if (Config.DEVELOPER) System.out.println("Set enchant error: " + e);
                                    }
                            }
                            
                            
                            }else {_print.println("Incorrect parameters!");}

                        } else
                        {_print.println("Character "+player+" is offline");}
                    }
                    catch (NoSuchElementException nsee)
                    {
                    _print.println("Use: <name> <slot[eh/ec/eg/eb/el/ew/es/le/re/lf/rf/en/un/ba]> <value>");
                    }
                    catch(Exception e)
                    {
                    }
                }



//============= так-же добовляем и сам метод для заточки==============


        private void setEnchant(String playername, int ench, int armorType)
    {
        L2PcInstance player = L2World.getInstance().getPlayer(playername);
        // now we need to find the equipped weapon of the targeted character...
        int curEnchant = 0; // display purposes only
        L2ItemInstance itemInstance = null;

        // only attempt to enchant if there is a weapon equipped
        L2ItemInstance parmorInstance = player.getInventory().getPaperdollItem(armorType);
        if (parmorInstance != null && parmorInstance.getEquipSlot() == armorType)
        {
            itemInstance = parmorInstance;
        } else
        {
            // for bows and double handed weapons
            parmorInstance = player.getInventory().getPaperdollItem(Inventory.PAPERDOLL_LRHAND);
            if (parmorInstance != null && parmorInstance.getEquipSlot() == Inventory.PAPERDOLL_LRHAND)
                itemInstance = parmorInstance;
        }

        if (itemInstance != null)
        {
            curEnchant = itemInstance.getEnchantLevel();

            // set enchant value
            player.getInventory().unEquipItemInSlotAndRecord(armorType);
            itemInstance.setEnchantLevel(ench);
            player.getInventory().equipItemAndRecord(itemInstance);
            InventoryUpdate iu = new InventoryUpdate();
            iu.addModifiedItem(itemInstance);
            player.sendPacket(iu);
            player.broadcastPacket(new CharInfo(player));
            player.sendPacket(new UserInfo(player));
            player.sendMessage((new StringBuilder()).append("Admin has changed the enchantment of your ").append(itemInstance.getItem().getName()).append(" from ").append(curEnchant).append(" to ").append(ench).append(".").toString());
            _print.println("Item ("+ itemInstance.getItem().getName() + ") succesfully enchanted from " + curEnchant + " to " + ench +".");
        }
    }



3. Выдача итемов персонажам (включая offline персонажей) + возможность выдачи заточенных вещей! :
Раскрывающийся текст
Код
                else if (_usrCommand.startsWith("give"))
                {
                    StringTokenizer st = new StringTokenizer(_usrCommand.substring(5));
                    int ench = 0;
                    try
                    {
                        String player = st.nextToken();
                        L2PcInstance playerObj = L2World.getInstance().getPlayer(player);
                        int itemId = Integer.parseInt(st.nextToken());
                        int amount = Integer.parseInt(st.nextToken());
                          try
                          {
                          ench = Integer.parseInt(st.nextToken());
                          }
                          catch(Exception e)
                            {
                            _print.println("Using default enchant value 0.");
                            }

                        if(playerObj != null)
                        {
                            L2ItemInstance item = playerObj.getInventory().addItem("Status-Give", itemId, amount, null, null);
                            InventoryUpdate iu = new InventoryUpdate();
                            iu.addItem(item);
                            SystemMessage sm = new SystemMessage(SystemMessageId.YOU_PICKED_UP_S1_S2);
                            sm.addItemName(itemId);
                            sm.addNumber(amount);
                            playerObj.sendPacket(iu);
                            _print.println("Item succesfully gived to online character.");
                        } else {
                        _print.println("Executing with offline Player!!!");
                        Connection con = null;
                            try
                            {
                            int ownerId = playerObj(player);
                            if (ownerId != 0)
                            {
                            con = L2DatabaseFactory.getInstance().getConnection();
                            PreparedStatement statement = con.prepareStatement("INSERT INTO items (owner_id, object_id, item_id, count, enchant_level, loc, loc_data, price_sell, price_buy, custom_type1, custom_type2, mana_left) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)");
                            int objectId = IdFactory.getInstance().getNextId();
                                statement.setInt(1, ownerId);                             //owner_id
                                statement.setInt(2, objectId);                             //object_id
                                statement.setInt(3, itemId);                             //item_id
                                statement.setInt(4, amount);                             //count
                                statement.setInt(5, ench);                                 //enchant_level
                                statement.setString(6, "INVENTORY");                     //loc
                                statement.setInt(7, 0 );                                 //loc_data
                                statement.setInt(8, 0 );                                 //price_sell
                                statement.setInt(9, 0 );                                 //price_buy
                                statement.setInt(10, 0 );                                 //custom_type1
                                statement.setInt(11, 0 );                                 //custom_type2
                                statement.setInt(12, -1);                                 //mana_left
                                statement.execute();
                                int count = statement.getUpdateCount();
                                statement.close();
                                    if(count == 0)
                                        _print.println("Nothing Added...!");
                                    else
                                        _print.println("Item succesfully gived to offline character.");
                                } else {
                                        _print.println("Character  <" + player + "> not found in DB!");
                                        }
            
                            }
                            catch (SQLException se)
                            {
                            _print.println("SQLException while giving item.");
                                if (Config.DEBUG) se.printStackTrace();
                                }
                            catch (NoSuchElementException nsee)
                            {
                            }
                                finally
                            {
                            try { con.close(); } catch (Exception e) {}
                            }
                        }
                    }
                    catch (NoSuchElementException nsee)
                    {
                    _print.println("Usage: give <player> <itemid> <itemcount> <enchant>.");
                    }
                    catch(Exception e)
                    {    
                    }
                }

// метод для определения obj_Id имея сhar_name (через ДБ) может есть более простой вариант, но я его не знаю)

    public int playerObj(String name)
    {
                int object = 0;
                Connection con = null;
          try
           {
               con = L2DatabaseFactory.getInstance().getConnection();
               PreparedStatement statement = con.prepareStatement("SELECT obj_Id FROM characters WHERE char_name=?");
               statement.setString(1, name);
            ResultSet rset = statement.executeQuery();

            while(rset.next())
            {
                object = rset.getInt(1);
            }
            rset.close();
            statement.close();

        }    
        catch (SQLException e)
        {
            _print.println("Error while inserting item to MySQL");    
        }
        finally
        {
            try { con.close(); } catch (Exception e) {}
        }
        return object;
    }



P.S. Джаву начал изучать недавно, так-что спецов попрошу не пинать ногами за возможно неоптимизированнный код.

Всё проверялось на RT, L2Emu сборках Interlude.

Кому помогло - жду спасибки...

Кстати, кому надо, во вложении архив с полным исходником GameStatusThread.java и уже скомпилированный GameStatusThread.class.

[attachment=4260:GameStatusThread.rar]

0
Войдите или зарегистрируйтесь чтобы ответить