Une petite bibliothèque pour vous!

Répondre
Partager Rechercher
Je suis un jeune scripteur totalement indépendant, j'ai décidé de me mettre à scripter sur nwn par passion du développement et la passion d'apprendre de nouveau langage , et pour aider les shards.

Donc voici une petite bibliothèque que je trouve très pratique personnellement .



Citation :
////////////////////////////////////////////////////
//::Fait par RAT
//:: nom du script : rat_replace
//////////////////////////////////////////////////////

// replace est une fonction permettant de changer une partie d'un mot par un autre mot
// exemple: smot : WP_way_1
// 1) sR1=WP sR2=RN resultat=RN_way_1
// 2) sR1=W sR2=N resultat=NP_Nay_1
string replace ( string smot , string sR1, string sR2 );

string replace ( string smot , string sR1, string sR2 )
{

///////////////////////////////
// Definition des variables
//////////////////////////////
int idebut=0;
int i=0;
int i3=0;
int ifin=GetStringLength(smot); // longueur du mot
int ifinr2=GetStringLength(sR2); // longueur du mot cherche
int ifinr1=GetStringLength(sR1); // longueur du mot remplacer
int lenrecup=0;
string remplace,insert,recup,concatenation;

while (i<=ifin) //boucle qui s'incremente suivant la longueur du mot
{

//test2=GetStringLeft(smot,i);


recup=GetSubString (smot,i3,ifinr1); // recuperation de la sous-chaine suivant
//la position du mot et le nbre a compter
//dependant de la longueur de sR1

//SendMessageToPC (oPC,test2);

if (recup!="")
{
if (recup==sR1) // si il trouve une egalite , alors il va remplacer sR1 par sR2
{
lenrecup=GetStringLength(recup); //longueur du mot trouve
insert=InsertString(smot,sR2,lenrecup); //insertion du sR2 a la position de recup
concatenation=concatenation + GetSubString (insert,lenrecup,ifinr2);
// et concatenation
// SendMessageToPC (oPC,concatenation);

}
else
{ concatenation= concatenation + recup;} //concatenation du mot qui est a
//garder

}
else
{break;} // si le string est une chaine vide il arrete la boucle

//////////////////////////
//incrementation
/////////////////////////

i3=i3+ifinr1;

i++;
}

//SendMessageToPC (oPC,concatenation);
//////////////////////////////////////////////////
//recuperation de la variable et renvoie la valeur
/////////////////////////////////////////////////

remplace=concatenation;


return remplace;



}


Je suis nul en script
et la je comprends même pas a quoi ça corresponds !!

on peut m'expliquer?
__________________
Congnois toy toy mesme. Nulle gloire dans le sang inutile
et voici , une autre bibliothèque que je me suis amusé à faire!
Citation :

////////////////////////////////////////
///Source tire sur zdm_generic_001
///Modifie par RAT
///pour creer le deplacement aleatoire
///nom du script : rat_i0_generic
///////////////////////////////////////
#include "NW_I0_GENERIC"

//fonction pour rendre plus vivant en faisant une demarche aleatoire a partir de waypoint
void RunCircuitrat(int nTens, int nNum, int nRun = FALSE, float fPause = 1.0);
void WalkWayPointsrat(int nRun = FALSE, float fPause = 1.0);
void RunNextCircuitrat(int nRun = FALSE, float fPause = 1.0);
int maxwaypoint();

