Jump to content

Recommended Posts

Posted

I Find something :)

 

Quote

[table][tr][td]Jython Quest: Tutorial

Jython Quest's Directory Structure

Class in quest package

Known limitations and potential problems

Tests [/td][/tr][/table]

 

For most parts of this documentation, we use the documentation on : https://www.l2jserver.com/trac/wiki/Development with some modifications. All credits is for l2j for 90% of this documentation.

 

 

Jython is well integrated with Java and there is no need to write special interface between python scripts and java code. Also Jython compiles its scripts to Java bytecode, and is executed several times faster then others scripting languages for Java. This is a full-featured programming language which have rather simple syntax. For these reasons it was selected as engine for our quest scripts.

 

Jython Quest: Tutorial

 

This is an example quest - the first (tutorial) quest players execute entering Lineage2.

 

First, we import Java classes from l2j quest interface (net.sf.l2j.gameserver.model.quest package)

 

 

Code:

import sys

from net.sf.l2j.gameserver.model.quest import State

from net.sf.l2j.gameserver.model.quest import QuestState

from net.sf.l2j.gameserver.model.quest.jython import QuestJython as JQuest

 

Class QuestJython (imported with name JQuest) holds information about a quest.

Class State is used to describe information about one state (step) or quest.

Class QuestState is an instance of quest for concrete player, which holds information about player, quest and quest state (step) for this player.

 

Next, we declare a few constants, to make code more readable. Try to avoid using numbers in code, this will help to understand and fix your text in future.

Constants for our quest are NPC and items IDs:

 

 

Code:

KELTIR_NPC_ID = 12082

FANGS_ITEM_ID = 1859

DROP_RATE     = 500000

WORLD_MAP_ITEM_ID = 1665

 

Next, declare a few helper functions.

 

A function to get number of keltir fangs current player have (st must be QuestState):

 

 

Code:

def getCount(st) :

  return st.getQuestItemsCount(FANGS_ITEM_ID)

 

 

A function to exit the quest (st must be QuestState):

 

 

Code:

def completed(st) :

  st.setState(COMPLETED)

  st.clearQuestDrops()

  st.takeItems(FANGS_ITEM_ID,-1)

  st.giveItems(WORLD_MAP_ITEM_ID,1)

  st.exitQuest(False)

  return

 

 

As you see from method names, we reset quest state, take all fangs from the player and give him a reward. Then we notify l2j that the quest is exited, and that the quest is not repeatable (False in exitQuest).

 

And finally a helper function to check is the player has collected enough fangs to exit the quest (st must be QuestState):

 

 

Code:

def check(st) :

  if getCount(st) >= 4 :

    completed(st)

  return

 

 

Next, we declare the quest itself. A quest is a python class, which extends java class net.sf.l2j.gameserver.model.quest.jython.QuestJython. We also declare a method onEvent which is called from Java in case something interesting is happen related to our quest.

 

 

Code:

class Quest (JQuest):

 

  def __init__(self,id,name,descr): JQuest.__init__(self,id,name,descr)

 

  def onEvent (self,event,st):

    id = st.getState()

    if   id == CREATED  : st.setState(STARTED)

    elif id == COMPLETED: pass

    elif id == STARTED  : check(st)

    return

 

 

The method init is a constructor of Jython class, which simply calls a constructor of Java class. The constructor has parameters:

 

 

self - reference to itself

id - integer identifier of the quest, for the client

descr - description name of the quest, show to player when it has to select between different quests from the same NPC

name - the name of the quest, which must uniquely identify this quest in l2j server

 

The method onEvent is called from java. We implemented in it state transition (logic) of our Tutorial quest. It has parameters:

 

 

self - reference to this Tutorial Qust itself

event - a string that identify event that happens in Java

st - a reference to QuestState, which holds information about current state of the quest for particular player

 

In the first line we take the current State of the quest for the player, and store it to local variable 'id'.

 

Then we check current state and optionally make transition to new state. If we just create our quest (state CREATED) we switch to state STARTED.

If if already completed the quest (state COMPLETED) we do nothing. If we are in STARTED state - we call method check() (defined above) to check

if player has enough fangs to exit the quest. We do not check 'event' variable, because in our Tutorial quest all events are coming from talks

with NPCs, so we know: if method onEvent is called - we are talking with trainer NPC.

 

And finally, when the Quest os declared, we create the quest (and register it in l2j server), and create quest states:

 

 

Code:

QUEST     = Quest(201,"Tutorial", "Tutorial quest")

CREATED   = State('Start',     QUEST)

STARTED   = State('Started',   QUEST)

COMPLETED = State('Completed', QUEST)

 

The quest will have cleint's ID 201, identifier "Tutorial" and descriotion "Tutorial quest". It will have 3 states - CREATED, STARTED, COMPLETED. Names of states may be used to automatically find .htm pages for dialogs, so for CREATED state we will show 'Start.htm', for STARTED state we will show 'Started.htm' and for COMPLETED state we will show 'Completed.htm'. Names of states are used to store quest state in DB (when players logout), so they must be different for all states of one quest.

 

We also need to specify initial state of the quest (the state it will have when a player just has started the quest) and NPCs that will give this quest:

 

Code:

QUEST.setInitialState(CREATED)

QUEST.addStartNpc(7056)

 

Note: htm file of start NPCs (7056.htm in this case) must use

 

Code:

<a action="bypass -h npc_%objectId%_Quest">

 

to talk about quests.

 

Finally, we specify a quest drop for the state STARTED, so that the player can collect items:

 

 

Code:

STARTED.addQuestDrop(KELTIR_NPC_ID,FANGS_ITEM_ID,DROP_RATE)

 

That's all for this quest. It's declared, registered in the server, and completly workable. Here is the full text of the quest:

 

Code:

import sys

from net.sf.l2j.gameserver.model.quest import State

from net.sf.l2j.gameserver.model.quest import QuestState

from net.sf.l2j.gameserver.model.quest.jython import QuestJython as JQuest

 

 

KELTIR_NPC_ID = 12082

FANGS_ITEM_ID = 1859

DROP_RATE     = 500000

WORLD_MAP_ITEM_ID = 1665

 

 

def getCount(st) :

  return st.getQuestItemsCount(FANGS_ITEM_ID)

 

def completed(st) :

  st.setState(COMPLETED)

  st.clearQuestDrops()

  st.takeItems(FANGS_ITEM_ID,-1)

  st.giveItems(WORLD_MAP_ITEM_ID,1)

  st.exitQuest(False)

  return

 

def check(st) :

  if getCount(st) >= 4 :

    completed(st)

  return

 

class Quest (JQuest):

 

  def __init__(self,id,name,descr): JQuest.__init__(self,id,name,descr)

 

  def onEvent (self,event,st):

    id = st.getState()

    if   id == CREATED  : st.setState(STARTED)

    elif id == COMPLETED: pass

    elif id == STARTED  : check(st)

    return

 

QUEST     = Quest(201,"Tutorial", "Tutorial quest")

CREATED   = State('Start',     QUEST)

STARTED   = State('Started',   QUEST)

COMPLETED = State('Completed', QUEST)

 

QUEST.setInitialState(CREATED)

QUEST.addStartNpc(7056)

 

STARTED.addQuestDrop(KELTIR_NPC_ID,FANGS_ITEM_ID,DROP_RATE)

 

Let me explain how it will work.

 

A player comes to a start NPC (ID 7056) and talks about quest. The quest will be created, and it's state will be set to initial state CREATED, and an HTML page Start.htm will be shown, explaining the task. Then method onEvent will be called from this Start.htm page, and the quest state will transit to STARTED, and Started.htm HTML page will be shown, to describe where to find keltirs and so on.

 