void WalkWayPointsrat(int nRun = FALSE, float fPause = 1.0) //Run first circuit
{
ClearAllActions();
string DayWayString;
string NightWayString;
string DayPostString;
string NightPostString;
string sWay;
string sPost;

//The block of code below deals with night and day cycle for postings and walkway points.
if(GetSpawnInCondition(NW_FLAG_DAY_NIGHT_POSTING))
{
DayWayString = "WP_";
NightWayString = "WN_";
DayPostString = "POST_";
NightPostString = "NIGHT_";
}
else
{
DayWayString = "WP_";
NightWayString = "WP_";
DayPostString = "POST_";
NightPostString = "POST_";
}

if(GetIsDay() || GetIsDawn())
{
SetLocalString(OBJECT_SELF, "NW_GENERIC_WALKWAYS_PREFIX", DayWayString);
SetLocalString(OBJECT_SELF, "NW_GENERIC_POSTING_PREFIX", DayPostString);
}
else
{
SetLocalString(OBJECT_SELF, "NW_GENERIC_WALKWAYS_PREFIX", NightWayString);
SetLocalString(OBJECT_SELF, "NW_GENERIC_POSTING_PREFIX", NightPostString);
}


sWay = GetLocalString(OBJECT_SELF, "NW_GENERIC_WALKWAYS_PREFIX");
sPost = GetLocalString(OBJECT_SELF, "NW_GENERIC_POSTING_PREFIX");

//I have now determined what the prefixs for the current walkways and postings are and will use them instead
// of POST_ and WP_

if(GetSpawnInCondition(NW_FLAG_STEALTH))
{
//MyPrintString("GENERIC SCRIPT DEBUG STRING ********** " + "Attempting to Activate Stealth");
ActionUseSkill(SKILL_HIDE, OBJECT_SELF);
}
if(GetSpawnInCondition(NW_FLAG_SEARCH))
{
//MyPrintString("GENERIC SCRIPT DEBUG STRING ********** " + "Attempting to Activate Search");
ActionUseSkill(SKILL_SEARCH, OBJECT_SELF);
}

//Test if OBJECT_SELF has waypoints to walk
string sWayTag = GetTag( OBJECT_SELF );
sWayTag = sWay + sWayTag + "_01";
object oWay1 = GetNearestObjectByTag(sWayTag);
if(!GetIsObjectValid(oWay1))
{
oWay1 = GetObjectByTag(sWayTag);
}
if(GetIsObjectValid(oWay1) && GetSpawnInCondition(NW_FLAG_AMBIENT_ANIMATIONS))
{
//turn off the ambient animations if the creature should walk way points.
SetSpawnInCondition(NW_FLAG_AMBIENT_ANIMATIONS, FALSE);
SetSpawnInCondition(NW_FLAG_IMMOBILE_AMBIENT_ANIMATIONS, FALSE);
}

if(GetIsObjectValid(oWay1))
{
int nNth = 1;
int nTens;
int nNum;
int nTens2;
int compt=0;
int ndizaine=0;
int NumMax=0;
object oNearest = GetNearestObject(OBJECT_TYPE_WAYPOINT, OBJECT_SELF, nNth);
while (GetIsObjectValid(oNearest))
{
string sNearestTag = GetTag(oNearest);
//removes the first 3 and last three characters from the waypoint's tag
//and checks it against his own tag. Waypoint tag format is WP_MyTag_XX.
if( GetSubString( sNearestTag, 3, GetStringLength( sNearestTag ) - 6 ) == GetTag( OBJECT_SELF ) )
{
string sTens = GetStringRight(GetTag(oNearest),2);
nTens = StringToInt(sTens)/10;
nNum= StringToInt(GetStringRight(GetTag(oNearest),1));



oNearest = OBJECT_INVALID;
}
else
{
nNth++;
oNearest = GetNearestObject(OBJECT_TYPE_WAYPOINT,OBJECT_SELF,nNth);
}
}
RunCircuitrat(nTens, nNum, nRun, fPause); //***************************************
ActionWait(fPause);
ActionDoCommand(RunNextCircuitrat(nRun, fPause));
//ActionDoCommand(SignalEvent(OBJECT_SELF,EventUserDefined(2)));
}
else
{
sWayTag = GetTag( OBJECT_SELF );
sWayTag = sPost + sWayTag;
oWay1 = GetNearestObjectByTag(sWayTag);
if(!GetIsObjectValid(oWay1))
{
oWay1 = GetObjectByTag(sWayTag);
}

if(GetIsObjectValid(oWay1))
{
ActionForceMoveToObject(oWay1, nRun, 1.0, 60.0);
float fFacing = GetFacing(oWay1);
ActionDoCommand(SetFacing(fFacing));
}
}
if(GetIsObjectValid(oWay1) && GetSpawnInCondition(NW_FLAG_AMBIENT_ANIMATIONS))
{
SetSpawnInCondition(NW_FLAG_AMBIENT_ANIMATIONS, FALSE);
SetSpawnInCondition(NW_FLAG_IMMOBILE_AMBIENT_ANIMATIONS, FALSE);
}
}

void RunNextCircuitrat( int nRun = FALSE, float fPause = 1.0)
{
RunCircuitrat(0,1, nRun, fPause); //***************************************
ActionWait(fPause);
ActionDoCommand(RunNextCircuitrat(nRun, fPause));
//ActionDoCommand(SignalEvent(OBJECT_SELF,EventUserDefined(2)));
}

//::///////////////////////////////////////////////
//:: Run Circuit
//:: Copyright (c) 2001 Bioware Corp.
//:://////////////////////////////////////////////
/*
Calculates the proper path to follow along a
predetermined set of way points
*/
//:://////////////////////////////////////////////
//:: Created By: Aidan Scanlan
//:: Created On: July 10, 2001
//:://////////////////////////////////////////////


//:://////////////////////////////////////////////
//:: Créé par: RAT
//:://////////////////////////////////////////////
int maxwaypoint()

{
//////////////////////////////
//Declaration des variables
/////////////////////////////
int nNth = 0;
int nrecup,nbr,nTens2;
int compt=0;
string ndizaine;
int NumMax=0;
object oNearest = GetNearestObject(OBJECT_TYPE_WAYPOINT, OBJECT_SELF);

////////////////////////////////////
//cacule du waypoint le plus grand
///////////////////////////////////
while (GetIsObjectValid(oNearest))
{
string sNearestTag = GetTag(oNearest);

if( GetSubString( sNearestTag, 3, GetStringLength( sNearestTag ) - 6 ) == GetTag( OBJECT_SELF ) )
{
string sTens = GetStringRight(GetTag(oNearest),2);
nrecup = StringToInt(sTens)/10;
nbr= StringToInt(GetStringRight(GetTag(oNearest),1));

ndizaine=IntToString(nrecup) + IntToString(nbr) ;
nTens2=StringToInt(ndizaine);

if (nTens2> NumMax ) /// si le nTens2 est superieur alors
{NumMax=nTens2;} /// NumMax recupere le chiffre le plus grand

//oNearest = OBJECT_INVALID;


}

nNth++; // incrementation du nbre d'objet qui se trouve
// sur l'area
oNearest = GetNearestObject(OBJECT_TYPE_WAYPOINT,OBJECT_SELF,nNth);



}



return NumMax;


}