The state STARTED has registerd drops for keltirs, so they will eventually drop their fangs being killed. The player may return to the NPC and ask about this quest again - the method onEvent will be called. If the player has not enough fangs, the method check() will not transit to next state, and the dialog Started.htm will be shown again. But if the player has collected 4 keltir fangs, the check() method will call method completed(), which will transit to new state COMPLETED, will exit the quest, will take away all fangs and will give a world's map as reward, and finally Completed.htm page will be shown.

 

Now, let's make our quest more tutorial-like.

 

First of all, in fact there are 3 methods that are called from Java - onTalk, onKill and onEvent. If methods onTalk or onKill are not declared, the method onEvent will be called in case of a quest monster kill or during a conversation with NPC. But note - methods onTalk and onKill will be called only for talk with NPC we are currently (at current quest state) interested to talk about the quest. And method onKill is only callled when we kill a quest monster.

 

Let's ask the quest to call method onKill when we kill a keltir in STARTED state of the quest:

 

 

Code:

STARTED.addKillId(KELTIR_NPC_ID)

 

and the method onKill in Quest class:

 

 

Code:

class Quest (JQuest):

  ...

  def onKill (self,npcId,st):

    if npcId == KELTIR_NPC_ID:

      n = getCount(st)

      if   n == 0:

          return "Chat0.htm"

      elif n == 1:

          return "Chat1.htm"

      elif n >= 4:

          return "Chat4.htm"

      return "Collected "+str(n)+" of 4 fangs"

    return

 

The method onKill (and method onTalk) has parameters:

 

 

self - the quest

npcId - the ID of NPC we killed (or we talk with, for onTalk method)

st - the QuestState of the quest for our player

 

In this method we, first, check that the killed NPC is in fact a keltir. Basically this check is not needed, since we subscribed for KELTIR_NPC_ID only.

 

Then we get count of collected fangs, and if there is no fangs yet - return string "!Chat0.htm", if one fang is collected - return string "!Chat1.htm", and if all 4 fangs are collected return "!Chat4.htm". If the string we returned from onEvent, onKill or onTalk method ends with ".htm" - l2j server will show it as an HTML dialog. !Chat0.htm may have text like "keep killing keltirs, they will drop fangs eventually". !Chat1.htm may have text like "you collected one fang, you can see quest items in ...", and !Chat4.htm may have text like "return to your trainer to complete the quest".

 

Note - if the returned string starts with "<html>" - we show it as a full HTML page. So, instead of

 

 

Code:

return "Chat4.htm"

 

we may write something like

 

 

Code:

return "<html><body>Return to your trainer to complete the quest</body></html>"

 

Also, if the string does not ends with ".htm" and does not start with "<html>" - we just show it as a system message in chat window of the client. In our case, after each keltik kill, we will show the system message "Collected N of 4 fangs".

 

Our code for onKill method has one problem - it will show !Chat0.htm, !Chat1.htm and !Chat4.htm again and again. We'd like to show !Chat0.htm and !Chat1.htm only once. How? We will use variables.

 

Each quest may store strings as variables. These variables are stored in DB, much like the quest state itself. We have methods to set, get and unset (forget) variables. Let's change onKill method to use variables and show the dialogs only once:

 

 

Code:

  def onKill (self,npcId,st):

    if npcId == KELTIR_NPC_ID:

      n = getCount(st)

      if   n == 0:

        if st.get('chat0') == None :

          st.set("chat0", "true")

          return "Chat0.htm"

      elif n == 1:

        if st.get('chat1') == None :

          st.set("chat1", "true")

          return "Chat1.htm"

      elif n >= 4:

          return "Chat4.htm"

      return "Collected "+str(n)+" of 4 fangs"

    return

 

If the player have no collected fangs (n is 0) we get value of 'chat0' variable. When it's the first time onKill method was called, we have no such variables, and python returns None. In this case we set the variable, and show !Chat0.htm dialog. Next time we will kill a keltir (and it will not drop the fang) - the st.get('chat0') will return string "true", which is not None, and we will not return "!Chat0.htm", but will return "Collected 0 of 4 fangs". The same trick is used for 1 collected fang.

 

Here is the final text of the whole quest:

 

 

Code:

import sys

from net.sf.l2j.gameserver.model.quest import State

from net.sf.l2j.gameserver.model.quest import QuestState

from net.sf.l2j.gameserver.model.quest.jython import QuestJython as JQuest

 

 

KELTIR_NPC_ID = 12082

FANGS_ITEM_ID = 1859

DROP_RATE     = 500000

 

WORLD_MAP_ITEM_ID = 1665

 

 

def getCount(st) :

  return st.getQuestItemsCount(FANGS_ITEM_ID)

 

def completed(st) :

  st.setState(COMPLETED)

  st.clearQuestDrops()

  st.takeItems(FANGS_ITEM_ID,-1)

  st.giveItems(WORLD_MAP_ITEM_ID,1)

  st.exitQuest(False)

  return

 

def check(st) :

  if getCount(st) >= 4 :

    completed(st)

  return

 

class Quest (JQuest):

 

  def __init__(self,id,name,descr): JQuest.__init__(self,id,name,descr)

 

  def onEvent (self,event,st):

    id = st.getState()

    if   id == CREATED  : st.setState(STARTED)

    elif id == COMPLETED: pass

    elif id == STARTED  : check(st)

    return

 

  def onKill (self,npcId,st):

    if npcId == KELTIR_NPC_ID:

      n = getCount(st)

      if   n == 0:

        if st.get('chat0') == None :

          st.set("chat0", "true")

          return "Chat0.htm"

      elif n == 1:

        if st.get('chat1') == None :

          st.set("chat1", "true")

          return "Chat1.htm"

      elif n >= 4:

          return "Chat4.htm"

      return "Collect "+str(n)+" of 4 fangs"

    return

 

QUEST     = Quest(201, "Tutorial", "Tutorial quest")

CREATED   = State('Start',     QUEST)

STARTED   = State('Started',   QUEST)

COMPLETED = State('Completed', QUEST)

 

QUEST.setInitialState(CREATED)

QUEST.addStartNpc(7056)

QUEST.addStartNpc(7012)

QUEST.addStartNpc(7009)

QUEST.addStartNpc(7011)

 

STARTED.addQuestDrop(KELTIR_NPC_ID,FANGS_ITEM_ID,DROP_RATE)

STARTED.addKillId(KELTIR_NPC_ID)

STARTED.addTalkId(7056)

STARTED.addTalkId(7012)

STARTED.addTalkId(7009)

STARTED.addTalkId(7011)

 

 

Jython Quest's Directory Structure

 

 

Quest files (scripts and HTML pages for dialogs) are placed in datapack's directory, in subdirectory data/quests.

 

The l2j initialized Jython as %import data% and script data/init.py is executed, which contains code like

 

Code:

__all__ = ['quests']

print "importing data"

import quests

which imports code from 'quests' package (that is - from data/quests subdirectory).

 

The init.py file must initialize all available python quests, it's done like

 

 

Code:

__all__ = ['Tutorial', 'SealBroken']

print "importing quests"

import Tutirial

import SealBroken

A quest's script may be a file like data/quests/Tutorial.py or a file data/quests/Tutorial/init.py

 

Quest's HTML files are taken from data/quests/QuestName/ directory, i.e. for Tutorial quest they are data/quests/Tutorial/Start.htm, data/quests/Tutorial/Started.htm, data/quests/Tutorial/!Chat0.htm and so on.

 

Each quest script must initialize itself and register itself in l2j server.

 

Class in quest package

 

Quest :

define the handler/actions onTalk, onKill, etc... All actions of the quest is defined here. Npcs available for those actions should be added with addTalkid, addKillId etc...

There is also some methods to update the status of the quest for a character in character_quests. Those methods should be moved in a service.