void RunCircuitrat( int nTens, int nNum, int nRun = FALSE, float fPause = 1.0)
{

////////////////////
//Variables
///////////////////

string sWay = GetLocalString(OBJECT_SELF, "NW_GENERIC_WALKWAYS_PREFIX");
int Maxint=0;
int finalint=0;
int actrand;
string actrand2;
int i=0;
object oTargetPoint;
/////////////////////////////////////////////////////////
//appelle de la fonction et recupere le nbre de waypoint
/////////////////////////////////////////////////////////

Maxint=maxwaypoint();
finalint=Maxint -1; //retire un pour le random

//////////////////////////////////////////////////
//boucle de deplacement du npc suivant le maxint
//////////////////////////////////////////////////
while(i <= Maxint)
{


actrand=Random(finalint); // random du finalint)chiffre aleatoire donc de 0 a finalint
actrand=actrand+1;//on rajoute +1 comme le premier waypoint est a 01

if (actrand < 10) //si c en dessous de 10 alors on rajoute un zero pour
{actrand2="0" + IntToString(actrand);}//respecter la gestion des waypoints
else
{ actrand2=IntToString(actrand); }

// concatenation pour avoir le tag du waypoint
oTargetPoint = GetWaypointByTag(sWay + GetTag(OBJECT_SELF) + "_"+ actrand2);
ActionWait(fPause);
ActionMoveToObject(oTargetPoint, nRun); //deplacement vers l object

i++; //incrementation pour la boucle


}
}
//:://////////////////////////////////////////////
//:: Fin du script
//:://////////////////////////////////////////////

Re: Je suis nul en script
Citation :
Provient du message de Blam
et la je comprends même pas a quoi ça corresponds !!

on peut m'expliquer?
Salut blam, pour t'expliquer un peu, enfin je vais essayer .
Dans la plupart des langages comme php4, ou ASP3, mm vb6.0 etc.... ils ont une fonction qui permette de prendre une partie de chaîne pour la remplacer par une autre.
Je vais essayer te donner un exemple.

par exemple : string sChaine="nw_demo"

par rapport a cette chaîne, un item par exemple possède ce tag, qui fait que quand tu l'utilise cela va créer un monstre avec pour tag "monstre_demo"

donc cela va te permettre de pouvoir faire un remplacement de chaine

string srep= replace("nw_demo", "nw","monstre")

cela va faire que srep aura pour valeur "monstre_demo" car la fonction aura remplacer nw par monstre.

un autre exemple :
string srep=replace ("nw_never","n","R")
donc "Rw_Rever"
etc

Enfin bon j'espère que je me suis fais à peu près comprendre lol .
a tes souhait !
merci rat, mais je suis trop nul, j'ai même pas compris ton explication, j'ai <0 pour les notions de base
__________________
Congnois toy toy mesme. Nulle gloire dans le sang inutile
je vais vous donner un exemple que j'ai utilisé pour mes test sur ma bibliothèque cela sera plus simple:

object oActivator = GetItemActivator();
object oLivre = GetItemActivated();

//si par exemple le livre se nomme Le Livre du Demon donc le tag
//peut-être "livremonster_balor"
// et vous aurez au préablement créer un démon personnalisé
//avec comme resref "lm_balor"

if (GetStringLeft(GetTag(oLivre),13)=="livremonster_" )
{

string stag=GetTag(oLivre);

string srepl;

location lLoc= GetLocation(oActivator);

srepl=replace(stag,"livremonster","lm");

//SendMessageToPC (oActivator,srepl);

CreateObject(OBJECT_TYPE_CREATURE,srepl,lLoc);

return;
}
J'ai écrit cette même fonction il y a peu de temps et je te signale que ta mise en place m'as l'air assez lourde, une fonction aussi longue pour faire si peu de chose...

Code PHP:

string StringReplace(string s1string s2string s3)
{
  
int nTemp;
  
int nL GetStringLength(s3);
  
int nLength GetStringLength(s1);
  
string sTemp;
  
string sR "";

  while ((
nTemp FindSubString(s3s1)) >= 0)
    {
    
sTemp GetStringLeft(s3nTemp);
    
s3 GetStringRight(s3nL nLength nTemp);
    
sR sR sTemp s2;
    
nL GetStringLength(s3);
    }
  
sR+=s3;

  return 
sR;

Sinon, c'est bien d'en faire profiter les autres , en fait j'avais écrit cette fonction en réponse à une question sur un autre forum, donc je l'avais posté là-bas mais..
ba si tu vires tous les commentaires la fonction ne fais qu'une trentaine de ligne, mais c'est vrai qu'elle reste plus longue que la tienne .

Je ne l'ai peut être pas assez optimiser sûrement.
C'est pas tellement la longueur que je te reproche, c'est surtout les boucles. Tu fais là un boulot que FindSubString() fait sans doute mieux (plus rapidement en fait). Non que tes boucles ne soit pas bien pensé mais FindSubString() est probablement une fonction qui a été programmé directement en C, utiliser d'autres fonctions "créés par Bioware" pour en émuler le fonctionnement est forcément plus long, surtout si la chaîne de caractère est longue...
Mais sinon c'est très bien.
vivi je te comprends tout à fait!
C'est juste que cela fait que depuis 2 semaines que je code sur never, donc je ne connaissais pas toutes les fonctions de never. Et je n'avais pas cherche cette fonction. .
Mais tu as totalement raison, les autres langages possèdent à peu près la mm fonction .
Mais merci de l'info cela me servira pour les autres scripts que je ferai
Pour la gestion des strings...
Code PHP:

//::///////////////////////////////////////////////
//:: Gestion avancee des chaines de caracteres
//:: inc_strings.nss
//:: Copyright (c) Althea 2002
//:://////////////////////////////////////////////
/*
    Bibliotheques de fonction de traitement
    avance des chaines de caracteres.
*/
//:://////////////////////////////////////////////
//:: Créé par : Tynril
//:: Créé le  : 21/09/2002
//:://////////////////////////////////////////////


//----------------------------------------------------------------------------
// CONSTANTES

// Succes de l'operation sur le Tokenizer.
int StrTOKENIZER_SUCCESS 0;

// Erreur retournee si l'on essaye d'initialise un Tokenizer existant.
int StrTOKENIZER_EXISTS = -1;

// Erreur retournee si l'on essaye d'utiliser un Tokenizer non-initialise.
int StrTOKENIZER_NOTINITIALIZED = -2;

// Erreur retournee si l'on essaye d'utiliser un Tokenizer avec un Token vide.
int StrTOKENIZER_EMPTYTOKEN = -3;

// Erreur retournee si l'on essaye d'utiliser un Tokenizer avec une chaine vide.
int StrTOKENIZER_EMPTYSTRING = -4;



//----------------------------------------------------------------------------
// PROTOTYPES DE FONCTIONS ET DECLARATIONS

// Retourne les caracteres se trouvant avant sPattern.
// Exemple : StrBefore("Un chien"," ") -> "Un"
// Si sPattern n'est pas trouve dans la chaine, celle-ci est retournee entiere.
string StrBefore(string sSourcestring sPattern);

// Retourne les caracteres se trouvant apres sPattern.
// Exemple : StrAfter("Un chien"," ") -> "chien"
// Si sPattern n'est pas trouve dans la chaine, celle-ci est retournee entiere.
string StrAfter(string sSourcestring sPattern);

// Initialize the string tokenizer with a given string and token.  Optionally,
// takes a tokenizer session, in case you need to run more than one tokenizer
// at a time.  The tokenized string can be walked with the function
// StrTokenizerNext, and freed with StrTokenizerFree.
//
int StrTokenizerInitialize(string sStringToTokenizestring sTokenint iTokenizerSession 0);

// Returns the next token-delimited string from a given initialized tokenizer,
// or "" if the tokenizer is not initialized or empty of tokens.  A tokenizer
// needs to be allocated with Strtokenizer_initialize and freed with
// Strtokenizer_free.
string StrTokenizerNext(int iTokenizerSession 0);

// Frees an initialized tokenizer.
int StrTokenizerFree(int iTokenizerSession 0);

// Turns a given string uppercase
string StrUpperCase(string sSource);

// Turns a given string lowercase
string StrLowerCase(string sSource);

// Replaces all instances of sReplaceMe in sSource with sNewText, and return
// the altered string.  If sReplaceMe is empty, then sSource is immediately
// returned unaltered.
string StrReplace(string sSourcestring sReplaceMestring sNewText);

// Capitalize the first letter of a string.  Useful for turning
// 'mister' into 'Mister', for example, in generating conversation or
// other text.
//
string StrCapStr(string sSource);

// Pads a string on the left with the pattern given.
string StrPadLeft(string sOriginalint iPadTostring sPadWith);

// Pads a string on the right with the pattern given.
string StrPadRight(string sOriginalint iPadTostring sPadWith);

// Returns the member position of the token in the string, beginning with 0,
// or -1 if the given token is not a member of the string list.  Token must
// be a complete one.
//
int StrMember(string sListstring sTokenstring sDelimit " "int iTokenizer 969);

// Returns the number of tokens in a delimited list string, or -1 on error.
int StrMemberCount(string sListstring sDelimit " "int iTokenizer 969);


//----------------------------------------------------------------------------
// ACTUAL FUNCTION SOURCES

// FUNCTION: StrBefore
//
// Returns the portion of sSource which is before the first occurance of
// sPattern.  For example, Strbefore("Foo bar"," ") -> "Foo"
//
// If the pattern does not exist in the string, the entire string is returned.
string StrBefore(string sSourcestring sPattern)
{
    
int iMarker;
    
string sResult;

    
// Sanity check!
    
if ((sPattern == "") || (sSource == ""))
        return 
sSource;

    
iMarker FindSubString(sSource,sPattern);

    if (
iMarker >= 0) {
        
sResult GetSubString(sSource,0,iMarker);
    }
    else {
        
sResult sSource;
    }

    return 
sResult;
}

// FUNCTION: StrAfter
//
// Returns the portion of sSource which is after the first occurance of
// sPattern.  For example, Strbefore("Foo bar"," ") -> "bar"
//
// If the pattern does not exist in the string, an empty string is returned.
string StrAfter(string sSourcestring sPattern)
{
    
int iMarkeriMarkerLength;
    
string sResult;

    
// Sanity check!
    
if ((sPattern == "") || (sSource == ""))
        return 
"";

    
iMarkerLength GetStringLength(sPattern);
    
iMarker FindSubString(sSource,sPattern);

    if (
iMarker >= 0) {
        
sResult GetSubString(sSource,iMarker iMarkerLength,
            
GetStringLength(sSource) - (iMarker iMarkerLength));
    }
    else {
        
sResult "";
    }

    return 
sResult;
}

// FUNCTION: StrTokenizerInitialize
//
// Initialize the string tokenizer with a given string and token.  Optionally,
// takes a tokenizer session, in case you need to run more than one tokenizer
// at a time.  The tokenized string can be walked with the function
// Strtokenizer_next, and freed with Strtokenizer_free.
//
int StrTokenizerInitialize(string sStringToTokenizestring sToken,
        
int iTokenizerSession 0)
{
    
// Sanity check to make sure we're not clobbering an existing token.
    
if (GetLocalString(OBJECT_SELF,"tokenizer_" IntToString(iTokenizerSession) + "_token") != "") {
        return 
StrTOKENIZER_EXISTS;
    }

    
// Sanity check that we have a token.
    
if (sToken == "")
        return 
StrTOKENIZER_EMPTYTOKEN;

    
// Sanity check that we have a string to tokenize!
    
if (sStringToTokenize == "")
        return 
StrTOKENIZER_EMPTYSTRING;

    
// Set up our data for later.
    
SetLocalString(OBJECT_SELF,
        
"tokenizer_" IntToString(iTokenizerSession) + "_token",
        
sToken);

    
SetLocalString(OBJECT_SELF,
        
"tokenizer_" IntToString(iTokenizerSession) + "_stringbuf",
        
sStringToTokenize);

    return 
StrTOKENIZER_SUCCESS;
}

// FUNCTION: StrTokenizerNext
//
// Returns the next token-delimited string from a given initialized tokenizer,
// or "" if the tokenizer is not initialized or empty of tokens.  A tokenizer
// needs to be allocated with Strtokenizer_initialize and freed with
// Strtokenizer_free.
//
string StrTokenizerNext(int iTokenizerSession 0)
{
    
string sCurBuffersNewBuffersToken;

    
sToken GetLocalString(OBJECT_SELF"tokenizer_" +
        
IntToString(iTokenizerSession) + "_token");
    
sCurBuffer GetLocalString(OBJECT_SELF"tokenizer_" +
        
IntToString(iTokenizerSession) + "_stringbuf");

    
// Sanity check to make sure we have an initialized tokenizer
    
if (sToken == "")
        return 
"";

    
sNewBuffer StrBefore(sCurBuffersToken);
    
sCurBuffer StrAfter(sCurBuffersToken);

    
SetLocalString(OBJECT_SELF"tokenizer_" +
        
IntToString(iTokenizerSession) + "_stringbuf"sCurBuffer);

    return 
sNewBuffer;
}

// FUNCTION: StrTokenizerFree
//
// Frees an initialized tokenizer.
//
int StrTokenizerFree(int iTokenizerSession 0)
{
    if (
GetLocalString(OBJECT_SELF"tokenizer_" +
        
IntToString(iTokenizerSession) + "_token") == "")
        return 
StrTOKENIZER_NOTINITIALIZED;

    
DeleteLocalString(OBJECT_SELF"tokenizer_" +
        
IntToString(iTokenizerSession) + "_token");
    
DeleteLocalString(OBJECT_SELF"tokenizer_" +
        
IntToString(iTokenizerSession) + "_stringbuf");

    return 
StrTOKENIZER_SUCCESS;
}

// FUNCTION: StrUpperCase
//
// Turns a given string uppercase
//
string StrUpperCase(string sSource)
{
    
string sResult;
    
string UppercaseLetters "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
string LowercaseLetters "abcdefghijklmnopqrstuvwxyz";
    
int loopmarker;

    
// Sanity check!
    
if (sSource == "")
        return 
"";

    
// Walk the string...
    
for (loop 0loop GetStringLength(sSource); loop++) {
        
string sChar;
        
int marker;

        
// Get the current character of the string...
        
sChar GetSubString(sSourceloop1);

        
// ...and see if it's in the LowercaseLetter set.
        
marker FindSubString(LowercaseLetterssChar);
        if (
marker >= 0) {
            
// If so, replace with a matching UppercaseLetter.
            
sChar GetSubString(UppercaseLettersmarker1);
        }

        
// Append the current character to the result.
        
sResult sResult sChar;
    }

    return 
sResult;
}

// FUNCTION: StrLowerCase
//
// Turns a given string lowercase
//
string StrLowerCase(string sSource)
{
    
string sResult;
    
string UppercaseLetters "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
string LowercaseLetters "abcdefghijklmnopqrstuvwxyz";
    
int loopmarker;

    
// Sanity check!
    
if (sSource == "")
        return 
"";

    
// Walk the string...
    
for (loop 0loop GetStringLength(sSource); loop++) {
        
string sChar;
        
int marker;

        
// Get the current character of the string...
        
sChar GetSubString(sSourceloop1);

        
// ...and see if it's in the UppercaseLetter set.
        
marker FindSubString(UppercaseLetterssChar);
        if (
marker >= 0) {
            
// If so, replace with a matching LowercaseLetter.
            
sChar GetSubString(LowercaseLettersmarker1);
        }

        
// Append the current character to the result.
        
sResult sResult sChar;
    }

    return 
sResult;
}

// FUNCTION: StrReplace
//
// Replaces all instances of sReplaceMe in sSource with sNewText, and return
// the altered string.  If sReplaceMe is empty, then sSource is immediately
// returned unaltered.
//
string StrReplace(string sSourcestring sReplaceMestring sNewText)
{
    
string sResult;
    
int marker;

    
// Sanity check!
    
if (sSource == "")
        return 
"";

    
// Sanity check!
    
if (sReplaceMe == "")
        return 
sSource;

    
sResult sSource;

    
// As long as an instance of our replace-string exists, keep walking
    // the string and altering it.
    
while ((marker FindSubString(sResultsReplaceMe)) >= 0) {

        
// Isn't it nice to be able to reuse your own library functions?
        
sResult =
            
StrBefore(sResultsReplaceMe) +
            
sNewText +
            
StrAfter(sResultsReplaceMe);

    }

    return 
sResult;
}

// FUNCTION: StrCapStr
//
// Capitalize the first letter of a string.  Useful for turning
// 'mister' into 'Mister', for example, in generating conversation or
// other text.
//
string StrCapStr(string sSource)
{
    
string sResult;
    
string UppercaseLetters "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
string LowercaseLetters "abcdefghijklmnopqrstuvwxyz";
    
string sChar;
    
int iPos;

    
sChar GetSubString(sSource01);
    
iPos FindSubString(LowercaseLetterssChar);

    if (
iPos != -1) {
        
sChar GetSubString(UppercaseLetters,iPos,1);
    }

    
sResult sChar GetSubString(sSource,1,GetStringLength(sSource) - 1);

    return 
sResult;
}

// FUNCTION: StrPadLeft
//
// Pads a string on the left with the pattern given.
string StrPadLeft(string sOriginalint iPadTostring sPadWith)
{
    
string sNew;

    
sNew sOriginal;
    while (
GetStringLength(sNew) < iPadTo) {
        
sNew sPadWith sNew;
    }

    if (
GetStringLength(sNew) > iPadTo) {
        
sNew GetStringRight(sNewiPadTo);
    }

    return 
sNew;
}

// FUNCTION: StrPadRight
//
// Pads a string on the right with the pattern given.
string StrPadRight(string sOriginalint iPadTostring sPadWith)
{
    
string sNew;

    
sNew sOriginal;
    while (
GetStringLength(sNew) < iPadTo) {
        
sNew sNew sPadWith;
    }

    if (
GetStringLength(sNew) > iPadTo) {
        
sNew GetStringLeft(sNewiPadTo);
    }

    return 
sNew;
}

// FUNCTION: StrMember
//
// Returns the member position of the token in the string, beginning with 0,
// or -1 if the given token is not a member of the string list.  Token must
// be a complete one.
//
int StrMember(string sListstring sTokenstring sDelimit " "int iTokenizer 969)
{
    
string sTempKey;
    
int iCounteriFound;

    
iCounter 0;
    
iFound = -1;

    if (
StrTokenizerInitialize(sListsDelimitiTokenizer) != StrTOKENIZER_SUCCESS) {
        return -
1;
    }

    while (((
sTempKey StrTokenizerNext(iTokenizer)) != "") && (iFound == -1)) {
        if (
sTempKey == sToken) {
            
iFound iCounter;
        }
        
iCounter++;
    }

    
StrTokenizerFree(iTokenizer);

    return 
iFound;
}

// FUNCTION: StrMemberCount
//
// Returns the number of tokens in a delimited list string, or -1 on error.
//
int StrMemberCount(string sListstring sDelimit " "int iTokenizer 969)
{
    
string sTempKey;
    
int iCounter;

    
iCounter 0;

    if (
sList == "")
        return 
0;

    if (
FindSubString(sListsDelimit) == -1)
        return 
0;

    if (
StrTokenizerInitialize(sListsDelimitiTokenizer) != StrTOKENIZER_SUCCESS) {
        return -
1;
    }

    while ((
sTempKey StrTokenizerNext(iTokenizer)) != "") {
        
iCounter++;
    }

    
StrTokenizerFree(iTokenizer);

    return 
iCounter;

Repompé d'un truc je sais plus où
MDR, bien vu coolstar pour le RAT de bibliothèque, je n'avais même pas fait le rapprochement .

1 point pour Coolstar .

Et merci à tynril , je pense que cela est très utile , et que je vais analyser le code .
un petit script à mettre ds le onHeartbeat d'un NPC
ce script permet surtout pour les mondes persistants, de créer des nettoyeurs publics, qui viendront ramasser au bout de X minutes (par defaut c'est 1 min) un item qu'un joueur aurait laissé trainer . A mettre dans le onSpawn la fonction " ActionRandomWalk(); " pour ne pas vous embeter de mettre des waypoints.

Voici le code :

Code PHP:

//::///////////////////////////////////////////////
//:: Default On Heartbeat
//:: NW_C2_DEFAULT1
//:: Copyright (c) 2001 Bioware Corp.
//:://////////////////////////////////////////////
/*
    This script will have people perform default
    animations.
*/
//:://////////////////////////////////////////////
//:: Created By: Preston Watamaniuk
//:: Created On: Nov 23, 2001
//:://////////////////////////////////////////////
//:://////////////////////////////////////////////
//:: Modifie par: RAT
//:://////////////////////////////////////////////
#include "NW_I0_GENERIC"

void main()
{
    if(
GetSpawnInCondition(NW_FLAG_FAST_BUFF_ENEMY))
    {
        if(
TalentAdvancedBuff(40.0))
        {
            
SetSpawnInCondition(NW_FLAG_FAST_BUFF_ENEMYFALSE);
            return;
        }
    }

    if(
GetSpawnInCondition(NW_FLAG_DAY_NIGHT_POSTING))
    {
        
int nDay FALSE;
        if(
GetIsDay() || GetIsDawn())
        {
            
nDay TRUE;
        }
        if(
GetLocalInt(OBJECT_SELF"NW_GENERIC_DAY_NIGHT") != nDay)
        {
            if(
nDay == TRUE)
            {
                
SetLocalInt(OBJECT_SELF"NW_GENERIC_DAY_NIGHT"TRUE);
            }
            else
            {
                
SetLocalInt(OBJECT_SELF"NW_GENERIC_DAY_NIGHT"FALSE);
            }
            
WalkWayPoints();
        }
    }

    if(!
GetHasEffect(EFFECT_TYPE_SLEEP))
    {
        if(!
GetIsPostOrWalking())
        {
            if(!
GetIsObjectValid(GetAttemptedAttackTarget()) && !GetIsObjectValid(GetAttemptedSpellTarget()))
            {
                if(!
GetIsObjectValid(GetNearestCreature(CREATURE_TYPE_REPUTATIONREPUTATION_TYPE_ENEMYOBJECT_SELF1CREATURE_TYPE_PERCEPTIONPERCEPTION_SEEN)))
                {
                    if(!
GetBehaviorState(NW_FLAG_BEHAVIOR_SPECIAL) && !IsInConversation(OBJECT_SELF))
                    {
                        if(
GetSpawnInCondition(NW_FLAG_AMBIENT_ANIMATIONS) || GetSpawnInCondition(NW_FLAG_AMBIENT_ANIMATIONS_AVIAN))
                        {
                            
PlayMobileAmbientAnimations();
                        }
                        else if(
GetIsEncounterCreature() &&
                        !
GetIsObjectValid(GetNearestCreature(CREATURE_TYPE_REPUTATIONREPUTATION_TYPE_ENEMYOBJECT_SELF1CREATURE_TYPE_PERCEPTIONPERCEPTION_SEEN)))
                        {
                            
PlayMobileAmbientAnimations();
                        }
                        else if(
GetSpawnInCondition(NW_FLAG_IMMOBILE_AMBIENT_ANIMATIONS) &&
                           !
GetIsObjectValid(GetNearestCreature(CREATURE_TYPE_REPUTATIONREPUTATION_TYPE_ENEMYOBJECT_SELF1CREATURE_TYPE_PERCEPTIONPERCEPTION_SEEN)))
                        {
                            
PlayImmobileAmbientAnimations();
                        }
                    }
                    else
                    {
                        
DetermineSpecialBehavior();
                    }
                }
                else
                {
                    
//DetermineCombatRound();
                
}
            }
        }
    }
    else
    {
        if(
GetSpawnInCondition(NW_FLAG_SLEEPING_AT_NIGHT))
        {
            
effect eVis EffectVisualEffect(VFX_IMP_SLEEP);
            if(
d10() > 6)
            {
                
ApplyEffectToObject(DURATION_TYPE_INSTANTeVisOBJECT_SELF);
            }
        }
    }
    if(
GetSpawnInCondition(NW_FLAG_HEARTBEAT_EVENT))
    {
        
SignalEvent(OBJECT_SELFEventUserDefined(1001));
    }

//:://////////////////////////////////////////////
//:: Cree par :RAT
//:: script permettant de faire les nettoyeux publics sur un module
//:: ils rammassent les objets qu'ils peuvent voir
//:: et le detruisent dans leur inventaire
//:: Mettre les NPC en perception longue
//:://////////////////////////////////////////////

//:://////////////////////////////////////////////
//:: Declaration des variables
//:://////////////////////////////////////////////

 
object oitem=GetNearestObject(OBJECT_TYPE_ITEM,OBJECT_SELF,1);
 
object oNPC=OBJECT_SELF;
 
int inth=1;
float fDuree=60.0;  // si vous voulez qu'ils attendent plus d'une minute, vous
// devez changer cette valeur

if (GetIsObjectValid(oitem))
{
  if (
GetDistanceToObject(oitem)<=20.0//s'il voit un objet ds un rayon de 20 metres
  
{

    
ClearAllActions();


   
string stag=GetTag(oitem);
     if (
GetLocalInt(oitem,"BLOKE_EBOUEUR")==0)  // verifie si l item possede le tag pour bloquer le NPC
      
{
      
DelayCommand(fDuree,SetLocalInt(oitem,"BLOKE_EBOUEUR",1)); // au bout d'une minute , on debloque le NPC
      
}
      else
      {
     
SetLocalInt(oitem,"BLOKE_EBOUEUR",0);
      
ActionPickUpItem(oitem);   // et donc va chercher l'item
      
object oinvent=GetFirstItemInInventory(OBJECT_SELF);   // on regarde le premier objet dans son inventaire
         // ActionRandomWalk();
      
DestroyObject(oinvent,1.0);   // et il le supprime
      // SendMessageToAllDMs(stag); // message de test
       
ActionRandomWalk();  // on redemande au NPC de marcher aleatoirement
       //break;

      
}
  }

  else
  {

   
string stag2=GetTag(oitem);   // si le NPC le voit a plus de 20 metre ,

   
ActionPickUpItem(oitem);  //on le deplace, mais il sera rebloquer pendant une minute quand l'item
                             //rentrera dans son rayon de 20 metres

    
SetLocalInt(oitem,"BLOKE_EBOUEUR",0);
  }

}
else
{
SetLocalInt(oitem,"BLOKE_EBOUEUR",0);
  
ActionRandomWalk();

}

//:://////////////////////////////////////////////
//::                FIN DU SCRIPT
//:://////////////////////////////////////////////






Si je me souviens bien, nos grands maîtres scripteurs sur ce forum ont déjà résolu ce problème de nettoyage de zone avec un script sur le OnExit de la zone, ce qui évite l'utilisation lourde du OnHeartbeat.

Edit\ plus précisement, je pensais à ce poste ci d'eMR.
Ah bon! je m'en souvenais pas , ba merci à toi Mastokk de me le rappeler, j'irai voir . Mais je trouvais que celui là, faisait un peu plus rp. Mais , c'est vrai qu'il fait chauffer le processeur un peu plus.

Question à part :
Mais est ce que le onheartbeat d'un NPC est aussi lourd que le onhearbeat d'un module??

juste pour savoir
1) Je trouve que le nettoyage "en cours" est plus RP...

2) Je ne suis pas convaincu que le OnHeartBeat soit le plus approprié... (OnEnter c'est mieux, suffit juste de créer une boucle par renvoi de Script avec un délai plus raisonnable... genre 600 sec... faut du temps pour les Eboueurs!)

3) A mon avis le OnHeartBeat est lourd selon ce qu'il doit gérer... donc, ça dépend... (mais j'imagine que pour un Module y'a souvent plus d'éléments à traiter...)

4) Tapez pas !!

...
Exclamation
Vive les strings
Une bonne bibliothèque Tyn', néanmoins :

  • Je comprend pas vraiment comment marche ces tokens et surtout quel est leur but... Si tu pouvais expliquer, sinon il va falloir plonger dans le code plus profondément....
  • A quoi servent les fonctions StrUpperCase() et StrLowerCase(), Bioware les proposent déjà en standard...
  • Cette fonction StrReplace() est efficace mais vu son implémentation, il a oublié un "Sanity check" : sReplaceMe != sNewText... On risque de se retrouver avec une boucle infinie, toujours désagréable !

Je signale par ailleurs que ma propre bibliothèque de gestion des tokens est beaucoup plus complète et plus claire (du moins pour moi ) pour ce qui est des tokens en tous cas. elle est disponible sur NWN-Fr. (Je ne la mettrai pas ici, elle fait dans les 900 lignes )



Je suis moi aussi pour des nettoyeurs publiques un peu lent comme proposé par Coolstar, pour les villes surtout. Pour les autres zones peut-être vaut-il mieux nettoyer sur le OnExit .
Répondre

Connectés sur ce fil

 
1 connecté (0 membre et 1 invité) Afficher la liste détaillée des connectés