Some methods show informations to players (showHtml, showError...). Those methods shouldn't be here.

 

QuestDropInfo :

define drop info for quests. Add informations for dropped items in the inventory of the player.

 

QuestPcSpawn :

define a npc spawn for quest (@see QuestPcSpawnManager)

This class gives access to various methods that add and remove spawns

 

QuestPcSpawnManager :

manager that help to add/remove spawns for quests

It is a just a wrapper around QuestPcSpawn. We could wondering why we use it if this is just a wrapper without additionnal treatments.

 

QuestState :

define quest state (completed etc..) and some methods that shouldn't be here... (not related to the state). Quite a junk object that regroup miscelleneaous methods.

 

QuestTimer

define timer for a quest

 

State

strange class with a lot of methods not related to state... We already have a method to add quest drops.

 

and in quest.jython

QuestJython very important class that load quest with BSFManager ! This is the only place where we know that we manipulate jython quest. If we want to use other types of quest, we just have to change this class.

 

Look the javadocs in the code for each functions.

 

Known limitations and potential problems

 

- jython quests use gameserver java objects. If we refactor in GS, we don't see the errors until we play the quest. And for the moment, two different teams work on dp and gs, so it's quite hard to synchronize.

- it is not possible to reload jython quest. We use BSF to execute a script in JythonQuest that load all classes in our classloader and we can't unload it.

- completion in jython quest don't work on dynamic object if jython don't know the type of the object.

 

=> open question : is it really a good choice to use jython ? why didn't we use java ?

 

 

 

Tests

 

For the moment, this package lacks of test. It should not be very hard to test some basic methods like the loading of a jython quest, add a spawn etc... There is no unit tests for now.

 

  • 3 weeks later...
Posted

hmm as it was bumped il answer to the open question...Simply because its much easier, not only to code but if you wanted to add just one quest you would have to do the same thing all over again with eclipse :P

  • 1 month later...
  • 2 weeks later...
  • 1 year later...
Posted

thx! nice guide man!

 

 

Look at the last posting date before you posting - lol

 

Posted on: October 10, 2007, 10:15:37 AM

Posted by: Rattys

  • Vision locked this topic
Guest
This topic is now closed to further replies.


  • Posts

    • L2 Kings    Stage 1 – The Awakening Dynasty and Moirai Level Cap: 83 Gear: Dynasty -Moirai & Weapons (Shop for Adena + Drop from mobs/instances ) Masterwork System: Available (Neolithics S required with neolithics u can do armor parts foundation aswell) Class Cloaks: Level 1 - Masterwork sets such us moirai/dynasty stats are boosted also vesper(stage 2) Olf T-Shirt: +6 (fails don’t reset) safe is +2 Dolls: Level 1 Belts: Low & Medium Enchant: Safe +3 / Max +8 / Attribution Easy in Moirai-Dynasty . Main Zones: Varka Outpost: Easy farm, Adena, EXP for new players = > 80- 100kk hour Dragon Valley: Main farm zone — , 100–120kk/hour Weapon Weakness System active (all classes can farm efficiently) Archers get vampiric auto-hits vs mobs Dragon Valley Center: Main Party Zone — boosted drops (Blessed enchants, Neolithics chance) => farm like 150-200kk per hour. Dragon Valley North: Spoil Zone (Asofe + crafting materials for MW) Primeval Isle: Safe autofarm zone (low adena for casual players) ==> 50kk per hour Forge of the Gods & Imperial Tomb: Available from Stage 1 (lower Adena reward in compare with Dragon Valley) Hellbound also avaliable from stage 1 In few words all zones opened but MAIN farm zone with boosted adena and drops is Dragon valley also has more mobs Instances: Zaken (24h Reuse) → Instead of Vespers drop Moirai , 100% chance to drop 1 of 9 dolls lvl 1, Zaken 7-Day Jewelry Raid Bosses (7 RBs): Drop Moirai Parts + Neolithic S grade instead of Vespers parts that has 7 Rb Quest give Icarus Weapons Special Feature 7rb bosses level up soul crystals aswell. Closed Areas : Monaster of SIlence, LOA, ( It wont have mobs) / Mahum Quest/Lizardmen off) Grand Epics: Unlocked on Day 4 of Stage 1 → Antharas, Valakas, Baium, AQ, etc ================================================================================= Stage 2 – Rise of Vespers Level Cap: 85 Gear: Moirai Armors (Adena GM SHOP / Craft/ Drop) Weapons: Icarus Cloaks: Level 2 Olf: +8 Dolls: Level 2 Belts: High & Top Enchant: Safe +3 / Max +8 Masterwork can be with Neolithics S84 aswell but higher so craft will be usefull aswell. 7 Raid Boss Quest Updated: Now works retail give vesper weapons 7rb Bosses Drops : Vespers Instances: Zaken : Drops to retail vespers + the dolls and the extra items that we added on stage 1 New Freya Instance: Added — drops vespers and instead of mid s84 weapons will drop vespers . Extra drops Blessed Bottle of Freya - drops 100% chance 1 of 9 dolls. Farm Areas Dragon Valley remains main farm New Zone : Lair of Antharas (mobs nerfed and added drop Noble stone so solo players can farm too) New Party Zone : LOA Circle   ============================================================================   Stage 3 – The Vorpal ERA Gear: Vorpal Unclock Cloaks: Level 3 Olf: +10 (max cap) Dolls: Level 3 Enchant: Safe +3 / Max +12 Farm Zones : Dragon Valley Center Scorpions becomes a normal solo zone (no longer party zone) Drops:   LOA & Knorik → Mid Weapons avaliable in drop New Party Zone Kariks Instances: Easy Freya Drops Mid Weapons Frintezza Release =================================================================================     Stage 4 – Elegia Era (Final Stage) Elegia Unlock Gear: Elegia Weapons: Elegia TOP s84 ( farmed via H-Freya/ Drops ) Cloaks: Level 5 Dolls: Level 3 (final bonuses) Enchant: Safe +6 / Max +16 Instances: Hard Freya → Drops Elegia Weapons + => The Instance will drop 2-3 parts for sure and also will be able to Join with 7 people . Party Zone will have also drop chances for elegia armor parts and weapons but small   Events (Hourly): Win: 50 Event Medals + 3 GCM + morewards Lose: 25 Medals + 1 GCM + more rewards Tie: 30 Medals + 2 GCM + more rewards   ================================================================================ Epic Fragments Currency Participating in Daily Bosses mass rewarding all players Participating in Instances (zaken freya frintezza etc) all players get reward ================================================================================ Adena - Main server currency (all items in gm shop require adena ) Event Medals (Festival Adena) - Event shop currency Donation coins you can buy with them dressme,cosmetics and premium account Epic Fragments you can buy with them fake epic jewels Olympiad Tokens you can buy many items from olympiad shop (Hero Coin even items that are on next stages) Olympiad Win = 1000 Tokens / Lose = 500 Tokens ================================================================================= Offline Autofarm Allows limited Offline farming requires offline autofarm ticket that you get by voting etc ================================================================================= Grand Epics have Specific Custom NPC that can spawn Epics EU/LATIN TIME ZONE ================================================================================= First Olympiad Day 19 December First Heroes 22 December ( 21 December Last day of 1st Period) After that olympiad will be weekly. ================================================================================= Item price and economy Since adena is main coin of server and NOT donation coins we will always add new items in gm shop with adena in order to burn the adena of server and not be inflation . =================================================================================        
    • Hello, I'd like to change a title color for custom npc.  I created custom NPC, cloned existing. I put unique id for it in npcname-e, npcgrp and database. I have "0" to serverSideName in db, so that it would use npcname-e, but instead it has "NoNameNPC"and no title color change.
    • Trusted Guy 100% ,  I asked him for some work and he did it right away.
  • 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