Compare commits
174 Commits
foundryvtt
...
foundryvtt
Author | SHA1 | Date | |
---|---|---|---|
7e75715d88 | |||
d62d1c45bc | |||
62914c343f | |||
9349e81580 | |||
404539a004 | |||
9eaeceafc4 | |||
1cd3bdef25 | |||
fa356bd7f8 | |||
771c8c9c8e | |||
ca860a0243 | |||
2e36221018 | |||
07e203513a | |||
31960ce940 | |||
19118911b9 | |||
652ae4cf51 | |||
cf340f73f1 | |||
3782ed9055 | |||
c3076fdbfc | |||
739fcbdf09 | |||
19b3adc222 | |||
388629d36e | |||
912b1d3df3 | |||
11e4ad09d3 | |||
8844f76b65 | |||
ec24126e75 | |||
b3c6845e68 | |||
cf8df182ba | |||
30cc8419c5 | |||
5ab6c5989e | |||
46df3d9f11 | |||
6a6759087c | |||
a7ce1db7c5 | |||
a0efefad3f | |||
8e0825b6b9 | |||
39d14c8496 | |||
89442ea6c6 | |||
a66fe122c4 | |||
2e0abaa284 | |||
5bddc548de | |||
4acd0879b0 | |||
060943ee53 | |||
80be0490eb | |||
ceacee8e6c | |||
d5453c9b04 | |||
7ca3306c6f | |||
aa5d175027 | |||
d4ddc4e940 | |||
87f12019ac | |||
128d7adf89 | |||
ee42bdcf83 | |||
5972db035d | |||
92388df5c7 | |||
274009d3fa | |||
d7e5a09540 | |||
7f5b2e0abf | |||
fbd3aa7121 | |||
2ca601b5f8 | |||
d77ecee9bd | |||
c2a3b5e246 | |||
09bf28eed1 | |||
33c20dd2b7 | |||
c933810b6b | |||
df92a65f5d | |||
dbcab12f24 | |||
454193490d | |||
c79298b60a | |||
26808d7b49 | |||
2062ff0777 | |||
6adeb790a0 | |||
2546b89b44 | |||
84f4a152a8 | |||
d6f8698189 | |||
4f80c719c2 | |||
7d8b5c9549 | |||
ec58317b35 | |||
7c70e944b1 | |||
f397c82c6d | |||
81e3ceb4dc | |||
7bec249e8d | |||
70b30b545b | |||
ed2eebf99d | |||
4ba2c384d7 | |||
7f27399f3c | |||
61389e117b | |||
46cc245abf | |||
a372531849 | |||
8a8323ac8d | |||
8e6d4fbb89 | |||
886307f24c | |||
f40dbd5d7b | |||
66da7d5eb4 | |||
b2d8c2439a | |||
ceb4095c31 | |||
2af37cf98f | |||
fd156960a7 | |||
80a904e533 | |||
c9dc847440 | |||
4e382d405e | |||
6a12dc97f6 | |||
e0b6957bc6 | |||
944120b524 | |||
bb6bf3387e | |||
467a4d53a4 | |||
d5635b27fe | |||
3a33f7c4fc | |||
d2e77dc61c | |||
320bc471e3 | |||
090241f0f5 | |||
ddc37c6969 | |||
6af6e41bc9 | |||
0f7f609a2a | |||
a58f701ca6 | |||
757b46080a | |||
df44cd66c7 | |||
1040ec1be2 | |||
92643d1c46 | |||
31c4aa32d9 | |||
f5431b58fb | |||
bd32e1039a | |||
6b8f0ed51e | |||
10681b3f61 | |||
bbde3b73fe | |||
57d52c1966 | |||
e3a29cdab5 | |||
10e4f14eb2 | |||
04273dfcf1 | |||
8c5c01114e | |||
19e6124330 | |||
1c908b50cb | |||
969cedfc3d | |||
830e66749d | |||
df26e654ae | |||
153bfe2e75 | |||
f6d42875ae | |||
450cb8e899 | |||
0202938910 | |||
512a056e59 | |||
214377c66d | |||
752e534350 | |||
c85a544cc9 | |||
3a90c693d9 | |||
c04b179176 | |||
63770790b9 | |||
aefc7a434b | |||
f02959adee | |||
e652027b02 | |||
2122a54db7 | |||
f027e3318b | |||
31b4d1cfcc | |||
5056c35038 | |||
7b58407634 | |||
7efa7be1c0 | |||
717bb6fc6e | |||
51273bcc3e | |||
b8f3a9af27 | |||
ab704c46d2 | |||
db8fd6dbf8 | |||
d998a4cb08 | |||
b1e27a9597 | |||
eaac9564b4 | |||
0826c7e9e3 | |||
bdd3802e72 | |||
b07cea40e2 | |||
bb7f4c42ad | |||
ac15a022df | |||
a43c725b06 | |||
1276c64835 | |||
4b4d778d9c | |||
86f9c37b30 | |||
ac77c6da9e | |||
344540ea8e | |||
8a5cf3cb09 | |||
3a29570bae | |||
02c48f4796 |
4
.gitignore
vendored
@ -3,3 +3,7 @@
|
||||
todo.md
|
||||
/.vscode
|
||||
/ignored/
|
||||
/node_modules/
|
||||
/jsconfig.json
|
||||
/package.json
|
||||
/package-lock.json
|
||||
|
BIN
icons/faune/Escargot.webp
Normal file
After Width: | Height: | Size: 8.2 KiB |
BIN
icons/faune/andurak.webp
Normal file
After Width: | Height: | Size: 15 KiB |
BIN
icons/faune/barbon.webp
Normal file
After Width: | Height: | Size: 7.0 KiB |
BIN
icons/faune/brocart.webp
Normal file
After Width: | Height: | Size: 8.8 KiB |
BIN
icons/faune/cancre.webp
Normal file
After Width: | Height: | Size: 9.6 KiB |
BIN
icons/faune/cancrelas.webp
Normal file
After Width: | Height: | Size: 8.5 KiB |
BIN
icons/faune/cerf.webp
Normal file
After Width: | Height: | Size: 7.0 KiB |
BIN
icons/faune/chamois.webp
Normal file
After Width: | Height: | Size: 16 KiB |
BIN
icons/faune/chevre.webp
Normal file
After Width: | Height: | Size: 6.6 KiB |
BIN
icons/faune/colimace.webp
Normal file
After Width: | Height: | Size: 5.7 KiB |
BIN
icons/faune/coquillage-pointe.webp
Normal file
After Width: | Height: | Size: 5.8 KiB |
BIN
icons/faune/coquille.webp
Normal file
After Width: | Height: | Size: 7.3 KiB |
BIN
icons/faune/crabe.webp
Normal file
After Width: | Height: | Size: 7.1 KiB |
BIN
icons/faune/fretin.webp
Normal file
After Width: | Height: | Size: 11 KiB |
BIN
icons/faune/lapin.webp
Normal file
After Width: | Height: | Size: 8.1 KiB |
BIN
icons/faune/oie.webp
Normal file
After Width: | Height: | Size: 5.2 KiB |
BIN
icons/faune/oiseau.webp
Normal file
After Width: | Height: | Size: 8.0 KiB |
BIN
icons/faune/ours.webp
Normal file
After Width: | Height: | Size: 16 KiB |
BIN
icons/faune/padongre.webp
Normal file
After Width: | Height: | Size: 15 KiB |
BIN
icons/faune/poisson.webp
Normal file
After Width: | Height: | Size: 6.3 KiB |
BIN
icons/faune/raton-laveur.webp
Normal file
After Width: | Height: | Size: 6.3 KiB |
BIN
icons/faune/rongeur.webp
Normal file
After Width: | Height: | Size: 7.8 KiB |
BIN
icons/faune/sanglier.webp
Normal file
After Width: | Height: | Size: 16 KiB |
BIN
icons/faune/saumon.webp
Normal file
After Width: | Height: | Size: 8.0 KiB |
BIN
icons/faune/singe-vert.webp
Normal file
After Width: | Height: | Size: 5.9 KiB |
BIN
icons/faune/soldieze.webp
Normal file
After Width: | Height: | Size: 8.8 KiB |
BIN
icons/faune/ver.webp
Normal file
After Width: | Height: | Size: 5.9 KiB |
BIN
icons/faune/wolf-head.webp
Normal file
After Width: | Height: | Size: 16 KiB |
BIN
icons/services/bacquet-eau.webp
Normal file
After Width: | Height: | Size: 8.1 KiB |
BIN
icons/services/biere.webp
Normal file
After Width: | Height: | Size: 6.2 KiB |
BIN
icons/services/brandevin.webp
Normal file
After Width: | Height: | Size: 6.0 KiB |
BIN
icons/services/commerce.webp
Normal file
After Width: | Height: | Size: 6.2 KiB |
BIN
icons/services/compagnie.webp
Normal file
After Width: | Height: | Size: 6.4 KiB |
BIN
icons/services/lit.webp
Normal file
After Width: | Height: | Size: 7.0 KiB |
BIN
icons/services/paiement.webp
Normal file
After Width: | Height: | Size: 5.1 KiB |
BIN
icons/services/repas.webp
Normal file
After Width: | Height: | Size: 5.9 KiB |
BIN
icons/services/verre.webp
Normal file
After Width: | Height: | Size: 5.1 KiB |
BIN
icons/services/vin.webp
Normal file
After Width: | Height: | Size: 5.5 KiB |
@ -3,6 +3,7 @@
|
||||
"TypePersonnage": "Personnage",
|
||||
"TypeCreature": "Créature",
|
||||
"TypeEntite": "Entité de cauchemar",
|
||||
"TypeCommerce": "Commerce",
|
||||
"TypeVehicule": "Véhicule"
|
||||
},
|
||||
"ITEM": {
|
||||
@ -20,12 +21,14 @@
|
||||
"TypeMonnaie": "Monnaie",
|
||||
"TypeHerbe": "Herbe ou plante",
|
||||
"TypeIngredient": "Ingrédient",
|
||||
"TypeFaune": "Faune",
|
||||
"TypeLivre": "Livre",
|
||||
"TypePotion": "Potion",
|
||||
"TypeArme": "Arme",
|
||||
"TypeArmure": "Armure",
|
||||
"TypeConteneur": "Conteneur",
|
||||
"TypeNourritureboisson": "Nourriture & boisson",
|
||||
"TypeService": "Service",
|
||||
"TypeChant": "Chant",
|
||||
"TypeDanse": "Danse",
|
||||
"TypeMusique": "Musique",
|
||||
|
@ -27,24 +27,17 @@ export class RdDActorCreatureSheet extends RdDActorSheet {
|
||||
if (!this.options.editable) return;
|
||||
|
||||
// On competence change
|
||||
html.find('.creature-carac').change(async event => {
|
||||
this.html.find('.creature-carac').change(async event => {
|
||||
let compName = event.currentTarget.attributes.compname.value;
|
||||
this.actor.updateCreatureCompetence(compName, "carac_value", parseInt(event.target.value));
|
||||
});
|
||||
html.find('.creature-niveau').change(async event => {
|
||||
this.html.find('.creature-niveau').change(async event => {
|
||||
let compName = event.currentTarget.attributes.compname.value;
|
||||
this.actor.updateCreatureCompetence(compName, "niveau", parseInt(event.target.value));
|
||||
});
|
||||
html.find('.creature-dommages').change(async event => {
|
||||
this.html.find('.creature-dommages').change(async event => {
|
||||
let compName = event.currentTarget.attributes.compname.value;
|
||||
this.actor.updateCreatureCompetence(compName, "dommages", parseInt(event.target.value));
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
/** @override */
|
||||
_updateObject(event, formData) {
|
||||
// Update the Actor
|
||||
return this.object.update(formData);
|
||||
}
|
||||
}
|
||||
|
@ -3,38 +3,38 @@ import { RdDActorSheet } from "./actor-sheet.js";
|
||||
export class RdDActorEntiteSheet extends RdDActorSheet {
|
||||
|
||||
/** @override */
|
||||
static get defaultOptions() {
|
||||
return mergeObject(super.defaultOptions, {
|
||||
classes: ["rdd", "sheet", "actor"],
|
||||
template: "systems/foundryvtt-reve-de-dragon/templates/actor-entite-sheet.html",
|
||||
static get defaultOptions() {
|
||||
return mergeObject(super.defaultOptions, {
|
||||
classes: ["rdd", "sheet", "actor"],
|
||||
template: "systems/foundryvtt-reve-de-dragon/templates/actor-entite-sheet.html",
|
||||
width: 640,
|
||||
height: 720,
|
||||
tabs: [{navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "carac"}],
|
||||
dragDrop: [{dragSelector: ".item-list .item", dropSelector: undefined}]
|
||||
tabs: [{ navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "carac" }],
|
||||
dragDrop: [{ dragSelector: ".item-list .item", dropSelector: undefined }]
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
/** @override */
|
||||
activateListeners(html) {
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
|
||||
// Everything below here is only needed if the sheet is editable
|
||||
if (!this.options.editable) return;
|
||||
|
||||
// On competence change
|
||||
html.find('.creature-carac').change(async event => {
|
||||
let compName = event.currentTarget.attributes.compname.value;
|
||||
this.actor.updateCreatureCompetence( compName, "carac_value", parseInt(event.target.value) );
|
||||
} );
|
||||
html.find('.creature-niveau').change(async event => {
|
||||
let compName = event.currentTarget.attributes.compname.value;
|
||||
this.actor.updateCreatureCompetence( compName, "niveau", parseInt(event.target.value) );
|
||||
} );
|
||||
html.find('.creature-dommages').change(async event => {
|
||||
let compName = event.currentTarget.attributes.compname.value;
|
||||
this.actor.updateCreatureCompetence( compName, "dommages", parseInt(event.target.value) );
|
||||
} );
|
||||
this.html.find('.creature-carac').change(async event => {
|
||||
let compName = event.currentTarget.attributes.compname.value;
|
||||
this.actor.updateCreatureCompetence(compName, "carac_value", parseInt(event.target.value));
|
||||
});
|
||||
this.html.find('.creature-niveau').change(async event => {
|
||||
let compName = event.currentTarget.attributes.compname.value;
|
||||
this.actor.updateCreatureCompetence(compName, "niveau", parseInt(event.target.value));
|
||||
});
|
||||
this.html.find('.creature-dommages').change(async event => {
|
||||
let compName = event.currentTarget.attributes.compname.value;
|
||||
this.actor.updateCreatureCompetence(compName, "dommages", parseInt(event.target.value));
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -8,16 +8,18 @@ import { RdDCombatManager } from "./rdd-combat.js";
|
||||
import { RdDCarac } from "./rdd-carac.js";
|
||||
import { DialogSplitItem } from "./dialog-split-item.js";
|
||||
import { ReglesOptionelles } from "./settings/regles-optionelles.js";
|
||||
import { DialogRepos } from "./dialog-repos.js";
|
||||
import { RdDSheetUtility } from "./rdd-sheet-utility.js";
|
||||
import { STATUSES } from "./settings/status-effects.js";
|
||||
import { MAINS_DIRECTRICES } from "./actor.js";
|
||||
import { RdDBaseActorSheet } from "./actor/base-actor-sheet.js";
|
||||
import { RdDItem } from "./item.js";
|
||||
|
||||
/* -------------------------------------------- */
|
||||
/**
|
||||
* Extend the basic ActorSheet with some very simple modifications
|
||||
* @extends {ActorSheet}
|
||||
*/
|
||||
export class RdDActorSheet extends ActorSheet {
|
||||
export class RdDActorSheet extends RdDBaseActorSheet {
|
||||
|
||||
/** @override */
|
||||
static get defaultOptions() {
|
||||
@ -35,51 +37,38 @@ export class RdDActorSheet extends ActorSheet {
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async getData() {
|
||||
let formData = await super.getData();
|
||||
mergeObject(formData,
|
||||
{
|
||||
editable: this.isEditable,
|
||||
cssClass: this.isEditable ? "editable" : "locked",
|
||||
effects: this.actor.effects.map(e => foundry.utils.deepClone(e)),
|
||||
limited: this.actor.limited,
|
||||
owner: this.actor.isOwner,
|
||||
biographie: await TextEditor.enrichHTML(this.actor.system.biographie, { async: true }),
|
||||
notes: await TextEditor.enrichHTML(this.actor.system.notes, { async: true }),
|
||||
});
|
||||
mergeObject(formData.calc, {
|
||||
surenc: this.actor.computeMalusSurEncombrement(),
|
||||
surprise: RdDBonus.find(this.actor.getSurprise(false)).descr,
|
||||
resumeBlessures: this.actor.computeResumeBlessure(this.actor.system.blessures),
|
||||
caracTotal: RdDCarac.computeTotal(this.actor.system.carac, this.actor.system.beaute),
|
||||
surEncombrementMessage: this.actor.getMessageSurEncombrement(),
|
||||
})
|
||||
|
||||
this.timerRecherche = undefined;
|
||||
this.actor.computeEtatGeneral();
|
||||
|
||||
let formData = {
|
||||
title: this.title,
|
||||
id: this.actor.id,
|
||||
type: this.actor.type,
|
||||
img: this.actor.img,
|
||||
name: this.actor.name,
|
||||
editable: this.isEditable,
|
||||
cssClass: this.isEditable ? "editable" : "locked",
|
||||
system: foundry.utils.deepClone(this.actor.system),
|
||||
effects: this.actor.effects.map(e => foundry.utils.deepClone(e)),
|
||||
limited: this.actor.limited,
|
||||
options: this.options,
|
||||
owner: this.actor.isOwner,
|
||||
description: await TextEditor.enrichHTML(this.object.system.description, {async: true}),
|
||||
biographie: await TextEditor.enrichHTML(this.object.system.biographie, {async: true}),
|
||||
notes: await TextEditor.enrichHTML(this.object.system.notes, {async: true}),
|
||||
notesmj: await TextEditor.enrichHTML(this.object.system.notesmj, {async: true}),
|
||||
calc: {
|
||||
encTotal: await this.actor.computeEncombrementTotalEtMalusArmure(),
|
||||
prixTotalEquipement: this.actor.computePrixTotalEquipement(),
|
||||
surprise: RdDBonus.find(this.actor.getSurprise(false)).descr,
|
||||
resumeBlessures: this.actor.computeResumeBlessure(this.actor.system.blessures),
|
||||
caracTotal: RdDCarac.computeTotal(this.actor.system.carac, this.actor.system.beaute),
|
||||
surEncombrementMessage: this.actor.getMessageSurEncombrement(),
|
||||
},
|
||||
}
|
||||
formData.options.isGM = game.user.isGM;
|
||||
|
||||
RdDUtility.filterItemsPerTypeForSheet(formData, this.actor.itemTypes);
|
||||
this.objetVersConteneur = RdDUtility.buildArbreDeConteneurs(formData.conteneurs, formData.objets);
|
||||
formData.conteneurs = RdDUtility.conteneursRacine(formData.conteneurs);
|
||||
|
||||
if (formData.type == 'personnage') {
|
||||
formData.options.mainsDirectrices = MAINS_DIRECTRICES;
|
||||
formData.byCateg = Misc.classify(formData.competences, it => it.system.categorie)
|
||||
formData.calc.comptageArchetype = RdDItemCompetence.computeResumeArchetype(formData.competences);
|
||||
formData.calc.competenceXPTotal= RdDItemCompetence.computeTotalXP(formData.competences);
|
||||
formData.calc.fatigue= RdDUtility.calculFatigueHtml(formData.system.sante.fatigue.value, formData.system.sante.endurance.max);
|
||||
formData.calc.comptageArchetype = RdDItemCompetence.computeResumeArchetype(formData.competences);
|
||||
formData.calc.competenceXPTotal = RdDItemCompetence.computeTotalXP(formData.competences);
|
||||
formData.calc.fatigue = RdDUtility.calculFatigueHtml(formData.system.sante.fatigue.value, formData.system.sante.endurance.max);
|
||||
|
||||
formData.competences.forEach(item => {
|
||||
item.system.isVisible = this.options.recherche
|
||||
? RdDItemCompetence.nomContientTexte(item, this.options.recherche.text)
|
||||
: (!this.options.showCompNiveauBase || !RdDItemCompetence.isNiveauBase(item));
|
||||
? RdDItemCompetence.nomContientTexte(item, this.options.recherche.text)
|
||||
: (!this.options.showCompNiveauBase || !RdDItemCompetence.isNiveauBase(item));
|
||||
RdDItemCompetence.levelUp(item, formData.system.compteurs.experience.value);
|
||||
});
|
||||
|
||||
@ -118,76 +107,18 @@ export class RdDActorSheet extends ActorSheet {
|
||||
return formData;
|
||||
}
|
||||
|
||||
isCompetenceAffichable(competence) {
|
||||
return !this.options.showCompNiveauBase || !RdDItemCompetence.isNiveauBase(competence);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async _onDropActor(event, dragData) {
|
||||
const dropActor = fromUuidSync(dragData.uuid);
|
||||
this.actor.addSubActeur(dropActor);
|
||||
super._onDropActor(event, dragData);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async _onDropItem(event, dragData) {
|
||||
const destItemId = $(event.target)?.closest('.item').attr('data-item-id')
|
||||
const dropParams = RdDSheetUtility.prepareItemDropParameters(destItemId, this.actor.id, dragData, this.objetVersConteneur)
|
||||
const callSuper = await this.actor.processDropItem(dropParams)
|
||||
if (callSuper) {
|
||||
await super._onDropItem(event, dragData)
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async createItem(name, type) {
|
||||
await this.actor.createEmbeddedDocuments('Item', [{ name: name, type: type }], { renderSheet: true });
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async createEmptyTache() {
|
||||
await this.createItem('Nouvelle tache', 'tache');
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */ /** @override */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
|
||||
HtmlUtility._showControlWhen($(".appliquerFatigue"), ReglesOptionelles.isUsing("appliquer-fatigue"));
|
||||
HtmlUtility._showControlWhen(this.html.find(".appliquerFatigue"), ReglesOptionelles.isUsing("appliquer-fatigue"));
|
||||
|
||||
// Everything below here is only needed if the sheet is editable
|
||||
if (!this.options.editable) return;
|
||||
|
||||
html.find('.item-split').click(async event => {
|
||||
const item = RdDSheetUtility.getItem(event, this.actor);
|
||||
RdDSheetUtility.splitItem(item, this.actor);
|
||||
});
|
||||
html.find('.item-edit').click(async event => {
|
||||
const item = RdDSheetUtility.getItem(event, this.actor)
|
||||
item.sheet.render(true)
|
||||
})
|
||||
html.find('.display-label a').click(async event => {
|
||||
const item = RdDSheetUtility.getItem(event, this.actor);
|
||||
item.sheet.render(true);
|
||||
});
|
||||
html.find('.item-delete').click(async event => {
|
||||
const li = RdDSheetUtility.getEventElement(event);
|
||||
const item = this.actor.getObjet(li.data("item-id"));
|
||||
RdDUtility.confirmerSuppressionItem(this, item, li);
|
||||
});
|
||||
html.find('.item-vendre').click(async event => {
|
||||
const item = RdDSheetUtility.getItem(event, this.actor);
|
||||
item?.proposerVente();
|
||||
});
|
||||
html.find('.item-montrer').click(async event => {
|
||||
const item = RdDSheetUtility.getItem(event, this.actor);
|
||||
item?.postItem();
|
||||
});
|
||||
html.find('.item-action').click(async event => {
|
||||
const item = RdDSheetUtility.getItem(event, this.actor)
|
||||
this.actor.actionItem(item);
|
||||
});
|
||||
html.find('.subacteur-delete').click(async event => {
|
||||
this.html.find('.item-action').click(async event => RdDSheetUtility.getItem(event, this.actor)?.actionPrincipale(this.actor));
|
||||
|
||||
this.html.find('.subacteur-delete').click(async event => {
|
||||
const li = RdDSheetUtility.getEventElement(event);
|
||||
const actorId = li.data("actor-id");
|
||||
if (actorId) {
|
||||
@ -195,54 +126,48 @@ export class RdDActorSheet extends ActorSheet {
|
||||
RdDUtility.confirmerSuppressionSubacteur(this, subActor, li);
|
||||
}
|
||||
});
|
||||
html.find('.experiencelog-delete').click(async event => {
|
||||
const li = $(event.currentTarget)?.parents(".experiencelog");
|
||||
this.html.find('.experiencelog-delete').click(async event => {
|
||||
const li = this.html.find(event.currentTarget)?.parents(".experiencelog");
|
||||
const key = Number(li.data("key") ?? -1);
|
||||
await this.actor.deleteExperienceLog(key, 1);
|
||||
});
|
||||
html.find('.experiencelog-delete-previous').click(async event => {
|
||||
const li = $(event.currentTarget)?.parents(".experiencelog");
|
||||
this.html.find('.experiencelog-delete-previous').click(async event => {
|
||||
const li = this.html.find(event.currentTarget)?.parents(".experiencelog");
|
||||
const key = Number(li.data("key") ?? -1);
|
||||
await this.actor.deleteExperienceLog(0, key + 1);
|
||||
});
|
||||
html.find('.encaisser-direct').click(async event => {
|
||||
this.html.find('.encaisser-direct').click(async event => {
|
||||
this.actor.encaisser();
|
||||
})
|
||||
html.find('.sheet-possession-attack').click(async event => {
|
||||
this.html.find('.sheet-possession-attack').click(async event => {
|
||||
const poss = RdDSheetUtility.getItem(event, this.actor)
|
||||
this.actor.conjurerPossession(poss)
|
||||
})
|
||||
html.find('.remise-a-neuf').click(async event => {
|
||||
this.html.find('.remise-a-neuf').click(async event => {
|
||||
if (game.user.isGM) {
|
||||
this.actor.remiseANeuf();
|
||||
}
|
||||
});
|
||||
html.find('.creer-tache').click(async event => {
|
||||
this.html.find('.creer-tache').click(async event => {
|
||||
this.createEmptyTache();
|
||||
});
|
||||
html.find('.creer-un-objet').click(async event => {
|
||||
RdDUtility.selectObjetType(this);
|
||||
});
|
||||
html.find('.creer-une-oeuvre').click(async event => {
|
||||
RdDUtility.selectTypeOeuvre(this);
|
||||
});
|
||||
html.find('.nettoyer-conteneurs').click(async event => {
|
||||
this.actor.nettoyerConteneurs();
|
||||
this.html.find('.creer-une-oeuvre').click(async event => {
|
||||
this.selectTypeOeuvreToCreate();
|
||||
});
|
||||
|
||||
// Blessure control
|
||||
html.find('.blessure-control').click(async event => {
|
||||
const tr = $(event.currentTarget).parents(".item");
|
||||
this.html.find('.blessure-control').click(async event => {
|
||||
const tr = this.html.find(event.currentTarget).parents(".item");
|
||||
let btype = tr.data("blessure-type");
|
||||
let index = tr.data('blessure-index');
|
||||
let active = $(event.currentTarget).data('blessure-active');
|
||||
let active = this.html.find(event.currentTarget).data('blessure-active');
|
||||
//console.log(btype, index, active);
|
||||
await this.actor.manageBlessureFromSheet(btype, index, active);
|
||||
});
|
||||
|
||||
// Blessure data
|
||||
html.find('.blessure-soins').change(async event => {
|
||||
const tr = $(event.currentTarget).parents(".item");
|
||||
this.html.find('.blessure-soins').change(async event => {
|
||||
const tr = this.html.find(event.currentTarget).parents(".item");
|
||||
let btype = tr.data('blessure-type');
|
||||
let index = tr.data('blessure-index');
|
||||
let psoins = tr.find('.blessure-premiers_soins').val();
|
||||
@ -256,57 +181,57 @@ export class RdDActorSheet extends ActorSheet {
|
||||
});
|
||||
|
||||
// Equip Inventory Item
|
||||
html.find('.item-equip').click(async event => {
|
||||
this.html.find('.item-equip').click(async event => {
|
||||
this.actor.equiperObjet(RdDSheetUtility.getItemId(event));
|
||||
});
|
||||
|
||||
// Roll Carac
|
||||
html.find('.carac-label a').click(async event => {
|
||||
this.html.find('.carac-label a').click(async event => {
|
||||
let caracName = event.currentTarget.attributes.name.value;
|
||||
this.actor.rollCarac(caracName.toLowerCase());
|
||||
});
|
||||
|
||||
html.find('.chance-actuelle').click(async event => {
|
||||
this.html.find('.chance-actuelle').click(async event => {
|
||||
this.actor.rollCarac('chance-actuelle');
|
||||
});
|
||||
|
||||
html.find('.chance-appel').click(async event => {
|
||||
this.html.find('.chance-appel').click(async event => {
|
||||
this.actor.rollAppelChance();
|
||||
});
|
||||
|
||||
html.find('#jet-astrologie').click(async event => {
|
||||
this.html.find('[name="jet-astrologie"]').click(async event => {
|
||||
this.actor.astrologieNombresAstraux();
|
||||
});
|
||||
|
||||
// Roll Skill
|
||||
html.find('a.competence-label').click(async event => {
|
||||
this.html.find('a.competence-label').click(async event => {
|
||||
this.actor.rollCompetence(RdDSheetUtility.getItemId(event));
|
||||
});
|
||||
html.find('.tache-label a').click(async event => {
|
||||
this.html.find('.tache-label a').click(async event => {
|
||||
this.actor.rollTache(RdDSheetUtility.getItemId(event));
|
||||
});
|
||||
html.find('.meditation-label a').click(async event => {
|
||||
this.html.find('.meditation-label a').click(async event => {
|
||||
this.actor.rollMeditation(RdDSheetUtility.getItemId(event));
|
||||
});
|
||||
html.find('.chant-label a').click(async event => {
|
||||
this.html.find('.chant-label a').click(async event => {
|
||||
this.actor.rollChant(RdDSheetUtility.getItemId(event));
|
||||
});
|
||||
html.find('.danse-label a').click(async event => {
|
||||
this.html.find('.danse-label a').click(async event => {
|
||||
this.actor.rollDanse(RdDSheetUtility.getItemId(event));
|
||||
});
|
||||
html.find('.musique-label a').click(async event => {
|
||||
this.html.find('.musique-label a').click(async event => {
|
||||
this.actor.rollMusique(RdDSheetUtility.getItemId(event));
|
||||
});
|
||||
html.find('.oeuvre-label a').click(async event => {
|
||||
this.html.find('.oeuvre-label a').click(async event => {
|
||||
this.actor.rollOeuvre(RdDSheetUtility.getItemId(event));
|
||||
});
|
||||
html.find('.jeu-label a').click(async event => {
|
||||
this.html.find('.jeu-label a').click(async event => {
|
||||
this.actor.rollJeu(RdDSheetUtility.getItemId(event));
|
||||
});
|
||||
html.find('.recettecuisine-label a').click(async event => {
|
||||
this.html.find('.recettecuisine-label a').click(async event => {
|
||||
this.actor.rollRecetteCuisine(RdDSheetUtility.getItemId(event));
|
||||
});
|
||||
html.find('.subacteur-label a').click(async event => {
|
||||
this.html.find('.subacteur-label a').click(async event => {
|
||||
let actorId = RdDSheetUtility.getEventItemData(event, 'actor-id');
|
||||
let actor = game.actors.get(actorId);
|
||||
if (actor) {
|
||||
@ -315,25 +240,25 @@ export class RdDActorSheet extends ActorSheet {
|
||||
});
|
||||
|
||||
// Boutons spéciaux MJs
|
||||
html.find('.forcer-tmr-aleatoire').click(async event => {
|
||||
this.html.find('.forcer-tmr-aleatoire').click(async event => {
|
||||
this.actor.reinsertionAleatoire("Action MJ");
|
||||
});
|
||||
html.find('.afficher-tmr').click(async event => {
|
||||
this.html.find('.afficher-tmr').click(async event => {
|
||||
this.actor.changeTMRVisible();
|
||||
});
|
||||
|
||||
// Points de reve actuel
|
||||
html.find('.ptreve-actuel a').click(async event => {
|
||||
this.html.find('.ptreve-actuel a').click(async event => {
|
||||
this.actor.rollCarac('reve-actuel');
|
||||
});
|
||||
|
||||
// Roll Weapon1
|
||||
html.find('.arme-label a').click(async event => {
|
||||
this.html.find('.arme-label a').click(async event => {
|
||||
let arme = this._getEventArmeCombat(event);
|
||||
this.actor.rollArme(duplicate(arme));
|
||||
});
|
||||
// Initiative pour l'arme
|
||||
html.find('.arme-initiative a').click(async event => {
|
||||
this.html.find('.arme-initiative a').click(async event => {
|
||||
let combatant = game.combat.combatants.find(c => c.actor.id == this.actor.id);
|
||||
if (combatant) {
|
||||
let action = this._getEventArmeCombat(event);
|
||||
@ -343,88 +268,84 @@ export class RdDActorSheet extends ActorSheet {
|
||||
}
|
||||
});
|
||||
// Display TMR, visualisation
|
||||
html.find('.visu-tmr').click(async event => {
|
||||
this.html.find('.visu-tmr').click(async event => {
|
||||
this.actor.displayTMR("visu");
|
||||
});
|
||||
|
||||
// Display TMR, normal
|
||||
html.find('.monte-tmr').click(async event => {
|
||||
this.html.find('.monte-tmr').click(async event => {
|
||||
this.actor.displayTMR("normal");
|
||||
});
|
||||
|
||||
// Display TMR, fast
|
||||
html.find('.monte-tmr-rapide').click(async event => {
|
||||
this.html.find('.monte-tmr-rapide').click(async event => {
|
||||
this.actor.displayTMR("rapide");
|
||||
});
|
||||
|
||||
html.find('.repos').click(async event => {
|
||||
await DialogRepos.create(this.actor);
|
||||
this.html.find('.repos').click(async event => {
|
||||
await this.actor.repos();
|
||||
});
|
||||
html.find('.delete-active-effect').click(async event => {
|
||||
this.html.find('.delete-active-effect').click(async event => {
|
||||
if (game.user.isGM) {
|
||||
let effect = $(event.currentTarget).parents(".active-effect").data('effect');
|
||||
let effect = this.html.find(event.currentTarget).parents(".active-effect").data('effect');
|
||||
this.actor.removeEffect(effect);
|
||||
}
|
||||
});
|
||||
html.find('.enlever-tous-effets').click(async event => {
|
||||
this.html.find('.enlever-tous-effets').click(async event => {
|
||||
if (game.user.isGM) {
|
||||
await this.actor.removeEffects();
|
||||
}
|
||||
});
|
||||
html.find('.conteneur-name a').click(async event => {
|
||||
RdDUtility.toggleAfficheContenu(RdDSheetUtility.getItemId(event));
|
||||
this.render(true);
|
||||
});
|
||||
html.find('.carac-xp-augmenter').click(async event => {
|
||||
this.html.find('.carac-xp-augmenter').click(async event => {
|
||||
let caracName = event.currentTarget.name.replace("augmenter.", "");
|
||||
this.actor.updateCaracXPAuto(caracName);
|
||||
});
|
||||
html.find('.competence-xp-augmenter').click(async event => {
|
||||
this.html.find('.competence-xp-augmenter').click(async event => {
|
||||
this.actor.updateCompetenceXPAuto(RdDSheetUtility.getItemId(event));
|
||||
});
|
||||
html.find('.competence-stress-augmenter').click(async event => {
|
||||
this.html.find('.competence-stress-augmenter').click(async event => {
|
||||
this.actor.updateCompetenceStress(RdDSheetUtility.getItemId(event));
|
||||
});
|
||||
|
||||
if (this.options.vueDetaillee) {
|
||||
// On carac change
|
||||
html.find('.carac-value').change(async event => {
|
||||
this.html.find('.carac-value').change(async event => {
|
||||
let caracName = event.currentTarget.name.replace(".value", "").replace("system.carac.", "");
|
||||
this.actor.updateCarac(caracName, parseInt(event.target.value));
|
||||
});
|
||||
html.find('input.carac-xp').change(async event => {
|
||||
this.html.find('input.carac-xp').change(async event => {
|
||||
let caracName = event.currentTarget.name.replace(".xp", "").replace("system.carac.", "");
|
||||
this.actor.updateCaracXP(caracName, parseInt(event.target.value));
|
||||
});
|
||||
// On competence change
|
||||
html.find('.competence-value').change(async event => {
|
||||
this.html.find('.competence-value').change(async event => {
|
||||
let compName = event.currentTarget.attributes.compname.value;
|
||||
//console.log("Competence changed :", compName);
|
||||
this.actor.updateCompetence(compName, parseInt(event.target.value));
|
||||
});
|
||||
// On competence xp change
|
||||
html.find('input.competence-xp').change(async event => {
|
||||
this.html.find('input.competence-xp').change(async event => {
|
||||
let compName = event.currentTarget.attributes.compname.value;
|
||||
this.actor.updateCompetenceXP(compName, parseInt(event.target.value));
|
||||
});
|
||||
// On competence xp change
|
||||
html.find('input.competence-xp-sort').change(async event => {
|
||||
this.html.find('input.competence-xp-sort').change(async event => {
|
||||
let compName = event.currentTarget.attributes.compname.value;
|
||||
this.actor.updateCompetenceXPSort(compName, parseInt(event.target.value));
|
||||
});
|
||||
// On competence archetype change
|
||||
html.find('.competence-archetype').change(async event => {
|
||||
this.html.find('.competence-archetype').change(async event => {
|
||||
let compName = event.currentTarget.attributes.compname.value;
|
||||
this.actor.updateCompetenceArchetype(compName, parseInt(event.target.value));
|
||||
});
|
||||
}
|
||||
|
||||
html.find('.show-hide-competences').click(async event => {
|
||||
this.html.find('.show-hide-competences').click(async event => {
|
||||
this.options.showCompNiveauBase = !this.options.showCompNiveauBase;
|
||||
this.render(true);
|
||||
});
|
||||
|
||||
html.find('.recherche')
|
||||
this.html.find('.recherche')
|
||||
.each((index, field) => {
|
||||
if (this.options.recherche) {
|
||||
field.focus();
|
||||
@ -433,7 +354,7 @@ export class RdDActorSheet extends ActorSheet {
|
||||
})
|
||||
.keyup(async event => {
|
||||
const nouvelleRecherche = this._optionRecherche(event.currentTarget);
|
||||
if (this.options.recherche?.text != nouvelleRecherche?.text){
|
||||
if (this.options.recherche?.text != nouvelleRecherche?.text) {
|
||||
this.options.recherche = nouvelleRecherche;
|
||||
if (this.timerRecherche) {
|
||||
clearTimeout(this.timerRecherche);
|
||||
@ -447,94 +368,118 @@ export class RdDActorSheet extends ActorSheet {
|
||||
.change(async event =>
|
||||
this.options.recherche = this._optionRecherche(event.currentTarget)
|
||||
);
|
||||
html.find('.vue-detaillee').click(async event => {
|
||||
this.html.find('.vue-detaillee').click(async event => {
|
||||
this.options.vueDetaillee = !this.options.vueDetaillee;
|
||||
this.render(true);
|
||||
});
|
||||
|
||||
// On pts de reve change
|
||||
html.find('.pointsreve-value').change(async event => {
|
||||
this.html.find('.pointsreve-value').change(async event => {
|
||||
let reveValue = event.currentTarget.value;
|
||||
this.actor.update({ "system.reve.reve.value": reveValue });
|
||||
});
|
||||
|
||||
// On seuil de reve change
|
||||
html.find('.seuil-reve-value').change(async event => {
|
||||
this.html.find('.seuil-reve-value').change(async event => {
|
||||
console.log("seuil-reve-value", event.currentTarget)
|
||||
this.actor.setPointsDeSeuil(event.currentTarget.value);
|
||||
});
|
||||
|
||||
html.find('#attribut-protection-edit').change(async event => {
|
||||
this.actor.updateAttributeValue(event.currentTarget.attributes.name.value, parseInt(event.target.value));
|
||||
});
|
||||
|
||||
// On stress change
|
||||
html.find('.compteur-edit').change(async event => {
|
||||
this.html.find('.compteur-edit').change(async event => {
|
||||
let fieldName = event.currentTarget.attributes.name.value;
|
||||
this.actor.updateCompteurValue(fieldName, parseInt(event.target.value));
|
||||
});
|
||||
|
||||
html.find('#ethylisme').change(async event => {
|
||||
this.actor.setEthylisme(parseInt(event.target.value));
|
||||
});
|
||||
html.find('.stress-test').click(async event => {
|
||||
this.html.find('.stress-test').click(async event => {
|
||||
this.actor.transformerStress();
|
||||
});
|
||||
html.find('.moral-malheureux').click(async event => {
|
||||
this.html.find('.moral-malheureux').click(async event => {
|
||||
this.actor.jetDeMoral('malheureuse');
|
||||
});
|
||||
html.find('.moral-neutre').click(async event => {
|
||||
this.html.find('.moral-neutre').click(async event => {
|
||||
this.actor.jetDeMoral('neutre');
|
||||
});
|
||||
html.find('.moral-heureux').click(async event => {
|
||||
this.html.find('.moral-heureux').click(async event => {
|
||||
this.actor.jetDeMoral('heureuse');
|
||||
});
|
||||
html.find('.ethylisme-test').click(async event => {
|
||||
this.html.find('.ethylisme-test').click(async event => {
|
||||
this.actor.jetEthylisme();
|
||||
});
|
||||
|
||||
html.find('.jet-vie').click(async event => {
|
||||
this.html.find('.jet-vie').click(async event => {
|
||||
this.actor.jetVie();
|
||||
});
|
||||
html.find('.jet-endurance').click(async event => {
|
||||
this.html.find('.jet-endurance').click(async event => {
|
||||
this.actor.jetEndurance();
|
||||
});
|
||||
|
||||
html.find('.monnaie-plus').click(async event => {
|
||||
this.actor.monnaieIncDec(RdDSheetUtility.getItemId(event), 1);
|
||||
});
|
||||
html.find('.monnaie-moins').click(async event => {
|
||||
this.actor.monnaieIncDec(RdDSheetUtility.getItemId(event), -1);
|
||||
});
|
||||
|
||||
html.find('.vie-plus').click(async event => {
|
||||
this.html.find('.vie-plus').click(async event => {
|
||||
this.actor.santeIncDec("vie", 1);
|
||||
});
|
||||
html.find('.vie-moins').click(async event => {
|
||||
this.html.find('.vie-moins').click(async event => {
|
||||
this.actor.santeIncDec("vie", -1);
|
||||
});
|
||||
html.find('.endurance-plus').click(async event => {
|
||||
this.html.find('.endurance-plus').click(async event => {
|
||||
this.actor.santeIncDec("endurance", 1);
|
||||
});
|
||||
html.find('.endurance-moins').click(async event => {
|
||||
this.html.find('.endurance-moins').click(async event => {
|
||||
this.actor.santeIncDec("endurance", -1);
|
||||
});
|
||||
html.find('.ptreve-actuel-plus').click(async event => {
|
||||
this.html.find('.ptreve-actuel-plus').click(async event => {
|
||||
this.actor.reveActuelIncDec(1);
|
||||
});
|
||||
html.find('.ptreve-actuel-moins').click(async event => {
|
||||
this.html.find('.ptreve-actuel-moins').click(async event => {
|
||||
this.actor.reveActuelIncDec(-1);
|
||||
});
|
||||
html.find('.fatigue-plus').click(async event => {
|
||||
this.html.find('.fatigue-plus').click(async event => {
|
||||
this.actor.santeIncDec("fatigue", 1);
|
||||
});
|
||||
html.find('.fatigue-moins').click(async event => {
|
||||
this.html.find('.fatigue-moins').click(async event => {
|
||||
this.actor.santeIncDec("fatigue", -1);
|
||||
});
|
||||
}
|
||||
|
||||
isCompetenceAffichable(competence) {
|
||||
return !this.options.showCompNiveauBase || !RdDItemCompetence.isNiveauBase(competence);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async _onDropActor(event, dragData) {
|
||||
const dropActor = fromUuidSync(dragData.uuid);
|
||||
this.actor.addSubActeur(dropActor);
|
||||
super._onDropActor(event, dragData);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async selectTypeOeuvreToCreate() {
|
||||
let typeObjets = RdDItem.getTypesOeuvres();
|
||||
let content = `<span class="competence-label">Selectionnez le type d'oeuvre</span><select class="item-type">`;
|
||||
for (let typeName of typeObjets) {
|
||||
content += `<option value="${typeName}">${Misc.typeName('Item', typeName)}</option>`
|
||||
}
|
||||
content += '</select>';
|
||||
let dialog = new Dialog({
|
||||
title: "Créer une oeuvre",
|
||||
content: content,
|
||||
buttons: {
|
||||
create: {
|
||||
icon: '<i class="fas fa-check"></i>',
|
||||
label: "Créer l'oeuvre",
|
||||
callback: () => this.actor.createItem($(".item-type").val())
|
||||
}
|
||||
}
|
||||
});
|
||||
dialog.render(true);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async createEmptyTache() {
|
||||
await this.actor.createItem('tache', 'Nouvelle tache');
|
||||
}
|
||||
|
||||
_optionRecherche(target) {
|
||||
if (!target.value?.length){
|
||||
if (!target.value?.length) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
@ -545,7 +490,7 @@ export class RdDActorSheet extends ActorSheet {
|
||||
}
|
||||
|
||||
_getEventArmeCombat(event) {
|
||||
const li = $(event.currentTarget)?.parents(".item");
|
||||
const li = this.html.find(event.currentTarget)?.parents(".item");
|
||||
let armeName = li.data("arme-name");
|
||||
let compName = li.data('competence-name');
|
||||
const arme = this.armesList.find(a => a.name == armeName && a.system.competence == compName);
|
||||
@ -563,8 +508,8 @@ export class RdDActorSheet extends ActorSheet {
|
||||
const sheetTabs = this.element.find(".sheet-tabs");
|
||||
const sheetBody = this.element.find(".sheet-body");
|
||||
let bodyHeight = position.height - sheetHeader[0].clientHeight;
|
||||
if (sheetTabs.length>0) {
|
||||
bodyHeight -= sheetTabs[0].clientHeight;
|
||||
if (sheetTabs.length > 0) {
|
||||
bodyHeight -= sheetTabs[0].clientHeight;
|
||||
}
|
||||
sheetBody.css("height", bodyHeight);
|
||||
return position;
|
||||
|
@ -22,16 +22,16 @@ export class RdDActorVehiculeSheet extends RdDActorSheet {
|
||||
super.activateListeners(html);
|
||||
if (!this.options.editable) return;
|
||||
|
||||
html.find('.resistance-moins').click(async event => {
|
||||
this.html.find('.resistance-moins').click(async event => {
|
||||
this.actor.vehicleIncDec("resistance", -1);
|
||||
});
|
||||
html.find('.resistance-plus').click(async event => {
|
||||
this.html.find('.resistance-plus').click(async event => {
|
||||
this.actor.vehicleIncDec("resistance", 1);
|
||||
});
|
||||
html.find('.structure-moins').click(async event => {
|
||||
this.html.find('.structure-moins').click(async event => {
|
||||
this.actor.vehicleIncDec("structure", -1);
|
||||
});
|
||||
html.find('.structure-plus').click(async event => {
|
||||
this.html.find('.structure-plus').click(async event => {
|
||||
this.actor.vehicleIncDec("structure", 1);
|
||||
});
|
||||
}
|
||||
|
1038
module/actor.js
260
module/actor/base-actor-sheet.js
Normal file
@ -0,0 +1,260 @@
|
||||
import { RdDUtility } from "../rdd-utility.js";
|
||||
import { Misc } from "../misc.js";
|
||||
import { DialogSplitItem } from "../dialog-split-item.js";
|
||||
import { RdDSheetUtility } from "../rdd-sheet-utility.js";
|
||||
import { Monnaie } from "../item-monnaie.js";
|
||||
import { RdDItem } from "../item.js";
|
||||
|
||||
/* -------------------------------------------- */
|
||||
/**
|
||||
* Extend the basic ActorSheet with some very simple modifications
|
||||
* @extends {ActorSheet}
|
||||
*/
|
||||
export class RdDBaseActorSheet extends ActorSheet {
|
||||
|
||||
/** @override */
|
||||
static get defaultOptions() {
|
||||
RdDUtility.initAfficheContenu();
|
||||
return mergeObject(super.defaultOptions, {
|
||||
classes: ["rdd", "sheet", "actor"],
|
||||
template: "systems/foundryvtt-reve-de-dragon/templates/actor-sheet.html",
|
||||
width: 550,
|
||||
tabs: [{ navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "carac" }],
|
||||
dragDrop: [{ dragSelector: ".item-list .item", dropSelector: undefined }],
|
||||
showCompNiveauBase: false,
|
||||
vueDetaillee: false
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async getData() {
|
||||
Monnaie.validerMonnaies(this.actor.itemTypes['monnaie']);
|
||||
|
||||
this.actor.recompute();
|
||||
const userRightLevel = game.user.isGM ? CONST.DOCUMENT_OWNERSHIP_LEVELS.OWNER : this.actor.getUserLevel(game.user)
|
||||
const options = duplicate(this.options);
|
||||
mergeObject(options, {
|
||||
isGM: game.user.isGM,
|
||||
editable: this.isEditable,
|
||||
cssClass: this.isEditable ? "editable" : "locked",
|
||||
isLimited: userRightLevel >= CONST.DOCUMENT_OWNERSHIP_LEVELS.LIMITED,
|
||||
isObserver: userRightLevel >= CONST.DOCUMENT_OWNERSHIP_LEVELS.OBSERVER,
|
||||
isOwner: userRightLevel >= CONST.DOCUMENT_OWNERSHIP_LEVELS.OWNER,
|
||||
owner: this.actor.isOwner,
|
||||
});
|
||||
|
||||
let formData = {
|
||||
title: this.title,
|
||||
id: this.actor.id,
|
||||
type: this.actor.type,
|
||||
img: this.actor.img,
|
||||
name: this.actor.name,
|
||||
system: foundry.utils.deepClone(this.actor.system),
|
||||
description: await TextEditor.enrichHTML(this.actor.system.description, { async: true }),
|
||||
notesmj: await TextEditor.enrichHTML(this.actor.system.notesmj, { async: true }),
|
||||
options: options,
|
||||
}
|
||||
this.filterItemsPerTypeForSheet(formData, this.actor.itemTypes);
|
||||
formData.calc = {
|
||||
fortune: this.toSolsDeniers(this.actor.getFortune()),
|
||||
prixTotalEquipement: this.actor.computePrixTotalEquipement(),
|
||||
encTotal: await this.actor.computeEncTotal(),
|
||||
}
|
||||
|
||||
this.objetVersConteneur = RdDUtility.buildArbreDeConteneurs(formData.conteneurs, formData.objets);
|
||||
formData.conteneurs = RdDUtility.conteneursRacine(formData.conteneurs);
|
||||
|
||||
|
||||
return formData;
|
||||
}
|
||||
|
||||
toSolsDeniers(fortune) {
|
||||
return {
|
||||
sols: Math.floor(fortune),
|
||||
deniers: Math.round(100 * (fortune - Math.floor(fortune)))
|
||||
};
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
filterItemsPerTypeForSheet(formData, itemTypes) {
|
||||
formData.recettescuisine = Misc.arrayOrEmpty(itemTypes['recettecuisine']);
|
||||
formData.recettesAlchimiques = Misc.arrayOrEmpty(itemTypes['recettealchimique']);
|
||||
formData.maladies = Misc.arrayOrEmpty(itemTypes['maladie']);
|
||||
formData.poisons = Misc.arrayOrEmpty(itemTypes['poison']);
|
||||
formData.possessions = Misc.arrayOrEmpty(itemTypes['possession']);
|
||||
formData.maladiesPoisons = formData.maladies.concat(formData.poisons);
|
||||
formData.competences = (itemTypes['competence'] ?? []).concat(itemTypes['competencecreature'] ?? []);
|
||||
formData.sortsReserve = Misc.arrayOrEmpty(itemTypes['sortreserve']);
|
||||
|
||||
formData.sorts = Misc.arrayOrEmpty(itemTypes['sort']);
|
||||
formData.rencontres = Misc.arrayOrEmpty(itemTypes['rencontre']);
|
||||
formData.casestmr = Misc.arrayOrEmpty(itemTypes['casetmr']);
|
||||
formData.signesdraconiques = Misc.arrayOrEmpty(itemTypes['signedraconique']);
|
||||
formData.queues = Misc.arrayOrEmpty(itemTypes['queue']);
|
||||
formData.souffles = Misc.arrayOrEmpty(itemTypes['souffle']);
|
||||
formData.ombres = Misc.arrayOrEmpty(itemTypes['ombre']);
|
||||
formData.tetes = Misc.arrayOrEmpty(itemTypes['tete']);
|
||||
formData.taches = Misc.arrayOrEmpty(itemTypes['tache']);
|
||||
formData.meditations = Misc.arrayOrEmpty(itemTypes['meditation']);
|
||||
formData.chants = Misc.arrayOrEmpty(itemTypes['chant']);
|
||||
formData.danses = Misc.arrayOrEmpty(itemTypes['danse']);
|
||||
formData.musiques = Misc.arrayOrEmpty(itemTypes['musique']);
|
||||
formData.oeuvres = Misc.arrayOrEmpty(itemTypes['oeuvre']);
|
||||
formData.jeux = Misc.arrayOrEmpty(itemTypes['jeu']);
|
||||
|
||||
formData.services = Misc.arrayOrEmpty(itemTypes['service']);
|
||||
formData.conteneurs = Misc.arrayOrEmpty(itemTypes['conteneur']);
|
||||
formData.materiel = Misc.arrayOrEmpty(itemTypes['objet']);
|
||||
formData.armes = Misc.arrayOrEmpty(itemTypes['arme']);
|
||||
formData.armures = Misc.arrayOrEmpty(itemTypes['armure']);
|
||||
formData.munitions = Misc.arrayOrEmpty(itemTypes['munition']);
|
||||
formData.livres = Misc.arrayOrEmpty(itemTypes['livre']);
|
||||
formData.potions = Misc.arrayOrEmpty(itemTypes['potion']);
|
||||
formData.ingredients = Misc.arrayOrEmpty(itemTypes['ingredient']);
|
||||
formData.faunes = Misc.arrayOrEmpty(itemTypes['faune']);
|
||||
formData.herbes = Misc.arrayOrEmpty(itemTypes['herbe']);
|
||||
formData.nourritureboissons = Misc.arrayOrEmpty(itemTypes['nourritureboisson']);
|
||||
formData.gemmes = Misc.arrayOrEmpty(itemTypes['gemme']);
|
||||
formData.monnaie = Misc.arrayOrEmpty(itemTypes['monnaie']).sort(Monnaie.triValeurEntiere());
|
||||
|
||||
formData.objets = RdDItem.getItemTypesInventaire('all')
|
||||
.map(t => Misc.arrayOrEmpty(itemTypes[t]))
|
||||
.reduce((a, b) => a.concat(b), [])
|
||||
.sort(Misc.ascending(it => it.name));
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */ /** @override */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
this.html = html;
|
||||
|
||||
this.html.find('.conteneur-name a').click(async event => {
|
||||
RdDUtility.toggleAfficheContenu(this.getItemId(event));
|
||||
this.render(true);
|
||||
});
|
||||
this.html.find('.item-edit').click(async event => this.getItem(event)?.sheet.render(true))
|
||||
this.html.find('.item-montrer').click(async event => this.getItem(event)?.postItemToChat());
|
||||
this.html.find('.actor-montrer').click(async event => this.actor.postActorToChat());
|
||||
|
||||
// Everything below here is only needed if the sheet is editable
|
||||
if (!this.options.editable) return;
|
||||
|
||||
this.html.find('.item-split').click(async event => {
|
||||
const item = this.getItem(event);
|
||||
RdDSheetUtility.splitItem(item, this.actor);
|
||||
});
|
||||
this.html.find('.item-delete').click(async event => RdDUtility.confirmActorItemDelete(this, this.getItem(event)));
|
||||
this.html.find('.item-vendre').click(async event => this.vendre(this.getItem(event)));
|
||||
|
||||
this.html.find('.creer-un-objet').click(async event => {
|
||||
this.selectObjetTypeToCreate();
|
||||
});
|
||||
this.html.find('.nettoyer-conteneurs').click(async event => {
|
||||
this.actor.nettoyerConteneurs();
|
||||
});
|
||||
this.html.find('.monnaie-plus').click(async event => {
|
||||
this.actor.monnaieIncDec(this.getItemId(event), 1);
|
||||
});
|
||||
this.html.find('.monnaie-moins').click(async event => {
|
||||
this.actor.monnaieIncDec(this.getItemId(event), -1);
|
||||
});
|
||||
}
|
||||
|
||||
getItemId(event) {
|
||||
return RdDSheetUtility.getItemId(event);
|
||||
}
|
||||
|
||||
getItem(event) {
|
||||
return RdDSheetUtility.getItem(event, this.actor);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
_getHeaderButtons() {
|
||||
let buttons = super._getHeaderButtons();
|
||||
buttons.unshift({
|
||||
class: "montrer",
|
||||
icon: "fas fa-comment",
|
||||
onclick: ev => this.actor.postActorToChat()
|
||||
});
|
||||
return buttons
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async _onDropItem(event, dragData) {
|
||||
const destItemId = this.html.find(event.target)?.closest('.item').attr('data-item-id')
|
||||
const dropParams = await RdDSheetUtility.prepareItemDropParameters(destItemId, this.actor, dragData, this.objetVersConteneur)
|
||||
if (dropParams) {
|
||||
const callSuper = await this.actor.processDropItem(dropParams)
|
||||
if (callSuper) {
|
||||
await super._onDropItem(event, dragData)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async selectObjetTypeToCreate() {
|
||||
let typeObjets = this.getTypesInventaire().sort(Misc.ascending(type => Misc.typeName('Item', type)));
|
||||
let content = `<span class="competence-label">Selectionnez le type d'équipement</span><select class="item-type">`;
|
||||
for (let typeName of typeObjets) {
|
||||
content += `<option value="${typeName}">${Misc.typeName('Item', typeName)}</option>`
|
||||
}
|
||||
content += '</select>';
|
||||
let d = new Dialog({
|
||||
title: "Créer un équipement",
|
||||
content: content,
|
||||
buttons: {
|
||||
create: {
|
||||
icon: '<i class="fas fa-check"></i>',
|
||||
label: "Créer l'objet",
|
||||
callback: () => this.actor.createItem($(".item-type").val())
|
||||
}
|
||||
}
|
||||
});
|
||||
d.render(true);
|
||||
}
|
||||
|
||||
getTypesInventaire() {
|
||||
return RdDItem.getItemTypesInventaire();
|
||||
}
|
||||
|
||||
/** @override */
|
||||
setPosition(options = {}) {
|
||||
const position = super.setPosition(options);
|
||||
const sheetHeader = this.element.find(".sheet-header");
|
||||
const sheetTabs = this.element.find(".sheet-tabs");
|
||||
const sheetBody = this.element.find(".sheet-body");
|
||||
let bodyHeight = position.height - sheetHeader[0].clientHeight;
|
||||
if (sheetTabs.length > 0) {
|
||||
bodyHeight -= sheetTabs[0].clientHeight;
|
||||
}
|
||||
sheetBody.css("height", bodyHeight);
|
||||
return position;
|
||||
}
|
||||
|
||||
|
||||
/* -------------------------------------------- */
|
||||
/** @override */
|
||||
_updateObject(event, formData) {
|
||||
// Update the Actor
|
||||
return this.actor.update(formData);
|
||||
}
|
||||
|
||||
async splitItem(item) {
|
||||
const dialog = await DialogSplitItem.create(item, (item, split) => this._onSplitItem(item, split));
|
||||
dialog.render(true);
|
||||
}
|
||||
|
||||
async _onSplitItem(item, split) {
|
||||
if (split >= 1 && split < item.system.quantite) {
|
||||
await item.diminuerQuantite(split);
|
||||
const splitItem = duplicate(item);
|
||||
splitItem.system.quantite = split;
|
||||
await this.actor.createEmbeddedDocuments('Item', [splitItem])
|
||||
}
|
||||
}
|
||||
|
||||
vendre(item) {
|
||||
item?.proposerVente(this.actor.getQuantiteDisponible(item));
|
||||
}
|
||||
|
||||
}
|
619
module/actor/base-actor.js
Normal file
@ -0,0 +1,619 @@
|
||||
import { ChatUtility } from "../chat-utility.js";
|
||||
import { SYSTEM_SOCKET_ID } from "../constants.js";
|
||||
import { Monnaie } from "../item-monnaie.js";
|
||||
import { Misc } from "../misc.js";
|
||||
import { RdDAudio } from "../rdd-audio.js";
|
||||
import { RdDUtility } from "../rdd-utility.js";
|
||||
import { SystemCompendiums } from "../settings/system-compendiums.js";
|
||||
|
||||
export class RdDBaseActor extends Actor {
|
||||
|
||||
static getDefaultImg(itemType) {
|
||||
return game.system.rdd.actorClasses[itemType]?.defaultIcon ?? defaultItemImg[itemType];
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static init() {
|
||||
Hooks.on("preUpdateItem", (item, change, options, id) => RdDBaseActor.getParentActor(item)?.onPreUpdateItem(item, change, options, id));
|
||||
Hooks.on("createItem", (item, options, id) => RdDBaseActor.getParentActor(item)?.onCreateItem(item, options, id));
|
||||
Hooks.on("deleteItem", (item, options, id) => RdDBaseActor.getParentActor(item)?.onDeleteItem(item, options, id));
|
||||
Hooks.on("updateActor", (actor, change, options, actorId) => actor.onUpdateActor(change, options, actorId));
|
||||
}
|
||||
|
||||
|
||||
static onSocketMessage(sockmsg) {
|
||||
switch (sockmsg.msg) {
|
||||
case "msg_remote_actor_call":
|
||||
return RdDBaseActor.onRemoteActorCall(sockmsg.data, sockmsg.userId);
|
||||
case "msg_reset_nombre_astral":
|
||||
console.log("RESET ASTRAL", game.user.character);
|
||||
game.user.character.resetNombreAstral();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
static remoteActorCall(callData, userId = undefined) {
|
||||
userId = userId ?? Misc.firstConnectedGMId();
|
||||
if (userId == game.user.id) {
|
||||
RdDBaseActor.onRemoteActorCall(callData, userId);
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
game.socket.emit(SYSTEM_SOCKET_ID, { msg: "msg_remote_actor_call", data: callData, userId: userId });
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
static onRemoteActorCall(callData, userId) {
|
||||
if (userId == game.user.id) {
|
||||
const actor = game.actors.get(callData?.actorId);
|
||||
if (Misc.isOwnerPlayerOrUniqueConnectedGM(actor)) { // Seul le joueur choisi effectue l'appel: le joueur courant si propriétaire de l'actor, ou le MJ sinon
|
||||
const args = callData.args;
|
||||
console.info(`RdDBaseActor.onRemoteActorCall: pour l'Actor ${callData.actorId}, appel de RdDBaseActor.${callData.method}(`, ...args, ')');
|
||||
actor[callData.method](...args);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static getParentActor(document) {
|
||||
return document?.parent instanceof Actor ? document.parent : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Cet methode surcharge Actor.create() pour ajouter si besoin des Items par défaut:
|
||||
* compétences et monnaies.
|
||||
*
|
||||
* @param {Object} actorData template d'acteur auquel ajouter des informations.
|
||||
* @param {Object} options optionspour customiser la création
|
||||
*/
|
||||
static async create(actorData, options) {
|
||||
// import depuis un compendium
|
||||
if (actorData instanceof Array) {
|
||||
return super.create(actorData, options);
|
||||
}
|
||||
// Création d'un acteur avec des items (uniquement en cas de duplication): pas besoin d'ajouter d'items
|
||||
if (actorData.items) {
|
||||
return await super.create(actorData, options);
|
||||
}
|
||||
actorData.items = [];
|
||||
if (actorData.type == "personnage") {
|
||||
const competences = await SystemCompendiums.getCompetences(actorData.type);
|
||||
actorData.items = actorData.items.concat(competences.map(i => i.toObject()))
|
||||
.concat(Monnaie.monnaiesStandard());
|
||||
}
|
||||
else if (actorData.type == "commerce") {
|
||||
actorData.items = actorData.items.concat(Monnaie.monnaiesStandard());
|
||||
}
|
||||
return super.create(actorData, options);
|
||||
}
|
||||
|
||||
constructor(docData, context = {}) {
|
||||
if (!context.rdd?.ready) {
|
||||
mergeObject(context, { rdd: { ready: true } });
|
||||
const ActorConstructor = game.system.rdd.actorClasses[docData.type];
|
||||
if (ActorConstructor) {
|
||||
if (!docData.img) {
|
||||
docData.img = ActorConstructor.defaultIcon;
|
||||
}
|
||||
return new ActorConstructor(docData, context);
|
||||
}
|
||||
}
|
||||
super(docData, context);
|
||||
}
|
||||
|
||||
isCreatureEntite() { return this.type == 'creature' || this.type == 'entite'; }
|
||||
isCreature() { return this.type == 'creature'; }
|
||||
isEntite() { return this.type == 'entite'; }
|
||||
isPersonnage() { return this.type == 'personnage'; }
|
||||
isVehicule() { return this.type == 'vehicule'; }
|
||||
|
||||
getItem(id, type = undefined) {
|
||||
const item = this.items.get(id);
|
||||
if (type == undefined || (item?.type == type)) {
|
||||
return item;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
listItems(type = undefined) { return (type ? this.itemTypes[type] : this.items); }
|
||||
filterItems(filter, type = undefined) { return this.listItems(type)?.filter(filter) ?? []; }
|
||||
findItemLike(idOrName, type) {
|
||||
return this.getItem(idOrName, type)
|
||||
?? Misc.findFirstLike(idOrName, this.listItems(type), { description: Misc.typeName('Item', type) });
|
||||
}
|
||||
|
||||
getMonnaie(id) { return this.findItemLike(id, 'monnaie'); }
|
||||
|
||||
recompute() { }
|
||||
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async onPreUpdateItem(item, change, options, id) { }
|
||||
|
||||
async onCreateItem(item, options, id) { }
|
||||
|
||||
async onDeleteItem(item, options, id) { }
|
||||
|
||||
async onUpdateActor(update, options, actorId) { }
|
||||
|
||||
async onTimeChanging(oldTimestamp, newTimestamp) {
|
||||
this.items.filter(it => it.isFinPeriode(oldTimestamp, newTimestamp))
|
||||
.forEach(async it => await it.onFinPeriodeTemporel(oldTimestamp, newTimestamp))
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getFortune() {
|
||||
return Monnaie.getFortune(this.itemTypes['monnaie']);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async monnaieIncDec(id, value) {
|
||||
let monnaie = this.getMonnaie(id);
|
||||
if (monnaie) {
|
||||
const quantite = Math.max(0, monnaie.system.quantite + value);
|
||||
await this.updateEmbeddedDocuments('Item', [{ _id: monnaie.id, 'system.quantite': quantite }]);
|
||||
}
|
||||
}
|
||||
|
||||
computePrixTotalEquipement() {
|
||||
return this.items.filter(it => it.isInventaire())
|
||||
.filter(it => !it.isMonnaie())
|
||||
.map(it => it.valeurTotale())
|
||||
.reduce(Misc.sum(), 0);
|
||||
}
|
||||
|
||||
async payerSols(depense) {
|
||||
depense = Number(depense);
|
||||
if (depense == 0) {
|
||||
return;
|
||||
}
|
||||
let fortune = this.getFortune();
|
||||
console.log("payer", game.user.character, depense, fortune);
|
||||
let msg = "";
|
||||
if (fortune >= depense) {
|
||||
await Monnaie.optimiserFortune(this, fortune - depense);
|
||||
msg = `Vous avez payé <strong>${depense} Sols</strong>, qui ont été soustraits de votre argent.`;
|
||||
RdDAudio.PlayContextAudio("argent"); // Petit son
|
||||
} else {
|
||||
msg = "Vous n'avez pas assez d'argent pour payer cette somme !";
|
||||
}
|
||||
|
||||
let message = {
|
||||
whisper: ChatUtility.getWhisperRecipientsAndGMs(this.name),
|
||||
content: msg
|
||||
};
|
||||
ChatMessage.create(message);
|
||||
}
|
||||
|
||||
async depenserSols(sols) {
|
||||
let reste = this.getFortune() - Number(sols);
|
||||
if (reste >= 0) {
|
||||
await Monnaie.optimiserFortune(this, reste);
|
||||
}
|
||||
return reste;
|
||||
}
|
||||
|
||||
async ajouterSols(sols, fromActorId = undefined) {
|
||||
sols = Number(sols);
|
||||
if (sols == 0) {
|
||||
return;
|
||||
}
|
||||
if (sols < 0) {
|
||||
ui.notifications.error(`Impossible d'ajouter un gain de ${sols} <0`);
|
||||
return;
|
||||
}
|
||||
if (fromActorId && !game.user.isGM) {
|
||||
RdDBaseActor.remoteActorCall({
|
||||
userId: Misc.connectedGMOrUser(),
|
||||
actorId: this.id,
|
||||
method: 'ajouterSols', args: [sols, fromActorId]
|
||||
});
|
||||
}
|
||||
else {
|
||||
const fromActor = game.actors.get(fromActorId)
|
||||
await Monnaie.optimiserFortune(this, sols + this.getFortune());
|
||||
|
||||
RdDAudio.PlayContextAudio("argent"); // Petit son
|
||||
ChatMessage.create({
|
||||
whisper: ChatUtility.getWhisperRecipientsAndGMs(this.name),
|
||||
content: `Vous avez reçu <strong>${sols} Sols</strong> ${fromActor ? " de " + fromActor.name : ''}, qui ont été ajoutés à votre argent.`
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
|
||||
getQuantiteDisponible(item) {
|
||||
return item?.isService() ? undefined : item?.getQuantite();
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async achatVente(achat) {
|
||||
if (achat.vendeurId == achat.acheteurId) {
|
||||
ui.notifications.info("Inutile de se vendre à soi-même");
|
||||
return;
|
||||
}
|
||||
if (!Misc.isUniqueConnectedGM()) {
|
||||
RdDBaseActor.remoteActorCall({
|
||||
actorId: achat.vendeurId ?? achat.acheteurId,
|
||||
method: 'achatVente',
|
||||
args: [achat]
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const cout = Number(achat.prixTotal ?? 0);
|
||||
const vendeur = achat.vendeurId ? game.actors.get(achat.vendeurId) : undefined;
|
||||
const acheteur = achat.acheteurId ? game.actors.get(achat.acheteurId) : undefined;
|
||||
const vente = achat.vente;
|
||||
const quantite = (achat.choix.nombreLots ?? 1) * (vente.tailleLot);
|
||||
const itemVendu = vendeur?.getItem(vente.item._id);
|
||||
if (!this.verifierQuantite(vendeur, itemVendu, quantite)) {
|
||||
ChatUtility.notifyUser(achat.userId, 'warn', `Le vendeur n'a pas assez de ${itemVendu.name} !`);
|
||||
return
|
||||
}
|
||||
if (acheteur && !acheteur.verifierFortune(cout)) {
|
||||
ChatUtility.notifyUser(achat.userId, 'warn', `Vous n'avez pas assez d'argent pour payer ${Math.ceil(cout / 100)} sols !`);
|
||||
return;
|
||||
}
|
||||
await this.decrementerVente(vendeur, itemVendu, quantite, cout);
|
||||
if (acheteur) {
|
||||
await acheteur.depenserSols(cout);
|
||||
const createdItemId = await acheteur.creerQuantiteItem(vente.item, quantite);
|
||||
await acheteur.consommerNourritureAchetee(achat, vente, createdItemId);
|
||||
}
|
||||
if (cout > 0) {
|
||||
RdDAudio.PlayContextAudio("argent");
|
||||
}
|
||||
const chatAchatItem = duplicate(vente);
|
||||
chatAchatItem.quantiteTotal = quantite;
|
||||
ChatMessage.create({
|
||||
user: achat.userId,
|
||||
speaker: { alias: (acheteur ?? vendeur).name },
|
||||
whisper: ChatUtility.getWhisperRecipientsAndGMs(this.name),
|
||||
content: await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/chat-achat-item.html', chatAchatItem)
|
||||
});
|
||||
|
||||
if (!vente.quantiteIllimite) {
|
||||
if (vente.quantiteNbLots <= achat.choix.nombreLots) {
|
||||
ChatUtility.removeChatMessageId(achat.chatMessageIdVente);
|
||||
}
|
||||
else if (achat.chatMessageIdVente) {
|
||||
vente["properties"] = itemVendu.getProprietes();
|
||||
vente.quantiteNbLots -= achat.choix.nombreLots;
|
||||
vente.jsondata = JSON.stringify(vente.item);
|
||||
const messageVente = game.messages.get(achat.chatMessageIdVente);
|
||||
messageVente.update({ content: await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/chat-vente-item.html', vente) });
|
||||
messageVente.render(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async decrementerVente(vendeur, itemVendu, quantite, cout) {
|
||||
if (vendeur) {
|
||||
await vendeur.ajouterSols(cout);
|
||||
await vendeur.decrementerQuantiteItem(itemVendu, quantite);
|
||||
}
|
||||
}
|
||||
|
||||
verifierFortune(cout) {
|
||||
return this.getFortune() >= cout;
|
||||
}
|
||||
|
||||
verifierQuantite(vendeur, item, quantiteTotal) {
|
||||
const disponible = vendeur?.getQuantiteDisponible(item);
|
||||
return disponible == undefined || disponible >= quantiteTotal;
|
||||
}
|
||||
|
||||
async consommerNourritureAchetee(achat, vente, createdItemId) {
|
||||
if (achat.choix.consommer && vente.item.type == 'nourritureboisson' && createdItemId != undefined) {
|
||||
achat.choix.doses = achat.choix.nombreLots;
|
||||
await this.consommerNourritureboisson(createdItemId, achat.choix, vente.actingUserId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async decrementerQuantiteItem(item, quantite, options = { supprimerSiZero: true }) {
|
||||
if (item.isService()) {
|
||||
return;
|
||||
}
|
||||
let resteQuantite = (item.system.quantite ?? 1) - quantite;
|
||||
if (resteQuantite <= 0) {
|
||||
if (options.supprimerSiZero) {
|
||||
await this.deleteEmbeddedDocuments("Item", [item.id]);
|
||||
}
|
||||
else {
|
||||
await this.updateEmbeddedDocuments("Item", [{ _id: item.id, 'system.quantite': 0 }]);
|
||||
}
|
||||
if (resteQuantite < 0) {
|
||||
ui.notifications.warn(`La quantité de ${item.name} était insuffisante, l'objet a donc été supprimé`)
|
||||
}
|
||||
}
|
||||
else if (resteQuantite > 0) {
|
||||
await this.updateEmbeddedDocuments("Item", [{ _id: item.id, 'system.quantite': resteQuantite }]);
|
||||
}
|
||||
}
|
||||
|
||||
async creerQuantiteItem(item, quantite) {
|
||||
if (this.canReceive(item)) {
|
||||
const isItemEmpilable = "quantite" in item.system;
|
||||
const baseItem = {
|
||||
type: item.type,
|
||||
img: item.img,
|
||||
name: item.name,
|
||||
system: mergeObject(item.system, { quantite: isItemEmpilable ? quantite : undefined })
|
||||
};
|
||||
const newItems = isItemEmpilable ? [baseItem] : Array.from({ length: quantite }, (_, i) => baseItem);
|
||||
const items = await this.createEmbeddedDocuments("Item", newItems);
|
||||
return items.length > 0 ? items[0].id : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async computeEncTotal() {
|
||||
if (!this.pack) {
|
||||
this.encTotal = this.items.map(it => it.getEncTotal()).reduce(Misc.sum(), 0);
|
||||
return this.encTotal;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
async createItem(type, name = undefined) {
|
||||
if (!name) {
|
||||
name = 'Nouveau ' + Misc.typeName('Item', type);
|
||||
}
|
||||
await this.createEmbeddedDocuments('Item', [{ name: name, type: type }], { renderSheet: true });
|
||||
}
|
||||
|
||||
canReceive(item) {
|
||||
return false;
|
||||
}
|
||||
|
||||
async processDropItem(params) {
|
||||
const targetActorId = this.id;
|
||||
const sourceActorId = params.sourceActorId;
|
||||
const itemId = params.itemId;
|
||||
const destId = params.destId;
|
||||
const srcId = params.srcId;
|
||||
if (sourceActorId && sourceActorId != targetActorId) {
|
||||
console.log("Moving objects", sourceActorId, targetActorId, itemId);
|
||||
this.moveItemsBetweenActors(itemId, sourceActorId);
|
||||
return false;
|
||||
}
|
||||
let result = true;
|
||||
const item = this.getItem(itemId);
|
||||
if (item?.isInventaire('all') && sourceActorId == targetActorId) {
|
||||
// rangement
|
||||
if (srcId != destId && itemId != destId) { // déplacement de l'objet
|
||||
const src = this.getItem(srcId);
|
||||
const dest = this.getItem(destId);
|
||||
const cible = this.getContenantOrParent(dest);
|
||||
const [empilable, message] = item.isInventaireEmpilable(dest);
|
||||
if (empilable) {
|
||||
await dest.empiler(item)
|
||||
result = false;
|
||||
}
|
||||
// changer de conteneur
|
||||
else if (!cible || this.conteneurPeutContenir(cible, item)) {
|
||||
await this.enleverDeConteneur(item, src, params.onEnleverConteneur);
|
||||
await this.ajouterDansConteneur(item, cible, params.onAjouterDansConteneur);
|
||||
if (message && !dest.isConteneur()) {
|
||||
ui.notifications.info(cible
|
||||
? `${message}<br>${item.name} a été déplacé dans: ${cible.name}`
|
||||
: `${message}<br>${item.name} a été sorti du conteneur`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
await this.computeEncTotal();
|
||||
return result;
|
||||
}
|
||||
|
||||
getContenantOrParent(dest) {
|
||||
if (!dest || dest.isConteneur()) {
|
||||
return dest;
|
||||
}
|
||||
return this.getContenant(dest);
|
||||
}
|
||||
|
||||
getContenant(item) {
|
||||
return this.itemTypes['conteneur'].find(it => it.system.contenu.includes(item.id));
|
||||
}
|
||||
|
||||
|
||||
/* -------------------------------------------- */
|
||||
conteneurPeutContenir(dest, item) {
|
||||
if (!dest) {
|
||||
return true;
|
||||
}
|
||||
if (!dest.isConteneur()) {
|
||||
return false;
|
||||
}
|
||||
const destData = dest
|
||||
if (this._isConteneurContenu(item, dest)) {
|
||||
ui.notifications.warn(`Impossible de déplacer un conteneur parent (${item.name}) dans un de ses contenus ${destData.name} !`);
|
||||
return false; // Loop detected !
|
||||
}
|
||||
|
||||
// Calculer le total actuel des contenus
|
||||
let encContenu = this.getRecursiveEnc(dest) - Number(destData.system.encombrement);
|
||||
let newEnc = this.getRecursiveEnc(item); // Calculer le total actuel du nouvel objet
|
||||
|
||||
// Teste si le conteneur de destination a suffisament de capacité pour recevoir le nouvel objet
|
||||
if (Number(destData.system.capacite) < encContenu + newEnc) {
|
||||
ui.notifications.warn(
|
||||
`Le conteneur ${dest.name} a une capacité de ${destData.system.capacite}, et contient déjà ${encContenu}.
|
||||
Impossible d'y ranger: ${item.name} d'encombrement ${newEnc}!`);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
_isConteneurContenu(item, conteneur) {
|
||||
if (item?.isConteneur()) { // Si c'est un conteneur, il faut vérifier qu'on ne le déplace pas vers un sous-conteneur lui appartenant
|
||||
for (let id of item.system.contenu) {
|
||||
let subObjet = this.getItem(id);
|
||||
if (subObjet?.id == conteneur.id) {
|
||||
return true; // Loop detected !
|
||||
}
|
||||
if (subObjet?.isConteneur()) {
|
||||
return this._isConteneurContenu(subObjet, conteneur);
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
getRecursiveEnc(objet) {
|
||||
if (!objet) {
|
||||
return 0;
|
||||
}
|
||||
const tplData = objet.system;
|
||||
if (objet.type != 'conteneur') {
|
||||
return Number(tplData.encombrement) * Number(tplData.quantite);
|
||||
}
|
||||
const encContenus = tplData.contenu.map(idContenu => this.getRecursiveEnc(this.getItem(idContenu)));
|
||||
return encContenus.reduce(Misc.sum(), 0)
|
||||
+ Number(tplData.encombrement) /* TODO? Number(tplData.quantite) -- on pourrait avoir plusieurs conteneurs...*/
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
/** Ajoute un item dans un conteneur, sur la base
|
||||
* de leurs ID */
|
||||
async ajouterDansConteneur(item, conteneur, onAjouterDansConteneur) {
|
||||
if (!conteneur) {
|
||||
// TODO: afficher
|
||||
item.estContenu = false;
|
||||
}
|
||||
else if (conteneur.isConteneur()) {
|
||||
item.estContenu = true;
|
||||
await this.updateEmbeddedDocuments('Item', [{
|
||||
_id: conteneur.id,
|
||||
'system.contenu': [...conteneur.system.contenu, item.id]
|
||||
}]);
|
||||
onAjouterDansConteneur(item.id, conteneur.id);
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
/** Fonction de remise à plat de l'équipement (ie vide les champs 'contenu') */
|
||||
async nettoyerConteneurs() {
|
||||
RdDConfirm.confirmer({
|
||||
settingConfirmer: "confirmation-vider",
|
||||
content: `<p>Etes vous certain de vouloir vider tous les conteneurs ?</p>`,
|
||||
title: 'Vider les conteneurs',
|
||||
buttonLabel: 'Vider',
|
||||
onAction: async () => {
|
||||
const corrections = [];
|
||||
for (let item of this.items) {
|
||||
if (item.estContenu) {
|
||||
item.estContenu = undefined;
|
||||
}
|
||||
if (item.type == 'conteneur' && item.system.contenu.length > 0) {
|
||||
corrections.push({ _id: item.id, 'system.contenu': [] });
|
||||
}
|
||||
}
|
||||
if (corrections.length > 0) {
|
||||
await this.updateEmbeddedDocuments('Item', corrections);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
buildSubConteneurObjetList(conteneurId, deleteList) {
|
||||
let conteneur = this.getItem(conteneurId);
|
||||
if (conteneur?.type == 'conteneur') { // Si c'est un conteneur
|
||||
for (let subId of conteneur.system.contenu) {
|
||||
let subObj = this.getItem(subId);
|
||||
if (subObj) {
|
||||
if (subObj.type == 'conteneur') {
|
||||
this.buildSubConteneurObjetList(subId, deleteList);
|
||||
}
|
||||
deleteList.push({ id: subId, conteneurId: conteneurId });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async deleteAllConteneur(itemId, options) {
|
||||
let list = [];
|
||||
list.push({ id: itemId, conteneurId: undefined }); // Init list
|
||||
this.buildSubConteneurObjetList(itemId, list);
|
||||
await this.deleteEmbeddedDocuments('Item', list.map(it => it.id), options);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
/** Supprime un item d'un conteneur, sur la base
|
||||
* de leurs ID */
|
||||
async enleverDeConteneur(item, conteneur, onEnleverDeConteneur) {
|
||||
if (conteneur?.isConteneur()) {
|
||||
item.estContenu = false;
|
||||
await this.updateEmbeddedDocuments('Item', [{
|
||||
_id: conteneur.id,
|
||||
'system.contenu': conteneur.system.contenu.filter(id => id != item.id)
|
||||
}]);
|
||||
onEnleverDeConteneur();
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async moveItemsBetweenActors(itemId, sourceActorId) {
|
||||
let itemsList = []
|
||||
let sourceActor = game.actors.get(sourceActorId);
|
||||
itemsList.push({ id: itemId, conteneurId: undefined }); // Init list
|
||||
sourceActor.buildSubConteneurObjetList(itemId, itemsList); // Get itemId list
|
||||
|
||||
const itemsDataToCreate = itemsList.map(it => sourceActor.getItem(it.id))
|
||||
.map(it => duplicate(it))
|
||||
.map(it => { it.system.contenu = []; return it; });
|
||||
let newItems = await this.createEmbeddedDocuments('Item', itemsDataToCreate);
|
||||
|
||||
let itemMap = this._buildMapOldNewId(itemsList, newItems);
|
||||
|
||||
for (let item of itemsList) { // Second boucle pour traiter la remise en conteneurs
|
||||
// gestion conteneur/contenu
|
||||
if (item.conteneurId) { // l'Objet était dans un conteneur
|
||||
let newConteneurId = itemMap[item.conteneurId]; // Get conteneur
|
||||
let newConteneur = this.getItem(newConteneurId);
|
||||
|
||||
let newItemId = itemMap[item.id]; // Get newItem
|
||||
|
||||
console.log('New conteneur filling!', newConteneur, newItemId, item);
|
||||
let contenu = duplicate(newConteneur.system.contenu);
|
||||
contenu.push(newItemId);
|
||||
await this.updateEmbeddedDocuments('Item', [{ _id: newConteneurId, 'system.contenu': contenu }]);
|
||||
}
|
||||
}
|
||||
for (let item of itemsList) {
|
||||
await sourceActor.deleteEmbeddedDocuments('Item', [item.id]);
|
||||
}
|
||||
}
|
||||
|
||||
_buildMapOldNewId(itemsList, newItems) {
|
||||
let itemMap = {};
|
||||
for (let i = 0; i < itemsList.length; i++) {
|
||||
itemMap[itemsList[i].id] = newItems[i].id; // Pour garder le lien ancien / nouveau
|
||||
}
|
||||
return itemMap;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async postActorToChat(modeOverride) {
|
||||
let chatData = {
|
||||
doctype: 'Actor',
|
||||
id: this.id,
|
||||
type: this.type,
|
||||
img: this.img,
|
||||
pack: this.pack,
|
||||
name: this.name,
|
||||
system: { description: this.system.description }
|
||||
}
|
||||
renderTemplate('systems/foundryvtt-reve-de-dragon/templates/post-actor.html', chatData)
|
||||
.then(html => ChatMessage.create(RdDUtility.chatDataSetup(html, modeOverride)));
|
||||
}
|
||||
|
||||
|
||||
}
|
74
module/actor/commerce-sheet.js
Normal file
@ -0,0 +1,74 @@
|
||||
import { DialogItemAchat } from "../dialog-item-achat.js";
|
||||
import { RdDItem } from "../item.js";
|
||||
import { RdDSheetUtility } from "../rdd-sheet-utility.js";
|
||||
import { RdDUtility } from "../rdd-utility.js";
|
||||
import { RdDBaseActorSheet } from "./base-actor-sheet.js";
|
||||
import { RdDCommerce } from "./commerce.js";
|
||||
|
||||
/**
|
||||
* Extend the basic ActorSheet with some very simple modifications
|
||||
* @extends {ActorSheet}
|
||||
*/
|
||||
export class RdDCommerceSheet extends RdDBaseActorSheet {
|
||||
|
||||
/** @override */
|
||||
static get defaultOptions() {
|
||||
return mergeObject(super.defaultOptions, {
|
||||
classes: ["rdd", "sheet", "actor"],
|
||||
template: "systems/foundryvtt-reve-de-dragon/templates/actor/commerce-actor-sheet.html",
|
||||
width: 600,
|
||||
height: 720,
|
||||
tabs: [],
|
||||
dragDrop: [{ dragSelector: ".item-list .item", dropSelector: undefined }]
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
/** @override */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
|
||||
this.html.find('a.item-acheter').click(async event => await this.vente(this.getItem(event)));
|
||||
|
||||
if (!this.options.editable) return;
|
||||
|
||||
this.html.find('a.item-quantite-moins').click(async event => await this.getItem(event)?.quantiteIncDec(-1, { supprimerSiZero: false}));
|
||||
this.html.find('a.item-quantite-plus').click(async event => await this.getItem(event)?.quantiteIncDec(1));
|
||||
this.html.find('input.item-quantite').change(async event => {
|
||||
const newQuantite = Math.max(0, Number.parseInt(this.html.find(event.currentTarget).val()));
|
||||
await this.getItem(event)?.update({ "system.quantite": newQuantite });
|
||||
})
|
||||
this.html.find('input.item-cout').change(async event => {
|
||||
const newCout = Math.max(0, Number(this.html.find(event.currentTarget).val()));
|
||||
await this.getItem(event)?.update({ "system.cout": newCout });
|
||||
})
|
||||
}
|
||||
|
||||
getTypesInventaire() {
|
||||
return RdDItem.getItemTypesInventaire('all');
|
||||
}
|
||||
|
||||
|
||||
async vente(item) {
|
||||
const acheteur = RdDUtility.getSelectedActor();
|
||||
if (!acheteur) {
|
||||
ui.notifications.warn(`Pas d'acheteur sélectionné`);
|
||||
return;
|
||||
}
|
||||
const disponible = this.actor.getQuantiteDisponible(item)
|
||||
if (disponible == 0) {
|
||||
ui.notifications.warn(`${this.name} n'a plus de ${item.name} en vente`);
|
||||
return;
|
||||
}
|
||||
|
||||
await DialogItemAchat.onAcheter({
|
||||
item,
|
||||
vendeur: this.actor,
|
||||
acheteur,
|
||||
quantiteIllimite: disponible == undefined,
|
||||
nbLots: disponible ?? 1,
|
||||
tailleLot: 1,
|
||||
prixLot: item.calculerPrixCommercant()
|
||||
});
|
||||
}
|
||||
}
|
53
module/actor/commerce.js
Normal file
@ -0,0 +1,53 @@
|
||||
import { Misc } from "../misc.js";
|
||||
import { RdDBaseActor } from "./base-actor.js";
|
||||
|
||||
export class RdDCommerce extends RdDBaseActor {
|
||||
|
||||
static get defaultIcon() {
|
||||
return "systems/foundryvtt-reve-de-dragon/icons/services/commerce.webp";
|
||||
}
|
||||
|
||||
prepareData() {
|
||||
super.prepareData();
|
||||
}
|
||||
prepareDerivedData() {
|
||||
super.prepareDerivedData();
|
||||
}
|
||||
|
||||
canReceive(item) {
|
||||
if (item.isInventaire('all')) {
|
||||
return true;
|
||||
}
|
||||
return super.canReceive(item);
|
||||
}
|
||||
|
||||
getQuantiteDisponible(item) {
|
||||
return this.system.illimite || item.isService() ? undefined : item.getQuantite();
|
||||
}
|
||||
|
||||
verifierFortune(cout) {
|
||||
return this.system.illimite || super.verifierFortune(cout);
|
||||
}
|
||||
async depenserSols(cout) {
|
||||
if (this.system.illimite) {
|
||||
return
|
||||
}
|
||||
await super.depenserSols(cout)
|
||||
}
|
||||
|
||||
async consommerNourritureAchetee(achat, vente, createdItemId) {
|
||||
// ne pas consommer pour un commerce
|
||||
}
|
||||
|
||||
async decrementerQuantiteItem(item, quantite) {
|
||||
if (this.system.illimite) {
|
||||
return;
|
||||
}
|
||||
await super.decrementerQuantiteItem(item, quantite, { supprimerSiZero: false });
|
||||
}
|
||||
|
||||
calculerPrix(item) {
|
||||
const pourcentage = this.system.pourcentage ?? 100;
|
||||
return Misc.keepDecimals(Math.ceil(item.system.cout * pourcentage) / 100, 2);
|
||||
}
|
||||
}
|
@ -1,5 +1,6 @@
|
||||
import { SYSTEM_RDD } from "./constants.js";
|
||||
import { Grammar } from "./grammar.js";
|
||||
import { RdDTimestamp } from "./rdd-timestamp.js";
|
||||
|
||||
|
||||
const LATEST_USED_JOURNAL_ID = "chronologie-dernier-journal";
|
||||
@ -16,16 +17,13 @@ export class DialogChronologie extends Dialog {
|
||||
});
|
||||
}
|
||||
static async create() {
|
||||
const dateRdD = game.system.rdd.calendrier.getCalendrier();
|
||||
const dialogData = {
|
||||
auteur: game.user.name,
|
||||
isGM: game.user.isGM,
|
||||
information: "",
|
||||
journalId: game.settings.get(SYSTEM_RDD, LATEST_USED_JOURNAL_ID),
|
||||
journaux: game.journal.filter(it => it.testUserPermission(game.user, CONST.DOCUMENT_OWNERSHIP_LEVELS.OWNER)),
|
||||
dateRdD: dateRdD,
|
||||
jourRdD: dateRdD.jour +1,
|
||||
heureRdD: game.system.rdd.calendrier.getCurrentHeure(),
|
||||
timestamp: game.system.rdd.calendrier.timestamp,
|
||||
dateReel: DialogChronologie.getCurrentDateTime()
|
||||
};
|
||||
const html = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/dialog-chronologie.html", dialogData);
|
||||
@ -62,6 +60,7 @@ export class DialogChronologie extends Dialog {
|
||||
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
this.html = html;
|
||||
}
|
||||
|
||||
async ajouter() {
|
||||
@ -74,11 +73,11 @@ export class DialogChronologie extends Dialog {
|
||||
}
|
||||
|
||||
async forceValidation() {
|
||||
await $("form.rdddialogchrono :input").change();
|
||||
await this.html.find("form.rdddialogchrono :input").change();
|
||||
}
|
||||
|
||||
findJournal() {
|
||||
const journalId = $("form.rdddialogchrono :input[name='journalId']").val();
|
||||
const journalId = this.html.find("form.rdddialogchrono :input[name='journalId']").val();
|
||||
const journalEntry = game.journal.get(journalId);
|
||||
return { journalId, journalEntry };
|
||||
}
|
||||
@ -89,15 +88,16 @@ export class DialogChronologie extends Dialog {
|
||||
|
||||
extractJournalParameters() {
|
||||
return {
|
||||
auteur: $("form.rdddialogchrono :input[name='auteur']").val(),
|
||||
information: $("form.rdddialogchrono :input[name='information']").val(),
|
||||
auteur: this.html.find("form.rdddialogchrono :input[name='auteur']").val(),
|
||||
information: this.html.find("form.rdddialogchrono :input[name='information']").val(),
|
||||
dateRdD: {
|
||||
jour: $("form.rdddialogchrono :input[name='jourRdD']").val(),
|
||||
moisRdD: $("form.rdddialogchrono :input[name='dateRdD.moisRdD.key']").val(),
|
||||
annee: $("form.rdddialogchrono :input[name='dateRdD.annee']").val()
|
||||
jour: this.html.find("form.rdddialogchrono :input[name='chronologie.jourDuMois']").val(),
|
||||
mois: RdDTimestamp.definition(this.html.find("form.rdddialogchrono :input[name='chronologie.mois']").val()),
|
||||
annee: this.html.find("form.rdddialogchrono :input[name='chronologie.annee']").val(),
|
||||
heure: RdDTimestamp.definition(this.html.find("form.rdddialogchrono :input[name='chronologie.heure']").val()),
|
||||
minute: this.html.find("form.rdddialogchrono :input[name='chronologie.minute']").val(),
|
||||
},
|
||||
heureRdD: $("form.rdddialogchrono :input[name='heureRdD']").val(),
|
||||
dateReel: $("form.rdddialogchrono :input[name='dateReel']").val().replace('T', ' ')
|
||||
dateReel: this.html.find("form.rdddialogchrono :input[name='dateReel']").val().replace('T', ' ')
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
import { ChatUtility } from "./chat-utility.js";
|
||||
import { HtmlUtility } from "./html-utility.js";
|
||||
import { RdDItemSigneDraconique } from "./item-signedraconique.js";
|
||||
import { RdDItemSigneDraconique } from "./item/item-signedraconique.js";
|
||||
import { TMRUtility } from "./tmr-utility.js";
|
||||
|
||||
export class DialogCreateSigneDraconique extends Dialog {
|
||||
@ -35,16 +35,16 @@ export class DialogCreateSigneDraconique extends Dialog {
|
||||
super(conf, options);
|
||||
this.dialogData = dialogData;
|
||||
}
|
||||
|
||||
|
||||
async _onCreerSigneActeurs() {
|
||||
await $("[name='signe.system.ephemere']").change();
|
||||
await $(".signe-xp-sort").change();
|
||||
await this.html.find("[name='signe.system.ephemere']").change();
|
||||
await this.html.find(".signe-xp-sort").change();
|
||||
this.validerSigne();
|
||||
this.dialogData.actors.filter(it => it.selected)
|
||||
.map(it => game.actors.get(it.id))
|
||||
.forEach(actor => this._createSigneForActor(actor, this.dialogData.signe));
|
||||
.map(it => game.actors.get(it.id))
|
||||
.forEach(actor => this._createSigneForActor(actor, this.dialogData.signe));
|
||||
}
|
||||
|
||||
|
||||
async _createSigneForActor(actor, signe) {
|
||||
actor.createEmbeddedDocuments("Item", [signe]);
|
||||
ChatMessage.create({
|
||||
@ -57,19 +57,20 @@ export class DialogCreateSigneDraconique extends Dialog {
|
||||
}
|
||||
|
||||
validerSigne() {
|
||||
this.dialogData.signe.name = $("[name='signe.name']").val();
|
||||
this.dialogData.signe.system.valeur.norm = $("[name='signe.system.valeur.norm']").val();
|
||||
this.dialogData.signe.system.valeur.sign = $("[name='signe.system.valeur.sign']").val();
|
||||
this.dialogData.signe.system.valeur.part = $("[name='signe.system.valeur.part']").val();
|
||||
this.dialogData.signe.system.difficulte = $("[name='signe.system.difficulte']").val();
|
||||
this.dialogData.signe.system.ephemere = $("[name='signe.system.ephemere']").prop("checked");
|
||||
this.dialogData.signe.system.duree = $("[name='signe.system.duree']").val();
|
||||
this.dialogData.signe.name = this.html.find("[name='signe.name']").val();
|
||||
this.dialogData.signe.system.valeur.norm = this.html.find("[name='signe.system.valeur.norm']").val();
|
||||
this.dialogData.signe.system.valeur.sign = this.html.find("[name='signe.system.valeur.sign']").val();
|
||||
this.dialogData.signe.system.valeur.part = this.html.find("[name='signe.system.valeur.part']").val();
|
||||
this.dialogData.signe.system.difficulte = this.html.find("[name='signe.system.difficulte']").val();
|
||||
this.dialogData.signe.system.ephemere = this.html.find("[name='signe.system.ephemere']").prop("checked");
|
||||
this.dialogData.signe.system.duree = this.html.find("[name='signe.system.duree']").val();
|
||||
this.dialogData.signe.system.typesTMR = TMRUtility.buildListTypesTMRSelection(this.dialogData.tmrs);
|
||||
}
|
||||
|
||||
|
||||
/* -------------------------------------------- */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
this.html = html;
|
||||
this.setEphemere(this.dialogData.signe.system.ephemere);
|
||||
html.find(".signe-aleatoire").click(event => this.setSigneAleatoire());
|
||||
html.find("[name='signe.system.ephemere']").change((event) => this.setEphemere(event.currentTarget.checked));
|
||||
@ -81,27 +82,27 @@ export class DialogCreateSigneDraconique extends Dialog {
|
||||
async setSigneAleatoire() {
|
||||
const newSigne = await RdDItemSigneDraconique.randomSigneDraconique({ephemere: true});
|
||||
|
||||
$("[name='signe.name']").val(newSigne.name);
|
||||
$("[name='signe.system.valeur.norm']").val(newSigne.system.valeur.norm);
|
||||
$("[name='signe.system.valeur.sign']").val(newSigne.system.valeur.sign);
|
||||
$("[name='signe.system.valeur.part']").val(newSigne.system.valeur.part);
|
||||
$("[name='signe.system.difficulte']").val(newSigne.system.difficulte);
|
||||
$("[name='signe.system.duree']").val(newSigne.system.duree);
|
||||
$("[name='signe.system.ephemere']").prop("checked", newSigne.system.ephemere);
|
||||
this.html.find("[name='signe.name']").val(newSigne.name);
|
||||
this.html.find("[name='signe.system.valeur.norm']").val(newSigne.system.valeur.norm);
|
||||
this.html.find("[name='signe.system.valeur.sign']").val(newSigne.system.valeur.sign);
|
||||
this.html.find("[name='signe.system.valeur.part']").val(newSigne.system.valeur.part);
|
||||
this.html.find("[name='signe.system.difficulte']").val(newSigne.system.difficulte);
|
||||
this.html.find("[name='signe.system.duree']").val(newSigne.system.duree);
|
||||
this.html.find("[name='signe.system.ephemere']").prop("checked", newSigne.system.ephemere);
|
||||
this.dialogData.tmrs = TMRUtility.buildSelectionTypesTMR(newSigne.system.typesTMR);
|
||||
this.dialogData.tmrs.forEach(t => {
|
||||
$(`[data-tmr-name='${t.name}']`).prop( "checked", t.selected);
|
||||
this.html.find(`[data-tmr-name='${t.name}']`).prop( "checked", t.selected);
|
||||
})
|
||||
this.setEphemere(newSigne.system.ephemere);
|
||||
}
|
||||
|
||||
async setEphemere(ephemere) {
|
||||
this.dialogData.signe.system.ephemere = ephemere;
|
||||
HtmlUtility._showControlWhen($(".signe-system-duree"), ephemere);
|
||||
HtmlUtility._showControlWhen(this.html.find(".signe-system-duree"), ephemere);
|
||||
}
|
||||
|
||||
async onSelectActor(event) {
|
||||
const actorId = $(event.currentTarget)?.data("actor-id");
|
||||
const actorId = this.html.find(event.currentTarget)?.data("actor-id");
|
||||
const actor = this.dialogData.actors.find(it => it.id == actorId);
|
||||
if (actor) {
|
||||
actor.selected = event.currentTarget.checked;
|
||||
@ -109,7 +110,7 @@ export class DialogCreateSigneDraconique extends Dialog {
|
||||
}
|
||||
|
||||
onSelectTmr(event) {
|
||||
const tmrName = $(event.currentTarget)?.data("tmr-name");
|
||||
const tmrName = this.html.find(event.currentTarget)?.data("tmr-name");
|
||||
const onTmr = this.tmrs.find(it => it.name == tmrName);
|
||||
if (onTmr){
|
||||
onTmr.selected = event.currentTarget.checked;
|
||||
|
@ -13,18 +13,12 @@ export class DialogFabriquerPotion extends Dialog {
|
||||
}
|
||||
let potionData = DialogFabriquerPotion.prepareData(actor, item);
|
||||
|
||||
let conf = {
|
||||
title: `Fabriquer une potion de ${potionData.system.categorie}`,
|
||||
content: await renderTemplate(dialogConfig.html, potionData),
|
||||
default: potionData.buttonName,
|
||||
};
|
||||
const html = await renderTemplate(dialogConfig.html, potionData);
|
||||
|
||||
let options = { classes: ["dialogfabriquerpotion"], width: 600, height: 160, 'z-index': 99999 };
|
||||
mergeObject(options, dialogConfig.options ?? {}, { overwrite: true })
|
||||
|
||||
const dialog = new DialogFabriquerPotion(actor, potionData, conf, options);
|
||||
dialog.render(true);
|
||||
return dialog;
|
||||
new DialogFabriquerPotion(actor, potionData, html, options).render(true);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
@ -40,10 +34,15 @@ export class DialogFabriquerPotion extends Dialog {
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
constructor(actor, potionData, conf, options) {
|
||||
conf.buttons = {
|
||||
[potionData.buttonName]: {
|
||||
label: potionData.buttonName, callback: it => this.onFabriquer(it)
|
||||
constructor(actor, potionData, html, options) {
|
||||
const conf = {
|
||||
title: `Fabriquer une potion de ${potionData.system.categorie}`,
|
||||
content: html,
|
||||
default: 'fabriquer',
|
||||
buttons: {
|
||||
'fabriquer': {
|
||||
label: potionData.buttonName, callback: it => this.onFabriquer(html)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@ -53,6 +52,24 @@ export class DialogFabriquerPotion extends Dialog {
|
||||
this.potionData = potionData;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
this.html = html;
|
||||
this.html.find("[name='nbBrins']").change(event => {
|
||||
this.potionData.nbBrins = Misc.toInt(event.currentTarget.value);
|
||||
const brinsManquants = Math.max(0, DialogFabriquerPotion.nombreBrinsOptimal(this.potionData) - this.potionData.nbBrins);
|
||||
this.potionData.herbebonus = Math.max(0, this.potionData.system.niveau - brinsManquants)
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async onFabriquer(html) {
|
||||
await this.html.find("[name='nbBrins']").change();
|
||||
this.actor.fabriquerPotion(this.potionData);
|
||||
this.close();
|
||||
}
|
||||
|
||||
static nombreBrinsMinimum(herbeData) {
|
||||
switch (herbeData.system.categorie ?? '') {
|
||||
case "Soin": return 1 + Math.max(0, 12 - 2 * herbeData.system.niveau);
|
||||
@ -68,22 +85,4 @@ export class DialogFabriquerPotion extends Dialog {
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
|
||||
html.find("#nbBrins").change(event => {
|
||||
this.potionData.nbBrins = Misc.toInt(event.currentTarget.value);
|
||||
const brinsManquants = Math.max(0, DialogFabriquerPotion.nombreBrinsOptimal(this.potionData) - this.potionData.nbBrins);
|
||||
this.potionData.herbebonus = Math.max(0, this.potionData.system.niveau - brinsManquants)
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async onFabriquer(it) {
|
||||
await $("#nbBrins").change();
|
||||
this.actor.fabriquerPotion(this.potionData);
|
||||
this.close();
|
||||
}
|
||||
}
|
@ -1,14 +1,13 @@
|
||||
|
||||
import { Monnaie } from "./item-monnaie.js";
|
||||
import { Misc } from "./misc.js";
|
||||
import { RdDUtility } from "./rdd-utility.js";
|
||||
|
||||
export class DialogItemAchat extends Dialog {
|
||||
|
||||
static venteData(button) {
|
||||
const vendeurId = button.attributes['data-vendeurId']?.value;
|
||||
static preparerAchat(chatButton) {
|
||||
const vendeurId = chatButton.attributes['data-vendeurId']?.value;
|
||||
const vendeur = vendeurId ? game.actors.get(vendeurId) : undefined;
|
||||
const acheteur = RdDUtility.getSelectedActor();
|
||||
const json = button.attributes['data-jsondata']?.value;
|
||||
const json = chatButton.attributes['data-jsondata']?.value;
|
||||
if (!acheteur && !vendeur) {
|
||||
ui.notifications.info("Pas d'acheteur ni de vendeur, aucun changement");
|
||||
return undefined;
|
||||
@ -18,59 +17,78 @@ export class DialogItemAchat extends Dialog {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const prixLot = Number(button.attributes['data-prixLot']?.value ?? 0);
|
||||
return {
|
||||
item: json ? JSON.parse(json) : undefined,
|
||||
actingUserId: game.user.id,
|
||||
vendeurId: vendeurId,
|
||||
vendeur: vendeur,
|
||||
acheteur: acheteur,
|
||||
tailleLot: parseInt(button.attributes['data-tailleLot']?.value ?? 1),
|
||||
quantiteIllimite: button.attributes['data-quantiteIllimite']?.value == 'true',
|
||||
quantiteNbLots: parseInt(button.attributes['data-quantiteNbLots']?.value),
|
||||
choix: {
|
||||
nombreLots: 1,
|
||||
seForcer: false,
|
||||
supprimerSiZero: true
|
||||
},
|
||||
prixLot: prixLot,
|
||||
prixTotal: prixLot,
|
||||
isVente: prixLot > 0,
|
||||
chatMessageIdVente: RdDUtility.findChatMessageId(button)
|
||||
item: (json ? JSON.parse(json) : undefined),
|
||||
vendeur,
|
||||
acheteur,
|
||||
nbLots: parseInt(chatButton.attributes['data-quantiteNbLots']?.value),
|
||||
tailleLot: parseInt(chatButton.attributes['data-tailleLot']?.value ?? 1),
|
||||
prixLot: Number(chatButton.attributes['data-prixLot']?.value ?? 0),
|
||||
quantiteIllimite: chatButton.attributes['data-quantiteIllimite']?.value == 'true',
|
||||
chatMessageIdVente: RdDUtility.findChatMessageId(chatButton),
|
||||
};
|
||||
}
|
||||
|
||||
static async onAcheter(venteData) {
|
||||
|
||||
static async onAcheter({ item, vendeur, acheteur, tailleLot, prixLot, nbLots, quantiteIllimite, chatMessageIdVente }) {
|
||||
const venteData = {
|
||||
item,
|
||||
actingUserId: game.user.id,
|
||||
vendeurId: vendeur?.id,
|
||||
vendeur,
|
||||
acheteur,
|
||||
tailleLot,
|
||||
quantiteIllimite,
|
||||
quantiteNbLots: nbLots,
|
||||
choix: { seForcer: false, supprimerSiZero: true },
|
||||
prixLot,
|
||||
isVente: prixLot > 0,
|
||||
isConsommable: item.type == 'nourritureboisson' && acheteur?.isPersonnage(),
|
||||
chatMessageIdVente
|
||||
};
|
||||
|
||||
DialogItemAchat.changeNombreLots(venteData, 1);
|
||||
const html = await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/dialog-item-achat.html`, venteData);
|
||||
const dialog = new DialogItemAchat(html, venteData);
|
||||
dialog.render(true);
|
||||
new DialogItemAchat(html, venteData).render(true);
|
||||
}
|
||||
|
||||
static changeNombreLots(venteData, nombreLots) {
|
||||
venteData.choix.nombreLots = nombreLots;
|
||||
venteData.prixTotal = (nombreLots * venteData.prixLot).toFixed(2);
|
||||
if (venteData.isConsommable) {
|
||||
const doses = nombreLots * venteData.tailleLot;
|
||||
venteData.totalSust = Misc.keepDecimals(doses * (venteData.item.system.sust ?? 0), 2);
|
||||
venteData.totalDesaltere = venteData.item.system.boisson
|
||||
? Misc.keepDecimals(doses * (venteData.item.system.desaltere ?? 0), 2)
|
||||
: 0;
|
||||
}
|
||||
}
|
||||
|
||||
constructor(html, venteData) {
|
||||
const isConsommable = venteData.item.type == 'nourritureboisson' && venteData.acheteur?.isPersonnage();
|
||||
let options = { classes: ["dialogachat"], width: 400, height: 'fit-content', 'z-index': 99999 };
|
||||
|
||||
const actionAchat = venteData.prixLot > 0 ? "Acheter" : "Prendre";
|
||||
const buttons = {};
|
||||
if (isConsommable) {
|
||||
if (venteData.isConsommable) {
|
||||
buttons["consommer"] = { label: venteData.item.system.boisson ? "Boire" : "Manger", callback: it => this.onAchatConsommer() }
|
||||
}
|
||||
buttons[actionAchat] = { label: actionAchat, callback: it => { this.onAchat(); } };
|
||||
buttons["decliner"] = { label: "Décliner", callback: it => { } };
|
||||
const acheteur = venteData.acheteur?.name ?? 'Un acheteur';
|
||||
const vendeur = venteData.vendeur?.name ?? 'Un vendeur';
|
||||
let conf = {
|
||||
title: venteData.acheteur ? venteData.acheteur.name + " - " + actionAchat : actionAchat,
|
||||
title: `${acheteur} - ${actionAchat} à ${vendeur}`,
|
||||
content: html,
|
||||
default: actionAchat,
|
||||
buttons: buttons
|
||||
};
|
||||
|
||||
super(conf, options);
|
||||
|
||||
this.venteData = venteData;
|
||||
}
|
||||
|
||||
async onAchat() {
|
||||
await $(".nombreLots").change();
|
||||
await this.html.find(".nombreLots").change();
|
||||
(this.venteData.vendeur ?? this.venteData.acheteur).achatVente({
|
||||
userId: game.user.id,
|
||||
vendeurId: this.venteData.vendeur?.id,
|
||||
@ -90,9 +108,9 @@ export class DialogItemAchat extends Dialog {
|
||||
/* -------------------------------------------- */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
|
||||
html.find(".nombreLots").change(event => this.setNombreLots(Number(event.currentTarget.value)));
|
||||
html.find(".se-forcer").change(event => this.setSeForcer(event));
|
||||
this.html = html;
|
||||
this.html.find(".nombreLots").change(event => this.setNombreLots(Number(event.currentTarget.value)));
|
||||
this.html.find(".se-forcer").change(event => this.setSeForcer(event));
|
||||
}
|
||||
|
||||
setSeForcer(event) {
|
||||
@ -100,13 +118,21 @@ export class DialogItemAchat extends Dialog {
|
||||
}
|
||||
|
||||
setNombreLots(nombreLots) {
|
||||
if (nombreLots > this.venteData.quantiteNbLots) {
|
||||
ui.notifications.warn(`Seulement ${this.venteData.quantiteNbLots} lots disponibles, vous ne pouvez pas en prendre ${nombreLots}`)
|
||||
|
||||
if (!this.venteData.quantiteIllimite) {
|
||||
if (!this.venteData.quantiteIllimite && nombreLots > this.venteData.quantiteNbLots) {
|
||||
ui.notifications.warn(`Seulement ${this.venteData.quantiteNbLots} lots disponibles, vous ne pouvez pas en prendre ${nombreLots}`)
|
||||
}
|
||||
nombreLots = Math.min(nombreLots, this.venteData.quantiteNbLots);
|
||||
}
|
||||
this.venteData.choix.nombreLots = Math.min(nombreLots, this.venteData.quantiteNbLots);
|
||||
this.venteData.prixTotal = (nombreLots * this.venteData.prixLot).toFixed(2);
|
||||
$(".nombreLots").val(this.venteData.choix.nombreLots);
|
||||
$(".prixTotal").text(this.venteData.prixTotal);
|
||||
|
||||
DialogItemAchat.changeNombreLots(this.venteData, nombreLots);
|
||||
|
||||
this.html.find(".nombreLots").val(nombreLots);
|
||||
this.html.find(".prixTotal").text(this.venteData.prixTotal);
|
||||
this.html.find("span.total-sust").text(this.venteData.totalSust);
|
||||
this.html.find("span.total-desaltere").text(this.venteData.totalDesaltere);
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -2,13 +2,13 @@ import { Misc } from "./misc.js";
|
||||
|
||||
export class DialogConsommer extends Dialog {
|
||||
|
||||
static async create(actor, item, onActionItem = async ()=>{}) {
|
||||
static async create(actor, item, onActionItem = async () => { }) {
|
||||
const consommerData = DialogConsommer.prepareData(actor, item);
|
||||
const html = await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/dialog-item-consommer.html', consommerData);
|
||||
return new DialogConsommer(actor, item, consommerData, html, onActionItem)
|
||||
}
|
||||
|
||||
constructor(actor, item, consommerData, html, onActionItem = async ()=>{}) {
|
||||
constructor(actor, item, consommerData, html, onActionItem = async () => { }) {
|
||||
const options = { classes: ["dialogconsommer"], width: 350, height: 'fit-content', 'z-index': 99999 };
|
||||
let conf = {
|
||||
title: consommerData.title,
|
||||
@ -17,8 +17,9 @@ export class DialogConsommer extends Dialog {
|
||||
buttons: {
|
||||
[consommerData.buttonName]: {
|
||||
label: consommerData.buttonName, callback: async it => {
|
||||
await this.onConsommer(it);
|
||||
await onActionItem();}
|
||||
await this.onConsommer();
|
||||
await onActionItem();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -30,17 +31,23 @@ export class DialogConsommer extends Dialog {
|
||||
this.consommerData = consommerData;
|
||||
}
|
||||
|
||||
async onConsommer(event) {
|
||||
await $(".se-forcer").change();
|
||||
await $(".consommer-doses").change();
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
this.html = html;
|
||||
this.html.find(".se-forcer").change(event => this.setSeForcer(event));
|
||||
this.html.find(".consommer-doses").change(event => this.selectDoses(event));
|
||||
}
|
||||
|
||||
async onConsommer() {
|
||||
await this.html.find(".se-forcer").change();
|
||||
await this.html.find(".consommer-doses").change();
|
||||
await this.actor.consommer(this.item, this.consommerData.choix);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static prepareData(actor, item) {
|
||||
item = duplicate(item);
|
||||
let consommerData = {
|
||||
item: item,
|
||||
item: duplicate(item),
|
||||
cuisine: actor.getCompetence('cuisine'),
|
||||
choix: {
|
||||
doses: 1,
|
||||
@ -48,33 +55,47 @@ export class DialogConsommer extends Dialog {
|
||||
}
|
||||
}
|
||||
switch (item.type) {
|
||||
case 'herbe': case 'faune':
|
||||
consommerData.title = 'Manger une portion crue: ';
|
||||
consommerData.buttonName = "Manger";
|
||||
break;
|
||||
case 'nourritureboisson':
|
||||
consommerData.title = item.system.boisson ? `${item.name}: boire une dose` : `${item.name}: manger une portion`;
|
||||
consommerData.title = item.system.boisson ? 'Boire une dose: ' : 'Manger une portion: ';
|
||||
consommerData.buttonName = item.system.boisson ? "Boire" : "Manger";
|
||||
break;
|
||||
case 'potion':
|
||||
consommerData.title = `${item.name}: boire la potion`;
|
||||
consommerData.title = 'Boire la potion: ';
|
||||
consommerData.buttonName = "Boire";
|
||||
break;
|
||||
}
|
||||
DialogConsommer.calculDoses(consommerData, consommerData.choix.doses)
|
||||
consommerData.title += item.name;
|
||||
DialogConsommer.calculDoses(consommerData, item)
|
||||
return consommerData;
|
||||
}
|
||||
|
||||
static calculDoses(consommer) {
|
||||
static calculDoses(consommer, item) {
|
||||
const doses = consommer.choix.doses;
|
||||
consommer.totalSust = Misc.keepDecimals(doses * (consommer.item.system.sust ?? 0), 2);
|
||||
consommer.totalDesaltere = consommer.item.system.boisson
|
||||
? Misc.keepDecimals(doses * (consommer.item.system.desaltere ?? 0), 2)
|
||||
: 0;
|
||||
}
|
||||
|
||||
|
||||
/* -------------------------------------------- */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
html.find(".se-forcer").change(event => this.setSeForcer(event));
|
||||
html.find(".consommer-doses").change(event => this.selectDoses(event));
|
||||
switch (item.type) {
|
||||
case 'herbe': case 'faune':
|
||||
consommer.totalSust = doses;
|
||||
consommer.totalDesaltere = 0;
|
||||
consommer.choix.sust = 1;
|
||||
consommer.choix.quantite = 0;
|
||||
consommer.choix.encombrement = Misc.keepDecimals(consommer.item.system.encombrement / item.system.sust, 2);
|
||||
return;
|
||||
case 'nourritureboisson':
|
||||
consommer.choix.sust = consommer.item.system.sust;
|
||||
consommer.choix.quantite = doses;
|
||||
consommer.choix.encombrement = 0
|
||||
consommer.totalSust = Misc.keepDecimals(doses * (consommer.item.system.sust ?? 0), 2);
|
||||
consommer.totalDesaltere = consommer.item.system.boisson
|
||||
? Misc.keepDecimals(doses * (consommer.item.system.desaltere ?? 0), 2)
|
||||
: 0;
|
||||
break;
|
||||
case 'potion':
|
||||
consommer.totalSust = 0
|
||||
consommer.totalDesaltere = 0
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -84,8 +105,8 @@ export class DialogConsommer extends Dialog {
|
||||
|
||||
selectDoses(event) {
|
||||
this.consommerData.choix.doses = Number(event.currentTarget.value);
|
||||
DialogConsommer.calculDoses(this.consommerData);
|
||||
$(".total-sust").text(this.consommerData.totalSust);
|
||||
$(".total-desaltere").text(this.consommerData.totalDesaltere);
|
||||
DialogConsommer.calculDoses(this.consommerData, this.item);
|
||||
this.html.find(".total-sust").text(this.consommerData.totalSust);
|
||||
this.html.find(".total-desaltere").text(this.consommerData.totalDesaltere);
|
||||
}
|
||||
}
|
@ -2,21 +2,22 @@ import { HtmlUtility } from "./html-utility.js";
|
||||
|
||||
export class DialogItemVente extends Dialog {
|
||||
|
||||
static async display(item, callback) {
|
||||
const quantite = item.isConteneur() ? 1 : item.system.quantite;
|
||||
static async display({ item, callback, quantiteMax = undefined }) {
|
||||
const quantite = quantiteMax ?? item.getQuantite() ?? 1;
|
||||
const isOwned = item.parent;
|
||||
const venteData = {
|
||||
item: item,
|
||||
alias: item.actor?.name ?? game.user.name,
|
||||
vendeurId: item.actor?.id,
|
||||
prixOrigine: item.system.cout,
|
||||
prixUnitaire: item.system.cout,
|
||||
prixLot: item.system.cout,
|
||||
vendeurId: item.actor?.id ,
|
||||
prixOrigine: item.calculerPrixCommercant(),
|
||||
prixUnitaire: item.calculerPrixCommercant(),
|
||||
prixLot: item.calculerPrixCommercant(),
|
||||
tailleLot: 1,
|
||||
quantiteNbLots: quantite,
|
||||
quantiteMaxLots: quantite,
|
||||
quantiteMax: quantite ,
|
||||
quantiteIllimite: !item.isOwned,
|
||||
isOwned: item.isOwned,
|
||||
quantiteMax: quantite,
|
||||
quantiteIllimite: item.isItemCommerce() ? quantiteMax == undefined : !isOwned,
|
||||
isOwned: isOwned,
|
||||
};
|
||||
const html = await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/dialog-item-vente.html`, venteData);
|
||||
return new DialogItemVente(venteData, html, callback).render(true);
|
||||
@ -37,26 +38,25 @@ export class DialogItemVente extends Dialog {
|
||||
this.venteData = venteData;
|
||||
}
|
||||
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
this.html = html;
|
||||
this.setQuantiteIllimite(this.venteData.quantiteIllimite);
|
||||
this.html.find(".tailleLot").change(event => this.setTailleLot(Number(event.currentTarget.value)));
|
||||
this.html.find(".quantiteNbLots").change(event => this.setNbLots(Number(event.currentTarget.value)));
|
||||
this.html.find(".quantiteIllimite").change(event => this.setQuantiteIllimite(event.currentTarget.checked));
|
||||
this.html.find(".prixLot").change(event => this.setPrixLot(Number(event.currentTarget.value)));
|
||||
}
|
||||
|
||||
async onProposer(it) {
|
||||
await $(".tailleLot").change();
|
||||
await $(".quantiteNbLots").change();
|
||||
await $(".quantiteIllimite").change();
|
||||
await $(".prixLot").change();
|
||||
await this.html.find(".tailleLot").change();
|
||||
await this.html.find(".quantiteNbLots").change();
|
||||
await this.html.find(".quantiteIllimite").change();
|
||||
await this.html.find(".prixLot").change();
|
||||
this.callback(this.venteData);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
|
||||
HtmlUtility._showControlWhen($(".quantiteNbLots"), !this.venteData.quantiteIllimite)
|
||||
|
||||
html.find(".tailleLot").change(event => this.setTailleLot(Number(event.currentTarget.value)));
|
||||
html.find(".quantiteNbLots").change(event => this.setNbLots(Number(event.currentTarget.value)));
|
||||
html.find(".quantiteIllimite").change(event => this.setQuantiteIllimite(event.currentTarget.checked));
|
||||
html.find(".prixLot").change(event => this.setPrixLot(Number(event.currentTarget.value)));
|
||||
}
|
||||
|
||||
setPrixLot(prixLot) {
|
||||
this.venteData.prixLot = prixLot;
|
||||
}
|
||||
@ -65,16 +65,14 @@ export class DialogItemVente extends Dialog {
|
||||
// recalculer le prix du lot
|
||||
if (tailleLot != this.venteData.tailleLot) {
|
||||
this.venteData.prixLot = (tailleLot * this.venteData.prixOrigine).toFixed(2);
|
||||
$(".prixLot").val(this.venteData.prixLot);
|
||||
this.html.find(".prixLot").val(this.venteData.prixLot);
|
||||
}
|
||||
this.venteData.tailleLot = tailleLot;
|
||||
if (this.venteData.isOwned) {
|
||||
// recalculer le nombre de lots max
|
||||
this.venteData.quantiteMaxLots = Math.floor(this.venteData.quantiteMax / tailleLot);
|
||||
this.venteData.quantiteNbLots = Math.min(this.venteData.quantiteMaxLots, this.venteData.quantiteNbLots);
|
||||
$(".quantiteNbLots").val(this.venteData.quantiteNbLots);
|
||||
$(".quantiteNbLots").attr("max", this.venteData.quantiteMaxLots)
|
||||
}
|
||||
// recalculer le nombre de lots max
|
||||
this.venteData.quantiteMaxLots = Math.floor(this.venteData.quantiteMax / tailleLot);
|
||||
this.venteData.quantiteNbLots = Math.min(this.venteData.quantiteMaxLots, this.venteData.quantiteNbLots);
|
||||
this.html.find(".quantiteNbLots").val(this.venteData.quantiteNbLots);
|
||||
this.html.find(".quantiteNbLots").attr("max", this.venteData.quantiteMaxLots)
|
||||
}
|
||||
|
||||
setNbLots(nbLots) {
|
||||
@ -82,12 +80,12 @@ export class DialogItemVente extends Dialog {
|
||||
nbLots = Math.max(0, Math.min(nbLots, this.venteData.quantiteMaxLots));
|
||||
}
|
||||
this.venteData.quantiteNbLots = nbLots;
|
||||
$(".quantiteNbLots").val(this.venteData.quantiteNbLots);
|
||||
this.html.find(".quantiteNbLots").val(this.venteData.quantiteNbLots);
|
||||
}
|
||||
|
||||
setQuantiteIllimite(checked) {
|
||||
this.venteData.quantiteIllimite = checked;
|
||||
$(".label-quantiteIllimite").text(this.venteData.quantiteIllimite ? "Illimités" : "disponibles");
|
||||
HtmlUtility._showControlWhen($(".quantiteNbLots"), !this.venteData.quantiteIllimite)
|
||||
this.html.find(".label-quantiteIllimite").text(this.venteData.quantiteIllimite ? "Illimités" : "disponibles");
|
||||
HtmlUtility._showControlWhen(this.html.find(".quantiteNbLots"), !this.venteData.quantiteIllimite)
|
||||
}
|
||||
}
|
@ -1,4 +1,3 @@
|
||||
import { Misc } from "./misc.js";
|
||||
|
||||
export class DialogRepos extends Dialog {
|
||||
|
||||
@ -9,7 +8,7 @@ export class DialogRepos extends Dialog {
|
||||
}
|
||||
|
||||
constructor(html, actor) {
|
||||
let options = { classes: ["DialogCreateSigneDraconiqueActorsActors"], width: 500, height: 400, 'z-index': 99999 };
|
||||
let options = { classes: ["DialogCreateSigneDraconiqueActorsActors"], width: 400, height: 'fit-content', 'z-index': 99999 };
|
||||
let conf = {
|
||||
title: "Se reposer",
|
||||
content: html,
|
||||
@ -21,13 +20,19 @@ export class DialogRepos extends Dialog {
|
||||
super(conf, options);
|
||||
this.actor = actor;
|
||||
}
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
this.html = html;
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
|
||||
async repos() {
|
||||
await $("[name='nb-heures']").change();
|
||||
await $("[name='nb-jours']").change();
|
||||
const selection = await $("[name='repos']:checked").val();
|
||||
const nbHeures = Number.parseInt(await $("[name='nb-heures']").val());
|
||||
const nbJours = Number.parseInt(await $("[name='nb-jours']").val());
|
||||
await this.html.find("[name='nb-heures']").change();
|
||||
await this.html.find("[name='nb-jours']").change();
|
||||
const selection = await this.html.find("[name='repos']:checked").val();
|
||||
const nbHeures = Number.parseInt(await this.html.find("[name='nb-heures']").val());
|
||||
const nbJours = Number.parseInt(await this.html.find("[name='nb-jours']").val());
|
||||
console.log("ACTOR", this.actor)
|
||||
switch (selection) {
|
||||
case "sieste": {
|
||||
await this.actor.dormir(nbHeures);
|
||||
@ -35,7 +40,7 @@ export class DialogRepos extends Dialog {
|
||||
}
|
||||
case "nuit": {
|
||||
let heuresDormies = await this.actor.dormir(nbHeures);
|
||||
if (heuresDormies == nbHeures){
|
||||
if (heuresDormies == nbHeures) {
|
||||
await this.actor.dormirChateauDormant();
|
||||
}
|
||||
return;
|
||||
@ -49,8 +54,4 @@ export class DialogRepos extends Dialog {
|
||||
}
|
||||
}
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
}
|
||||
}
|
@ -20,8 +20,9 @@ export class DialogSelectTarget extends Dialog {
|
||||
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
html.find("li.select-target").click((event) => {
|
||||
this.targetSelected($(event.currentTarget)?.data("token-id"));
|
||||
this.html = html;
|
||||
this.html.find("li.select-target").click((event) => {
|
||||
this.targetSelected(this.html.find(event.currentTarget)?.data("token-id"));
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -12,40 +12,34 @@ export class DialogSplitItem extends Dialog {
|
||||
}
|
||||
|
||||
constructor(item, splitData, html, callback) {
|
||||
let options = { classes: ["dialogsplit"], width: 300, height: 160, 'z-index': 99999 };
|
||||
|
||||
let options = { classes: ["dialogsplit"], width: 300, height: 'fit-content', 'z-index': 99999 };
|
||||
let conf = {
|
||||
title: "Séparer en deux",
|
||||
content: html,
|
||||
default: "separer",
|
||||
buttons: {
|
||||
"separer": {
|
||||
label: "Séparer", callback: it => {
|
||||
this.onSplit();
|
||||
}
|
||||
}
|
||||
"separer": { label: "Séparer", callback: it => this.onSplit() }
|
||||
}
|
||||
};
|
||||
|
||||
super(conf, options);
|
||||
|
||||
|
||||
this.callback = callback;
|
||||
this.item = item;
|
||||
this.splitData = splitData;
|
||||
}
|
||||
|
||||
async onSplit(){
|
||||
await $(".choix-quantite").change();
|
||||
this.callback(this.item, this.splitData.choix.quantite);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
|
||||
html.find(".choix-quantite").change(event => {
|
||||
this.html = html;
|
||||
this.html.find(".choix-quantite").change(event => {
|
||||
this.splitData.choix.quantite = Number(event.currentTarget.value);
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async onSplit() {
|
||||
await this.html.find(".choix-quantite").change();
|
||||
this.callback(this.item, this.splitData.choix.quantite);
|
||||
}
|
||||
|
||||
}
|
@ -37,24 +37,24 @@ export class DialogStress extends Dialog {
|
||||
this.dialogData = dialogData;
|
||||
}
|
||||
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
this.html = html;
|
||||
this.html.find("input.select-actor").change((event) => this.onSelectActor(event));
|
||||
}
|
||||
|
||||
async onStress() {
|
||||
const motif = $("form.rdddialogstress input[name='motif']").val();
|
||||
const stress = Number($("form.rdddialogstress input[name='stress']").val());
|
||||
const compteur = ($("form.rdddialogstress input[name='immediat']").prop("checked")) ? 'experience' : 'stress';
|
||||
const motif = this.html.find("form.rdddialogstress input[name='motif']").val();
|
||||
const stress = Number(this.html.find("form.rdddialogstress input[name='stress']").val());
|
||||
const compteur = (this.html.find("form.rdddialogstress input[name='immediat']").prop("checked")) ? 'experience' : 'stress';
|
||||
|
||||
this.dialogData.actors.filter(it => it.selected)
|
||||
.map(it => game.actors.get(it.id))
|
||||
.forEach(actor => actor.distribuerStress(compteur, stress, motif));
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
html.find("input.select-actor").change((event) => this.onSelectActor(event));
|
||||
}
|
||||
|
||||
async onSelectActor(event) {
|
||||
const actorId = $(event.currentTarget)?.data("actor-id");
|
||||
const actorId = this.html.find(event.currentTarget)?.data("actor-id");
|
||||
const actor = this.dialogData.actors.find(it => it.id == actorId);
|
||||
if (actor) {
|
||||
actor.selected = event.currentTarget.checked;
|
||||
|
@ -35,7 +35,7 @@ export class DialogValidationEncaissement extends Dialog {
|
||||
}
|
||||
|
||||
let dialogOptions = {
|
||||
classes: ["rdddialog"],
|
||||
classes: ["rdd-roll-dialog"],
|
||||
width: 350,
|
||||
height: 290
|
||||
}
|
||||
@ -55,11 +55,12 @@ export class DialogValidationEncaissement extends Dialog {
|
||||
/* -------------------------------------------- */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
html.find('input.encaissement-roll-result').keyup(async event => {
|
||||
this.html = html;
|
||||
this.html.find('input.encaissement-roll-result').keyup(async event => {
|
||||
this.forceDiceResult.total = event.currentTarget.value;
|
||||
this.encaissement = await RdDUtility.jetEncaissement(this.rollData, this.armure, { showDice: HIDE_DICE, forceDiceResult: this.forceDiceResult});
|
||||
$('label.encaissement-total').text(this.encaissement.total);
|
||||
$('label.encaissement-blessure').text(this.encaissement.blessures)
|
||||
this.html.find('label.encaissement-total').text(this.encaissement.total);
|
||||
this.html.find('label.encaissement-blessure').text(this.encaissement.blessures)
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -1,30 +1,29 @@
|
||||
import { SYSTEM_RDD } from "./constants.js";
|
||||
import { Grammar } from "./grammar.js";
|
||||
import { Misc } from "./misc.js";
|
||||
import { CompendiumTableHelpers, SystemCompendiums, CompendiumTable } from "./settings/system-compendiums.js";
|
||||
import { CompendiumTableHelpers, CompendiumTable } from "./settings/system-compendiums.js";
|
||||
|
||||
const RARETES = [
|
||||
{ name: 'Commune', frequence: 54, min: 27, max: 108 },
|
||||
{ name: 'Frequente', frequence: 18, min: 9, max: 36 },
|
||||
{ name: 'Rare', frequence: 6, min: 3, max: 12 },
|
||||
{ name: 'Rarissime', frequence: 2, min: 1, max: 4 }]
|
||||
const DEFAULT_RARETE = 1;
|
||||
|
||||
const SETTINGS_LISTE_MILIEUX = "liste-milieux";
|
||||
const MILIEUX = [
|
||||
"Collines",
|
||||
"Cours d'eau",
|
||||
"Déserts",
|
||||
"Désolations",
|
||||
"Forêts",
|
||||
"Forêts Tropicales",
|
||||
"Marais",
|
||||
"Milieux Aquatiques",
|
||||
"Milieux Maritimes",
|
||||
"Maritimes",
|
||||
"Montagnes",
|
||||
"Plaines",
|
||||
"Sous-Sols",
|
||||
"Sous-sols"
|
||||
]
|
||||
const ITEM_ENVIRONNEMENT_TYPES = [
|
||||
'herbe', 'ingredient'
|
||||
'herbe', 'ingredient', 'faune'
|
||||
]
|
||||
|
||||
export class Environnement {
|
||||
@ -46,7 +45,7 @@ export class Environnement {
|
||||
}
|
||||
|
||||
static getRarete(name = undefined) {
|
||||
return RARETES.find(it => it.name == name) ?? RARETES[0];
|
||||
return RARETES.find(it => it.name == name) ?? RARETES[DEFAULT_RARETE];
|
||||
}
|
||||
|
||||
static getFrequenceRarete(rarete, field = undefined) {
|
||||
@ -55,25 +54,45 @@ export class Environnement {
|
||||
}
|
||||
|
||||
async milieux() {
|
||||
const milieux = new Set(this.getMilieuxSettings());
|
||||
const elements = await this.getElements(it => 1, it => ITEM_ENVIRONNEMENT_TYPES.includes(it.type));
|
||||
elements.forEach(it => it.system.environnement.forEach(env => milieux.add(env.milieu)))
|
||||
return [...milieux].filter(env => env);
|
||||
return Object.values(await this.mapMilieux());
|
||||
}
|
||||
|
||||
async mapMilieux() {
|
||||
const compendiumItems = await this.getElements(it => 1, it => ITEM_ENVIRONNEMENT_TYPES.includes(it.type));
|
||||
return Misc.indexLowercase(this.getMilieuxSettings().concat(Environnement.listMilieux(compendiumItems)));
|
||||
}
|
||||
|
||||
static listMilieux(items) {
|
||||
return Misc.concat(items.map(it => Environnement.$itemToMilieux(it).filter(m => m)));
|
||||
}
|
||||
|
||||
async autresMilieux(item) {
|
||||
const mapMilieux = await this.mapMilieux();
|
||||
const milieuxExistants = Environnement.$itemToMilieux(item).map(it => Grammar.toLowerCaseNoAccent(it));
|
||||
return Object.keys(mapMilieux)
|
||||
.filter(it => !milieuxExistants.includes(it))
|
||||
.map(it => mapMilieux[it]);
|
||||
}
|
||||
|
||||
static $itemToMilieux(item) {
|
||||
return item.system.environnement.map(env => env.milieu);
|
||||
}
|
||||
|
||||
getMilieuxSettings() {
|
||||
return game.settings.get(SYSTEM_RDD, SETTINGS_LISTE_MILIEUX).split(',');
|
||||
return game.settings.get(SYSTEM_RDD, SETTINGS_LISTE_MILIEUX).split(',').map(it => it.trim()).filter(it => it != '');
|
||||
}
|
||||
|
||||
async findEnvironnementsLike(search) {
|
||||
const milieux = (await this.milieux()).filter(it => Grammar.includesLowerCaseNoAccent(it, search));
|
||||
if (milieux.length > 1){
|
||||
const milieuExact = milieux.find(it => Grammar.equalsInsensitive(it, search));
|
||||
const milieux = await this.mapMilieux();
|
||||
const searchLower = Grammar.toLowerCaseNoAccent(search);
|
||||
const keys = Object.keys(milieux).filter(it => it.includes(searchLower));
|
||||
if (keys.length > 1) {
|
||||
const milieuExact = milieux[searchLower];
|
||||
if (milieuExact) {
|
||||
return [milieuExact];
|
||||
}
|
||||
}
|
||||
return milieux;
|
||||
return keys.map(k => milieux[k]);
|
||||
}
|
||||
|
||||
async searchToChatMessage(milieux, typeName) {
|
||||
@ -107,22 +126,12 @@ export class Environnement {
|
||||
|
||||
export class EnvironmentSheetHelper {
|
||||
|
||||
static defaultOptions(defaultOptions, type) {
|
||||
static defaultOptions(defaultOptions) {
|
||||
return mergeObject(defaultOptions, {
|
||||
classes: ["rdd", "sheet", "item"],
|
||||
template: `systems/foundryvtt-reve-de-dragon/templates/item-${type}-sheet.html`,
|
||||
width: 500,
|
||||
height: 600,
|
||||
tabs: [{ navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "informations" }]
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static getHeaderButtons(sheet, buttons) {
|
||||
buttons.unshift({ class: "post", icon: "fas fa-comment", onclick: ev => sheet.item.postItem() });
|
||||
return buttons;
|
||||
}
|
||||
|
||||
static setPosition(sheet, superPosition) {
|
||||
const position = superPosition;
|
||||
const sheetHeader = sheet.element.find(".sheet-header");
|
||||
@ -132,44 +141,45 @@ export class EnvironmentSheetHelper {
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static async getData(sheet) {
|
||||
const formData = duplicate(sheet.item);
|
||||
const milieux = await game.system.rdd.environnement.milieux();
|
||||
const milieuxDisponibles = milieux.filter(it => !sheet.item.system.environnement.find(e => e.milieu == it));
|
||||
mergeObject(formData, {
|
||||
title: formData.name,
|
||||
isGM: game.user.isGM,
|
||||
owner: sheet.actor?.isOwner,
|
||||
isOwned: sheet.actor ? true : false,
|
||||
actorId: sheet.actor?.id,
|
||||
editable: sheet.isEditable,
|
||||
cssClass: sheet.isEditable ? "editable" : "locked",
|
||||
milieux: milieuxDisponibles
|
||||
static async getData(sheet, formData) {
|
||||
return mergeObject(formData, {
|
||||
milieux: await game.system.rdd.environnement.autresMilieux(sheet.item)
|
||||
});
|
||||
return formData;
|
||||
}
|
||||
|
||||
static activateListeners(sheet, html) {
|
||||
static activateListeners(sheet) {
|
||||
if (!sheet.options.editable) return;
|
||||
html.find("a.milieu-add").click(event => EnvironmentSheetHelper.onAddMilieu(html, sheet, event));
|
||||
html.find("div.environnement-milieu a.milieu-delete").click(event => EnvironmentSheetHelper.onDeleteMilieu(sheet, event));
|
||||
html.find("div.environnement-milieu select.environnement-rarete").change(event => EnvironmentSheetHelper.onChange(sheet, event,
|
||||
(updated) => {
|
||||
const name = $(event.currentTarget).val();
|
||||
const rarete = Environnement.getRarete(name);
|
||||
updated.rarete = rarete.name;
|
||||
updated.frequence = Math.min(
|
||||
Math.max(rarete.min, updated.frequence ?? rarete.frequence),
|
||||
rarete.max);
|
||||
}));
|
||||
html.find("div.environnement-milieu input[name='environnement-frequence']").change(event => EnvironmentSheetHelper.onChange(sheet, event,
|
||||
(updated) => {
|
||||
updated.frequence = Number($(event.currentTarget).val())
|
||||
}));
|
||||
|
||||
sheet.html.find("input.input-selection-milieu").keypress(event => {
|
||||
if (event.keyCode == '13') {
|
||||
EnvironmentSheetHelper.onAddMilieu(sheet, event);
|
||||
}
|
||||
event.stopPropagation();
|
||||
})
|
||||
sheet.html.find("a.milieu-add").click(event => EnvironmentSheetHelper.onAddMilieu(sheet, event));
|
||||
sheet.html.find("div.environnement-milieu a.milieu-delete").click(event => EnvironmentSheetHelper.onDeleteMilieu(sheet, event));
|
||||
sheet.html.find("div.environnement-milieu select.environnement-rarete").change(event => EnvironmentSheetHelper.onChange(sheet, event,
|
||||
updated => EnvironmentSheetHelper.$changeRarete(sheet, event, updated)));
|
||||
sheet.html.find("div.environnement-milieu input[name='environnement-frequence']").change(event => EnvironmentSheetHelper.onChange(sheet, event,
|
||||
updated => EnvironmentSheetHelper.$changeFrequence(sheet, event, updated)));
|
||||
}
|
||||
|
||||
static async onAddMilieu(html, sheet, event) {
|
||||
const milieu = html.find('input.input-selection-milieu').val();
|
||||
static $changeFrequence(sheet, event, updated) {
|
||||
updated.frequence = Number(sheet.html.find(event.currentTarget).val());
|
||||
}
|
||||
|
||||
static $changeRarete(sheet, event, updated) {
|
||||
const name = sheet.html.find(event.currentTarget).val();
|
||||
const rarete = Environnement.getRarete(name);
|
||||
updated.rarete = rarete.name;
|
||||
updated.frequence = rarete.frequence;
|
||||
// updated.frequence = Math.min(
|
||||
// Math.max(rarete.min, updated.frequence ?? rarete.frequence),
|
||||
// rarete.max);
|
||||
}
|
||||
|
||||
static async onAddMilieu(sheet, event) {
|
||||
const milieu = sheet.html.find('input.input-selection-milieu').val();
|
||||
if (!milieu) {
|
||||
ui.notifications.warn(`Choisissez le milieu dans lequel se trouve le/la ${sheet.item.name}`);
|
||||
return
|
||||
@ -186,8 +196,8 @@ export class EnvironmentSheetHelper {
|
||||
}
|
||||
|
||||
static async onDeleteMilieu(sheet, event) {
|
||||
const milieu = EnvironmentSheetHelper.$getEventMilieu(event);
|
||||
if (milieu) {
|
||||
const milieu = EnvironmentSheetHelper.$getEventMilieu(sheet, event);
|
||||
if (milieu != undefined) {
|
||||
const newList = sheet.item.system.environnement.filter(it => it.milieu != milieu)
|
||||
.sort(Misc.ascending(it => it.milieu));
|
||||
await sheet.item.update({ 'system.environnement': newList });
|
||||
@ -196,7 +206,7 @@ export class EnvironmentSheetHelper {
|
||||
|
||||
static async onChange(sheet, event, doMutation) {
|
||||
const list = sheet.item.system.environnement;
|
||||
const milieu = EnvironmentSheetHelper.$getEventMilieu(event);
|
||||
const milieu = EnvironmentSheetHelper.$getEventMilieu(sheet, event);
|
||||
const updated = list.find(it => it.milieu == milieu);
|
||||
if (updated) {
|
||||
doMutation(updated);
|
||||
@ -206,17 +216,8 @@ export class EnvironmentSheetHelper {
|
||||
}
|
||||
}
|
||||
|
||||
static $getEventMilieu(event) {
|
||||
return $(event.currentTarget)?.parents("div.environnement-milieu").data("milieu");
|
||||
}
|
||||
|
||||
static template(itemType) {
|
||||
/* -------------------------------------------- */
|
||||
return `systems/foundryvtt-reve-de-dragon/templates/item-${itemType}-sheet.html`;
|
||||
}
|
||||
|
||||
static title(item) {
|
||||
return Misc.typeName('Item', item.type) + ': ' + item.name;
|
||||
static $getEventMilieu(sheet, event) {
|
||||
return sheet.html.find(event.currentTarget)?.parents("div.environnement-milieu").data("milieu");
|
||||
}
|
||||
|
||||
}
|
@ -1,10 +1,10 @@
|
||||
export class HtmlUtility{
|
||||
static _showControlWhen(control, condition) {
|
||||
static _showControlWhen(jQuerySelector, condition) {
|
||||
if (condition) {
|
||||
control.show();
|
||||
jQuerySelector.show();
|
||||
}
|
||||
else {
|
||||
control.hide();
|
||||
jQuerySelector.hide();
|
||||
}
|
||||
}
|
||||
}
|
@ -8,18 +8,18 @@ const xp_par_niveau = [5, 5, 5, 10, 10, 10, 10, 15, 15, 15, 15, 20, 20, 20, 20,
|
||||
const niveau_max = xp_par_niveau.length - 10;
|
||||
/* -------------------------------------------- */
|
||||
const limitesArchetypes = [
|
||||
{ "niveau": 0, "nombreMax": 100, "nombre": 0 },
|
||||
{ "niveau": 1, "nombreMax": 10, "nombre": 0 },
|
||||
{ "niveau": 2, "nombreMax": 9, "nombre": 0 },
|
||||
{ "niveau": 3, "nombreMax": 8, "nombre": 0 },
|
||||
{ "niveau": 4, "nombreMax": 7, "nombre": 0 },
|
||||
{ "niveau": 5, "nombreMax": 6, "nombre": 0 },
|
||||
{ "niveau": 6, "nombreMax": 5, "nombre": 0 },
|
||||
{ "niveau": 7, "nombreMax": 4, "nombre": 0 },
|
||||
{ "niveau": 8, "nombreMax": 3, "nombre": 0 },
|
||||
{ "niveau": 9, "nombreMax": 2, "nombre": 0 },
|
||||
{ "niveau": 10, "nombreMax": 1, "nombre": 0 },
|
||||
{ "niveau": 11, "nombreMax": 1, "nombre": 0 }
|
||||
{ "niveau": 0, "nombreMax": 100, "reste": 100 },
|
||||
{ "niveau": 1, "nombreMax": 10, "reste": 10 },
|
||||
{ "niveau": 2, "nombreMax": 9, "reste": 9 },
|
||||
{ "niveau": 3, "nombreMax": 8, "reste": 8 },
|
||||
{ "niveau": 4, "nombreMax": 7, "reste": 7 },
|
||||
{ "niveau": 5, "nombreMax": 6, "reste": 6 },
|
||||
{ "niveau": 6, "nombreMax": 5, "reste": 5 },
|
||||
{ "niveau": 7, "nombreMax": 4, "reste": 4 },
|
||||
{ "niveau": 8, "nombreMax": 3, "reste": 3 },
|
||||
{ "niveau": 9, "nombreMax": 2, "reste": 2 },
|
||||
{ "niveau": 10, "nombreMax": 1, "reste": 1 },
|
||||
{ "niveau": 11, "nombreMax": 1, "reste": 1 }
|
||||
];
|
||||
|
||||
/* -------------------------------------------- */
|
||||
@ -267,18 +267,47 @@ export class RdDItemCompetence extends Item {
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static computeResumeArchetype(competences) {
|
||||
const archetype = RdDItemCompetence.getLimitesArchetypes();
|
||||
const computed = duplicate(limitesArchetypes);
|
||||
competences.map(it => Math.max(0, it.system.niveau_archetype))
|
||||
.forEach(niveau => {
|
||||
archetype[niveau] = archetype[niveau] ?? { "niveau": niveau, "nombreMax": 0, "nombre": 0 };
|
||||
archetype[niveau].nombre = (archetype[niveau]?.nombre ?? 0) + 1;
|
||||
.filter(n => n > 0)
|
||||
.forEach(n => {
|
||||
computed[n] = computed[n] ?? { niveau: n, nombreMax: 0, reste: 0 };
|
||||
computed[n].reste = computed[n].reste - 1;
|
||||
});
|
||||
return archetype;
|
||||
return computed.filter(it => it.reste > 0 && it.niveau > 0);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static getLimitesArchetypes() {
|
||||
return duplicate(limitesArchetypes);
|
||||
static triVisible(competences) {
|
||||
return competences.filter(it => it.system.isVisible)
|
||||
.sort((a, b) => RdDItemCompetence.compare(a, b))
|
||||
}
|
||||
|
||||
static $positionTri(comp) {
|
||||
if (comp.name.startsWith("Survie")) {
|
||||
if (comp.name.includes("Cité")) return 0;
|
||||
if (comp.name.includes("Extérieur")) return 1;
|
||||
return 2;
|
||||
}
|
||||
if (comp.system.categorie.startsWith("melee")) {
|
||||
if (comp.name.includes("Corps")) return 0;
|
||||
if (comp.name.includes("Dague")) return 1;
|
||||
if (comp.name.includes("Esquive")) return 2;
|
||||
return 3;
|
||||
}
|
||||
if (comp.system.categorie.startsWith("draconic")) {
|
||||
if (comp.name.includes("Oniros")) return 0;
|
||||
if (comp.name.includes("Hypnos")) return 1;
|
||||
if (comp.name.includes("Narcos")) return 2;
|
||||
if (comp.name.includes("Thanatos")) return 3;
|
||||
return 4;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static compare(a, b) {
|
||||
const diff = RdDItemCompetence.$positionTri(a) - RdDItemCompetence.$positionTri(b);
|
||||
return diff ? diff : a.name.localeCompare(b.name);
|
||||
}
|
||||
|
||||
}
|
60
module/item-conteneur-sheet.js
Normal file
@ -0,0 +1,60 @@
|
||||
import { RdDItemSheet } from "./item-sheet.js";
|
||||
import { RdDSheetUtility } from "./rdd-sheet-utility.js";
|
||||
import { RdDUtility } from "./rdd-utility.js";
|
||||
|
||||
export class RdDConteneurItemSheet extends RdDItemSheet {
|
||||
|
||||
static get ITEM_TYPE() { return "conteneur" };
|
||||
|
||||
async getData() {
|
||||
const formData = await super.getData();
|
||||
if (this.actor) {
|
||||
this.prepareConteneurData(formData);
|
||||
}
|
||||
return formData;
|
||||
}
|
||||
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
|
||||
if (!this.options.editable) return;
|
||||
|
||||
this.html.find('.conteneur-name a').click(async event => {
|
||||
RdDUtility.toggleAfficheContenu(RdDSheetUtility.getItemId(event));
|
||||
this.render(true);
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
prepareConteneurData(formData) {
|
||||
RdDUtility.filterEquipementParType(formData, this.actor.itemTypes);
|
||||
|
||||
this.objetVersConteneur = RdDUtility.buildArbreDeConteneurs(formData.conteneurs, formData.objets);
|
||||
formData.subItems = formData.conteneurs.find(it => it._id == this.item.id)?.subItems;
|
||||
}
|
||||
|
||||
async _onDragStart(event) {
|
||||
console.log("_onDragStart", event);
|
||||
if (event.target.classList.contains("entity-link")) return;
|
||||
|
||||
const itemId = event.srcElement?.attributes["data-item-id"].value;
|
||||
const item = this.actor.items.get(itemId);
|
||||
// Create drag data
|
||||
const dragData = {
|
||||
actorId: this.actor.id,
|
||||
type: "Item",
|
||||
data: item.system
|
||||
};
|
||||
|
||||
event.dataTransfer.setData("text/plain", JSON.stringify(dragData));
|
||||
}
|
||||
|
||||
async _onDropItem(event, dragData) {
|
||||
if (this.actor) {
|
||||
const dropParams = await RdDSheetUtility.prepareItemDropParameters(this.item.id, this.actor, dragData, this.objetVersConteneur);
|
||||
await this.actor.processDropItem(dropParams);
|
||||
await this.render(true);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
67
module/item-faune-sheet.js
Normal file
@ -0,0 +1,67 @@
|
||||
import { EnvironmentSheetHelper } from "./environnement.js";
|
||||
import { RdDItemSheet } from "./item-sheet.js";
|
||||
import { RdDUtility } from "./rdd-utility.js";
|
||||
|
||||
export class RdDFauneItemSheet extends RdDItemSheet {
|
||||
|
||||
static get ITEM_TYPE() { return "faune" };
|
||||
|
||||
static get defaultOptions() {
|
||||
return EnvironmentSheetHelper.defaultOptions(super.defaultOptions);
|
||||
}
|
||||
|
||||
setPosition(options = {}) {
|
||||
return EnvironmentSheetHelper.setPosition(this, super.setPosition(options));
|
||||
}
|
||||
|
||||
async getData() {
|
||||
const formData = await super.getData();
|
||||
return await EnvironmentSheetHelper.getData(this, formData);
|
||||
}
|
||||
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
if (!this.options.editable) return;
|
||||
|
||||
EnvironmentSheetHelper.activateListeners(this);
|
||||
|
||||
html.find("a.linked-actor-delete").click(event => this.onDeleteLinkedActor());
|
||||
html.find("a.preparer-nourriture").click(event => this.preparerNourriture(event));
|
||||
html.find("a.manger-nourriture").click(event => this.mangerNourriture(event));
|
||||
}
|
||||
|
||||
async _onDropActor(event, dragData) {
|
||||
console.log('faune:dropActor', event, dragData)
|
||||
const linkedActor = fromUuidSync(dragData.uuid);
|
||||
if (linkedActor?.pack) {
|
||||
this.item.update({
|
||||
'system.actor.pack': linkedActor.pack,
|
||||
'system.actor.id': linkedActor._id,
|
||||
'system.actor.name': linkedActor.name
|
||||
});
|
||||
}
|
||||
else {
|
||||
ui.notifications.warn(`${linkedActor.name} ne provient pas d'un compendium.
|
||||
<br>Choisissez une créature du compendium pour représenter un élément de faune générique`)
|
||||
}
|
||||
}
|
||||
async onDeleteLinkedActor() {
|
||||
this.item.update({
|
||||
'system.actor.pack': '',
|
||||
'system.actor.id': '',
|
||||
'system.actor.name': ''
|
||||
});
|
||||
}
|
||||
|
||||
async preparerNourriture(event) {
|
||||
if (this.actor) {
|
||||
await this.actor.preparerNourriture(this.item);
|
||||
}
|
||||
}
|
||||
async mangerNourriture(event) {
|
||||
if (this.actor) {
|
||||
await this.actor.mangerNourriture(this.item);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,45 +1,25 @@
|
||||
import { SYSTEM_RDD } from "./constants.js";
|
||||
import { EnvironmentSheetHelper as EnvironmentItemSheet } from "./environnement.js";
|
||||
import { Misc } from "./misc.js";
|
||||
import { EnvironmentSheetHelper } from "./environnement.js";
|
||||
import { RdDItemSheet } from "./item-sheet.js";
|
||||
|
||||
const ITEM_TYPE = 'herbe';
|
||||
export class RdDHerbeItemSheet extends RdDItemSheet {
|
||||
|
||||
export class RdDHerbeItemSheet extends ItemSheet {
|
||||
|
||||
static register() {
|
||||
Items.registerSheet(SYSTEM_RDD, RdDHerbeItemSheet, {
|
||||
label: Misc.typeName('Item', ITEM_TYPE),
|
||||
types: [ITEM_TYPE],
|
||||
makeDefault: true
|
||||
});
|
||||
}
|
||||
static get ITEM_TYPE() { return "herbe" };
|
||||
|
||||
static get defaultOptions() {
|
||||
return EnvironmentItemSheet.defaultOptions(super.defaultOptions, ITEM_TYPE);
|
||||
}
|
||||
|
||||
_getHeaderButtons() {
|
||||
return EnvironmentItemSheet.getHeaderButtons(this, super._getHeaderButtons());
|
||||
return EnvironmentSheetHelper.defaultOptions(super.defaultOptions);
|
||||
}
|
||||
|
||||
setPosition(options = {}) {
|
||||
return EnvironmentItemSheet.setPosition(this, super.setPosition(options));
|
||||
return EnvironmentSheetHelper.setPosition(this, super.setPosition(options));
|
||||
}
|
||||
|
||||
async getData() {
|
||||
return await EnvironmentItemSheet.getData(this);
|
||||
const formData = await super.getData();
|
||||
return await EnvironmentSheetHelper.getData(this, formData);
|
||||
}
|
||||
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
EnvironmentItemSheet.activateListeners(this, html);
|
||||
}
|
||||
|
||||
get template() {
|
||||
return EnvironmentItemSheet.template(this.item.type);
|
||||
}
|
||||
|
||||
get title() {
|
||||
return EnvironmentItemSheet.title(this.item);
|
||||
EnvironmentSheetHelper.activateListeners(this);
|
||||
}
|
||||
}
|
||||
|
@ -1,24 +1,12 @@
|
||||
import { SYSTEM_RDD } from "./constants.js";
|
||||
import { EnvironmentSheetHelper } from "./environnement.js";
|
||||
import { Misc } from "./misc.js";
|
||||
import { RdDItemSheet } from "./item-sheet.js";
|
||||
|
||||
const ITEM_TYPE = 'ingredient';
|
||||
export class RdDIngredientItemSheet extends ItemSheet {
|
||||
export class RdDIngredientItemSheet extends RdDItemSheet {
|
||||
|
||||
static register() {
|
||||
Items.registerSheet(SYSTEM_RDD, RdDIngredientItemSheet, {
|
||||
label: Misc.typeName('Item', ITEM_TYPE),
|
||||
types: [ITEM_TYPE],
|
||||
makeDefault: true
|
||||
});
|
||||
}
|
||||
static get ITEM_TYPE() { return "ingredient" };
|
||||
|
||||
static get defaultOptions() {
|
||||
return EnvironmentSheetHelper.defaultOptions(super.defaultOptions, ITEM_TYPE);
|
||||
}
|
||||
|
||||
_getHeaderButtons() {
|
||||
return EnvironmentSheetHelper.getHeaderButtons(this, super._getHeaderButtons());
|
||||
return EnvironmentSheetHelper.defaultOptions(super.defaultOptions);
|
||||
}
|
||||
|
||||
setPosition(options = {}) {
|
||||
@ -26,19 +14,12 @@ export class RdDIngredientItemSheet extends ItemSheet {
|
||||
}
|
||||
|
||||
async getData() {
|
||||
return await EnvironmentSheetHelper.getData(this);
|
||||
const formData = await super.getData();
|
||||
return await EnvironmentSheetHelper.getData(this, formData);
|
||||
}
|
||||
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
EnvironmentSheetHelper.activateListeners(this, html);
|
||||
}
|
||||
|
||||
get template() {
|
||||
return EnvironmentSheetHelper.template(this.item.type);
|
||||
}
|
||||
|
||||
get title() {
|
||||
return EnvironmentSheetHelper.title(this.item);
|
||||
EnvironmentSheetHelper.activateListeners(this);
|
||||
}
|
||||
}
|
||||
|
@ -2,27 +2,28 @@ import { Misc } from "./misc.js";
|
||||
import { LOG_HEAD } from "./constants.js";
|
||||
|
||||
const MONNAIE_ETAIN = {
|
||||
name: "Etain (1 denier)", type: 'monnaie',
|
||||
name: "Denier (étain)", type: 'monnaie',
|
||||
img: "systems/foundryvtt-reve-de-dragon/icons/objets/piece_etain_poisson.webp",
|
||||
system: { quantite: 0, cout: 0.01, encombrement: 0.001, description: "" }
|
||||
};
|
||||
const MONNAIE_BRONZE = {
|
||||
name: "Bronze (10 deniers)", type: 'monnaie',
|
||||
name: "Sou (bronze)", type: 'monnaie',
|
||||
img: "systems/foundryvtt-reve-de-dragon/icons/objets/piece_bronze_epees.webp",
|
||||
system: { quantite: 0, cout: 0.10, encombrement: 0.002, description: "" }
|
||||
};
|
||||
const MONNAIE_ARGENT = {
|
||||
name: "Argent (1 sol)", type: 'monnaie',
|
||||
name: "Sol (argent)", type: 'monnaie',
|
||||
img: "systems/foundryvtt-reve-de-dragon/icons/objets/piece_argent_sol.webp",
|
||||
system: { quantite: 0, cout: 1, encombrement: 0.003, description: "" }
|
||||
};
|
||||
const MONNAIE_OR = {
|
||||
name: "Or (10 sols)", type: 'monnaie',
|
||||
name: "Dreagon (or)", type: 'monnaie',
|
||||
img: "systems/foundryvtt-reve-de-dragon/icons/objets/piece_or_sol.webp",
|
||||
system: { quantite: 0, cout: 10, encombrement: 0.004, description: "" }
|
||||
};
|
||||
|
||||
const MONNAIES_STANDARD = [MONNAIE_ETAIN, MONNAIE_BRONZE, MONNAIE_ARGENT, MONNAIE_OR];
|
||||
const VALEUR_DENIERS = sols => Math.max(Math.floor((sols ?? 0) * 100), 0);
|
||||
|
||||
export class Monnaie {
|
||||
|
||||
@ -40,15 +41,11 @@ export class Monnaie {
|
||||
}
|
||||
|
||||
static deValeur(monnaie, valeur) {
|
||||
return Monnaie.valEntiere(valeur) == Monnaie.valEntiere(monnaie.system.cout)
|
||||
}
|
||||
|
||||
static valEntiere(sols) {
|
||||
return Math.max(Math.floor((sols??0)*100), 0);
|
||||
return VALEUR_DENIERS(valeur) == VALEUR_DENIERS(monnaie.system.cout)
|
||||
}
|
||||
|
||||
static triValeurEntiere() {
|
||||
return Misc.ascending(item => Monnaie.valEntiere(item.system.cout))
|
||||
return Misc.ascending(item => VALEUR_DENIERS(item.system.cout))
|
||||
}
|
||||
|
||||
static async creerMonnaiesStandard(actor) {
|
||||
@ -65,29 +62,45 @@ export class Monnaie {
|
||||
return deniers;
|
||||
}
|
||||
|
||||
static getFortune(monnaies) {
|
||||
return (monnaies??[])
|
||||
.map(m => Number(m.system.cout) * Number(m.system.quantite))
|
||||
.reduce(Misc.sum(), 0);
|
||||
}
|
||||
|
||||
static async optimiserFortune(actor, fortune) {
|
||||
let resteEnDeniers = Math.round(fortune*100);
|
||||
let resteEnDeniers = Math.round(fortune * 100);
|
||||
let monnaies = actor.itemTypes['monnaie'];
|
||||
let updates = [];
|
||||
let parValeur = Misc.classifyFirst(monnaies, it => Monnaie.valEntiere(it.system.cout));
|
||||
for (let valeurDeniers of [1000, 100, 10, 1]) {
|
||||
Monnaie.validerMonnaies(monnaies, actor);
|
||||
|
||||
let parValeur = Misc.classifyFirst(monnaies, it => VALEUR_DENIERS(it.system.cout));
|
||||
for (let valeurDeniers of [1000, 100, 10, 1]) {
|
||||
const itemPiece = parValeur[valeurDeniers];
|
||||
if (itemPiece) {
|
||||
const quantite = Math.floor(resteEnDeniers / valeurDeniers);
|
||||
if (quantite != itemPiece.system.quantite) {
|
||||
updates.push({ _id: parValeur[valeurDeniers].id, 'system.quantite': quantite });
|
||||
}
|
||||
resteEnDeniers -= quantite*valeurDeniers;
|
||||
resteEnDeniers -= quantite * valeurDeniers;
|
||||
}
|
||||
}
|
||||
console.log('Monnaie.optimiserFortune', actor.name, 'total', fortune, 'parValeur', parValeur, 'updates', updates, 'reste', resteEnDeniers);
|
||||
if (updates.length > 0) {
|
||||
await actor.updateEmbeddedDocuments('Item', updates);
|
||||
}
|
||||
if (resteEnDeniers > 0){
|
||||
if (resteEnDeniers > 0) {
|
||||
// créer le reste en deniers fortune en deniers
|
||||
await Monnaie.creerMonnaiesDeniers(actor, resteEnDeniers);
|
||||
}
|
||||
}
|
||||
|
||||
static validerMonnaies(monnaies, actor = undefined) {
|
||||
monnaies.filter(it => VALEUR_DENIERS(it.system.cout) == 0)
|
||||
.map(it => `La monnaie ${it.name} de l'acteur ${actor?.name ?? 'sélectionné'} a une valeur de 0!`)
|
||||
.forEach(message => {
|
||||
ui.notifications.warn(message);
|
||||
console.warn(message);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
@ -1,29 +1,16 @@
|
||||
import { RdDRencontre } from "./item-rencontre.js";
|
||||
import { RdDRencontre } from "./item/item-rencontre.js";
|
||||
import { RdDItemSheet } from "./item-sheet.js";
|
||||
|
||||
/**
|
||||
* Item sheet pour configurer les rencontres
|
||||
* @extends {ItemSheet}
|
||||
*/
|
||||
export class RdDRencontreItemSheet extends ItemSheet {
|
||||
export class RdDRencontreItemSheet extends RdDItemSheet {
|
||||
|
||||
static get ITEM_TYPE() { return "rencontre" };
|
||||
|
||||
/** @override */
|
||||
static get defaultOptions() {
|
||||
return mergeObject(super.defaultOptions, {
|
||||
classes: ["rdd", "sheet", "item"],
|
||||
template: "systems/foundryvtt-reve-de-dragon/templates/item-rencontre-sheet.html",
|
||||
width: 500,
|
||||
height: 500,
|
||||
tabs: [{ navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "carac" }]
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
_getHeaderButtons() {
|
||||
let buttons = super._getHeaderButtons();
|
||||
buttons.unshift({ class: "post", icon: "fas fa-comment", onclick: ev => this.item.postItem() });
|
||||
return buttons;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
/** @override */
|
||||
setPosition(options = {}) {
|
||||
@ -34,18 +21,10 @@ export class RdDRencontreItemSheet extends ItemSheet {
|
||||
return position;
|
||||
}
|
||||
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async getData() {
|
||||
const formData = duplicate(this.item);
|
||||
const formData = await super.getData();
|
||||
mergeObject(formData, {
|
||||
title: formData.name,
|
||||
isGM: game.user.isGM,
|
||||
owner: this.actor?.isOwner,
|
||||
isOwned: this.actor ? true : false,
|
||||
actorId: this.actor?.id,
|
||||
editable: this.isEditable,
|
||||
cssClass: this.isEditable ? "editable" : "locked",
|
||||
effets: {
|
||||
succes: {
|
||||
liste: RdDRencontre.getEffetsSucces(),
|
||||
@ -65,15 +44,15 @@ export class RdDRencontreItemSheet extends ItemSheet {
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
if (!this.options.editable) return;
|
||||
html.find("a.effet-add").click(event => this.onAddEffet(event));
|
||||
html.find("a.effet-delete").click(event => this.onDeleteEffet(event));
|
||||
this.html.find("a.effet-add").click(event => this.onAddEffet(event));
|
||||
this.html.find("a.effet-delete").click(event => this.onDeleteEffet(event));
|
||||
}
|
||||
|
||||
async onAddEffet(event) {
|
||||
const resultat = $(event.currentTarget)?.data("effet-resultat");
|
||||
const resultat = this.html.find(event.currentTarget)?.data("effet-resultat");
|
||||
const keyEffets = `system.${resultat}.effets`;
|
||||
|
||||
const code = $(event.currentTarget)?.data("effet-code");
|
||||
const code = this.html.find(event.currentTarget)?.data("effet-code");
|
||||
const liste = RdDRencontre.getListeEffets(this.item, resultat);
|
||||
liste.push(code);
|
||||
|
||||
@ -81,10 +60,10 @@ export class RdDRencontreItemSheet extends ItemSheet {
|
||||
}
|
||||
|
||||
async onDeleteEffet(event) {
|
||||
const resultat = $(event.currentTarget)?.data("effet-resultat");
|
||||
const resultat = this.html.find(event.currentTarget)?.data("effet-resultat");
|
||||
const keyEffets = `system.${resultat}.effets`;
|
||||
|
||||
const pos = $(event.currentTarget)?.data("effet-pos");
|
||||
const pos = this.html.find(event.currentTarget)?.data("effet-pos");
|
||||
const liste = RdDRencontre.getListeEffets(this.item, resultat);
|
||||
liste.splice(pos, 1);
|
||||
|
||||
@ -96,13 +75,4 @@ export class RdDRencontreItemSheet extends ItemSheet {
|
||||
updates[key] = liste;
|
||||
this.item.update(updates);
|
||||
}
|
||||
|
||||
get template() {
|
||||
/* -------------------------------------------- */
|
||||
return `systems/foundryvtt-reve-de-dragon/templates/item-rencontre-sheet.html`;
|
||||
}
|
||||
|
||||
get title() {
|
||||
return `Rencontre: ${this.object.name}`;
|
||||
}
|
||||
}
|
||||
|
16
module/item-service-sheet.js
Normal file
@ -0,0 +1,16 @@
|
||||
import { RdDItemSheet } from "./item-sheet.js";
|
||||
|
||||
export class RdDServiceItemSheet extends RdDItemSheet {
|
||||
|
||||
static get ITEM_TYPE() { return "service" };
|
||||
|
||||
async getData() {
|
||||
const formData = await super.getData();
|
||||
formData.disabled = formData.isGM || formData.isOwned ? '' : 'disabled';
|
||||
return formData;
|
||||
}
|
||||
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
}
|
||||
}
|
@ -9,40 +9,65 @@ import { ReglesOptionelles } from "./settings/regles-optionelles.js";
|
||||
import { SYSTEM_RDD } from "./constants.js";
|
||||
import { RdDSheetUtility } from "./rdd-sheet-utility.js";
|
||||
import { SystemCompendiums } from "./settings/system-compendiums.js";
|
||||
import { Misc } from "./misc.js";
|
||||
import { RdDTimestamp } from "./rdd-timestamp.js";
|
||||
|
||||
/**
|
||||
* Extend the basic ItemSheet with some very simple modifications
|
||||
* @extends {ItemSheet}
|
||||
* Extend the basic ItemSheet for RdD specific items
|
||||
*/
|
||||
export class RdDItemSheet extends ItemSheet {
|
||||
|
||||
static get ITEM_TYPE() {
|
||||
return undefined
|
||||
}
|
||||
|
||||
static defaultTemplate(type) {
|
||||
return type ?
|
||||
`systems/foundryvtt-reve-de-dragon/templates/item-${type}-sheet.html` :
|
||||
"systems/foundryvtt-reve-de-dragon/templates/item-sheet.html";
|
||||
}
|
||||
|
||||
static register(sheetClass) {
|
||||
Items.registerSheet(SYSTEM_RDD, sheetClass, {
|
||||
label: Misc.typeName('Item', sheetClass.ITEM_TYPE),
|
||||
types: [sheetClass.ITEM_TYPE],
|
||||
makeDefault: true
|
||||
})
|
||||
}
|
||||
|
||||
/** @override */
|
||||
static get defaultOptions() {
|
||||
return mergeObject(super.defaultOptions, {
|
||||
classes: [SYSTEM_RDD, "sheet", "item"],
|
||||
template: "systems/foundryvtt-reve-de-dragon/templates/item-sheet.html",
|
||||
template: RdDItemSheet.defaultTemplate(RdDItemSheet.ITEM_TYPE),
|
||||
width: 550,
|
||||
height: 550
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
get template() {
|
||||
return RdDItemSheet.defaultTemplate(this.item.type);
|
||||
}
|
||||
|
||||
get title() {
|
||||
return `${Misc.typeName('Item', this.item.type)}: ${this.item.name}`;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
_getHeaderButtons() {
|
||||
let buttons = super._getHeaderButtons();
|
||||
// Add "Post to chat" button
|
||||
// We previously restricted this to GM and editable items only. If you ever find this comment because it broke something: eh, sorry!
|
||||
if ("cout" in this.item.system && this.item.isVideOuNonConteneur()) {
|
||||
if (this.item.isInventaire() && this.item.isVideOuNonConteneur()) {
|
||||
buttons.unshift({
|
||||
class: "vendre",
|
||||
icon: "fas fa-comments-dollar",
|
||||
onclick: ev => this.item.proposerVente()
|
||||
onclick: ev => this.item.proposerVente(1)
|
||||
});
|
||||
}
|
||||
buttons.unshift({
|
||||
class: "montrer",
|
||||
icon: "fas fa-comment",
|
||||
onclick: ev => this.item.postItem()
|
||||
onclick: ev => this.item.postItemToChat()
|
||||
});
|
||||
return buttons
|
||||
}
|
||||
@ -69,19 +94,14 @@ export class RdDItemSheet extends ItemSheet {
|
||||
system: this.item.system,
|
||||
isGM: game.user.isGM,
|
||||
actorId: this.actor?.id,
|
||||
isOwned: this.actor ? true : false,
|
||||
owner: this.item.isOwner,
|
||||
editable: this.isEditable,
|
||||
cssClass: this.isEditable ? "editable" : "locked",
|
||||
isSoins: false,
|
||||
description: await TextEditor.enrichHTML(this.object.system.description, {async: true}),
|
||||
descriptionmj: await TextEditor.enrichHTML(this.object.system.descriptionmj, {async: true})
|
||||
|
||||
}
|
||||
if (this.actor) {
|
||||
formData.isOwned = true;
|
||||
if (this.item.type == 'conteneur') {
|
||||
this.prepareConteneurData(formData);
|
||||
}
|
||||
description: await TextEditor.enrichHTML(this.item.system.description, { async: true }),
|
||||
descriptionmj: await TextEditor.enrichHTML(this.item.system.descriptionmj, { async: true }),
|
||||
isComestible: this.item.isComestible()
|
||||
}
|
||||
|
||||
const competences = await SystemCompendiums.getCompetences(this.actor?.type);
|
||||
@ -98,29 +118,25 @@ export class RdDItemSheet extends ItemSheet {
|
||||
formData.competences = competences.filter(it => RdDItemCompetence.isDraconic(it));
|
||||
}
|
||||
if (this.item.type == 'recettecuisine') {
|
||||
formData.ingredients = await TextEditor.enrichHTML(this.object.system.ingredients, {async: true})
|
||||
formData.ingredients = await TextEditor.enrichHTML(this.object.system.ingredients, { async: true })
|
||||
}
|
||||
if (this.item.type == 'extraitpoetique') {
|
||||
formData.extrait = await TextEditor.enrichHTML(this.object.system.extrait, {async: true})
|
||||
formData.texte = await TextEditor.enrichHTML(this.object.system.texte, {async: true})
|
||||
formData.extrait = await TextEditor.enrichHTML(this.object.system.extrait, { async: true })
|
||||
formData.texte = await TextEditor.enrichHTML(this.object.system.texte, { async: true })
|
||||
}
|
||||
if (this.item.type == 'recettealchimique') {
|
||||
RdDAlchimie.processManipulation(this.item, this.actor && this.actor.id);
|
||||
formData.manipulation_update = await TextEditor.enrichHTML(this.object.system.manipulation_update, {async: true})
|
||||
formData.utilisation = await TextEditor.enrichHTML(this.object.system.utilisation, {async: true})
|
||||
formData.enchantement = await TextEditor.enrichHTML(this.object.system.enchantement, {async: true})
|
||||
formData.sureffet = await TextEditor.enrichHTML(this.object.system.sureffet, {async: true})
|
||||
formData.manipulation_update = await TextEditor.enrichHTML(this.object.system.manipulation_update, { async: true })
|
||||
formData.utilisation = await TextEditor.enrichHTML(this.object.system.utilisation, { async: true })
|
||||
formData.enchantement = await TextEditor.enrichHTML(this.object.system.enchantement, { async: true })
|
||||
formData.sureffet = await TextEditor.enrichHTML(this.object.system.sureffet, { async: true })
|
||||
}
|
||||
if (this.item.type == 'gemme') {
|
||||
formData.gemmeTypeList = RdDGemme.getGemmeTypeOptionList();
|
||||
RdDGemme.calculDataDerivees(this.item);
|
||||
}
|
||||
if (this.item.type == 'potion') {
|
||||
if (this.dateUpdated) {
|
||||
formData.system.prdate = this.dateUpdated;
|
||||
this.dateUpdated = undefined;
|
||||
}
|
||||
await RdDHerbes.updatePotionData(formData);
|
||||
await RdDHerbes.addPotionFormData(formData);
|
||||
}
|
||||
if (formData.isOwned && this.item.type == 'herbe' && (formData.system.categorie == 'Soin' || formData.system.categorie == 'Repos')) {
|
||||
formData.isIngredientPotionBase = true;
|
||||
@ -134,108 +150,82 @@ export class RdDItemSheet extends ItemSheet {
|
||||
return formData;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
prepareConteneurData(formData) {
|
||||
RdDUtility.filterEquipementParType(formData, this.actor.itemTypes);
|
||||
|
||||
this.objetVersConteneur = RdDUtility.buildArbreDeConteneurs(formData.conteneurs, formData.objets);
|
||||
formData.subItems = formData.conteneurs.find(it => it._id == this.item.id)?.subItems;
|
||||
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
/** @override */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
this.html = html;
|
||||
|
||||
if (this.item.type == 'conteneur') {
|
||||
this.form.ondragstart = (event) => this._onDragStart(event);
|
||||
this.form.ondrop = (event) => this._onDrop(event);
|
||||
}
|
||||
|
||||
let itemSheetDialog = this;
|
||||
|
||||
HtmlUtility._showControlWhen($(".item-cout"), ReglesOptionelles.isUsing('afficher-prix-joueurs') || game.user.isGM || !this.item.isOwned);
|
||||
HtmlUtility._showControlWhen($(".item-magique"), this.item.isMagique());
|
||||
HtmlUtility._showControlWhen(this.html.find(".item-cout"), ReglesOptionelles.isUsing('afficher-prix-joueurs') || game.user.isGM || !this.item.isOwned);
|
||||
HtmlUtility._showControlWhen(this.html.find(".item-magique"), this.item.isMagique());
|
||||
|
||||
// Everything below here is only needed if the sheet is editable
|
||||
if (!this.options.editable) return;
|
||||
|
||||
// Select competence categorie
|
||||
html.find(".categorie").change(event => this._onSelectCategorie(event));
|
||||
this.form.ondragstart = (event) => this._onDragStart(event);
|
||||
this.form.ondrop = (event) => this._onDrop(event);
|
||||
|
||||
html.find('.sheet-competence-xp').change((event) => {
|
||||
// Select competence categorie
|
||||
this.html.find(".categorie").change(event => this._onSelectCategorie(event));
|
||||
|
||||
this.html.find('.sheet-competence-xp').change((event) => {
|
||||
if (this.item.isCompetencePersonnage()) {
|
||||
RdDUtility.checkThanatosXP(this.item.name);
|
||||
}
|
||||
});
|
||||
this.html.find(".item-cout input[name='system.cout']").change(event => {
|
||||
if (this.item.isMonnaie()) {
|
||||
const value = event.currentTarget.value;
|
||||
if (Number(value) == 0) {
|
||||
ui.notifications.error(`${this.actor?.name ?? 'Monnaie'}: La monnaie ${this.item.name} a maintenant une valeur de 0, et ne peut plus être utilisée pour payer!`)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
html.find('.enchanteDate').change((event) => {
|
||||
let jour = Number($('#jourMois').val());
|
||||
let mois = $('#nomMois').val();
|
||||
this.dateUpdated = game.system.rdd.calendrier.getIndexFromDate(jour, mois);
|
||||
this.html.find('.date-enchantement').change((event) => {
|
||||
const jour = Number(this.html.find('input.date-enchantement[name="enchantement.jour"]').val());
|
||||
const mois = RdDTimestamp.definition(this.html.find('select.date-enchantement[name="enchantement.mois"]').val());
|
||||
const indexDate = game.system.rdd.calendrier.getIndexFromDate(jour, mois.heure);
|
||||
this.item.update({ 'system.prdate': indexDate });
|
||||
console.warn(`Date d'enchantement modifiée ${jour}/${mois.heure}: ${indexDate}`)
|
||||
});
|
||||
|
||||
html.find('.creer-tache-livre').click((event) => {
|
||||
let actorId = event.currentTarget.attributes['data-actor-id'].value;
|
||||
let actor = game.actors.get(actorId);
|
||||
actor.creerTacheDepuisLivre(this.item);
|
||||
});
|
||||
html.find('.consommer-potion').click((event) => {
|
||||
let actorId = event.currentTarget.attributes['data-actor-id'].value;
|
||||
let actor = game.actors.get(actorId);
|
||||
actor.consommerPotion(this.item);
|
||||
});
|
||||
html.find('.creer-potion-base').click((event) => {
|
||||
let actorId = event.currentTarget.attributes['data-actor-id'].value;
|
||||
let actor = game.actors.get(actorId);
|
||||
actor.dialogFabriquerPotion(this.item);
|
||||
});
|
||||
this.html.find('.creer-tache-livre').click((event) => this._getEventActor(event).creerTacheDepuisLivre(this.item));
|
||||
this.html.find('.consommer-potion').click((event) => this._getEventActor(event).consommerPotion(this.item));
|
||||
this.html.find('.creer-potion-base').click((event) => this._getEventActor(event).dialogFabriquerPotion(this.item));
|
||||
|
||||
html.find('.alchimie-tache a').click((event) => {
|
||||
let actorId = event.currentTarget.attributes['data-actor-id'].value;
|
||||
let recetteId = event.currentTarget.attributes['data-recette-id'].value;
|
||||
let tacheName = event.currentTarget.attributes['data-alchimie-tache'].value;
|
||||
let tacheData = event.currentTarget.attributes['data-alchimie-data'].value;
|
||||
let actor = game.actors.get(actorId);
|
||||
this.html.find('.alchimie-tache a').click((event) => {
|
||||
let actor = this._getEventActor(event);
|
||||
if (actor) {
|
||||
let recetteId = event.currentTarget.attributes['data-recette-id'].value;
|
||||
let tacheName = event.currentTarget.attributes['data-alchimie-tache'].value;
|
||||
let tacheData = event.currentTarget.attributes['data-alchimie-data'].value;
|
||||
actor.effectuerTacheAlchimie(recetteId, tacheName, tacheData);
|
||||
} else {
|
||||
ui.notifications.info("Impossible trouver un acteur pour réaliser cette tache Alchimique.");
|
||||
}
|
||||
});
|
||||
|
||||
html.find('.item-split').click(async event => {
|
||||
const item = RdDSheetUtility.getItem(event, this.actor);
|
||||
await RdDSheetUtility.splitItem(item, this.actor, async () => itemSheetDialog.render(true));
|
||||
});
|
||||
html.find('.item-edit').click(async event => {
|
||||
const item = RdDSheetUtility.getItem(event, this.actor);
|
||||
item.sheet.render(true);
|
||||
});
|
||||
html.find('.item-delete').click(async event => {
|
||||
const li = RdDSheetUtility.getEventElement(event);
|
||||
const item = this.actor.getObjet(li.data("item-id"));
|
||||
RdDUtility.confirmerSuppressionItem(this, item, li);
|
||||
});
|
||||
html.find('.item-vendre').click(async event => {
|
||||
const item = RdDSheetUtility.getItem(event, this.actor);
|
||||
item?.proposerVente();
|
||||
});
|
||||
html.find('.item-montrer').click(async event => {
|
||||
const item = RdDSheetUtility.getItem(event, this.actor);
|
||||
item?.postItem();
|
||||
});
|
||||
html.find('.item-action').click(async event => {
|
||||
const item = RdDSheetUtility.getItem(event, this.actor);
|
||||
this.actor.actionItem(item, async () => itemSheetDialog.render(true));
|
||||
});
|
||||
html.find('.conteneur-name a').click(async event => {
|
||||
RdDUtility.toggleAfficheContenu(RdDSheetUtility.getItemId(event));
|
||||
this.render(true);
|
||||
});
|
||||
this.html.find('.item-split').click(async event => RdDSheetUtility.splitItem(RdDSheetUtility.getItem(event, this.actor), this.actor, async () => this.render(true)));
|
||||
this.html.find('.item-edit').click(async event => RdDSheetUtility.getItem(event, this.actor)?.sheet.render(true));
|
||||
this.html.find('.item-delete').click(async event => RdDUtility.confirmActorItemDelete(this, RdDSheetUtility.getItem(event, this.actor)));
|
||||
this.html.find('.item-vendre').click(async event => RdDSheetUtility.getItem(event, this.actor)?.proposerVente());
|
||||
this.html.find('.item-montrer').click(async event => RdDSheetUtility.getItem(event, this.actor)?.postItemToChat());
|
||||
this.html.find('.item-action').click(async event => RdDSheetUtility.getItem(event, this.actor)?.actionPrincipale(this.actor, async () => this.render(true)));
|
||||
|
||||
const updateItemTimestamp = (path, timestamp) => this.item.update({ [path]: duplicate(timestamp) })
|
||||
|
||||
RdDTimestamp.handleTimestampEditor(this.html, 'system.temporel.debut', updateItemTimestamp);
|
||||
RdDTimestamp.handleTimestampEditor(this.html, 'system.temporel.fin', updateItemTimestamp);
|
||||
}
|
||||
|
||||
_getEventActor(event) {
|
||||
let actorId = event.currentTarget.attributes['data-actor-id'].value;
|
||||
let actor = game.actors.get(actorId);
|
||||
return actor;
|
||||
}
|
||||
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async _onSelectCategorie(event) {
|
||||
event.preventDefault();
|
||||
@ -243,70 +233,56 @@ export class RdDItemSheet extends ItemSheet {
|
||||
if (this.item.isCompetence()) {
|
||||
let level = RdDItemCompetence.getNiveauBase(event.currentTarget.value);
|
||||
this.item.system.base = level;
|
||||
$("#base").val(level);
|
||||
this.html.find('[name="system.base"]').val(level);
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
get template() {
|
||||
let type = this.item.type
|
||||
return `systems/foundryvtt-reve-de-dragon/templates/item-${type}-sheet.html`;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
|
||||
/** @override */
|
||||
_updateObject(event, formData) {
|
||||
// Données de bonus de cases ?
|
||||
formData['system.bonuscase'] = RdDItemSort.buildBonusCaseStringFromFormData(formData.bonusValue, formData.caseValue);
|
||||
if (this.item.type == 'sort') {
|
||||
// Données de bonus de cases ?
|
||||
formData['system.bonuscase'] = RdDItemSort.buildBonusCaseStringFromFormData(formData.bonusValue, formData.caseValue);
|
||||
}
|
||||
|
||||
return this.item.update(formData);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async _onDragStart(event) {
|
||||
console.log("_onDragStart", event);
|
||||
if (event.target.classList.contains("entity-link")) return;
|
||||
|
||||
const itemId = event.srcElement?.attributes["data-item-id"].value;
|
||||
const item = this.actor.items.get(itemId);
|
||||
// Create drag data
|
||||
const dragData = {
|
||||
actorId: this.actor.id,
|
||||
type: "Item",
|
||||
data: item.system
|
||||
};
|
||||
|
||||
event.dataTransfer.setData("text/plain", JSON.stringify(dragData));
|
||||
}
|
||||
|
||||
async _onDrop(event) {
|
||||
// Try to extract the dragData
|
||||
let dragData;
|
||||
try {
|
||||
dragData = JSON.parse(event.dataTransfer.getData('text/plain'));
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let dragData = RdDItemSheet.$extractDragData(event);
|
||||
if (!dragData) return false;
|
||||
const allowed = Hooks.call("dropActorSheetData", this.actor, this, dragData);
|
||||
if (allowed === false) return;
|
||||
if (allowed === false) return false;
|
||||
|
||||
// Handle different dragData types
|
||||
switch (dragData.type) {
|
||||
case "Item":
|
||||
return this._onDropItem(event, dragData);
|
||||
case "Actor":
|
||||
return this._onDropActor(event, dragData);
|
||||
}
|
||||
return super._onDrop(event);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async _onDropItem(event, dragData) {
|
||||
if (this.actor) {
|
||||
const dropParams = RdDSheetUtility.prepareItemDropParameters(this.item.id, this.actor.id, dragData, this.objetVersConteneur);
|
||||
await this.actor.processDropItem(dropParams);
|
||||
await this.render(true);
|
||||
}
|
||||
static $extractDragData(event) {
|
||||
try {
|
||||
const eventData = event?.dataTransfer?.getData('text/plain');
|
||||
if (eventData) {
|
||||
return JSON.parse(eventData);
|
||||
}
|
||||
} catch (err) { }
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async _onDropItem(event, dragData) {
|
||||
}
|
||||
|
||||
async _onDropActor(event, dragData) {
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,29 +1,14 @@
|
||||
import { SYSTEM_RDD } from "./constants.js";
|
||||
import { RdDItemSigneDraconique } from "./item-signedraconique.js";
|
||||
import { RdDItemSheet } from "./item-sheet.js";
|
||||
import { RdDItemSigneDraconique } from "./item/item-signedraconique.js";
|
||||
import { TMRUtility } from "./tmr-utility.js";
|
||||
|
||||
/**
|
||||
* Item sheet pour signes draconiques
|
||||
* @extends {ItemSheet}
|
||||
* @extends {RdDItemSheet}
|
||||
*/
|
||||
export class RdDSigneDraconiqueItemSheet extends ItemSheet {
|
||||
export class RdDSigneDraconiqueItemSheet extends RdDItemSheet {
|
||||
|
||||
/** @override */
|
||||
static get defaultOptions() {
|
||||
return mergeObject(super.defaultOptions, {
|
||||
classes: [SYSTEM_RDD, "sheet", "item"],
|
||||
template: "systems/foundryvtt-reve-de-dragon/templates/item-signedraconique-sheet.html",
|
||||
width: 550,
|
||||
height: 550
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
_getHeaderButtons() {
|
||||
let buttons = super._getHeaderButtons();
|
||||
buttons.unshift({ class: "post", icon: "fas fa-comment", onclick: ev => this.item.postItem() });
|
||||
return buttons;
|
||||
}
|
||||
static get ITEM_TYPE() { return "signedraconique" }
|
||||
|
||||
/* -------------------------------------------- */
|
||||
/** @override */
|
||||
@ -38,18 +23,9 @@ export class RdDSigneDraconiqueItemSheet extends ItemSheet {
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async getData() {
|
||||
const formData = duplicate(this.item);
|
||||
const formData = await super.getData();
|
||||
this.tmrs = TMRUtility.buildSelectionTypesTMR(this.item.system.typesTMR);
|
||||
mergeObject(formData, {
|
||||
tmrs: this.tmrs,
|
||||
title: formData.name,
|
||||
isGM: game.user.isGM,
|
||||
owner: this.actor?.isOwner,
|
||||
isOwned: this.actor ? true : false,
|
||||
actorId: this.actor?.id,
|
||||
editable: this.isEditable,
|
||||
cssClass: this.isEditable ? "editable" : "locked",
|
||||
});
|
||||
formData.tmrs = this.tmrs;
|
||||
return formData;
|
||||
}
|
||||
|
||||
@ -61,12 +37,13 @@ export class RdDSigneDraconiqueItemSheet extends ItemSheet {
|
||||
if (!this.options.editable) return;
|
||||
|
||||
html.find(".signe-aleatoire").click(event => this.setSigneAleatoire());
|
||||
html.find("input.select-tmr").change((event) => this.onSelectTmr(event));
|
||||
html.find(".signe-xp-sort").change((event) => this.onValeurXpSort(event.currentTarget.attributes['data-typereussite']?.value, Number(event.currentTarget.value)));
|
||||
html.find("input.select-tmr").change(event => this.onSelectTmr(event));
|
||||
html.find(".signe-xp-sort").change(event => this.onValeurXpSort(event.currentTarget.attributes['data-typereussite']?.value, Number(event.currentTarget.value)));
|
||||
}
|
||||
|
||||
async setSigneAleatoire() {
|
||||
const newSigne = await RdDItemSigneDraconique.randomSigneDraconique();
|
||||
newSigne.name = this.item.name;
|
||||
this.item.update(newSigne);
|
||||
}
|
||||
|
||||
@ -88,12 +65,4 @@ export class RdDSigneDraconiqueItemSheet extends ItemSheet {
|
||||
await this.item.update({ 'system.valeur': newValeur });
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
get template() {
|
||||
return `systems/foundryvtt-reve-de-dragon/templates/item-signedraconique-sheet.html`;
|
||||
}
|
||||
|
||||
get title() {
|
||||
return `Signe draconique: ${this.object.name}`;
|
||||
}
|
||||
}
|
||||
|
473
module/item.js
@ -1,13 +1,16 @@
|
||||
import { DialogItemVente } from "./dialog-item-vente.js";
|
||||
import { Grammar } from "./grammar.js";
|
||||
import { Monnaie } from "./item-monnaie.js";
|
||||
import { Misc } from "./misc.js";
|
||||
import { RdDHerbes } from "./rdd-herbes.js";
|
||||
import { RdDTimestamp } from "./rdd-timestamp.js";
|
||||
import { RdDUtility } from "./rdd-utility.js";
|
||||
import { SystemCompendiums } from "./settings/system-compendiums.js";
|
||||
|
||||
const typesObjetsEquipement = [
|
||||
const typesInventaireMateriel = [
|
||||
"arme",
|
||||
"armure",
|
||||
"conteneur",
|
||||
"faune",
|
||||
"gemme",
|
||||
"herbe",
|
||||
"ingredient",
|
||||
@ -18,11 +21,17 @@ const typesObjetsEquipement = [
|
||||
"objet",
|
||||
"potion",
|
||||
]
|
||||
const typesInventaire = {
|
||||
materiel: typesInventaireMateriel,
|
||||
all: ['service'].concat(typesInventaireMateriel),
|
||||
}
|
||||
|
||||
const typesObjetsOeuvres = ["oeuvre", "recettecuisine", "musique", "chant", "danse", "jeu"]
|
||||
const typesObjetsDraconiques = ["queue", "ombre", "souffle", "tete", "signedraconique", "sortreserve", "rencontre"]
|
||||
const typesObjetsConnaissance = ["meditation", "recettealchimique", "sort"]
|
||||
const typesObjetsEffet = ["possession", "poison", "maladie"]
|
||||
const typesObjetsCompetence = ["competence", "competencecreature"]
|
||||
const typesObjetsTemporels = ["poison", "maladie", "queue", "ombre", "souffle", "signedraconique", "rencontre"]
|
||||
const encBrin = 0.00005; // un brin = 1 décigramme = 1/10g = 1/10000kg = 1/20000 enc
|
||||
const encPepin = 0.0007; /* un pépin de gemme = 1/10 cm3 = 1/1000 l = 3.5/1000 kg = 7/2000 kg = 7/1000 enc
|
||||
densité 3.5 (~2.3 à 4, parfois plus) -- https://www.juwelo.fr/guide-des-pierres/faits-et-chiffres/
|
||||
@ -36,6 +45,7 @@ export const defaultItemImg = {
|
||||
conteneur: "systems/foundryvtt-reve-de-dragon/icons/objets/sac_a_dos.webp",
|
||||
sort: "systems/foundryvtt-reve-de-dragon/icons/competence_oniros.webp",
|
||||
herbe: "systems/foundryvtt-reve-de-dragon/icons/botanique/Endorlotte.webp",
|
||||
faune: "systems/foundryvtt-reve-de-dragon/icons/faune/rongeur.webp",
|
||||
ingredient: "systems/foundryvtt-reve-de-dragon/icons/objets/sable_poudre.webp",
|
||||
livre: "systems/foundryvtt-reve-de-dragon/icons/objets/livre.webp",
|
||||
potion: "systems/foundryvtt-reve-de-dragon/icons/objets/liqueur_de_bagdol.webp",
|
||||
@ -55,6 +65,7 @@ export const defaultItemImg = {
|
||||
poison: "systems/foundryvtt-reve-de-dragon/icons/maladies_venins/venin.webp",
|
||||
oeuvre: "systems/foundryvtt-reve-de-dragon/icons/competence_comedie.webp",
|
||||
nourritureboisson: "systems/foundryvtt-reve-de-dragon/icons/objets/provision_crue.webp",
|
||||
service: "systems/foundryvtt-reve-de-dragon/icons/services/lit.webp",
|
||||
signedraconique: "systems/foundryvtt-reve-de-dragon/icons/tmr/signe_draconique.webp",
|
||||
gemme: "systems/foundryvtt-reve-de-dragon/icons/gemmes/almaze.webp",
|
||||
possession: "systems/foundryvtt-reve-de-dragon/icons/entites/possession2.webp",
|
||||
@ -67,10 +78,10 @@ export const defaultItemImg = {
|
||||
export class RdDItem extends Item {
|
||||
|
||||
static getDefaultImg(itemType) {
|
||||
return defaultItemImg[itemType];
|
||||
return game.system.rdd.itemClasses[itemType]?.defaultIcon ?? defaultItemImg[itemType];
|
||||
}
|
||||
|
||||
static isEquipementFieldEditable(type, field) {
|
||||
static isFieldInventaireModifiable(type, field) {
|
||||
switch (field) {
|
||||
case 'quantite':
|
||||
if (['conteneur'].includes(type)) {
|
||||
@ -78,65 +89,86 @@ export class RdDItem extends Item {
|
||||
}
|
||||
break;
|
||||
case 'cout':
|
||||
if(['monnaie'].includes(type)){
|
||||
return game.user.isGM;
|
||||
if (['monnaie'].includes(type)) {
|
||||
return game.user.isGM;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static getUniteQuantite(type) {
|
||||
switch (type) {
|
||||
case "monnaie": return "(Pièces)"
|
||||
case "herbe": return "(Brins)"
|
||||
case "ingredient": return "(Pépins ou Brins)"
|
||||
static async getCorrespondingItem(itemRef) {
|
||||
if (itemRef.pack) {
|
||||
return await SystemCompendiums.loadDocument(itemRef)
|
||||
}
|
||||
return '';
|
||||
return game.items.get(itemRef.id ?? itemRef._id);
|
||||
}
|
||||
|
||||
constructor(itemData, context) {
|
||||
if (!itemData.img) {
|
||||
itemData.img = RdDItem.getDefaultImg(itemData.type);
|
||||
}
|
||||
super(itemData, context);
|
||||
}
|
||||
|
||||
static getTypesObjetsEquipement() {
|
||||
return typesObjetsEquipement
|
||||
static getItemTypesInventaire(mode = 'materiel') {
|
||||
return typesInventaire[mode ?? 'materiel']
|
||||
}
|
||||
|
||||
static getTypesOeuvres() {
|
||||
return typesObjetsOeuvres
|
||||
}
|
||||
|
||||
isCompetencePersonnage() {
|
||||
return this.type == 'competence'
|
||||
}
|
||||
isCompetence() {
|
||||
return typesObjetsCompetence.includes(this.type)
|
||||
}
|
||||
isEquipement() {
|
||||
return typesObjetsEquipement.includes(this.type)
|
||||
}
|
||||
isOeuvre() {
|
||||
return typesObjetsOeuvres.includes(this.type)
|
||||
}
|
||||
isDraconique() {
|
||||
return typesObjetsDraconiques.includes(this.type)
|
||||
}
|
||||
isEffet() {
|
||||
return typesObjetsEffet.includes(this.type)
|
||||
}
|
||||
isConnaissance() {
|
||||
return typesObjetsConnaissance.includes(this.type)
|
||||
}
|
||||
isConteneur() {
|
||||
return this.type == 'conteneur';
|
||||
constructor(docData, context = {}) {
|
||||
if (!context.rdd?.ready) {
|
||||
mergeObject(context, { rdd: { ready: true } });
|
||||
const ItemConstructor = game.system.rdd.itemClasses[docData.type];
|
||||
if (ItemConstructor) {
|
||||
if (!docData.img) {
|
||||
docData.img = ItemConstructor.defaultIcon;
|
||||
}
|
||||
return new ItemConstructor(docData, context);
|
||||
}
|
||||
}
|
||||
if (!docData.img) {
|
||||
docData.img = RdDItem.getDefaultImg(docData.type);
|
||||
}
|
||||
super(docData, context);
|
||||
}
|
||||
|
||||
static get defaultIcon() {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
getUniteQuantite() {
|
||||
switch (this.type) {
|
||||
case "monnaie": return "(Pièces)"
|
||||
case "herbe":
|
||||
switch (this.system.categorie) {
|
||||
case 'Alchimie': case 'Repos': case 'Soin':
|
||||
return "(Brins)"
|
||||
case 'Cuisine': return '';
|
||||
}
|
||||
return '';
|
||||
case "ingredient": return "(Pépins ou Brins)"
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
isCompetencePersonnage() { return this.type == 'competence' }
|
||||
isCompetenceCreature() { return this.type == 'competencecreature' }
|
||||
isConteneur() { return this.type == 'conteneur'; }
|
||||
isMonnaie() { return this.type == 'monnaie'; }
|
||||
isPotion() { return this.type == 'potion'; }
|
||||
isNourritureBoisson() { return this.type == 'nourritureboisson'; }
|
||||
isService() { return this.type == 'service'; }
|
||||
|
||||
isCompetence() { return typesObjetsCompetence.includes(this.type) }
|
||||
isTemporel() { return typesObjetsTemporels.includes(this.type) }
|
||||
isOeuvre() { return typesObjetsOeuvres.includes(this.type) }
|
||||
isDraconique() { return typesObjetsDraconiques.includes(this.type) }
|
||||
isEffet() { return typesObjetsEffet.includes(this.type) }
|
||||
isConnaissance() { return typesObjetsConnaissance.includes(this.type) }
|
||||
|
||||
isInventaire(mode = 'materiel') { return RdDItem.getItemTypesInventaire(mode).includes(this.type); }
|
||||
isAlcool() { return this.isNourritureBoisson() && this.system.boisson && this.system.alcoolise; }
|
||||
isHerbeAPotion() { return this.type == 'herbe' && (this.system.categorie == 'Soin' || this.system.categorie == 'Repos'); }
|
||||
|
||||
getItemGroup() {
|
||||
if (this.isEquipement()) return "equipement";
|
||||
if (this.isInventaire()) return "equipement";
|
||||
if (this.isOeuvre()) return "oeuvre";
|
||||
if (this.isDraconique()) return "draconique";
|
||||
if (this.isConnaissance()) return "connaissance";
|
||||
@ -145,27 +177,56 @@ export class RdDItem extends Item {
|
||||
return "autres";
|
||||
}
|
||||
|
||||
isConteneurNonVide() {
|
||||
return this.isConteneur() && (this.system.contenu?.length ?? 0) > 0;
|
||||
isConteneurNonVide() { return this.isConteneur() && (this.system.contenu?.length ?? 0) > 0; }
|
||||
isConteneurVide() { return this.isConteneur() && (this.system.contenu?.length ?? 0) == 0; }
|
||||
isVideOuNonConteneur() { return !this.isConteneur() || (this.system.contenu?.length ?? 0) == 0; }
|
||||
|
||||
isFinPeriode(oldTimestamp, newTimestamp) {
|
||||
if (!this.isTemporel()) {
|
||||
return false;
|
||||
}
|
||||
const finPeriode = new RdDTimestamp(this.system.temporel.fin);
|
||||
return oldTimestamp.compare(finPeriode) < 0 && finPeriode.compare(newTimestamp) <= 0
|
||||
}
|
||||
|
||||
isConteneurVide() {
|
||||
return this.isConteneur() && (this.system.contenu?.length ?? 0) == 0;
|
||||
async onCreateItemTemporel(actor) {
|
||||
if (this.isTemporel()) {
|
||||
const timestampDebut = game.system.rdd.calendrier.timestamp;
|
||||
const timestampFin = await this.calculerFinPeriodeTemporel(timestampDebut);
|
||||
await actor.updateEmbeddedDocuments('Item', [{
|
||||
_id: this.id,
|
||||
'system.temporel.debut': duplicate(timestampDebut),
|
||||
'system.temporel.fin': duplicate(timestampFin),
|
||||
}])
|
||||
}
|
||||
}
|
||||
|
||||
isVideOuNonConteneur() {
|
||||
return !this.isConteneur() || (this.system.contenu?.length ?? 0) == 0;
|
||||
async calculerFinPeriodeTemporel(timestampDebut) {
|
||||
return timestampDebut;
|
||||
}
|
||||
|
||||
isAlcool() {
|
||||
return this.type == 'nourritureboisson' && this.system.boisson && this.system.alcoolise;
|
||||
async onFinPeriodeTemporel(oldTimestamp, newTimestamp) {
|
||||
if (this.isTemporel() && this.actor) {
|
||||
await this.onFinPeriode(oldTimestamp, newTimestamp);
|
||||
}
|
||||
}
|
||||
isHerbeAPotion() {
|
||||
return this.type == 'herbe' && (this.system.categorie == 'Soin' || this.system.categorie == 'Repos');
|
||||
|
||||
async onFinPeriode(oldTimestamp, newTimestamp) {
|
||||
console.log(`${this.actor.name}: l'objet ${this.name} a expiré et été supprimé`);
|
||||
await this.actor?.deleteEmbeddedDocuments('Item', [this.id]);
|
||||
}
|
||||
isPotion() {
|
||||
return this.type == 'potion';
|
||||
|
||||
isComestible() {
|
||||
switch (this.type) {
|
||||
case 'nourritureboisson': return 'pret';
|
||||
case 'herbe':
|
||||
return this.system.categorie == 'Cuisine' && this.system.sust > 0 ? 'brut' : '';
|
||||
case 'faune':
|
||||
return this.system.sust > 0 ? 'brut' : '';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
isCristalAlchimique() {
|
||||
return this.type == 'objet' && Grammar.toLowerCaseNoAccent(this.name) == 'cristal alchimique' && this.system.quantite > 0;
|
||||
}
|
||||
@ -174,35 +235,58 @@ export class RdDItem extends Item {
|
||||
return this.system.magique
|
||||
}
|
||||
|
||||
isItemCommerce() {
|
||||
return this.parent?.type == 'commerce';
|
||||
}
|
||||
|
||||
getQuantite() {
|
||||
return Math.round(this.isConteneur() ? 1 : (this.system.quantite ?? 0))
|
||||
return this.isService() ? undefined : Math.round(this.system.quantite ?? 0)
|
||||
}
|
||||
|
||||
getEncTotal() {
|
||||
return this.getEnc() * this.getQuantite();
|
||||
}
|
||||
return (this.isService() ? 0 : this.getQuantite()) * this.getEnc();
|
||||
}
|
||||
|
||||
getEnc() {
|
||||
switch (this.type) {
|
||||
case 'service':
|
||||
return 0;
|
||||
case 'herbe':
|
||||
return encBrin;
|
||||
return this.getEncHerbe();
|
||||
case 'gemme':
|
||||
return encPepin * this.system.taille;
|
||||
}
|
||||
return Math.max(this.system.encombrement ?? 0, 0);
|
||||
}
|
||||
|
||||
getEncHerbe() {
|
||||
switch (this.system.categorie) {
|
||||
case 'Repos': case 'Soin': case 'Alchimie':
|
||||
return encBrin;
|
||||
}
|
||||
return this.system.encombrement;
|
||||
|
||||
}
|
||||
|
||||
valeurTotale() {
|
||||
return this.getQuantite() * this.valeur()
|
||||
return (this.isService() ? 1 : this.getQuantite()) * this.valeur()
|
||||
}
|
||||
|
||||
valeur() {
|
||||
return this.system.cout ?? 0
|
||||
}
|
||||
|
||||
calculerPrixCommercant() {
|
||||
if (this.isItemCommerce()) {
|
||||
// appliquer le pourcentage
|
||||
return this.parent.calculerPrix(this);
|
||||
}
|
||||
return this.system.cout;
|
||||
}
|
||||
|
||||
prepareDerivedData() {
|
||||
super.prepareDerivedData();
|
||||
if (this.isEquipement()) {
|
||||
if (this.isInventaire()) {
|
||||
this.system.encTotal = this.getEncTotal();
|
||||
if (this.isPotion()) {
|
||||
this.prepareDataPotion()
|
||||
@ -223,19 +307,43 @@ export class RdDItem extends Item {
|
||||
}
|
||||
|
||||
getActionPrincipale(options = { warnIfNot: true }) {
|
||||
const warn = options.warnIfNot;
|
||||
switch (this.type) {
|
||||
case 'nourritureboisson': return this._actionOrWarnQuantiteZero(this.system.boisson ? 'Boire' : 'Manger', warn);
|
||||
case 'potion': return this._actionOrWarnQuantiteZero('Boire', warn);
|
||||
case 'livre': return this._actionOrWarnQuantiteZero('Lire', warn);
|
||||
case 'conteneur': return 'Ouvrir';
|
||||
case 'herbe': return this.isHerbeAPotion() ? this._actionOrWarnQuantiteZero('Décoction', warn) : undefined;
|
||||
case 'queue': case 'ombre': return this.system.refoulement>0 ? 'Refouler' : undefined;
|
||||
}
|
||||
if (this.actor?.isPersonnage()) {
|
||||
const warn = options.warnIfNot;
|
||||
if (this.isComestible() == 'brut') {
|
||||
return 'Utiliser';
|
||||
}
|
||||
switch (this.type) {
|
||||
case 'nourritureboisson': return this._actionOrWarnQuantiteZero(this.system.boisson ? 'Boire' : 'Manger', warn);
|
||||
case 'potion': return this._actionOrWarnQuantiteZero('Boire', warn);
|
||||
case 'livre': return this._actionOrWarnQuantiteZero('Lire', warn);
|
||||
case 'herbe': return this.isHerbeAPotion() ? this._actionOrWarnQuantiteZero('Décoction', warn) : undefined;
|
||||
case 'queue': case 'ombre': return this.system.refoulement > 0 ? 'Refouler' : undefined;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
_actionOrWarnQuantiteZero(actionName, warn){
|
||||
/* -------------------------------------------- */
|
||||
async actionPrincipale(actor, onActionItem = async () => { }) {
|
||||
if (!this.getActionPrincipale()) {
|
||||
return;
|
||||
}
|
||||
if (await actor.actionNourritureboisson(this, onActionItem)) {
|
||||
return;
|
||||
}
|
||||
switch (this.type) {
|
||||
case 'potion': return await actor.consommerPotion(this, onActionItem);
|
||||
case 'livre': return await actor.actionLire(this);
|
||||
case 'conteneur': return await this.sheet.render(true);
|
||||
case 'herbe': return await actor.actionHerbe(this);
|
||||
case 'queue': case 'ombre': return await actor.actionRefoulement(this);
|
||||
}
|
||||
}
|
||||
|
||||
_actionOrWarnQuantiteZero(actionName, warn) {
|
||||
if ((this.system.quantite ?? 0) <= 0) {
|
||||
if (warn) {
|
||||
ui.notifications.warn(`Vous n'avez plus de ${this.name}.`);
|
||||
@ -252,7 +360,43 @@ export class RdDItem extends Item {
|
||||
await this.quantiteIncDec(-nombre, options);
|
||||
}
|
||||
|
||||
async quantiteIncDec(nombre, options = { diminuerQuantite: true, supprimerSiZero: false }) {
|
||||
async onCreateDecoupeComestible(actor) {
|
||||
if (actor && this.isComestible() == 'brut' && this.system.sust != 1) {
|
||||
if (this.system.sust < 1) {
|
||||
await actor.updateEmbeddedDocuments('Item', [{
|
||||
_id: this.id,
|
||||
'system.sust': 0
|
||||
}])
|
||||
}
|
||||
else {
|
||||
const sust = Math.floor(this.system.sust);
|
||||
await actor.updateEmbeddedDocuments('Item', [{
|
||||
_id: this.id,
|
||||
'system.quantite': this.system.quantite * sust,
|
||||
'system.encombrement': Misc.keepDecimals(this.system.encombrement / sust, 2),
|
||||
'system.cout': Misc.keepDecimals(this.system.cout / sust, 2),
|
||||
'system.sust': 1
|
||||
}])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async empiler(item) {
|
||||
if (this.isComestible() == 'brut') {
|
||||
const sust = this.system.sust + item.system.sust;
|
||||
const encombrement = this.system.encombrement + item.system.encombrement;
|
||||
await this.update({
|
||||
"system.sust": sust,
|
||||
"system.encombrement": encombrement
|
||||
});
|
||||
}
|
||||
else {
|
||||
await this.quantiteIncDec(item.system.quantite);
|
||||
}
|
||||
await item.delete();
|
||||
}
|
||||
|
||||
async quantiteIncDec(nombre, options = { supprimerSiZero: false }) {
|
||||
const quantite = Number(this.system.quantite ?? -1);
|
||||
if (quantite >= 0) {
|
||||
const reste = Math.max(quantite + Number(nombre), 0);
|
||||
@ -275,14 +419,13 @@ export class RdDItem extends Item {
|
||||
|
||||
/* -------------------------------------------- */
|
||||
// détermine si deux équipements sont similaires: de même type, et avec les même champs hormis la quantité
|
||||
isEquipementEmpilable(other) {
|
||||
if (!other || !this.isEquipement()) {
|
||||
isInventaireEmpilable(other) {
|
||||
if (!other || !this.isInventaire()) {
|
||||
return [false, undefined];
|
||||
}
|
||||
|
||||
if (this.system.quantite == undefined) {
|
||||
return [false, `Impossible de regrouper des ${this.type}, ils ne sont pas empilables`];
|
||||
}
|
||||
}
|
||||
else if (this.type != other.type) {
|
||||
return [false, `Impossible de regrouper des ${this.type} avec des ${other.type}`];
|
||||
}
|
||||
@ -290,8 +433,13 @@ export class RdDItem extends Item {
|
||||
return [false, `Impossible de regrouper ${this.name} avec ${other.name}`];
|
||||
}
|
||||
else {
|
||||
const differences = Object.entries(this.system)
|
||||
.filter(([key, value]) => !['quantite', 'cout', 'encTotal'].includes(key) && value != other.system[key]);
|
||||
const excludedProperties = ['quantite', 'cout', 'encTotal', 'environnement'];
|
||||
if (this.isComestible()) {
|
||||
excludedProperties.push('sust', 'encombrement');
|
||||
}
|
||||
let differences = Object.entries(this.system)
|
||||
.filter(([key, value]) => !excludedProperties.includes(key))
|
||||
.filter(([key, value]) => value != other.system[key])
|
||||
if (differences.length > 0) {
|
||||
let message = `Impossible de regrouper les ${this.type} ${this.name}: `;
|
||||
for (const [key, value] of differences) {
|
||||
@ -303,77 +451,88 @@ export class RdDItem extends Item {
|
||||
return [true, undefined];
|
||||
}
|
||||
|
||||
async proposerVente() {
|
||||
async proposerVente(quantiteMax = undefined) {
|
||||
console.log(this);
|
||||
if (this.isConteneurNonVide()) {
|
||||
ui.notifications.warn(`Votre ${this.name} n'est pas vide, pas possible de le proposer`);
|
||||
return;
|
||||
}
|
||||
await DialogItemVente.display(this, async (vente) => {
|
||||
vente["properties"] = this.getProprietes();
|
||||
if (vente.isOwned) {
|
||||
if (vente.quantiteNbLots * vente.tailleLot > vente.quantiteMax) {
|
||||
ui.notifications.warn(`Vous avez ${vente.quantiteMax} ${vente.item.name}, ce n'est pas suffisant pour vendre ${vente.quantiteNbLots} de ${vente.tailleLot}`)
|
||||
return;
|
||||
await DialogItemVente.display({
|
||||
item: this,
|
||||
quantiteMax,
|
||||
callback: async (vente) => {
|
||||
vente["properties"] = this.getProprietes();
|
||||
if (vente.isOwned) {
|
||||
if (vente.quantiteNbLots * vente.tailleLot > vente.quantiteMax) {
|
||||
ui.notifications.warn(`Vous avez ${vente.quantiteMax} ${vente.item.name}, ce n'est pas suffisant pour vendre ${vente.quantiteNbLots} de ${vente.tailleLot}`)
|
||||
return;
|
||||
}
|
||||
}
|
||||
vente.jsondata = JSON.stringify(vente.item);
|
||||
|
||||
let html = await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/chat-vente-item.html', vente);
|
||||
ChatMessage.create(RdDUtility.chatDataSetup(html));
|
||||
}
|
||||
vente.jsondata = JSON.stringify(vente.item);
|
||||
|
||||
console.log(vente);
|
||||
let html = await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/chat-vente-item.html', vente);
|
||||
ChatMessage.create(RdDUtility.chatDataSetup(html));
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getProprietes() {
|
||||
return this[`_${this.type}ChatData`]();
|
||||
if (this[`_${this.type}ChatData`]) {
|
||||
return this[`_${this.type}ChatData`]().filter(it => it != undefined);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async postItem(modeOverride) {
|
||||
async postItemToChat(modeOverride) {
|
||||
console.log(this);
|
||||
let chatData = duplicate(this);
|
||||
chatData["properties"] = this.getProprietes();
|
||||
if (this.actor) {
|
||||
chatData.actor = { id: this.actor.id };
|
||||
let chatData = {
|
||||
doctype: 'Item',
|
||||
id: this.id,
|
||||
type: this.type,
|
||||
img: this.img,
|
||||
pack: this.pack,
|
||||
name: this.name,
|
||||
actor: this.actor ? { id: this.actor.id } : undefined,
|
||||
system: { description: this.system.description },
|
||||
properties: this.getProprietes(),
|
||||
}
|
||||
// JSON object for easy creation
|
||||
chatData.jsondata = JSON.stringify(
|
||||
{
|
||||
compendium: "postedItem",
|
||||
payload: chatData,
|
||||
});
|
||||
|
||||
renderTemplate('systems/foundryvtt-reve-de-dragon/templates/post-item.html', chatData).then(html => {
|
||||
renderTemplate(this.getChatItemTemplate(), chatData).then(html => {
|
||||
let chatOptions = RdDUtility.chatDataSetup(html, modeOverride);
|
||||
ChatMessage.create(chatOptions)
|
||||
});
|
||||
}
|
||||
|
||||
static propertyIfDefined(name, val, condition = (it) => true) {
|
||||
return condition ? [`<b>${name}</b>: ${val}`] : [];
|
||||
getChatItemTemplate() {
|
||||
return 'systems/foundryvtt-reve-de-dragon/templates/post-item.html';
|
||||
}
|
||||
|
||||
static propertyIfDefined(name, val, condition = true) {
|
||||
return condition ? `<b>${name}</b>: ${val}` : undefined;
|
||||
}
|
||||
|
||||
_inventaireTemplateChatData() {
|
||||
return [
|
||||
RdDItem.propertyIfDefined('Qualité', this.system.qualite, this.system.qualite != 0),
|
||||
RdDItem.propertyIfDefined('Encombrement', this.system.encombrement)
|
||||
// cout et quantité masqués
|
||||
]
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
_objetChatData() {
|
||||
return [].concat(
|
||||
RdDItem.propertyIfDefined('Résistance', this.system.resistance, this.system.resistance),
|
||||
RdDItem.propertyIfDefined('Qualité', this.system.qualite, this.system.qualite),
|
||||
RdDItem.propertyIfDefined('Encombrement', this.system.encombrement),
|
||||
);
|
||||
return this._inventaireTemplateChatData()
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
_nourritureboissonChatData() {
|
||||
return [].concat(
|
||||
return [
|
||||
RdDItem.propertyIfDefined('Sustentation', this.system.sust, this.system.sust > 0),
|
||||
RdDItem.propertyIfDefined('Désaltère', this.system.desaltere, this.system.boisson),
|
||||
RdDItem.propertyIfDefined('Force alcool', this.system.force, this.system.boisson && this.system.alcoolise),
|
||||
RdDItem.propertyIfDefined('Exotisme', this.system.exotisme, this.system.exotisme < 0),
|
||||
RdDItem.propertyIfDefined('Qualité', this.system.qualite, this.system.qualite),
|
||||
RdDItem.propertyIfDefined('Encombrement', this.system.encombrement),
|
||||
);
|
||||
...this._inventaireTemplateChatData()
|
||||
]
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
_armeChatData() {
|
||||
@ -382,21 +541,19 @@ export class RdDItem extends Item {
|
||||
`<b>Dommages</b>: ${this.system.dommages}`,
|
||||
`<b>Force minimum</b>: ${this.system.force}`,
|
||||
`<b>Resistance</b>: ${this.system.resistance}`,
|
||||
`<b>Encombrement</b>: ${this.system.encombrement}`
|
||||
...this._inventaireTemplateChatData()
|
||||
]
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
_conteneurChatData() {
|
||||
return [
|
||||
`<b>Capacité</b>: ${this.system.capacite} Enc.`,
|
||||
`<b>Encombrement</b>: ${this.system.encombrement}`
|
||||
...this._inventaireTemplateChatData()
|
||||
]
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
_munitionChatData() {
|
||||
return [
|
||||
`<b>Encombrement</b>: ${this.system.encombrement}`
|
||||
]
|
||||
return this._inventaireTemplateChatData()
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
_armureChatData() {
|
||||
@ -404,7 +561,7 @@ export class RdDItem extends Item {
|
||||
`<b>Protection</b>: ${this.system.protection}`,
|
||||
`<b>Détérioration</b>: ${this.system.deterioration}`,
|
||||
`<b>Malus armure</b>: ${this.system.malus}`,
|
||||
`<b>Encombrement</b>: ${this.system.encombrement}`
|
||||
...this._inventaireTemplateChatData()
|
||||
]
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
@ -438,16 +595,24 @@ export class RdDItem extends Item {
|
||||
_herbeChatData() {
|
||||
return [
|
||||
`<b>Milieu</b>: ${this.system.milieu}`,
|
||||
`<b>Rareté</b>: ${this.system.rarete}`,
|
||||
`<b>Catégorie</b>: ${this.system.categorie}`,
|
||||
...this._inventaireTemplateChatData()
|
||||
]
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
_ingredientChatData() {
|
||||
return [
|
||||
`<b>Milieu</b>: ${this.system.milieu}`,
|
||||
`<b>Rareté</b>: ${this.system.rarete}`,
|
||||
`<b>Catégorie</b>: ${this.system.categorie}`,
|
||||
...this._inventaireTemplateChatData()
|
||||
]
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
_fauneChatData() {
|
||||
return [
|
||||
`<b>Sustentation</b>: ${this.system.sust}`,
|
||||
`<b>Milieu</b>: ${this.system.milieu}`,
|
||||
...this._inventaireTemplateChatData()
|
||||
]
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
@ -457,12 +622,9 @@ export class RdDItem extends Item {
|
||||
`<b>Compétence</b>: ${this.system.competence}`,
|
||||
`<b>Périodicité</b>: ${this.system.periodicite}`,
|
||||
`<b>Fatigue</b>: ${this.system.fatigue}`,
|
||||
`<b>Difficulté</b>: ${this.system.difficulte}`
|
||||
].concat([
|
||||
this.system.cacher_points_de_tache ? [] :`<b>Points de Tâche</b>: ${this.system.points_de_tache}`
|
||||
]).concat([
|
||||
`<b>Difficulté</b>: ${this.system.difficulte}`,
|
||||
RdDItem.propertyIfDefined('Points de Tâche', this.system.points_de_tache, this.system.cacher_points_de_tache),
|
||||
`<b>Points de Tâche atteints</b>: ${this.system.points_de_tache_courant}`]
|
||||
);
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
_livreChatData() {
|
||||
@ -470,8 +632,8 @@ export class RdDItem extends Item {
|
||||
`<b>Compétence</b>: ${this.system.competence}`,
|
||||
`<b>Auteur</b>: ${this.system.auteur}`,
|
||||
`<b>Difficulté</b>: ${this.system.difficulte}`,
|
||||
`<b>Points de Tâche</b>: ${this.system.points_de_tache}`,
|
||||
`<b>Encombrement</b>: ${this.system.encombrement}`
|
||||
RdDItem.propertyIfDefined('Points de Tâche', this.system.points_de_tache, this.system.cacher_points_de_tache),
|
||||
...this._inventaireTemplateChatData()
|
||||
]
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
@ -479,32 +641,44 @@ export class RdDItem extends Item {
|
||||
return [
|
||||
`<b>Rareté</b>: ${this.system.rarete}`,
|
||||
`<b>Catégorie</b>: ${this.system.categorie}`,
|
||||
`<b>Encombrement</b>: ${this.system.encombrement}`,
|
||||
...this._inventaireTemplateChatData()
|
||||
]
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
_queueChatData() {
|
||||
function label(categorie) {
|
||||
switch (categorie) {
|
||||
case 'ideefixe': return 'Idée fixe';
|
||||
case 'lancinant': return 'Désir lancinant';
|
||||
}
|
||||
return ''
|
||||
}
|
||||
return [
|
||||
`<b>Refoulement</b>: ${this.system.refoulement}`
|
||||
`<b>Refoulement</b>: ${this.system.refoulement}`,
|
||||
`<b>Catégorie</b>: ${label(this.system.categorie)}`,
|
||||
`<b>Affecte</b>: ${this.system.hautrevant ? 'les haut-rêvants' : 'tout le monde'}`,
|
||||
]
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
_ombreChatData() {
|
||||
return [
|
||||
`<b>Refoulement</b>: ${this.system.refoulement}`
|
||||
]
|
||||
return this._queueChatData()
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
_souffleChatData() {
|
||||
return [];
|
||||
return [
|
||||
`<b>Affecte</b>: ${this.system.hautrevant ? 'les haut-rêvants' : 'tout le monde'}`,
|
||||
];
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
_teteChatData() {
|
||||
return [];
|
||||
return [
|
||||
`<b>Affecte</b>: ${this.system.hautrevant ? 'les haut-rêvants' : 'tout le monde'}`,
|
||||
];
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
_tarotChatData() {
|
||||
return [
|
||||
RdDItem.propertyIfDefined('Carte', RdDUtility.linkCompendium(this.pack, this.id, this.name), this.pack),
|
||||
`<b>Concept</b>: ${this.system.concept}`,
|
||||
`<b>Aspect</b>: ${this.system.aspect}`,
|
||||
]
|
||||
@ -518,10 +692,7 @@ export class RdDItem extends Item {
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
_monnaieChatData() {
|
||||
return [
|
||||
`<b>Valeur en Sols</b>: ${this.system.cout}`,
|
||||
`<b>Encombrement</b>: ${this.system.encombrement}`
|
||||
]
|
||||
return this._inventaireTemplateChatData()
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
_meditationChatData() {
|
||||
@ -545,9 +716,9 @@ export class RdDItem extends Item {
|
||||
]
|
||||
}
|
||||
return [
|
||||
`<b>Force</b>: ${this.system.force}`,
|
||||
`<b>Force</b>: ${this.system.formule}`,
|
||||
`<b>Refoulement</b>: ${this.system.refoulement}`,
|
||||
`<b>Présent de cités</b>: ${this.system.presentCite}`,
|
||||
RdDItem.propertyIfDefined('<b>Présent de cités</b>', '', this.system.presentCite),
|
||||
]
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
@ -562,15 +733,12 @@ export class RdDItem extends Item {
|
||||
if (!this.system.identifie) {
|
||||
return [`<b>Inconnue</b>`]
|
||||
}
|
||||
let properties = [
|
||||
`<b>Malignité</b>: ${this.system.malignite}`,
|
||||
`<b>Périodicité</b>: ${this.system.periodicite}`,
|
||||
`<b>Dommages</b>: ${this.system.dommages}`
|
||||
]
|
||||
if (this.system.remedesconnus) {
|
||||
properties.push(`<b>Remedes</b>: ${this.system.remedes}`)
|
||||
}
|
||||
return properties;
|
||||
return [
|
||||
`<b>Malignité</b>: ${this.system.malignite}`,
|
||||
`<b>Périodicité</b>: ${this.system.periodicite}`,
|
||||
`<b>Dommages</b>: ${this.system.dommages}`,
|
||||
RdDItem.propertyIfDefined('<b>Remedes</b>', this.system.remedes, this.system.remedesconnus),
|
||||
]
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
@ -585,8 +753,7 @@ export class RdDItem extends Item {
|
||||
`<b>Taille</b>: ${this.system.taille}`,
|
||||
`<b>Inertie</b>: ${this.system.inertie}`,
|
||||
`<b>Enchantabilité</b>: ${this.system.enchantabilite}`,
|
||||
`<b>Prix</b>: ${this.system.cout}`,
|
||||
...this._inventaireTemplateChatData()
|
||||
]
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,4 +1,5 @@
|
||||
import { EffetsRencontre } from "./effets-rencontres.js";
|
||||
import { EffetsRencontre } from "../effets-rencontres.js";
|
||||
import { RdDItem } from "../item.js";
|
||||
|
||||
const tableEffets = [
|
||||
{ code: "messager", resultat: "succes", description: "Envoie un message à (force) cases", method: EffetsRencontre.messager },
|
||||
@ -36,7 +37,11 @@ const tableEffets = [
|
||||
// { code: "epart-souffle", resultat: "echec", description: "Souffle de dragon sur échec particulier" },
|
||||
];
|
||||
|
||||
export class RdDRencontre {
|
||||
export class RdDRencontre extends RdDItem {
|
||||
|
||||
static get defaultIcon() {
|
||||
return "systems/foundryvtt-reve-de-dragon/icons/tete_dragon.webp";
|
||||
}
|
||||
|
||||
static getEffetsSucces() { return RdDRencontre.getEffets("succes"); }
|
||||
static getEffetsEchec() { return RdDRencontre.getEffets("echec"); }
|
||||
@ -68,4 +73,8 @@ export class RdDRencontre {
|
||||
}
|
||||
}
|
||||
|
||||
async calculerFinPeriodeTemporel(debut) {
|
||||
return await debut.nouvelleHeure().addHeures(12);
|
||||
}
|
||||
|
||||
}
|
17
module/item/item-service.js
Normal file
@ -0,0 +1,17 @@
|
||||
import { RdDItem } from "../item.js";
|
||||
|
||||
export class RdDItemService extends RdDItem {
|
||||
|
||||
static get defaultIcon() {
|
||||
return "systems/foundryvtt-reve-de-dragon/icons/services/lit.webp";
|
||||
}
|
||||
|
||||
isService() { return true; }
|
||||
getProprietes() {
|
||||
return [
|
||||
RdDItem.propertyIfDefined('Qualité', this.system.qualite, this.system.qualite != 0),
|
||||
RdDItem.propertyIfDefined('Moral', 'Situation heureuse', this.system.moral),
|
||||
RdDItem.propertyIfDefined('Coût', `${this.calculerPrixCommercant()} sols`),
|
||||
];
|
||||
}
|
||||
}
|
@ -1,8 +1,9 @@
|
||||
import { defaultItemImg } from "./item.js";
|
||||
import { Misc } from "./misc.js";
|
||||
import { RdDDice } from "./rdd-dice.js";
|
||||
import { RdDRollTables } from "./rdd-rolltables.js";
|
||||
import { TMRType, TMRUtility } from "./tmr-utility.js";
|
||||
import { RdDItem, defaultItemImg } from "../item.js";
|
||||
import { Misc } from "../misc.js";
|
||||
import { RdDDice } from "../rdd-dice.js";
|
||||
import { RdDRollTables } from "../rdd-rolltables.js";
|
||||
import { RdDTimestamp } from "../rdd-timestamp.js";
|
||||
import { TMRType, TMRUtility } from "../tmr-utility.js";
|
||||
|
||||
const tableSignesIndicatifs = [
|
||||
{ rarete: "Très facile", difficulte: 0, xp: 6, nbCases: 14 },
|
||||
@ -15,7 +16,17 @@ const tableSignesIndicatifs = [
|
||||
|
||||
const DIFFICULTE_LECTURE_SIGNE_MANQUE = +11;
|
||||
|
||||
export class RdDItemSigneDraconique {
|
||||
export class RdDItemSigneDraconique extends RdDItem {
|
||||
|
||||
static get defaultIcon() {
|
||||
return "systems/foundryvtt-reve-de-dragon/icons/tmr/signe_draconique.webp";
|
||||
}
|
||||
|
||||
|
||||
async calculerFinPeriodeTemporel(debut) {
|
||||
// TODO
|
||||
return RdDTimestamp.formulesDuree().find(it => it.code == "").calcul(debut, this.actor);
|
||||
}
|
||||
|
||||
static prepareSigneDraconiqueMeditation(meditation, rolled) {
|
||||
return {
|
||||
@ -96,6 +107,6 @@ export class RdDItemSigneDraconique {
|
||||
|
||||
static async randomSigneDescription() {
|
||||
return await RdDRollTables.drawTextFromRollTable("Signes draconiques", false);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
47
module/item/maladie.js
Normal file
@ -0,0 +1,47 @@
|
||||
import { RdDItem } from "../item.js";
|
||||
import { Misc } from "../misc.js";
|
||||
import { RdDTimestamp } from "../rdd-timestamp.js";
|
||||
|
||||
export class RdDItemMaladie extends RdDItem {
|
||||
|
||||
static get defaultIcon() {
|
||||
return "systems/foundryvtt-reve-de-dragon/icons/maladies_venins/maladie.webp";
|
||||
}
|
||||
|
||||
async calculerFinPeriodeTemporel(debut) {
|
||||
return await debut.addPeriode(this.system.periode.nombre, this.system.periode.unite);
|
||||
}
|
||||
|
||||
async onFinPeriode(oldTimestamp, newTimestamp) {
|
||||
await RdDItemMaladie.notifierMaladiePoison(this, oldTimestamp, newTimestamp)
|
||||
}
|
||||
|
||||
static async notifierMaladiePoison(mal, oldTimestamp, newTimestamp) {
|
||||
if (mal.actor) {
|
||||
const souffrance = mal.system.identifie
|
||||
? `de ${mal.name}`
|
||||
: `d'un mal inconnu`
|
||||
ChatMessage.create({ content: `${mal.actor.name} souffre ${souffrance} (${Misc.typeName('Item', mal.type)}): vérifiez que les effets ne se sont pas aggravés !` });
|
||||
mal.postItemToChat('gmroll');
|
||||
await RdDItemMaladie.prolongerPeriode(mal,oldTimestamp, newTimestamp);
|
||||
}
|
||||
}
|
||||
|
||||
static async prolongerPeriode(mal, oldTimestamp, newTimestamp) {
|
||||
if (mal.actor) {
|
||||
// TODO: déterminer le nombre de périodes écoulées
|
||||
console.log(`${mal.actor.name}: le mal ${mal.name} a atteint la fin de sa période et été prolongé`);
|
||||
const current = newTimestamp;
|
||||
const finPeriode = new RdDTimestamp(mal.system.temporel.fin)
|
||||
const periodeSuivante = (finPeriode.compare(current) > 0 ? finPeriode : current);
|
||||
const timestampFin = await mal.calculerFinPeriodeTemporel(periodeSuivante);
|
||||
|
||||
await mal.actor.updateEmbeddedDocuments('Item', [{
|
||||
_id: mal.id,
|
||||
'system.temporel.fin': duplicate(timestampFin),
|
||||
}])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
11
module/item/ombre.js
Normal file
@ -0,0 +1,11 @@
|
||||
import { RdDItem } from "../item.js";
|
||||
|
||||
export class RdDItemOmbre extends RdDItem {
|
||||
static get defaultIcon() {
|
||||
return "systems/foundryvtt-reve-de-dragon/icons/queue_dragon.webp";
|
||||
}
|
||||
|
||||
async calculerFinPeriodeTemporel(debut) {
|
||||
return await debut.appliquerDuree(this.system.duree, this.parent);
|
||||
}
|
||||
}
|
17
module/item/poison.js
Normal file
@ -0,0 +1,17 @@
|
||||
import { RdDItem } from "../item.js";
|
||||
import { RdDItemMaladie } from "./maladie.js";
|
||||
|
||||
export class RdDItemPoison extends RdDItem {
|
||||
|
||||
static get defaultIcon() {
|
||||
return "systems/foundryvtt-reve-de-dragon/icons/maladies_venins/venin.webp";
|
||||
}
|
||||
|
||||
async calculerFinPeriodeTemporel(debut) {
|
||||
return await debut.addPeriode(this.system.periode.nombre, this.system.periode.unite) ;
|
||||
}
|
||||
|
||||
async onFinPeriode(oldTimestamp, newTimestamp) {
|
||||
RdDItemMaladie.notifierMaladiePoison(this, oldTimestamp, newTimestamp)
|
||||
}
|
||||
}
|
13
module/item/queue.js
Normal file
@ -0,0 +1,13 @@
|
||||
import { RdDItem } from "../item.js";
|
||||
|
||||
export class RdDItemQueue extends RdDItem {
|
||||
|
||||
static get defaultIcon() {
|
||||
return "systems/foundryvtt-reve-de-dragon/icons/queue_dragon.webp";
|
||||
}
|
||||
|
||||
async calculerFinPeriodeTemporel(debut) {
|
||||
return await debut.appliquerDuree(this.system.duree, this.parent);
|
||||
}
|
||||
|
||||
}
|
13
module/item/souffle.js
Normal file
@ -0,0 +1,13 @@
|
||||
import { RdDItem } from "../item.js";
|
||||
|
||||
export class RdDItemSouffle extends RdDItem {
|
||||
|
||||
static get defaultIcon() {
|
||||
return "systems/foundryvtt-reve-de-dragon/icons/souffle_dragon.webp";
|
||||
}
|
||||
|
||||
async calculerFinPeriodeTemporel(debut) {
|
||||
return await debut.appliquerDuree(this.system.duree, this.parent);
|
||||
}
|
||||
|
||||
}
|
@ -1,6 +1,10 @@
|
||||
import { RdDBaseActor } from "./actor/base-actor.js";
|
||||
import { LOG_HEAD, SYSTEM_RDD } from "./constants.js";
|
||||
import { Environnement } from "./environnement.js";
|
||||
import { Grammar } from "./grammar.js";
|
||||
import { Monnaie } from "./item-monnaie.js";
|
||||
import { RdDItem } from "./item.js";
|
||||
import { RdDTimestamp } from "./rdd-timestamp.js";
|
||||
|
||||
class Migration {
|
||||
get code() { return "sample"; }
|
||||
@ -29,6 +33,39 @@ class Migration {
|
||||
|
||||
}
|
||||
|
||||
class _1_5_34_migrationPngWebp {
|
||||
get code() { return "migrationPngWebp"; }
|
||||
get version() { return "1.5.34"; }
|
||||
async migrate() {
|
||||
|
||||
const regexOldPngJpg = /(systems\/foundryvtt-reve-de-dragon\/icons\/.*)\.(png|jpg)/;
|
||||
const replaceWithWebp = '$1.webp';
|
||||
function convertImgToWebp(img) {
|
||||
return img.replace(regexOldPngJpg, replaceWithWebp);
|
||||
}
|
||||
function prepareDocumentsImgUpdate(documents) {
|
||||
return documents.filter(it => it.img && it.img.match(regexOldPngJpg))
|
||||
.map(it => {
|
||||
return { _id: it.id, img: convertImgToWebp(it.img) }
|
||||
});
|
||||
}
|
||||
|
||||
const itemsUpdates = prepareDocumentsImgUpdate(game.items);
|
||||
const actorsUpdates = prepareDocumentsImgUpdate(game.actors);
|
||||
//Migrate system png to webp
|
||||
await Item.updateDocuments(itemsUpdates);
|
||||
await Actor.updateDocuments(actorsUpdates);
|
||||
game.actors.forEach(actor => {
|
||||
if (actor.token?.img && actor.token.img.match(regexOldPngJpg)) {
|
||||
actor.update({ "token.img": convertImgToWebp(actor.token.img) });
|
||||
}
|
||||
const actorItemsToUpdate = prepareDocumentsImgUpdate(actor.items);
|
||||
actor.updateEmbeddedDocuments('Item', actorItemsToUpdate);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class _10_0_16_MigrationSortsReserve extends Migration {
|
||||
get code() { return "creation-item-sort-reserve"; }
|
||||
get version() { return "10.0.16"; }
|
||||
@ -236,7 +273,7 @@ class _10_3_0_Inventaire extends Migration {
|
||||
}
|
||||
_updatesMonnaies(items) {
|
||||
return items
|
||||
.filter(it => ['monnaie'].includes(it.type) && it.system.cout == undefined)
|
||||
.filter(it => ['monnaie'].includes(it.type) && it.system.valeur_deniers != undefined)
|
||||
.map(it => { return { _id: it.id, 'system.cout': it.system.valeur_deniers / 100, 'system.valeur_deniers': undefined } });
|
||||
}
|
||||
}
|
||||
@ -259,9 +296,129 @@ class _10_3_0_FrequenceEnvironnement extends Migration {
|
||||
}
|
||||
}
|
||||
|
||||
class _10_3_17_Monnaies extends Migration {
|
||||
constructor() {
|
||||
super();
|
||||
this.mapValeur = {
|
||||
"Etain (1 denier)": { name: 'Denier (étain)', system: { cout: 0.01 } },
|
||||
"Bronze (10 deniers)": { name: "Sou (bronze)", system: { cout: 0.1 } },
|
||||
"Argent (1 sol)": { name: "Sol (argent)", system: { cout: 1 } },
|
||||
"Or (10 sols)": { name: "Dragon (or)", system: { cout: 10 } }
|
||||
};
|
||||
}
|
||||
get code() { return "migration-monnaies"; }
|
||||
get version() { return "10.3.17"; }
|
||||
|
||||
async migrate() {
|
||||
await this.applyItemsUpdates(items => this._updatesMonnaies(items));
|
||||
}
|
||||
|
||||
_updatesMonnaies(items) {
|
||||
return items
|
||||
.filter(it => 'monnaie' == it.type)
|
||||
.filter(it => this.mapValeur[it.name] != undefined)
|
||||
.map(it => {
|
||||
const correction = this.mapValeur[it.name];
|
||||
return {
|
||||
_id: it.id,
|
||||
'name': correction.name,
|
||||
'system.cout': correction.system.cout,
|
||||
'system.valeur_deniers': undefined
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class _10_4_6_ServicesEnCommerces extends Migration {
|
||||
|
||||
get code() { return "migration-service-acteurs"; }
|
||||
get version() { return "10.4.6"; }
|
||||
|
||||
async migrate() {
|
||||
const servicesToMigrate = game.items.filter(it => it.type == 'service');
|
||||
servicesToMigrate.forEach(async service => {
|
||||
const commerce = await this.convertServiceToCommerce(service);
|
||||
await RdDBaseActor.create(commerce, { renderSheet: false });
|
||||
await service.delete();
|
||||
});
|
||||
}
|
||||
|
||||
async convertServiceToCommerce(service) {
|
||||
return {
|
||||
name: service.name, img: service.img, type: 'commerce',
|
||||
system: {
|
||||
description: service.system.description,
|
||||
notesmj: service.system.descriptionmj,
|
||||
illimite: service.system.illimite
|
||||
},
|
||||
items: await this.transformInventaireCommerce(service)
|
||||
}
|
||||
}
|
||||
async transformInventaireCommerce(service) {
|
||||
const serviceItems = (service.system.items ?? []);
|
||||
const commerceItems = await Promise.all(serviceItems.map(async (it) => { return await this.transformToItemBoutique(it); }));
|
||||
return commerceItems.concat(Monnaie.monnaiesStandard());
|
||||
}
|
||||
|
||||
async transformToItemBoutique(serviceRefItem) {
|
||||
const item = await RdDItem.getCorrespondingItem(serviceRefItem);
|
||||
const itemToCreate = {
|
||||
name: item.name, img: item.img, type: item.type,
|
||||
system: mergeObject({ cout: serviceRefItem.system.cout, quantite: serviceRefItem.system.quantite }, item.system, { overwrite: false })
|
||||
};
|
||||
return itemToCreate;
|
||||
}
|
||||
}
|
||||
class _10_5_0_UpdatePeriodicite extends Migration {
|
||||
get code() { return "migration-periodicite-poisons-maladies"; }
|
||||
get version() { return "10.5.0"; }
|
||||
|
||||
async migrate() {
|
||||
await this.applyItemsUpdates(items => this._updatePeriodicite(items));
|
||||
}
|
||||
|
||||
_updatePeriodicite(items) {
|
||||
return items.filter(it => ['poison', 'maladie'].includes(it.type))
|
||||
.filter(it => it.system.periodicite != "")
|
||||
.map(it => {
|
||||
let [incubation, periodicite] = this.getPeriodicite(it);
|
||||
const periode = periodicite.split(' ');
|
||||
let unite = periode.length == 2
|
||||
? RdDTimestamp.formulesPeriode().find(it => Grammar.includesLowerCaseNoAccent(periode[1], it.code))?.code
|
||||
: undefined
|
||||
if (unite && Number(periode[0])) {
|
||||
return {
|
||||
_id: it.id,
|
||||
'system.periodicite': undefined,
|
||||
'system.incubation': incubation,
|
||||
'system.periode.nombre': Number.parseInt(periode[0]),
|
||||
'system.periode.unite': unite
|
||||
};
|
||||
}
|
||||
else {
|
||||
return {
|
||||
_id: it.id,
|
||||
'system.periodicite': undefined,
|
||||
'system.incubation': it.system.periodicite
|
||||
};
|
||||
}
|
||||
}).filter(it => it != undefined);
|
||||
}
|
||||
|
||||
getPeriodicite(it) {
|
||||
let p = it.system.periodicite.split(/[\/\\]/);
|
||||
switch (p.length) {
|
||||
case 2: return [p[0].trim(), p[1].trim()];
|
||||
case 1: return ["", it.system.periodicite.trim()];
|
||||
default: return [it.system.periodicite.trim(), ""];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class Migrations {
|
||||
static getMigrations() {
|
||||
return [
|
||||
new _1_5_34_migrationPngWebp(),
|
||||
new _10_0_16_MigrationSortsReserve(),
|
||||
new _10_0_17_MigrationCompetenceCreature(),
|
||||
new _10_0_21_VehiculeStructureResistanceMax(),
|
||||
@ -269,7 +426,10 @@ export class Migrations {
|
||||
new _10_2_5_ArmesTirLancer(),
|
||||
new _10_2_10_DesirLancinant_IdeeFixe(),
|
||||
new _10_3_0_Inventaire(),
|
||||
new _10_3_0_FrequenceEnvironnement()
|
||||
new _10_3_0_FrequenceEnvironnement(),
|
||||
new _10_3_17_Monnaies(),
|
||||
new _10_4_6_ServicesEnCommerces(),
|
||||
new _10_5_0_UpdatePeriodicite(),
|
||||
];
|
||||
}
|
||||
|
||||
@ -284,18 +444,12 @@ export class Migrations {
|
||||
}
|
||||
|
||||
migrate() {
|
||||
const currentVersion = game.settings.get(SYSTEM_RDD,"systemMigrationVersion");
|
||||
//if (isNewerVersion(game.system.version, currentVersion)) {
|
||||
if (true) { /* comment previous and uncomment here to test before upgrade */
|
||||
const currentVersion = game.settings.get(SYSTEM_RDD, "systemMigrationVersion");
|
||||
if (isNewerVersion(game.system.version, currentVersion)) {
|
||||
//if (true) { /* comment previous and uncomment here to test before upgrade */
|
||||
const migrations = Migrations.getMigrations().filter(m => isNewerVersion(m.version, currentVersion));
|
||||
if (migrations.length > 0) {
|
||||
migrations.sort((a, b) =>
|
||||
isNewerVersion(a.version, b.version)
|
||||
? 1
|
||||
: isNewerVersion(b.version, a.version)
|
||||
? -1
|
||||
: 0
|
||||
);
|
||||
migrations.sort((a, b) => this.compareVersions(a, b));
|
||||
migrations.forEach(async (m) => {
|
||||
ui.notifications.info(
|
||||
`Executing migration ${m.code}: version ${currentVersion} is lower than ${m.version}`
|
||||
@ -321,4 +475,8 @@ export class Migrations {
|
||||
console.log(LOG_HEAD + `No system version changed`);
|
||||
}
|
||||
}
|
||||
|
||||
compareVersions(a, b) {
|
||||
return isNewerVersion(a.version, b.version) ? 1 : isNewerVersion(b.version, a.version) ? -1 : 0;
|
||||
}
|
||||
}
|
||||
|
@ -42,9 +42,13 @@ export class Misc {
|
||||
}
|
||||
|
||||
static typeName(type, subType) {
|
||||
return game.i18n.localize(`${type.toUpperCase()}.Type${Misc.upperFirst(subType)}`);
|
||||
return subType ? game.i18n.localize(`${type.toUpperCase()}.Type${Misc.upperFirst(subType)}`)
|
||||
: '';
|
||||
}
|
||||
|
||||
static arrayOrEmpty(items) {
|
||||
return items?.length ? items : [];
|
||||
}
|
||||
/**
|
||||
* Converts the value to an integer, or to 0 if undefined/null/not representing integer
|
||||
* @param {*} value value to convert to an integer using parseInt
|
||||
@ -72,6 +76,19 @@ export class Misc {
|
||||
}
|
||||
}
|
||||
|
||||
static indexLowercase(list) {
|
||||
const obj = {};
|
||||
const addToObj = (map, val) => {
|
||||
const key = Grammar.toLowerCaseNoAccent(val);
|
||||
if (key && !map[key]) map[key] = val
|
||||
}
|
||||
list.forEach(it => addToObj(obj, it))
|
||||
return obj;
|
||||
}
|
||||
static concat(lists) {
|
||||
return lists.reduce((a, b) => a.concat(b), []);
|
||||
}
|
||||
|
||||
static classify(items, classifier = it => it.type) {
|
||||
let itemsBy = {}
|
||||
Misc.classifyInto(itemsBy, items, classifier)
|
||||
@ -120,20 +137,27 @@ export class Misc {
|
||||
return Misc.firstConnectedGM()?.id ?? game.user.id;
|
||||
}
|
||||
|
||||
static isRollModeHiddenToPlayer() {
|
||||
switch (game.settings.get("core", "rollMode")) {
|
||||
case CONST.DICE_ROLL_MODES.BLIND:
|
||||
case CONST.DICE_ROLL_MODES.SELF: return true;
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
static getActiveUser(id) {
|
||||
return game.users.find(u => u.id == id && u.active);
|
||||
}
|
||||
}
|
||||
|
||||
static firstConnectedGM() {
|
||||
return game.users.filter(u => u.isGM && u.active).sort(Misc.ascending(u => u.id)).find(u => u.isGM && u.active);
|
||||
|
||||
}
|
||||
|
||||
static isOwnerPlayer(actor, user=undefined) {
|
||||
static isOwnerPlayer(actor, user = undefined) {
|
||||
return actor.testUserPermission(user ?? game.user, CONST.DOCUMENT_PERMISSION_LEVELS.OWNER)
|
||||
}
|
||||
|
||||
static isOwnerPlayerOrUniqueConnectedGM(actor, user =undefined){
|
||||
static isOwnerPlayerOrUniqueConnectedGM(actor, user = undefined) {
|
||||
return Misc.isOwnerPlayer(actor, user) ?? Misc.isUniqueConnectedGM();
|
||||
}
|
||||
|
||||
|
@ -3,26 +3,37 @@
|
||||
* Extend the base Dialog entity by defining a custom window to perform roll.
|
||||
* @extends {Dialog}
|
||||
*/
|
||||
export class RdDAstrologieEditeur extends Dialog {
|
||||
export class RdDAstrologieEditeur extends Dialog {
|
||||
|
||||
/* -------------------------------------------- */
|
||||
constructor(html, calendrier, calendrierData) {
|
||||
|
||||
let myButtons = {
|
||||
resetButton: { label: "Re-tirer les nombres astraux", callback: html => this.resetNombreAstraux() },
|
||||
saveButton: { label: "Fermer", callback: html => this.fillData() }
|
||||
};
|
||||
resetButton: { label: "Re-tirer les nombres astraux", callback: html => this.resetNombreAstraux() },
|
||||
saveButton: { label: "Fermer", callback: html => this.fillData() }
|
||||
};
|
||||
|
||||
// Common conf
|
||||
let dialogConf = { content: html, title: "Editeur d'Astrologie", buttons: myButtons, default: "saveButton" };
|
||||
let dialogOptions = { classes: ["rdddialog"], width: 600, height: 300, 'z-index': 99999 }
|
||||
let dialogOptions = {
|
||||
classes: ["rdd-roll-dialog"], width: 600,
|
||||
height: 'fit-content',
|
||||
'max-height': 800,
|
||||
'z-index': 99999
|
||||
}
|
||||
super(dialogConf, dialogOptions)
|
||||
|
||||
|
||||
this.calendrier = calendrier;
|
||||
this.updateData( calendrierData );
|
||||
this.updateData(calendrierData);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
this.html = html;
|
||||
}
|
||||
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async resetNombreAstraux() {
|
||||
game.system.rdd.calendrier.resetNombreAstral();
|
||||
await game.system.rdd.calendrier.rebuildListeNombreAstral();
|
||||
@ -30,24 +41,13 @@
|
||||
game.system.rdd.calendrier.showAstrologieEditor();
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
fillData( ) {
|
||||
/* -------------------------------------------- */
|
||||
fillData() {
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
updateData( calendrierData ) {
|
||||
updateData(calendrierData) {
|
||||
this.calendrierData = duplicate(calendrierData);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
|
||||
let astrologieData = this.astrologieData;
|
||||
|
||||
$(function () {
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -10,7 +10,7 @@ import { SYSTEM_SOCKET_ID } from "./constants.js";
|
||||
export class RdDAstrologieJoueur extends Dialog {
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static async create(actor, dialogConfig) {
|
||||
static async create(actor) {
|
||||
|
||||
let dialogData = {
|
||||
nombres: this.organizeNombres(actor),
|
||||
@ -20,33 +20,43 @@ export class RdDAstrologieJoueur extends Dialog {
|
||||
astrologie: RdDItemCompetence.findCompetence(actor.items, 'Astrologie')
|
||||
}
|
||||
const html = await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/dialog-astrologie-joueur.html', dialogData);
|
||||
let options = { classes: ["rdddialog"], width: 600, height: 500, 'z-index': 99999 };
|
||||
if (dialogConfig.options) {
|
||||
mergeObject(options, dialogConfig.options, { overwrite: true });
|
||||
}
|
||||
return new RdDAstrologieJoueur(html, actor, dialogData);
|
||||
|
||||
const options = { classes: ["rdd-roll-dialog"], width: 600, height: 'fit-content', 'z-index': 99999 };
|
||||
const dialog = new RdDAstrologieJoueur(html, actor, dialogData, options);
|
||||
dialog.render(true);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
constructor(html, actor, dialogData) {
|
||||
|
||||
let myButtons = {
|
||||
saveButton: { label: "Fermer", callback: html => this.quitDialog() }
|
||||
constructor(html, actor, dialogData, dialogOptions) {
|
||||
const dialogConf = {
|
||||
title: "Nombres Astraux",
|
||||
content: html,
|
||||
default: "saveButton",
|
||||
buttons: {
|
||||
saveButton: { label: "Fermer", callback: html => this.quitDialog() }
|
||||
},
|
||||
};
|
||||
|
||||
// Get all n
|
||||
// Common conf
|
||||
let dialogConf = { content: html, title: "Nombres Astraux", buttons: myButtons, default: "saveButton" };
|
||||
let dialogOptions = { classes: ["rdddialog"], width: 600, height: 300, 'z-index': 99999 };
|
||||
super(dialogConf, dialogOptions);
|
||||
|
||||
this.actor = actor;
|
||||
this.dataNombreAstral = duplicate(dialogData);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
this.html = html;
|
||||
|
||||
this.html.find("[name='diffConditions']").val(0);
|
||||
|
||||
this.html.find('[name="jet-astrologie"]').click((event) => {
|
||||
this.requestJetAstrologie();
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static organizeNombres(actor) {
|
||||
let itemNombres = actor.listItemsData('nombreastral');
|
||||
let itemNombres = actor.listItems('nombreastral');
|
||||
let itemFiltered = {};
|
||||
for (let item of itemNombres) {
|
||||
if (itemFiltered[item.system.jourindex]) {
|
||||
@ -68,8 +78,8 @@ export class RdDAstrologieJoueur extends Dialog {
|
||||
carac_vue: this.actor.system.carac['vue'].value,
|
||||
etat: this.dataNombreAstral.etat,
|
||||
astrologie: this.dataNombreAstral.astrologie,
|
||||
conditions: $("#diffConditions").val(),
|
||||
date: $("#joursAstrologie").val(),
|
||||
conditions: this.html.find('[name="diffConditions"]').val(),
|
||||
date: this.html.find('[name="joursAstrologie"]').val(),
|
||||
userId: game.user.id
|
||||
}
|
||||
if (Misc.isUniqueConnectedGM()) {
|
||||
@ -87,17 +97,4 @@ export class RdDAstrologieJoueur extends Dialog {
|
||||
quitDialog() {
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
|
||||
$(function () {
|
||||
$("#diffConditions").val(0);
|
||||
});
|
||||
|
||||
html.find('#jet-astrologie').click((event) => {
|
||||
this.requestJetAstrologie();
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,4 +1,4 @@
|
||||
import { Misc } from "./misc.js";
|
||||
import { RdDTimestamp } from "./rdd-timestamp.js";
|
||||
|
||||
/**
|
||||
* Extend the base Dialog entity by defining a custom window to perform roll.
|
||||
@ -12,7 +12,7 @@ export class RdDCalendrierEditeur extends Dialog {
|
||||
content: html,
|
||||
title: "Editeur de date/heure",
|
||||
buttons: {
|
||||
save: { label: "Enregistrer", callback: html => this.fillData() }
|
||||
save: { label: "Enregistrer", callback: html => this.saveCalendrier() }
|
||||
},
|
||||
default: "save"
|
||||
};
|
||||
@ -23,16 +23,40 @@ export class RdDCalendrierEditeur extends Dialog {
|
||||
this.calendrierData = calendrierData;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
fillData() {
|
||||
this.calendrierData.annee = $("input[name='annee']").val();
|
||||
this.calendrierData.moisKey = $("select[name='nomMois']").val();
|
||||
this.calendrierData.heureKey = $("select[name='nomHeure']").val();
|
||||
this.calendrierData.jourMois = $("select[name='jourMois']").val();
|
||||
this.calendrierData.minutesRelative = $("select[name='minutesRelative']").val();
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
this.html = html;
|
||||
|
||||
console.log("UPDATE ", this.calendrierData);
|
||||
this.calendrier.saveEditeur(this.calendrierData)
|
||||
this.html.find("input[name='calendar.annee']").val(this.calendrierData.annee);
|
||||
this.html.find("select[name='calendar.mois']").val(this.calendrierData.mois.key);
|
||||
this.html.find("select[name='calendar.heure']").val(this.calendrierData.heure.key);
|
||||
RdDCalendrierEditeur.setLimited(this.html.find("input[name='calendar.jourDuMois']"), this.calendrierData.jourDuMois, 1, 28);
|
||||
RdDCalendrierEditeur.setLimited(this.html.find("input[name='calendar.minute']"), this.calendrierData.minute, 0, 119);
|
||||
}
|
||||
|
||||
static setLimited(input, init, min, max) {
|
||||
input.val(init);
|
||||
input.change(event => {
|
||||
const val = Number.parseInt(input.val());
|
||||
if (val < min) {
|
||||
input.val(min);
|
||||
}
|
||||
if (val > max) {
|
||||
input.val(max);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
saveCalendrier() {
|
||||
const annee = Number.parseInt(this.html.find("input[name='calendar.annee']").val());
|
||||
const mois = this.html.find("select[name='calendar.mois']").val();
|
||||
const jour = Number.parseInt(this.html.find("input[name='calendar.jourDuMois']").val());
|
||||
const heure = this.html.find("select[name='calendar.heure']").val();
|
||||
const minute = Number.parseInt(this.html.find("input[name='calendar.minute']").val());
|
||||
|
||||
this.calendrier.setNewTimestamp(RdDTimestamp.timestamp(annee, mois, jour, heure, minute))
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
@ -40,21 +64,4 @@ export class RdDCalendrierEditeur extends Dialog {
|
||||
this.calendrierData = duplicate(calendrierData);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
|
||||
let calendrierData = this.calendrierData;
|
||||
|
||||
$(function () {
|
||||
console.log(calendrierData);
|
||||
$("input[name='nomMois']").val(calendrierData.moisKey);
|
||||
$("select[name='nomHeure']").val(calendrierData.heureKey);
|
||||
$("select[name='jourMois']").val(calendrierData.jourMois);
|
||||
$("select[name='minutesRelative']").val(calendrierData.minutesRelative);
|
||||
$("select[name='annee']").val(calendrierData.annee);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,103 +1,33 @@
|
||||
/* -------------------------------------------- */
|
||||
import { RdDCalendrierEditeur } from "./rdd-calendrier-editeur.js";
|
||||
import { RdDAstrologieEditeur } from "./rdd-astrologie-editeur.js";
|
||||
import { HtmlUtility } from "./html-utility.js";
|
||||
import { RdDResolutionTable } from "./rdd-resolution-table.js";
|
||||
import { RdDUtility } from "./rdd-utility.js";
|
||||
import { Grammar } from "./grammar.js";
|
||||
import { RdDDice } from "./rdd-dice.js";
|
||||
import { Misc } from "./misc.js";
|
||||
import { HIDE_DICE, SHOW_DICE, SYSTEM_RDD, SYSTEM_SOCKET_ID } from "./constants.js";
|
||||
import { DialogChronologie } from "./dialog-chronologie.js";
|
||||
import { RdDTimestamp, WORLD_TIMESTAMP_SETTING } from "./rdd-timestamp.js";
|
||||
|
||||
/* -------------------------------------------- */
|
||||
const dossierIconesHeures = 'systems/foundryvtt-reve-de-dragon/icons/heures/'
|
||||
const heuresList = ["vaisseau", "sirene", "faucon", "couronne", "dragon", "epees", "lyre", "serpent", "poissonacrobate", "araignee", "roseau", "chateaudormant"];
|
||||
const heuresDef = {
|
||||
"vaisseau": {key: "vaisseau", label: "Vaisseau", lettreFont: 'v', saison: "printemps", heure: 0, icon: 'hd01.svg' },
|
||||
"sirene": { key: "sirene", label: "Sirène", lettreFont: 'i', saison: "printemps", heure: 1, icon: 'hd02.svg' },
|
||||
"faucon": { key: "faucon", label: "Faucon", lettreFont: 'f', saison: "printemps", heure: 2, icon: 'hd03.svg' },
|
||||
"couronne": { key: "couronne", label: "Couronne", lettreFont: '', saison: "ete", heure: 3, icon: 'hd04.svg' },
|
||||
"dragon": { key: "dragon", label: "Dragon", lettreFont: 'd', saison: "ete", heure: 4, icon: 'hd05.svg' },
|
||||
"epees": { key: "epees", label: "Epées", lettreFont: 'e', saison: "ete", heure: 5, icon: 'hd06.svg' },
|
||||
"lyre": { key: "lyre", label: "Lyre", lettreFont: 'l', saison: "automne", heure: 6, icon: 'hd07.svg' },
|
||||
"serpent": { key: "serpent", label: "Serpent", lettreFont: 's', saison: "automne", heure: 7, icon: 'hd08.svg' },
|
||||
"poissonacrobate": { key: "poissonacrobate", label: "Poisson Acrobate", lettreFont: 'p', saison: "automne", heure: 8, icon: 'hd09.svg' },
|
||||
"araignee": { key: "araignee", label: "Araignée", lettreFont: 'a', saison: "hiver", heure: 9, icon: 'hd10.svg' },
|
||||
"roseau": { key: "roseau", label: "Roseau", lettreFont: 'r', saison: "hiver", heure: 10, icon: 'hd11.svg' },
|
||||
"chateaudormant": { key: "chateaudormant", label: "Château Dormant", lettreFont: 'c', saison: "hiver", heure: 11, icon: 'hd12.svg' }
|
||||
};
|
||||
const saisonsDef = {
|
||||
"printemps": { label: "Printemps" },
|
||||
"ete": { label: "Eté" },
|
||||
"automne": { label: "Automne" },
|
||||
"hiver": { label: "Hiver" }
|
||||
};
|
||||
|
||||
const RDD_MOIS_PAR_AN = 12;
|
||||
export const RDD_JOUR_PAR_MOIS = 28;
|
||||
const RDD_JOUR_PAR_MOIS = 28;
|
||||
const RDD_HEURES_PAR_JOUR = 12;
|
||||
const RDD_MINUTES_PAR_HEURES = 120;
|
||||
const MAX_NOMBRE_ASTRAL = 12;
|
||||
const JOURS_DU_MOIS = Array(RDD_JOUR_PAR_MOIS).fill().map((item, index) => 1 + index);
|
||||
|
||||
/* -------------------------------------------- */
|
||||
export class RdDCalendrier extends Application {
|
||||
|
||||
static get defaultOptions() {
|
||||
return mergeObject(super.defaultOptions, {
|
||||
template: "systems/foundryvtt-reve-de-dragon/templates/calendar-template.html",
|
||||
popOut: false,
|
||||
resizable: false
|
||||
});
|
||||
}
|
||||
|
||||
static createCalendrierPos() {
|
||||
return { top: 200, left: 200 };
|
||||
}
|
||||
|
||||
static getDefSigne(chiffre) {
|
||||
chiffre = chiffre % RDD_MOIS_PAR_AN;
|
||||
return Object.values(heuresDef).find(h => h.heure == chiffre);
|
||||
}
|
||||
|
||||
static getSigneAs(key, value) {
|
||||
const heure = (typeof value == 'string' || typeof value == 'number') && Number.isInteger(Number(value))
|
||||
? Number(value)
|
||||
: (typeof value == 'string') ? RdDCalendrier.getChiffreFromSigne(value)
|
||||
: undefined
|
||||
|
||||
if (heure != undefined && ['key', 'label', 'lettreFont', 'saison', 'heure', 'icon'].includes(key)) {
|
||||
return RdDCalendrier.getDefSigne(heure)[key]
|
||||
}
|
||||
if (heure != undefined && ['webp'].includes(key)) {
|
||||
return RdDCalendrier.getDefSigne(heure)['icon'].replace('svg', 'webp');
|
||||
}
|
||||
console.error(`Appel à getSigneAs('${key}', ${value}) avec une clé/heure incorrects`);
|
||||
return value;
|
||||
|
||||
}
|
||||
static getChiffreFromSigne(signe) {
|
||||
return heuresList.indexOf(signe);
|
||||
}
|
||||
|
||||
static createCalendrierInitial() {
|
||||
return {
|
||||
heureRdD: 0,
|
||||
minutesRelative: 0,
|
||||
indexJour: 0,
|
||||
annee: 0,
|
||||
moisRdD: 0,
|
||||
moisLabel: heuresDef["vaisseau"].label,
|
||||
jour: 0
|
||||
}
|
||||
}
|
||||
|
||||
getCalendrier(index) {
|
||||
index = index ?? this.getCurrentDayIndex();
|
||||
const mois = Math.floor(index / RDD_JOUR_PAR_MOIS) % RDD_MOIS_PAR_AN;
|
||||
return {
|
||||
heureRdD: 0, // Index dans heuresList / heuresDef[x].heure
|
||||
minutesRelative: 0,
|
||||
indexJour: index,
|
||||
annee: Math.floor(index / (RDD_JOUR_PAR_MOIS * RDD_MOIS_PAR_AN)),
|
||||
moisRdD: RdDCalendrier.getDefSigne(mois).heure,
|
||||
moisLabel: RdDCalendrier.getDefSigne(mois).label,
|
||||
jour: (index % RDD_JOUR_PAR_MOIS) // Le calendrier stocke le jour en 0-27, mais en 1-28 à l'affichage
|
||||
}
|
||||
}
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
// position
|
||||
@ -106,478 +36,48 @@ export class RdDCalendrier extends Application {
|
||||
this.calendrierPos = RdDCalendrier.createCalendrierPos();
|
||||
game.settings.set(SYSTEM_RDD, "calendrier-pos", this.calendrierPos);
|
||||
}
|
||||
|
||||
// Calendrier
|
||||
this.calendrier = duplicate(game.settings.get(SYSTEM_RDD, "calendrier") ?? RdDCalendrier.createCalendrierInitial());
|
||||
this.calendrier.annee = this.calendrier.annee ?? Math.floor((this.calendrier.moisRdD ?? 0) / RDD_MOIS_PAR_AN);
|
||||
this.calendrier.moisRdD = (this.calendrier.moisRdD ?? 0) % RDD_MOIS_PAR_AN;
|
||||
this.timestamp = RdDTimestamp.getWorldTime();
|
||||
|
||||
if (Misc.isUniqueConnectedGM()) { // Uniquement si GM
|
||||
game.settings.set(SYSTEM_RDD, "calendrier", this.calendrier);
|
||||
|
||||
RdDTimestamp.setWorldTime(this.timestamp);
|
||||
this.listeNombreAstral = this.getListeNombreAstral();
|
||||
this.rebuildListeNombreAstral(HIDE_DICE); // Ensure always up-to-date
|
||||
}
|
||||
console.log('RdDCalendrier.constructor()', this.calendrier, this.calendrierPos, this.listeNombreAstral);
|
||||
console.log('RdDCalendrier.constructor()', this.timestamp, this.timestamp.toCalendrier(), this.calendrierPos, this.listeNombreAstral);
|
||||
Hooks.on('updateSetting', async (setting, update, options, id) => this.onUpdateSetting(setting, update, options, id));
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getListeNombreAstral() {
|
||||
return game.settings.get(SYSTEM_RDD, "liste-nombre-astral") ?? [];
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static get defaultOptions() {
|
||||
return mergeObject(super.defaultOptions, {
|
||||
template: "systems/foundryvtt-reve-de-dragon/templates/calendar-template.html",
|
||||
popOut: false,
|
||||
resizable: false
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getDateFromIndex(index) {
|
||||
const dateRdD = this.getCalendrier(index);
|
||||
return (dateRdD.jour + 1) + ' ' + dateRdD.moisLabel;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getDayMonthFromIndex(index = undefined) {
|
||||
const dateRdD = this.getCalendrier(index);
|
||||
return {
|
||||
day: dateRdD.jour + 1,
|
||||
month: heuresList[dateRdD.moisRdD]
|
||||
async onUpdateSetting(setting, update, options, id) {
|
||||
if (setting.key == SYSTEM_RDD + '.' + WORLD_TIMESTAMP_SETTING) {
|
||||
this.timestamp = RdDTimestamp.getWorldTime();
|
||||
this.updateDisplay();
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getCurrentHeure() {
|
||||
return heuresList[this.calendrier.heureRdD];
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getCurrentDayIndex() {
|
||||
return (((this.calendrier.annee ?? 0) * RDD_MOIS_PAR_AN + (this.calendrier.moisRdD ?? 0)) * RDD_JOUR_PAR_MOIS) + (this.calendrier.jour ?? 0);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getIndexFromDate(jour, mois) {
|
||||
return (heuresDef[mois].heure * RDD_JOUR_PAR_MOIS) + jour - 1;
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
getJoursSuivants(num) {
|
||||
let jours = [];
|
||||
let index = this.getCurrentDayIndex();
|
||||
for (let i = 0; i < num; i++) {
|
||||
jours[i] = { label: this.getDateFromIndex(index + i), index: index + i };
|
||||
}
|
||||
return jours;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async ajouterNombreAstral(index, showDice = SHOW_DICE) {
|
||||
const nombreAstral = await RdDDice.rollTotal("1dh", { showDice: showDice, rollMode: "selfroll" });
|
||||
const dateFuture = this.getDateFromIndex(index);
|
||||
if (showDice != HIDE_DICE) {
|
||||
ChatMessage.create({
|
||||
whisper: ChatMessage.getWhisperRecipients("GM"),
|
||||
content: `Le chiffre astrologique du ${dateFuture} sera le ${nombreAstral}`
|
||||
});
|
||||
}
|
||||
return {
|
||||
nombreAstral: nombreAstral,
|
||||
valeursFausses: [],
|
||||
index: index
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getCurrentNombreAstral() {
|
||||
let indexDate = this.getCurrentDayIndex();
|
||||
return this.getNombreAstral(indexDate);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
resetNombreAstral() {
|
||||
this.listeNombreAstral = [];
|
||||
game.settings.set(SYSTEM_RDD, "liste-nombre-astral", this.listeNombreAstral);
|
||||
|
||||
game.socket.emit(SYSTEM_SOCKET_ID, {
|
||||
msg: "msg_reset_nombre_astral",
|
||||
data: {}
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getNombreAstral(indexDate) {
|
||||
const listNombreAstral = this.getListeNombreAstral();
|
||||
let astralData = listNombreAstral.find((nombreAstral, i) => nombreAstral.index == indexDate);
|
||||
return astralData?.nombreAstral;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async rebuildListeNombreAstral(showDice = HIDE_DICE) {
|
||||
if (Misc.isUniqueConnectedGM()) {
|
||||
let jourCourant = this.getCurrentDayIndex();
|
||||
let newList = [];
|
||||
for (let i = 0; i < MAX_NOMBRE_ASTRAL; i++) {
|
||||
let dayIndex = jourCourant + i;
|
||||
let na = this.listeNombreAstral.find(n => n.index == dayIndex);
|
||||
if (na) {
|
||||
newList[i] = na;
|
||||
} else {
|
||||
newList[i] = await this.ajouterNombreAstral(dayIndex, showDice);
|
||||
}
|
||||
}
|
||||
game.settings.set(SYSTEM_RDD, "liste-nombre-astral", newList);
|
||||
this.listeNombreAstral = newList;
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async onCalendarButton(ev) {
|
||||
ev.preventDefault();
|
||||
const calendarAvance = ev.currentTarget.attributes['data-calendar-avance'];
|
||||
const calendarSet = ev.currentTarget.attributes['data-calendar-set'];
|
||||
if (calendarAvance) {
|
||||
await this.incrementTime(Number(calendarAvance.value));
|
||||
}
|
||||
else if (calendarSet) {
|
||||
this.positionnerHeure(Number(calendarSet.value));
|
||||
}
|
||||
this.updateDisplay();
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
checkMaladie( periode) {
|
||||
for (let actor of game.actors) {
|
||||
if (actor.type == 'personnage') {
|
||||
let maladies = actor.items.filter( item => (item.type == 'maladie' || (item.type == 'poison' && item.system.active) ) && item.system.periodicite.toLowerCase().includes(periode) );
|
||||
for (let maladie of maladies) {
|
||||
if ( maladie.system.identifie) {
|
||||
ChatMessage.create({ content: `${actor.name} souffre de ${maladie.name} (${maladie.type}): vérifiez que les effets ne se sont pas aggravés !` });
|
||||
} else {
|
||||
ChatMessage.create({ content: `${actor.name} souffre d'un mal inconnu (${maladie.type}): vérifiez que les effets ne se sont pas aggravés !` });
|
||||
}
|
||||
let itemMaladie = actor.getObjet(maladie.id)
|
||||
itemMaladie.postItem( 'gmroll');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async incrementTime(minutes = 0) {
|
||||
this.calendrier.minutesRelative += minutes;
|
||||
this.checkMaladie("round");
|
||||
this.checkMaladie("minute");
|
||||
if (this.calendrier.minutesRelative >= RDD_MINUTES_PAR_HEURES) {
|
||||
this.calendrier.minutesRelative -= RDD_MINUTES_PAR_HEURES;
|
||||
this.calendrier.heureRdD += 1;
|
||||
this.checkMaladie("heure");
|
||||
}
|
||||
if (this.calendrier.heureRdD >= RDD_HEURES_PAR_JOUR) {
|
||||
this.calendrier.heureRdD -= RDD_HEURES_PAR_JOUR;
|
||||
await this.incrementerJour();
|
||||
this.checkMaladie("heure");
|
||||
this.checkMaladie("jour");
|
||||
}
|
||||
game.settings.set(SYSTEM_RDD, "calendrier", duplicate(this.calendrier));
|
||||
// Notification aux joueurs // TODO: replace with Hook on game settings update
|
||||
game.socket.emit(SYSTEM_SOCKET_ID, {
|
||||
msg: "msg_sync_time",
|
||||
data: duplicate(this.calendrier)
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async incrementerJour() {
|
||||
const index = this.getCurrentDayIndex() + 1;
|
||||
this.calendrier = this.getCalendrier(index);
|
||||
await this.rebuildListeNombreAstral();
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
syncPlayerTime(calendrier) {
|
||||
this.calendrier = duplicate(calendrier); // Local copy update
|
||||
this.updateDisplay();
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async positionnerHeure(indexHeure) {
|
||||
if (indexHeure <= this.calendrier.heureRdD) {
|
||||
await this.incrementerJour();
|
||||
}
|
||||
this.calendrier.heureRdD = indexHeure;
|
||||
this.calendrier.minutesRelative = 0;
|
||||
game.settings.set(SYSTEM_RDD, "calendrier", duplicate(this.calendrier));
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
fillCalendrierData(formData = {}) {
|
||||
const mois = RdDCalendrier.getDefSigne(this.calendrier.moisRdD);
|
||||
const heure = RdDCalendrier.getDefSigne(this.calendrier.heureRdD);
|
||||
console.log('fillCalendrierData', this.calendrier, mois, heure);
|
||||
|
||||
formData.heureKey = heure.key;
|
||||
formData.moisKey = mois.key;
|
||||
formData.jourMois = this.calendrier.jour + 1;
|
||||
formData.nomMois = mois.label; // heures et mois nommés identiques
|
||||
formData.annee = this.calendrier.annee;
|
||||
formData.iconMois = dossierIconesHeures + mois.icon;
|
||||
formData.nomHeure = heure.label;
|
||||
formData.iconHeure = dossierIconesHeures + heure.icon;
|
||||
formData.nomSaison = saisonsDef[mois.saison].label;
|
||||
formData.heureRdD = this.calendrier.heureRdD;
|
||||
formData.minutesRelative = this.calendrier.minutesRelative;
|
||||
formData.isGM = game.user.isGM;
|
||||
return formData;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getLectureAstrologieDifficulte(dateIndex) {
|
||||
let indexNow = this.getCurrentDayIndex();
|
||||
let diffDay = dateIndex - indexNow;
|
||||
return - Math.floor(diffDay / 2);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async requestNombreAstral(request) {
|
||||
if (Misc.isUniqueConnectedGM()) { // Only once
|
||||
console.log(request);
|
||||
let jourDiff = this.getLectureAstrologieDifficulte(request.date);
|
||||
let niveau = Number(request.astrologie.system.niveau) + Number(request.conditions) + Number(jourDiff) + Number(request.etat);
|
||||
let rollData = {
|
||||
caracValue: request.carac_vue,
|
||||
finalLevel: niveau,
|
||||
showDice: HIDE_DICE,
|
||||
rollMode: "blindroll"
|
||||
};
|
||||
await RdDResolutionTable.rollData(rollData);
|
||||
let nbAstral = this.getNombreAstral(request.date);
|
||||
request.rolled = rollData.rolled;
|
||||
request.isValid = true;
|
||||
if (!request.rolled.isSuccess) {
|
||||
request.isValid = false;
|
||||
nbAstral = await RdDDice.rollTotal("1dhr" + nbAstral, { rollMode: "selfroll" });
|
||||
// Mise à jour des nombres astraux du joueur
|
||||
let astralData = this.listeNombreAstral.find((nombreAstral, i) => nombreAstral.index == request.date);
|
||||
astralData.valeursFausses.push({ actorId: request.id, nombreAstral: nbAstral });
|
||||
game.settings.set(SYSTEM_RDD, "liste-nombre-astral", this.listeNombreAstral);
|
||||
}
|
||||
request.nbAstral = nbAstral;
|
||||
if (Misc.getActiveUser(request.userId)?.isGM) {
|
||||
RdDUtility.responseNombreAstral(request);
|
||||
} else {
|
||||
game.socket.emit(SYSTEM_SOCKET_ID, {
|
||||
msg: "msg_response_nombre_astral",
|
||||
data: request
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
findHeure(heure) {
|
||||
heure = Grammar.toLowerCaseNoAccentNoSpace(heure);
|
||||
let parHeureOuLabel = Object.values(heuresDef).filter(it => (it.heure + 1) == parseInt(heure) || Grammar.toLowerCaseNoAccentNoSpace(it.label) == heure);
|
||||
if (parHeureOuLabel.length == 1) {
|
||||
return parHeureOuLabel[0];
|
||||
}
|
||||
let parLabelPartiel = Object.values(heuresDef).filter(it => Grammar.toLowerCaseNoAccentNoSpace(it.label).includes(heure));
|
||||
if (parLabelPartiel.length > 0) {
|
||||
parLabelPartiel.sort(Misc.ascending(h => h.label.length));
|
||||
return parLabelPartiel[0];
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
getHeureNumber( hNum) {
|
||||
let heure = Object.values(heuresDef).find(it => (it.heure) == hNum);
|
||||
return heure
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getHeuresChanceMalchance(heureNaissance) {
|
||||
let heuresChancesMalchances = [];
|
||||
let defHeure = this.findHeure(heureNaissance);
|
||||
if (defHeure) {
|
||||
let hn = defHeure.heure;
|
||||
let chiffreAstral = this.getCurrentNombreAstral() ?? 0;
|
||||
heuresChancesMalchances[0] = { value : "+4", heures: [this.getHeureNumber((hn + chiffreAstral) % RDD_HEURES_PAR_JOUR).label]};
|
||||
heuresChancesMalchances[1] = { value : "+2", heures: [this.getHeureNumber((hn + chiffreAstral+4) % RDD_HEURES_PAR_JOUR).label,
|
||||
this.getHeureNumber((hn + chiffreAstral + 8) % RDD_HEURES_PAR_JOUR).label ] };
|
||||
heuresChancesMalchances[2] = { value : "-4", heures: [this.getHeureNumber((hn + chiffreAstral+6) % RDD_HEURES_PAR_JOUR).label]};
|
||||
heuresChancesMalchances[3] = { value : "-2", heures: [this.getHeureNumber((hn + chiffreAstral+3) % RDD_HEURES_PAR_JOUR).label,
|
||||
this.getHeureNumber((hn + chiffreAstral + 9) % RDD_HEURES_PAR_JOUR).label ]};
|
||||
}
|
||||
return heuresChancesMalchances;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getAjustementAstrologique(heureNaissance, name = undefined) {
|
||||
let defHeure = this.findHeure(heureNaissance);
|
||||
if (defHeure) {
|
||||
let hn = defHeure.heure;
|
||||
let chiffreAstral = this.getCurrentNombreAstral() ?? 0;
|
||||
let heureCourante = this.calendrier.heureRdD;
|
||||
let ecartChance = (hn + chiffreAstral - heureCourante) % RDD_HEURES_PAR_JOUR;
|
||||
switch (ecartChance) {
|
||||
case 0: return 4;
|
||||
case 4: case 8: return 2;
|
||||
case 6: return -4;
|
||||
case 3: case 9: return -2;
|
||||
}
|
||||
}
|
||||
else if (name) {
|
||||
ui.notifications.warn(name + " n'a pas d'heure de naissance, ou elle est incorrecte : " + heureNaissance);
|
||||
}
|
||||
else {
|
||||
ui.notifications.warn(heureNaissance + " ne correspond pas à une heure de naissance");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getData() {
|
||||
let formData = super.getData();
|
||||
|
||||
this.fillCalendrierData(formData);
|
||||
|
||||
this.setPos(this.calendrierPos);
|
||||
return formData;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
setPos(pos) {
|
||||
return new Promise(resolve => {
|
||||
function check() {
|
||||
let elmnt = document.getElementById("calendar-time-container");
|
||||
if (elmnt) {
|
||||
elmnt.style.bottom = undefined;
|
||||
let xPos = (pos.left) > window.innerWidth ? window.innerWidth - 200 : pos.left;
|
||||
let yPos = (pos.top) > window.innerHeight - 20 ? window.innerHeight - 100 : pos.top;
|
||||
elmnt.style.top = (yPos) + "px";
|
||||
elmnt.style.left = (xPos) + "px";
|
||||
resolve();
|
||||
} else {
|
||||
setTimeout(check, 30);
|
||||
}
|
||||
}
|
||||
check();
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
updateDisplay() {
|
||||
let calendrier = this.fillCalendrierData();
|
||||
// Rebuild text du calendrier
|
||||
let dateHTML = `${calendrier.jourMois} ${calendrier.nomMois} ${calendrier.annee} (${calendrier.nomSaison})`
|
||||
if (game.user.isGM) {
|
||||
dateHTML = dateHTML + " - NA: " + (this.getCurrentNombreAstral() ?? "indéterminé");
|
||||
}
|
||||
for (let handle of document.getElementsByClassName("calendar-date-rdd")) {
|
||||
handle.innerHTML = dateHTML;
|
||||
}
|
||||
for (let heure of document.getElementsByClassName("calendar-heure-texte")) {
|
||||
heure.innerHTML = calendrier.nomHeure;
|
||||
}
|
||||
for (const minute of document.getElementsByClassName("calendar-time-disp")) {
|
||||
minute.innerHTML = `${calendrier.minutesRelative} minutes`;
|
||||
}
|
||||
for (const heureImg of document.getElementsByClassName("calendar-heure-img")) {
|
||||
heureImg.src = calendrier.iconHeure;
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async saveEditeur(calendrierData) {
|
||||
this.calendrier.minutesRelative = Number(calendrierData.minutesRelative);
|
||||
this.calendrier.jour = Number(calendrierData.jourMois) - 1;
|
||||
this.calendrier.moisRdD = RdDCalendrier.getChiffreFromSigne(calendrierData.moisKey);
|
||||
this.calendrier.annee = Number(calendrierData.annee);
|
||||
this.calendrier.heureRdD = RdDCalendrier.getChiffreFromSigne(calendrierData.heureKey);
|
||||
game.settings.set(SYSTEM_RDD, "calendrier", duplicate(this.calendrier));
|
||||
|
||||
await this.rebuildListeNombreAstral();
|
||||
|
||||
game.socket.emit(SYSTEM_SOCKET_ID, {
|
||||
msg: "msg_sync_time",
|
||||
data: duplicate(this.calendrier)
|
||||
});
|
||||
|
||||
this.updateDisplay();
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async showCalendarEditor() {
|
||||
let calendrierData = duplicate(this.fillCalendrierData());
|
||||
if (this.editeur == undefined) {
|
||||
calendrierData.jourMoisOptions = RdDCalendrier.buildJoursMois();
|
||||
calendrierData.heuresOptions = [0, 1];
|
||||
calendrierData.minutesOptions = Array(RDD_MINUTES_PAR_HEURES).fill().map((item, index) => 0 + index);
|
||||
let html = await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/calendar-editor-template.html', calendrierData);
|
||||
this.editeur = new RdDCalendrierEditeur(html, this, calendrierData)
|
||||
}
|
||||
this.editeur.updateData(calendrierData);
|
||||
this.editeur.render(true);
|
||||
}
|
||||
|
||||
static buildJoursMois() {
|
||||
return Array(RDD_JOUR_PAR_MOIS).fill().map((item, index) => 1 + index);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async showAstrologieEditor() {
|
||||
let calendrierData = duplicate(this.fillCalendrierData());
|
||||
let astrologieArray = [];
|
||||
this.listeNombreAstral = this.listeNombreAstral || [];
|
||||
for (let astralData of this.listeNombreAstral) {
|
||||
astralData.humanDate = this.getDateFromIndex(astralData.index);
|
||||
for (let vf of astralData.valeursFausses) {
|
||||
let actor = game.actors.get(vf.actorId);
|
||||
vf.actorName = (actor) ? actor.name : "Inconnu";
|
||||
}
|
||||
astrologieArray.push(duplicate(astralData));
|
||||
}
|
||||
let heuresParActeur = {};
|
||||
for (let actor of game.actors) {
|
||||
let heureNaissance = actor.getHeureNaissance();
|
||||
if ( heureNaissance) {
|
||||
heuresParActeur[actor.name] = this.getHeuresChanceMalchance(heureNaissance);
|
||||
}
|
||||
}
|
||||
//console.log("ASTRO", astrologieArray);
|
||||
calendrierData.astrologieData = astrologieArray;
|
||||
calendrierData.heuresParActeur = heuresParActeur;
|
||||
let html = await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/calendar-astrologie-template.html', calendrierData);
|
||||
let astrologieEditeur = new RdDAstrologieEditeur(html, this, calendrierData)
|
||||
astrologieEditeur.updateData(calendrierData);
|
||||
astrologieEditeur.render(true);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
/** @override */
|
||||
async activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
this.html = html;
|
||||
|
||||
this.updateDisplay();
|
||||
|
||||
html.find('.ajout-chronologie').click(ev => DialogChronologie.create());
|
||||
this.html.find('.ajout-chronologie').click(ev => DialogChronologie.create());
|
||||
|
||||
html.find('.calendar-btn').click(ev => this.onCalendarButton(ev));
|
||||
this.html.find('.calendar-btn').click(ev => this.onCalendarButton(ev));
|
||||
|
||||
html.find('.calendar-btn-edit').click(ev => {
|
||||
this.html.find('.calendar-btn-edit').click(ev => {
|
||||
ev.preventDefault();
|
||||
this.showCalendarEditor();
|
||||
});
|
||||
|
||||
html.find('.astrologie-btn-edit').click(ev => {
|
||||
this.html.find('.astrologie-btn-edit').click(ev => {
|
||||
ev.preventDefault();
|
||||
this.showAstrologieEditor();
|
||||
});
|
||||
|
||||
html.find('#calendar-move-handle').mousedown(ev => {
|
||||
this.html.find('#calendar-move-handle').mousedown(ev => {
|
||||
ev.preventDefault();
|
||||
ev = ev || window.event;
|
||||
let isRightMB = false;
|
||||
@ -647,5 +147,359 @@ export class RdDCalendrier extends Application {
|
||||
}
|
||||
});
|
||||
}
|
||||
/* -------------------------------------------- */
|
||||
getListeNombreAstral() {
|
||||
return game.settings.get(SYSTEM_RDD, "liste-nombre-astral") ?? [];
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
dateCourante() {
|
||||
return this.timestamp.formatDate();
|
||||
}
|
||||
|
||||
isAfterIndexDate(indexDate) {
|
||||
// TODO: standardize
|
||||
return indexDate < this.timestamp.indexDate;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
heureCourante() { return RdDTimestamp.definition(this.timestamp.heure); }
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getCurrentMinute() { return this.timestamp.indexMinute; }
|
||||
|
||||
getTimestampFinChateauDormant(nbJours = 0) {
|
||||
return this.timestamp.nouveauJour().addJour(nbJours);
|
||||
}
|
||||
|
||||
getTimestampFinHeure(nbHeures = 0) {
|
||||
return this.timestamp.nouvelleHeure().addHeures(nbHeures);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getIndexFromDate(jour, mois) {
|
||||
const addYear = mois < this.timestamp.mois || (mois == this.timestamp.mois && jour < this.timestamp.jour)
|
||||
const time = RdDTimestamp.timestamp(this.timestamp.annee + (addYear ? 1 : 0), mois, jour);
|
||||
return time.indexDate;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getJoursSuivants(count) {
|
||||
let jours = [];
|
||||
let indexDate = this.timestamp.indexDate;
|
||||
for (let i = 0; i < count; i++, indexDate++) {
|
||||
jours[i] = { label: RdDTimestamp.formatIndexDate(indexDate), index: indexDate };
|
||||
}
|
||||
return jours;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async ajouterNombreAstral(indexDate, showDice = SHOW_DICE) {
|
||||
const nombreAstral = await RdDDice.rollTotal("1dh", { showDice: showDice, rollMode: "selfroll" });
|
||||
const dateFuture = RdDTimestamp.formatIndexDate(indexDate);
|
||||
if (showDice != HIDE_DICE) {
|
||||
ChatMessage.create({
|
||||
whisper: ChatMessage.getWhisperRecipients("GM"),
|
||||
content: `Le chiffre astrologique du ${dateFuture} sera le ${nombreAstral}`
|
||||
});
|
||||
}
|
||||
return {
|
||||
nombreAstral: nombreAstral,
|
||||
valeursFausses: [],
|
||||
index: indexDate
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getCurrentNombreAstral() {
|
||||
return this.getNombreAstral(this.timestamp.indexDate);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
resetNombreAstral() {
|
||||
this.listeNombreAstral = [];
|
||||
game.settings.set(SYSTEM_RDD, "liste-nombre-astral", this.listeNombreAstral);
|
||||
|
||||
game.socket.emit(SYSTEM_SOCKET_ID, {
|
||||
msg: "msg_reset_nombre_astral",
|
||||
data: {}
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getNombreAstral(indexDate) {
|
||||
const listNombreAstral = this.getListeNombreAstral();
|
||||
let astralData = listNombreAstral.find((nombreAstral, i) => nombreAstral.index == indexDate);
|
||||
return astralData?.nombreAstral;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async rebuildListeNombreAstral(showDice = HIDE_DICE) {
|
||||
if (Misc.isUniqueConnectedGM()) {
|
||||
let newList = [];
|
||||
for (let i = 0; i < MAX_NOMBRE_ASTRAL; i++) {
|
||||
let dayIndex = this.timestamp.indexDate + i;
|
||||
let na = this.listeNombreAstral.find(n => n.index == dayIndex);
|
||||
if (na) {
|
||||
newList[i] = na;
|
||||
} else {
|
||||
newList[i] = await this.ajouterNombreAstral(dayIndex, showDice);
|
||||
}
|
||||
}
|
||||
this.listeNombreAstral = newList;
|
||||
game.settings.set(SYSTEM_RDD, "liste-nombre-astral", newList);
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async setNewTimestamp(newTimestamp) {
|
||||
game.actors.forEach(actor => actor.onTimeChanging(this.timestamp, newTimestamp));
|
||||
RdDTimestamp.setWorldTime(newTimestamp);
|
||||
this.timestamp = newTimestamp;
|
||||
await this.rebuildListeNombreAstral();
|
||||
this.updateDisplay();
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async onCalendarButton(ev) {
|
||||
ev.preventDefault();
|
||||
const calendarAvance = ev.currentTarget.attributes['data-calendar-avance'];
|
||||
const calendarSet = ev.currentTarget.attributes['data-calendar-set'];
|
||||
if (calendarAvance) {
|
||||
await this.incrementTime(Number(calendarAvance.value));
|
||||
}
|
||||
else if (calendarSet) {
|
||||
this.positionnerHeure(Number(calendarSet.value));
|
||||
}
|
||||
this.updateDisplay();
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async incrementTime(minutes = 0) {
|
||||
await this.setNewTimestamp(this.timestamp.addMinutes(minutes));
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async incrementerJour() {
|
||||
await this.setNewTimestamp(this.timestamp.nouveauJour());
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async positionnerHeure(heure) {
|
||||
const indexDate = this.timestamp.indexDate;
|
||||
const addDay = this.timestamp.heure < heure ? 0 : 1;
|
||||
await this.setNewTimestamp(new RdDTimestamp({
|
||||
indexDate: indexDate + addDay, indexHeure: 0 })
|
||||
.addHeures(heure))
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
fillCalendrierData(formData = {}) {
|
||||
mergeObject(formData, this.timestamp.toCalendrier());
|
||||
formData.isGM = game.user.isGM;
|
||||
return formData;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getLectureAstrologieDifficulte(dateIndex) {
|
||||
let indexNow = this.timestamp.indexDate;
|
||||
let diffDay = dateIndex - indexNow;
|
||||
return - Math.floor(diffDay / 2);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async requestNombreAstral(request) {
|
||||
const actor = game.actors.get(request.id);
|
||||
if (Misc.isUniqueConnectedGM()) { // Only once
|
||||
console.log(request);
|
||||
let jourDiff = this.getLectureAstrologieDifficulte(request.date);
|
||||
let niveau = Number(request.astrologie.system.niveau) + Number(request.conditions) + Number(jourDiff) + Number(request.etat);
|
||||
let rollData = {
|
||||
caracValue: request.carac_vue,
|
||||
finalLevel: niveau,
|
||||
showDice: HIDE_DICE,
|
||||
rollMode: "blindroll"
|
||||
};
|
||||
await RdDResolutionTable.rollData(rollData);
|
||||
request.rolled = rollData.rolled;
|
||||
request.isValid = request.rolled.isSuccess;
|
||||
request.nbAstral = this.getNombreAstral(request.date);
|
||||
|
||||
if (request.rolled.isSuccess) {
|
||||
if (request.rolled.isPart) {
|
||||
// Gestion expérience (si existante)
|
||||
request.competence = actor.getCompetence("astrologie")
|
||||
request.selectedCarac = actor.system.carac["vue"];
|
||||
actor.appliquerAjoutExperience(request, 'hide');
|
||||
}
|
||||
}
|
||||
else {
|
||||
request.nbAstral = await RdDDice.rollTotal("1dhr" + request.nbAstral, {
|
||||
rollMode: "selfroll", showDice: HIDE_DICE
|
||||
});
|
||||
// Mise à jour des nombres astraux du joueur
|
||||
this.addNbAstralIncorect(request.id, request.date, request.nbAstral);
|
||||
}
|
||||
|
||||
if (Misc.getActiveUser(request.userId)?.isGM) {
|
||||
RdDUtility.responseNombreAstral(request);
|
||||
} else {
|
||||
game.socket.emit(SYSTEM_SOCKET_ID, {
|
||||
msg: "msg_response_nombre_astral",
|
||||
data: request
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
addNbAstralIncorect(actorId, date, nbAstral) {
|
||||
let astralData = this.listeNombreAstral.find((nombreAstral, i) => nombreAstral.index == date);
|
||||
astralData.valeursFausses.push({ actorId: actorId, nombreAstral: nbAstral });
|
||||
game.settings.set(SYSTEM_RDD, "liste-nombre-astral", this.listeNombreAstral);
|
||||
}
|
||||
|
||||
getHeureChance(heure) {
|
||||
return heure + (this.getCurrentNombreAstral() ?? 0);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getHeuresChanceMalchance(heureNaissance) {
|
||||
let defHeure = RdDTimestamp.findHeure(heureNaissance);
|
||||
if (defHeure) {
|
||||
const signe = h => h % RDD_HEURES_PAR_JOUR;
|
||||
const chance = this.getHeureChance(defHeure.heure);
|
||||
return [
|
||||
{ ajustement: "+4", heures: [signe(chance)] },
|
||||
{ ajustement: "+2", heures: [signe(chance + 4), signe(chance + 8)] },
|
||||
{ ajustement: "-4", heures: [signe(chance + 6)] },
|
||||
{ ajustement: "-2", heures: [signe(chance + 3), signe(chance + 9)] }
|
||||
];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getAjustementAstrologique(heureNaissance, name = undefined) {
|
||||
let defHeure = RdDTimestamp.findHeure(heureNaissance);
|
||||
if (defHeure) {
|
||||
const chance = this.getHeureChance(defHeure.heure);
|
||||
const ecartChance = (chance - this.timestamp.heure) % RDD_HEURES_PAR_JOUR;
|
||||
switch (ecartChance) {
|
||||
case 0: return 4;
|
||||
case 4: case 8: return 2;
|
||||
case 6: return -4;
|
||||
case 3: case 9: return -2;
|
||||
}
|
||||
}
|
||||
else if (name) {
|
||||
ui.notifications.warn(name + " n'a pas d'heure de naissance, ou elle est incorrecte : " + heureNaissance);
|
||||
}
|
||||
else {
|
||||
ui.notifications.warn(heureNaissance + " ne correspond pas à une heure de naissance");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
getData() {
|
||||
let formData = super.getData();
|
||||
this.fillCalendrierData(formData);
|
||||
this.setPos(this.calendrierPos);
|
||||
return formData;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
setPos(pos) {
|
||||
return new Promise(resolve => {
|
||||
function check() {
|
||||
let elmnt = document.getElementById("calendar-time-container");
|
||||
if (elmnt) {
|
||||
elmnt.style.bottom = undefined;
|
||||
let xPos = (pos.left) > window.innerWidth ? window.innerWidth - 200 : pos.left;
|
||||
let yPos = (pos.top) > window.innerHeight - 20 ? window.innerHeight - 100 : pos.top;
|
||||
elmnt.style.top = (yPos) + "px";
|
||||
elmnt.style.left = (xPos) + "px";
|
||||
resolve();
|
||||
} else {
|
||||
setTimeout(check, 30);
|
||||
}
|
||||
}
|
||||
check();
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
updateDisplay() {
|
||||
let calendrier = this.fillCalendrierData();
|
||||
// Rebuild text du calendrier
|
||||
let dateHTML = `${calendrier.jourDuMois} ${calendrier.mois.label} (${calendrier.mois.saison}) de l'année ${calendrier.annee}`
|
||||
if (game.user.isGM) {
|
||||
dateHTML = dateHTML + "<br>Nombre Astral: " + (this.getCurrentNombreAstral() ?? "?");
|
||||
}
|
||||
for (let handle of document.getElementsByClassName("calendar-date-rdd")) {
|
||||
handle.innerHTML = dateHTML;
|
||||
}
|
||||
for (let heure of document.getElementsByClassName("calendar-heure-texte")) {
|
||||
heure.innerHTML = calendrier.heure.label;
|
||||
}
|
||||
for (const minute of document.getElementsByClassName("calendar-time-disp")) {
|
||||
minute.innerHTML = `${calendrier.minute} minutes`;
|
||||
}
|
||||
for (const heureImg of document.getElementsByClassName("calendar-heure-img")) {
|
||||
heureImg.src = calendrier.heure.icon;
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async saveEditeur(calendrierData) {
|
||||
const newTimestamp = RdDTimestamp.timestamp(
|
||||
Number.parseInt(calendrierData.annee),
|
||||
calendrierData.mois.heure,
|
||||
Number.parseInt(calendrierData.jourMois),
|
||||
calendrierData.heure.heure,
|
||||
Number.parseInt(calendrierData.minutes)
|
||||
);
|
||||
await this.setNewTimestamp(newTimestamp);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async showCalendarEditor() {
|
||||
let calendrierData = this.fillCalendrierData();
|
||||
if (this.editeur == undefined) {
|
||||
let html = await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/calendar-editor-template.html', calendrierData);
|
||||
this.editeur = new RdDCalendrierEditeur(html, this, calendrierData)
|
||||
}
|
||||
this.editeur.updateData(calendrierData);
|
||||
this.editeur.render(true);
|
||||
}
|
||||
|
||||
static buildJoursMois() { return JOURS_DU_MOIS; }
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async showAstrologieEditor() {
|
||||
const calendrierData = duplicate(this.fillCalendrierData());
|
||||
this.listeNombreAstral = this.listeNombreAstral || [];
|
||||
|
||||
calendrierData.astrologieData = this.listeNombreAstral.map(astro => {
|
||||
const timestamp = new RdDTimestamp({ indexDate: astro.index });
|
||||
astro.date = { mois: timestamp.mois, jour: timestamp.jour + 1 }
|
||||
for (let vf of astro.valeursFausses) {
|
||||
let actor = game.actors.get(vf.actorId);
|
||||
vf.actorName = (actor) ? actor.name : "Inconnu";
|
||||
}
|
||||
return astro;
|
||||
});
|
||||
|
||||
calendrierData.heuresParActeur = {};
|
||||
game.actors.filter(it => it.isPersonnage() && it.hasPlayerOwner).forEach(actor => {
|
||||
let heureNaissance = actor.getHeureNaissance();
|
||||
if (heureNaissance) {
|
||||
calendrierData.heuresParActeur[actor.name] = this.getHeuresChanceMalchance(heureNaissance);
|
||||
}
|
||||
})
|
||||
let html = await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/calendar-astrologie-template.html', calendrierData);
|
||||
let astrologieEditeur = new RdDAstrologieEditeur(html, this, calendrierData)
|
||||
astrologieEditeur.updateData(calendrierData);
|
||||
astrologieEditeur.render(true);
|
||||
}
|
||||
}
|
@ -84,7 +84,6 @@ export class RdDCombatManager extends Combat {
|
||||
console.log(`${game.system.title} | Combat.rollInitiative()`, ids, formula, messageOptions);
|
||||
|
||||
ids = typeof ids === "string" ? [ids] : ids;
|
||||
const currentId = this.combatant._id;
|
||||
// calculate initiative
|
||||
for (let cId = 0; cId < ids.length; cId++) {
|
||||
const combatant = this.combatants.get(ids[cId]);
|
||||
@ -163,7 +162,6 @@ export class RdDCombatManager extends Combat {
|
||||
if (arme.system.unemain && arme.system.deuxmains && !dommages.includes("/")) {
|
||||
ui.notifications.info("Les dommages de l'arme à 1/2 mains " + arme.name + " ne sont pas corrects (ie sous la forme X/Y)");
|
||||
}
|
||||
console.log(">>>>", arme)
|
||||
if ((arme.system.unemain && arme.system.competence) ||
|
||||
(arme.system.competence.toLowerCase().includes("corps à corps"))) {
|
||||
actions.push(RdDCombatManager.$prepareAttaqueArme({
|
||||
@ -247,9 +245,9 @@ export class RdDCombatManager extends Combat {
|
||||
if (actions.length > 0) {
|
||||
return actions;
|
||||
}
|
||||
if (actor.isCreature()) {
|
||||
if (actor.isCreatureEntite()) {
|
||||
actions = actions.concat(RdDCombatManager.listActionsCreature(actor.itemTypes['competencecreature']));
|
||||
} else {
|
||||
} else if (actor.isPersonnage()) {
|
||||
// Recupération des items 'arme'
|
||||
const armes = actor.itemTypes['arme'].filter(it => RdDItemArme.isArmeUtilisable(it))
|
||||
//.concat(RdDItemArme.empoignade())
|
||||
@ -768,7 +766,7 @@ export class RdDCombat {
|
||||
// whisper: ChatMessage.getWhisperRecipients("GM")})
|
||||
// }
|
||||
|
||||
if (!await this.accorderEntite('avant-attaque')) {
|
||||
if (!await this.attacker.accorder(this.defender, 'avant-attaque')) {
|
||||
return;
|
||||
}
|
||||
if (arme.system.cac == 'empoignade' && this.attacker.isCombatTouche()) {
|
||||
@ -822,7 +820,7 @@ export class RdDCombat {
|
||||
essais: {}
|
||||
};
|
||||
|
||||
if (this.attacker.isCreature()) {
|
||||
if (this.attacker.isCreatureEntite()) {
|
||||
RdDItemCompetenceCreature.setRollDataCreature(rollData);
|
||||
}
|
||||
else if (arme) {
|
||||
@ -887,7 +885,7 @@ export class RdDCombat {
|
||||
}
|
||||
await RdDResolutionTable.displayRollData(attackerRoll, this.attacker, 'chat-resultat-attaque.html');
|
||||
|
||||
if (!await this.accorderEntite('avant-defense')) {
|
||||
if (!await this.attacker.accorder(this.defender, 'avant-defense')) {
|
||||
return;
|
||||
}
|
||||
|
||||
@ -1080,7 +1078,7 @@ export class RdDCombat {
|
||||
show: {}
|
||||
};
|
||||
|
||||
if (this.defender.isCreature()) {
|
||||
if (this.defender.isCreatureEntite()) {
|
||||
RdDItemCompetenceCreature.setRollDataCreature(defenderRoll);
|
||||
}
|
||||
|
||||
@ -1159,7 +1157,7 @@ export class RdDCombat {
|
||||
show: {}
|
||||
};
|
||||
|
||||
if (this.defender.isCreature()) {
|
||||
if (this.defender.isCreatureEntite()) {
|
||||
RdDItemCompetenceCreature.setRollDataCreature(rollData);
|
||||
}
|
||||
return rollData;
|
||||
@ -1320,35 +1318,6 @@ export class RdDCombat {
|
||||
this.removeChatMessageActionsPasseArme(attackerRoll.passeArme);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
/* retourne true si on peut continuer, false si on ne peut pas continuer */
|
||||
async accorderEntite(when = 'avant-encaissement') {
|
||||
if (when != game.settings.get(SYSTEM_RDD, "accorder-entite-cauchemar")
|
||||
|| this.defender == undefined
|
||||
|| !this.defender.isEntite([ENTITE_INCARNE])
|
||||
|| this.defender.isEntiteAccordee(this.attacker)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
let rolled = await RdDResolutionTable.roll(this.attacker.getReveActuel(), - Number(this.defender.system.carac.niveau.value));
|
||||
|
||||
let message = {
|
||||
content: "Jet de points actuels de rêve à " + rolled.finalLevel + RdDResolutionTable.explain(rolled) + "<br>",
|
||||
whisper: ChatMessage.getWhisperRecipients(this.attacker.name)
|
||||
};
|
||||
|
||||
if (rolled.isSuccess) {
|
||||
await this.defender.setEntiteReveAccordee(this.attacker);
|
||||
message.content += this.attacker.name + " s'est accordé avec " + this.defender.name;
|
||||
}
|
||||
else {
|
||||
message.content += this.attacker.name + " n'est pas accordé avec " + this.defender.name;
|
||||
}
|
||||
|
||||
ChatMessage.create(message);
|
||||
return rolled.isSuccess;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static async displayActorCombatStatus(combat, actor) {
|
||||
let formData = {
|
||||
|
@ -206,16 +206,16 @@ export class RdDCommands {
|
||||
let rollMode = game.settings.get("core", "rollMode");
|
||||
if (["gmroll", "blindroll"].includes(rollMode)) {
|
||||
msg["whisper"] = ChatMessage.getWhisperRecipients("GM");
|
||||
}
|
||||
if (rollMode === "blindroll"){
|
||||
}
|
||||
if (rollMode === "blindroll") {
|
||||
msg["blind"] = true;
|
||||
}
|
||||
}
|
||||
msg["type"] = 0;
|
||||
|
||||
if (!this.commandsTable) {
|
||||
this._registerCommands();
|
||||
}
|
||||
|
||||
|
||||
let command = commandLine[0].toLowerCase();
|
||||
if (this._isCommandHandled(command)) {
|
||||
let params = commandLine.slice(1);
|
||||
@ -225,7 +225,7 @@ export class RdDCommands {
|
||||
return false;
|
||||
}
|
||||
|
||||
_isCommandHandled(command){
|
||||
_isCommandHandled(command) {
|
||||
return this.commandsTable[command] != undefined;
|
||||
}
|
||||
|
||||
@ -331,7 +331,7 @@ export class RdDCommands {
|
||||
diff = 0;
|
||||
}
|
||||
const caracName = params[0];
|
||||
let competence = length > 1 ? actors[0].getCompetence(Misc.join(params.slice(1, length), ' ')) : undefined;
|
||||
let competence = length > 1 ? actors[0].getCompetence(Misc.join(params.slice(1, length), ' ')) : { name: undefined };
|
||||
if (competence) {
|
||||
for (let actor of actors) {
|
||||
await actor.rollCaracCompetence(caracName, competence.name, diff);
|
||||
@ -403,11 +403,14 @@ export class RdDCommands {
|
||||
const search = Misc.join(params, ' ');
|
||||
const milieux = await game.system.rdd.environnement.findEnvironnementsLike(search);
|
||||
if (milieux.length == 0) {
|
||||
return RdDCommands._chatAnswer(msg, 'Aucun milieu correspondant à ' + search);
|
||||
const tous = Object.values(await game.system.rdd.environnement.milieux());
|
||||
return RdDCommands._chatAnswer(msg, `<strong>Aucun milieu correspondant à '${search}'.</strong>
|
||||
<br>Milieux disponibles:
|
||||
<br><ul class="chat-list"><li>${tous.reduce(Misc.joining('</li><li>'))}</li></ul>`);
|
||||
}
|
||||
if (milieux.length > 1) {
|
||||
ui.notifications.warn(`<strong>Plusieurs milieux correspondent à '${search}'</strong>:
|
||||
<br><ul><li>${milieux.reduce(Misc.joining('</li><li>'))}</li></ul>`);
|
||||
<br><ul class="chat-list"><li>${milieux.reduce(Misc.joining('</li><li>'))}</li></ul>`);
|
||||
}
|
||||
const tableName = `ressources en ${milieux.reduce(Misc.joining(', '))}`;
|
||||
if (toChat == 'liste') {
|
||||
@ -445,17 +448,27 @@ export class RdDCommands {
|
||||
}
|
||||
|
||||
async creerSignesDraconiques() {
|
||||
DialogCreateSigneDraconique.createSigneForActors();
|
||||
if (game.user.isGM) {
|
||||
DialogCreateSigneDraconique.createSigneForActors();
|
||||
}
|
||||
else {
|
||||
ui.notifications.warn("Seul le MJ est autorisé à utiliser la commande /signe");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async supprimerSignesDraconiquesEphemeres() {
|
||||
game.actors.forEach(actor => {
|
||||
const ephemeres = actor.items.filter(item => item.type = 'signedraconique' && item.system.ephemere);
|
||||
if (ephemeres.length > 0) {
|
||||
actor.deleteEmbeddedDocuments("Item", ephemeres.map(item => item.id));
|
||||
}
|
||||
});
|
||||
if (game.user.isGM) {
|
||||
game.actors.forEach(actor => {
|
||||
const ephemeres = actor.items.filter(item => item.type = 'signedraconique' && item.system.ephemere);
|
||||
if (ephemeres.length > 0) {
|
||||
actor.deleteEmbeddedDocuments("Item", ephemeres.map(item => item.id));
|
||||
}
|
||||
});
|
||||
}
|
||||
else {
|
||||
ui.notifications.warn("Seul le MJ est autorisé à utiliser la commande /signe");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
@ -1,7 +1,6 @@
|
||||
import { RdDUtility } from "./rdd-utility.js";
|
||||
import { RdDCalendrier } from "./rdd-calendrier.js";
|
||||
import { Grammar } from "./grammar.js";
|
||||
import { SystemCompendiums } from "./settings/system-compendiums.js";
|
||||
import { RdDTimestamp } from "./rdd-timestamp.js";
|
||||
|
||||
/* -------------------------------------------- */
|
||||
export class RdDHerbes extends Item {
|
||||
@ -29,7 +28,7 @@ export class RdDHerbes extends Item {
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static async updatePotionData(formData) {
|
||||
static async addPotionFormData(formData) {
|
||||
formData.isSoins = formData.system.categorie.includes('Soin');
|
||||
formData.isRepos = formData.system.categorie.includes('Repos');
|
||||
if (formData.isSoins) {
|
||||
@ -40,9 +39,8 @@ export class RdDHerbes extends Item {
|
||||
}
|
||||
formData.herbesSoins = RdDHerbes.buildHerbesList(this.herbesSoins, 12);
|
||||
formData.herbesRepos = RdDHerbes.buildHerbesList(this.herbesRepos, 7);
|
||||
formData.jourMoisOptions = RdDCalendrier.buildJoursMois();
|
||||
formData.dateActuelle = game.system.rdd.calendrier.getDateFromIndex();
|
||||
formData.splitDate = game.system.rdd.calendrier.getDayMonthFromIndex(formData.system.prdate);
|
||||
formData.dateActuelle = game.system.rdd.calendrier.dateCourante();
|
||||
formData.enchantement = RdDTimestamp.splitIndexDate(formData.system.prdate);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
|
@ -1,4 +1,3 @@
|
||||
import { Misc } from "./misc.js";
|
||||
|
||||
export class RdDHotbar {
|
||||
|
||||
|
@ -1,20 +1,6 @@
|
||||
/**
|
||||
* RdD system
|
||||
* Author: LeRatierBretonnien
|
||||
* Software License: GNU GPLv3
|
||||
*/
|
||||
|
||||
/* -------------------------------------------- */
|
||||
|
||||
/* -------------------------------------------- */
|
||||
// Import Modules
|
||||
import { SYSTEM_RDD, SYSTEM_SOCKET_ID } from "./constants.js";
|
||||
import { RdDActor } from "./actor.js";
|
||||
import { RdDItemSheet } from "./item-sheet.js";
|
||||
import { RdDActorSheet } from "./actor-sheet.js";
|
||||
import { RdDActorCreatureSheet } from "./actor-creature-sheet.js";
|
||||
import { RdDActorVehiculeSheet } from "./actor-vehicule-sheet.js";
|
||||
import { RdDActorEntiteSheet } from "./actor-entite-sheet.js";
|
||||
import { RdDItem } from "./item.js";
|
||||
import { RdDUtility } from "./rdd-utility.js";
|
||||
import { TMRUtility } from "./tmr-utility.js";
|
||||
import { RdDCalendrier } from "./rdd-calendrier.js";
|
||||
@ -29,319 +15,323 @@ import { ReglesOptionelles } from "./settings/regles-optionelles.js";
|
||||
import { RdDHotbar } from "./rdd-hotbar-drop.js"
|
||||
import { EffetsDraconiques } from "./tmr/effets-draconiques.js";
|
||||
import { RdDHerbes } from "./rdd-herbes.js";
|
||||
import { RdDItem } from "./item.js";
|
||||
import { RdDDice } from "./rdd-dice.js";
|
||||
import { RdDPossession } from "./rdd-possession.js";
|
||||
import { RdDSigneDraconiqueItemSheet } from "./item-signedraconique-sheet.js";
|
||||
import { Misc } from "./misc.js";
|
||||
import { Migrations } from './migrations.js';
|
||||
import { DialogChronologie } from "./dialog-chronologie.js";
|
||||
import { SystemCompendiums } from "./settings/system-compendiums.js";
|
||||
import { RdDRencontreItemSheet } from "./item-rencontre-sheet.js";
|
||||
import { TMRRencontres } from "./tmr-rencontres.js";
|
||||
import { RdDHerbeItemSheet } from "./item-herbe-sheet.js";
|
||||
import { Environnement } from "./environnement.js";
|
||||
import { RdDItemService } from "./item/item-service.js";
|
||||
import { RdDBaseActor } from "./actor/base-actor.js";
|
||||
import { RdDCommerceSheet } from "./actor/commerce-sheet.js";
|
||||
import { RdDCommerce } from "./actor/commerce.js";
|
||||
import { RdDTimestamp } from "./rdd-timestamp.js";
|
||||
import { RdDItemMaladie } from "./item/maladie.js";
|
||||
import { RdDItemPoison } from "./item/poison.js";
|
||||
import { RdDItemSigneDraconique } from "./item/item-signedraconique.js";
|
||||
import { RdDItemQueue } from "./item/queue.js";
|
||||
import { RdDItemOmbre } from "./item/ombre.js";
|
||||
import { RdDItemSouffle } from "./item/souffle.js";
|
||||
import { RdDRencontre } from "./item/item-rencontre.js";
|
||||
|
||||
import { RdDActorSheet } from "./actor-sheet.js";
|
||||
import { RdDActorCreatureSheet } from "./actor-creature-sheet.js";
|
||||
import { RdDActorVehiculeSheet } from "./actor-vehicule-sheet.js";
|
||||
import { RdDActorEntiteSheet } from "./actor-entite-sheet.js";
|
||||
import { RdDItemSheet } from "./item-sheet.js";
|
||||
import { RdDServiceItemSheet } from "./item-service-sheet.js";
|
||||
import { RdDHerbeItemSheet } from "./item-herbe-sheet.js";
|
||||
import { RdDRencontreItemSheet } from "./item-rencontre-sheet.js";
|
||||
import { RdDIngredientItemSheet } from "./item-ingredient-sheet.js";
|
||||
import { RdDFauneItemSheet } from "./item-faune-sheet.js";
|
||||
import { RdDConteneurItemSheet } from "./item-conteneur-sheet.js";
|
||||
import { RdDSigneDraconiqueItemSheet } from "./item-signedraconique-sheet.js";
|
||||
|
||||
/* -------------------------------------------- */
|
||||
/* Foundry VTT Initialization */
|
||||
/* -------------------------------------------- */
|
||||
import { TMRRencontres } from "./tmr-rencontres.js";
|
||||
|
||||
/**
|
||||
* RdD system
|
||||
* Author: LeRatierBretonnien
|
||||
* Software License: GNU GPLv3
|
||||
*/
|
||||
export class SystemReveDeDragon {
|
||||
|
||||
|
||||
/************************************************************************************/
|
||||
Hooks.once("init", async function () {
|
||||
console.log(`Initializing Reve de Dragon System`);
|
||||
|
||||
// preload handlebars templates
|
||||
RdDUtility.preloadHandlebarsTemplates();
|
||||
// Create useful storage space
|
||||
game.system.rdd = {
|
||||
TMRUtility,
|
||||
RdDUtility,
|
||||
RdDHotbar,
|
||||
RdDPossession,
|
||||
static start() {
|
||||
const system = new SystemReveDeDragon();
|
||||
Hooks.once('init', async () => await system.onInit());
|
||||
Hooks.once('diceSoNiceReady', (dice3d) => RdDDice.diceSoNiceReady(dice3d));
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
game.settings.register(SYSTEM_RDD, "accorder-entite-cauchemar", {
|
||||
name: "Accorder le rêve aux entités",
|
||||
hint: "A quel moment les personnages doivent accorder leur rêve aux entités de cauchemar",
|
||||
scope: "world",
|
||||
config: true,
|
||||
type: String,
|
||||
choices: { // If choices are defined, the resulting setting will be a select menu
|
||||
"avant-attaque": "Avant l'attaque",
|
||||
"avant-defense": "Avant la défense",
|
||||
"avant-encaissement": "Avant l'encaissement",
|
||||
},
|
||||
default: "avant-encaissement"
|
||||
});
|
||||
|
||||
/* -------------------------------------------- */
|
||||
game.settings.register(SYSTEM_RDD, "calendrier", {
|
||||
name: "calendrier",
|
||||
scope: "world",
|
||||
config: false,
|
||||
default: RdDCalendrier.createCalendrierInitial(),
|
||||
type: Object
|
||||
});
|
||||
|
||||
/* -------------------------------------------- */
|
||||
game.settings.register(SYSTEM_RDD, "migration-png-webp-1.5.34", {
|
||||
name: "calendrier",
|
||||
scope: "world",
|
||||
config: false,
|
||||
default: false,
|
||||
type: Boolean
|
||||
});
|
||||
|
||||
/* -------------------------------------------- */
|
||||
game.settings.register(SYSTEM_RDD, "liste-nombre-astral", {
|
||||
name: "liste-nombre-astral",
|
||||
scope: "world",
|
||||
config: false,
|
||||
default: [],
|
||||
type: Object
|
||||
});
|
||||
|
||||
/* -------------------------------------------- */
|
||||
game.settings.register(SYSTEM_RDD, "calendrier-pos", {
|
||||
name: "calendrierPos",
|
||||
scope: "client",
|
||||
config: false,
|
||||
default: RdDCalendrier.createCalendrierPos(),
|
||||
type: Object
|
||||
});
|
||||
|
||||
|
||||
/* -------------------------------------------- */
|
||||
game.settings.register(SYSTEM_RDD, "supprimer-dialogues-combat-chat", {
|
||||
name: "Supprimer les dialogues de combat",
|
||||
hint: "Si désactivée, tous les dialogues de combat sont conservés dans la conversation",
|
||||
scope: "world",
|
||||
config: true,
|
||||
default: true,
|
||||
type: Boolean
|
||||
});
|
||||
/* -------------------------------------------- */
|
||||
game.settings.register(SYSTEM_RDD, "activer-sons-audio", {
|
||||
name: "Activer les bruitages intégrés",
|
||||
hint: "Si activé, certaines actions en jeu déclenchent un son d'ambiance",
|
||||
scope: "world",
|
||||
config: true,
|
||||
default: true,
|
||||
type: Boolean
|
||||
});
|
||||
/* -------------------------------------------- */
|
||||
game.settings.register(SYSTEM_RDD, "appliquer-famine-soif", {
|
||||
name: "Notifier de la famine et la soif pour",
|
||||
hint: "Indique si les cas de famine et de soif seront indiqués durant Château Dormant",
|
||||
scope: "world",
|
||||
config: true,
|
||||
type: String,
|
||||
choices: {
|
||||
"aucun": "ni la famine, ni la soif",
|
||||
"famine": "seulement la famine",
|
||||
"famine-soif": "la famine et la soif",
|
||||
},
|
||||
default: "aucun"
|
||||
});
|
||||
|
||||
/* -------------------------------------------- */
|
||||
// Set an initiative formula for the system
|
||||
CONFIG.Combat.initiative = {
|
||||
formula: "1+(1d6/10)",
|
||||
decimals: 2
|
||||
};
|
||||
|
||||
/* -------------------------------------------- */
|
||||
game.socket.on(SYSTEM_SOCKET_ID, async (sockmsg) => {
|
||||
console.log(">>>>> MSG RECV", sockmsg);
|
||||
try {
|
||||
RdDUtility.onSocketMessage(sockmsg);
|
||||
RdDCombat.onSocketMessage(sockmsg);
|
||||
ChatUtility.onSocketMessage(sockmsg);
|
||||
RdDActor.onSocketMessage(sockmsg);
|
||||
} catch(e) {
|
||||
console.error('game.socket.on(SYSTEM_SOCKET_ID) Exception: ', sockmsg,' => ', e)
|
||||
constructor() {
|
||||
this.RdDUtility = RdDUtility;
|
||||
this.RdDHotbar = RdDHotbar;
|
||||
this.itemClasses = {
|
||||
service: RdDItemService,
|
||||
maladie: RdDItemMaladie,
|
||||
poison: RdDItemPoison,
|
||||
queue: RdDItemQueue,
|
||||
ombre: RdDItemOmbre,
|
||||
souffle: RdDItemSouffle,
|
||||
signedraconique: RdDItemSigneDraconique,
|
||||
rencontre: RdDRencontre
|
||||
}
|
||||
this.actorClasses = {
|
||||
creature: RdDActor,
|
||||
entite: RdDActor,
|
||||
personnage: RdDActor,
|
||||
vehicule: RdDActor,
|
||||
commerce: RdDCommerce,
|
||||
}
|
||||
});
|
||||
|
||||
/* -------------------------------------------- */
|
||||
// Define custom Entity classes
|
||||
CONFIG.Actor.documentClass = RdDActor;
|
||||
CONFIG.Item.documentClass = RdDItem;
|
||||
CONFIG.RDD = {
|
||||
resolutionTable: RdDResolutionTable.resolutionTable,
|
||||
carac_array: RdDUtility.getCaracArray(),
|
||||
ajustementsConditions: RdDUtility.getAjustementsConditions(),
|
||||
difficultesLibres: RdDUtility.getDifficultesLibres()
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
// Register sheet application classes
|
||||
Actors.unregisterSheet("core", ActorSheet);
|
||||
Actors.registerSheet(SYSTEM_RDD, RdDActorSheet, { types: ["personnage"], makeDefault: true });
|
||||
Actors.registerSheet(SYSTEM_RDD, RdDActorCreatureSheet, { types: ["creature"], makeDefault: true });
|
||||
Actors.registerSheet(SYSTEM_RDD, RdDActorVehiculeSheet, { types: ["vehicule"], makeDefault: true });
|
||||
Actors.registerSheet(SYSTEM_RDD, RdDActorEntiteSheet, { types: ["entite"], makeDefault: true });
|
||||
Items.unregisterSheet("core", ItemSheet);
|
||||
Items.registerSheet(SYSTEM_RDD, RdDSigneDraconiqueItemSheet, {
|
||||
label: "Signe draconique",
|
||||
types: ["signedraconique"],
|
||||
makeDefault: true
|
||||
});
|
||||
Items.registerSheet(SYSTEM_RDD, RdDRencontreItemSheet, {
|
||||
label: "Rencontre",
|
||||
types: ["rencontre"],
|
||||
makeDefault: true
|
||||
});
|
||||
RdDHerbeItemSheet.register();
|
||||
RdDIngredientItemSheet.register();
|
||||
Items.registerSheet(SYSTEM_RDD, RdDItemSheet, {
|
||||
types: [
|
||||
"competence", "competencecreature",
|
||||
"recettealchimique", "musique", "chant", "danse", "jeu", "recettecuisine", "oeuvre",
|
||||
"objet", "arme", "armure", "conteneur", "livre", "potion", "munition",
|
||||
"monnaie", "nourritureboisson", "gemme",
|
||||
"meditation", "queue", "ombre", "souffle", "tete", "casetmr", "sort", "sortreserve",
|
||||
"nombreastral", "tache", "maladie", "poison", "possession",
|
||||
"tarot", "extraitpoetique"
|
||||
], makeDefault: true
|
||||
});
|
||||
CONFIG.Combat.documentClass = RdDCombatManager;
|
||||
/* Foundry VTT Initialization */
|
||||
/* -------------------------------------------- */
|
||||
async onInit() {
|
||||
game.system.rdd = this;
|
||||
|
||||
// préparation des différents modules
|
||||
SystemCompendiums.init();
|
||||
DialogChronologie.init();
|
||||
ReglesOptionelles.init();
|
||||
RdDUtility.init();
|
||||
RdDDice.init();
|
||||
RdDCommands.init();
|
||||
RdDCombat.init();
|
||||
RdDCombatManager.init();
|
||||
RdDTokenHud.init();
|
||||
RdDActor.init();
|
||||
RddCompendiumOrganiser.init();
|
||||
EffetsDraconiques.init()
|
||||
TMRUtility.init();
|
||||
RdDHotbar.initDropbar();
|
||||
RdDPossession.init();
|
||||
TMRRencontres.init();
|
||||
Environnement.init();
|
||||
});
|
||||
console.log(`Initializing Reve de Dragon System`);
|
||||
|
||||
/* -------------------------------------------- */
|
||||
function messageDeBienvenue() {
|
||||
if (game.user.isGM) {
|
||||
ChatUtility.removeChatMessageContaining('<div id="message-bienvenue-rdd">');
|
||||
ChatMessage.create({
|
||||
user: game.user.id,
|
||||
content: `<div id="message-bienvenue-rdd"><span class="rdd-roll-part">Bienvenue dans le Rêve des Dragons !</span>
|
||||
// preload handlebars templates
|
||||
RdDUtility.preloadHandlebarsTemplates();
|
||||
|
||||
/* -------------------------------------------- */
|
||||
this.initSystemSettings();
|
||||
|
||||
/* -------------------------------------------- */
|
||||
// Set an initiative formula for the system
|
||||
CONFIG.Combat.initiative = {
|
||||
formula: "1+(1d6/10)",
|
||||
decimals: 2
|
||||
};
|
||||
|
||||
/* -------------------------------------------- */
|
||||
game.socket.on(SYSTEM_SOCKET_ID, async (sockmsg) => {
|
||||
console.log(">>>>> MSG RECV", sockmsg);
|
||||
try {
|
||||
RdDUtility.onSocketMessage(sockmsg);
|
||||
RdDCombat.onSocketMessage(sockmsg);
|
||||
ChatUtility.onSocketMessage(sockmsg);
|
||||
RdDBaseActor.onSocketMessage(sockmsg);
|
||||
} catch (e) {
|
||||
console.error('game.socket.on(SYSTEM_SOCKET_ID) Exception: ', sockmsg, ' => ', e)
|
||||
}
|
||||
});
|
||||
|
||||
/* -------------------------------------------- */
|
||||
// Define custom Entity classes
|
||||
CONFIG.Actor.documentClass = RdDBaseActor;
|
||||
CONFIG.Item.documentClass = RdDItem;
|
||||
CONFIG.RDD = {
|
||||
resolutionTable: RdDResolutionTable.resolutionTable,
|
||||
carac_array: RdDUtility.getCaracArray(),
|
||||
ajustementsConditions: RdDUtility.getAjustementsConditions(),
|
||||
difficultesLibres: RdDUtility.getDifficultesLibres()
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
// Register sheet application classes
|
||||
Actors.unregisterSheet("core", ActorSheet);
|
||||
Actors.registerSheet(SYSTEM_RDD, RdDCommerceSheet, { types: ["commerce"], makeDefault: true });
|
||||
Actors.registerSheet(SYSTEM_RDD, RdDActorSheet, { types: ["personnage"], makeDefault: true });
|
||||
Actors.registerSheet(SYSTEM_RDD, RdDActorCreatureSheet, { types: ["creature"], makeDefault: true });
|
||||
Actors.registerSheet(SYSTEM_RDD, RdDActorVehiculeSheet, { types: ["vehicule"], makeDefault: true });
|
||||
Actors.registerSheet(SYSTEM_RDD, RdDActorEntiteSheet, { types: ["entite"], makeDefault: true });
|
||||
Items.unregisterSheet("core", ItemSheet);
|
||||
|
||||
RdDItemSheet.register(RdDSigneDraconiqueItemSheet);
|
||||
RdDItemSheet.register(RdDRencontreItemSheet);
|
||||
RdDItemSheet.register(RdDConteneurItemSheet);
|
||||
RdDItemSheet.register(RdDHerbeItemSheet);
|
||||
RdDItemSheet.register(RdDFauneItemSheet);
|
||||
RdDItemSheet.register(RdDIngredientItemSheet);
|
||||
RdDItemSheet.register(RdDServiceItemSheet);
|
||||
|
||||
Items.registerSheet(SYSTEM_RDD, RdDItemSheet, {
|
||||
types: [
|
||||
"competence", "competencecreature",
|
||||
"recettealchimique", "musique", "chant", "danse", "jeu", "recettecuisine", "oeuvre",
|
||||
"objet", "arme", "armure", "livre", "potion", "munition",
|
||||
"monnaie", "nourritureboisson", "gemme",
|
||||
"meditation", "queue", "ombre", "souffle", "tete", "casetmr", "sort", "sortreserve",
|
||||
"nombreastral", "tache", "maladie", "poison", "possession",
|
||||
"tarot", "extraitpoetique"
|
||||
], makeDefault: true
|
||||
});
|
||||
CONFIG.Combat.documentClass = RdDCombatManager;
|
||||
|
||||
// préparation des différents modules
|
||||
RdDTimestamp.init();
|
||||
SystemCompendiums.init();
|
||||
DialogChronologie.init();
|
||||
ReglesOptionelles.init();
|
||||
RdDUtility.init();
|
||||
RdDDice.init();
|
||||
RdDCommands.init();
|
||||
RdDCombat.init();
|
||||
RdDCombatManager.init();
|
||||
RdDTokenHud.init();
|
||||
RdDBaseActor.init();
|
||||
RddCompendiumOrganiser.init();
|
||||
EffetsDraconiques.init()
|
||||
TMRUtility.init();
|
||||
RdDHotbar.initDropbar();
|
||||
RdDPossession.init();
|
||||
TMRRencontres.init();
|
||||
Environnement.init();
|
||||
|
||||
Hooks.once('ready', () => this.onReady());
|
||||
}
|
||||
|
||||
initSystemSettings() {
|
||||
game.settings.register(SYSTEM_RDD, "accorder-entite-cauchemar", {
|
||||
name: "Accorder le rêve aux entités",
|
||||
hint: "A quel moment les personnages doivent accorder leur rêve aux entités de cauchemar",
|
||||
scope: "world",
|
||||
config: true,
|
||||
type: String,
|
||||
choices: {
|
||||
"avant-attaque": "Avant l'attaque",
|
||||
"avant-defense": "Avant la défense",
|
||||
"avant-encaissement": "Avant l'encaissement",
|
||||
},
|
||||
default: "avant-encaissement"
|
||||
});
|
||||
|
||||
/* -------------------------------------------- */
|
||||
game.settings.register(SYSTEM_RDD, "liste-nombre-astral", {
|
||||
name: "liste-nombre-astral",
|
||||
scope: "world",
|
||||
config: false,
|
||||
default: [],
|
||||
type: Object
|
||||
});
|
||||
|
||||
/* -------------------------------------------- */
|
||||
game.settings.register(SYSTEM_RDD, "calendrier-pos", {
|
||||
name: "calendrierPos",
|
||||
scope: "client",
|
||||
config: false,
|
||||
default: RdDCalendrier.createCalendrierPos(),
|
||||
type: Object
|
||||
});
|
||||
|
||||
|
||||
/* -------------------------------------------- */
|
||||
game.settings.register(SYSTEM_RDD, "supprimer-dialogues-combat-chat", {
|
||||
name: "Supprimer les dialogues de combat",
|
||||
hint: "Si désactivée, tous les dialogues de combat sont conservés dans la conversation",
|
||||
scope: "world",
|
||||
config: true,
|
||||
default: true,
|
||||
type: Boolean
|
||||
});
|
||||
|
||||
/* -------------------------------------------- */
|
||||
game.settings.register(SYSTEM_RDD, "activer-sons-audio", {
|
||||
name: "Activer les bruitages intégrés",
|
||||
hint: "Si activé, certaines actions en jeu déclenchent un son d'ambiance",
|
||||
scope: "world",
|
||||
config: true,
|
||||
default: true,
|
||||
type: Boolean
|
||||
});
|
||||
/* -------------------------------------------- */
|
||||
game.settings.register(SYSTEM_RDD, "appliquer-famine-soif", {
|
||||
name: "Notifier de la famine et la soif pour",
|
||||
hint: "Indique si les cas de famine et de soif seront indiqués durant Château Dormant",
|
||||
scope: "world",
|
||||
config: true,
|
||||
type: String,
|
||||
choices: {
|
||||
"aucun": "ni la famine, ni la soif",
|
||||
"famine": "seulement la famine",
|
||||
"famine-soif": "la famine et la soif",
|
||||
},
|
||||
default: "aucun"
|
||||
});
|
||||
}
|
||||
|
||||
async onReady() {
|
||||
|
||||
/* -------------------------------------------- */
|
||||
/* Foundry VTT Initialization */
|
||||
/* -------------------------------------------- */
|
||||
// CSS patch for v9
|
||||
if (game.version) {
|
||||
let sidebar = document.getElementById("sidebar");
|
||||
sidebar.style.width = "min-content";
|
||||
}
|
||||
|
||||
if (Misc.isUniqueConnectedGM()) {
|
||||
new Migrations().migrate();
|
||||
}
|
||||
|
||||
StatusEffects.onReady();
|
||||
RdDHerbes.initializeHerbes();
|
||||
RdDDice.onReady();
|
||||
/* -------------------------------------------- */
|
||||
/* Affiche/Init le calendrier */
|
||||
let calendrier = new RdDCalendrier();
|
||||
let templatePath = "systems/foundryvtt-reve-de-dragon/templates/calendar-template.html";
|
||||
let templateData = {};
|
||||
renderTemplate(templatePath, templateData).then(html => {
|
||||
calendrier.render(true);
|
||||
});
|
||||
game.system.rdd.calendrier = calendrier; // Reference;
|
||||
|
||||
// Avertissement si joueur sans personnage
|
||||
if (!game.user.isGM && game.user.character == undefined) {
|
||||
ui.notifications.info("Attention ! Vous n'êtes connecté à aucun personnage !");
|
||||
ChatMessage.create({
|
||||
content: "<b>ATTENTION</b> Le joueur " + game.user.name + " n'est connecté à aucun personnage !",
|
||||
user: game.user.id
|
||||
});
|
||||
}
|
||||
if (Misc.isUniqueConnectedGM()) {
|
||||
this.messageDeBienvenue();
|
||||
this.registerUsageCount(SYSTEM_RDD);
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
messageDeBienvenue() {
|
||||
if (game.user.isGM) {
|
||||
ChatUtility.removeChatMessageContaining('<div id="message-bienvenue-rdd">');
|
||||
ChatMessage.create({
|
||||
user: game.user.id,
|
||||
content: `<div id="message-bienvenue-rdd"><span class="rdd-roll-part">Bienvenue dans le Rêve des Dragons !</span>
|
||||
<br>Vous trouverez quelques informations pour démarrer dans ce document : @Compendium[foundryvtt-reve-de-dragon.rappel-des-regles.7uGrUHGdPu0EmIu2]{Documentation MJ/Joueurs}
|
||||
<br>La commande <code>/aide</code> dans le chat permet de voir les commandes spécifiques à Rêve de Dragon.</div>
|
||||
` });
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
// Register world usage statistics
|
||||
function registerUsageCount( registerKey ) {
|
||||
if ( game.user.isGM ) {
|
||||
game.settings.register("world", "world-key", {
|
||||
name: "Unique world key",
|
||||
scope: "world",
|
||||
config: false,
|
||||
default: "NONE",
|
||||
type: String
|
||||
});
|
||||
|
||||
let worldKey = game.settings.get("world", "world-key")
|
||||
if ( worldKey == undefined || worldKey == "" ) {
|
||||
worldKey = randomID(32)
|
||||
game.settings.set("world", "world-key", worldKey )
|
||||
}
|
||||
let regURL = `https://www.uberwald.me/fvtt_appcount/count.php?name="${registerKey}"&worldKey="${worldKey}"&version="${game.release.generation}.${game.release.build}"&system="${game.system.id}"&systemversion="${game.system.version}"`
|
||||
$.ajax(regURL)
|
||||
/* -------------------------------------------- */
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
/* Foundry VTT Initialization */
|
||||
/* -------------------------------------------- */
|
||||
Hooks.once("ready", async function () {
|
||||
await migrationPngWebp_1_5_34()
|
||||
if (Misc.isUniqueConnectedGM()) {
|
||||
new Migrations().migrate();
|
||||
}
|
||||
|
||||
StatusEffects.onReady();
|
||||
RdDHerbes.initializeHerbes();
|
||||
RdDDice.onReady();
|
||||
/* -------------------------------------------- */
|
||||
/* Affiche/Init le calendrier */
|
||||
let calendrier = new RdDCalendrier();
|
||||
let templatePath = "systems/foundryvtt-reve-de-dragon/templates/calendar-template.html";
|
||||
let templateData = {};
|
||||
renderTemplate(templatePath, templateData).then(html => {
|
||||
calendrier.render(true);
|
||||
});
|
||||
game.system.rdd.calendrier = calendrier; // Reference;
|
||||
// Register world usage statistics
|
||||
async registerUsageCount(registerKey) {
|
||||
if (game.user.isGM) {
|
||||
game.settings.register("world", "world-key", {
|
||||
name: "Unique world key",
|
||||
scope: "world",
|
||||
config: false,
|
||||
default: "NONE",
|
||||
type: String
|
||||
});
|
||||
|
||||
// Avertissement si joueur sans personnage
|
||||
if (!game.user.isGM && game.user.character == undefined) {
|
||||
ui.notifications.info("Attention ! Vous n'êtes connecté à aucun personnage !");
|
||||
ChatMessage.create({
|
||||
content: "<b>ATTENTION</b> Le joueur " + game.user.name + " n'est connecté à aucun personnage !",
|
||||
user: game.user.id
|
||||
});
|
||||
}
|
||||
if (Misc.isUniqueConnectedGM()) {
|
||||
messageDeBienvenue();
|
||||
registerUsageCount( SYSTEM_RDD );
|
||||
}
|
||||
});
|
||||
|
||||
async function migrationPngWebp_1_5_34() {
|
||||
if (!game.settings.get(SYSTEM_RDD, "migration-png-webp-1.5.34")) {
|
||||
const regexOldPngJpg = /(systems\/foundryvtt-reve-de-dragon\/icons\/.*)\.(png|jpg)/;
|
||||
const replaceWithWebp = '$1.webp';
|
||||
function convertImgToWebp(img) {
|
||||
return img.replace(regexOldPngJpg, replaceWithWebp);
|
||||
}
|
||||
function prepareDocumentsImgUpdate(documents) {
|
||||
return documents.filter(it => it.img && it.img.match(regexOldPngJpg))
|
||||
.map(it => {
|
||||
return { _id: it.id, img: convertImgToWebp(it.img) }
|
||||
});
|
||||
}
|
||||
const itemsUpdates = prepareDocumentsImgUpdate(game.items);
|
||||
const actorsUpdates = prepareDocumentsImgUpdate(game.actors);
|
||||
//Migrate system png to webp
|
||||
await Item.updateDocuments(itemsUpdates);
|
||||
await Actor.updateDocuments(actorsUpdates);
|
||||
game.actors.forEach(actor => {
|
||||
if (actor.token?.img && actor.token.img.match(regexOldPngJpg)) {
|
||||
actor.update({ "token.img": convertImgToWebp(actor.token.img) });
|
||||
let worldKey = game.settings.get("world", "world-key")
|
||||
if (worldKey == undefined || worldKey == "") {
|
||||
worldKey = randomID(32)
|
||||
game.settings.set("world", "world-key", worldKey)
|
||||
}
|
||||
const actorItemsToUpdate = prepareDocumentsImgUpdate(actor.items);
|
||||
actor.updateEmbeddedDocuments('Item', actorItemsToUpdate);
|
||||
});
|
||||
game.settings.set(SYSTEM_RDD, "migration-png-webp-1.5.34", true)
|
||||
}
|
||||
|
||||
// CSS patch for v9
|
||||
if (game.version) {
|
||||
let sidebar = document.getElementById("sidebar");
|
||||
sidebar.style.width = "min-content";
|
||||
let regURL = `https://www.uberwald.me/fvtt_appcount/count.php?name="${registerKey}"&worldKey="${worldKey}"&version="${game.release.generation}.${game.release.build}"&system="${game.system.id}"&systemversion="${game.system.version}"`
|
||||
$.ajax(regURL)
|
||||
/* -------------------------------------------- */
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
/* Dice-so-nice ready */
|
||||
/* -------------------------------------------- */
|
||||
Hooks.once('diceSoNiceReady', (dice3d) => RdDDice.diceSoNiceReady(dice3d));
|
||||
SystemReveDeDragon.start();
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
import { RdDActor } from "./actor.js";
|
||||
import { RdDBaseActor } from "./actor/base-actor.js";
|
||||
import { Misc } from "./misc.js";
|
||||
import { RdDDice } from "./rdd-dice.js";
|
||||
|
||||
@ -20,7 +20,7 @@ export class RdDNameGen {
|
||||
|
||||
static async onCreerActeur(event) {
|
||||
const button = event.currentTarget;
|
||||
await RdDActor.create({
|
||||
await RdDBaseActor.create({
|
||||
name: button.attributes['data-nom'].value,
|
||||
type: button.attributes['data-type'].value
|
||||
},
|
||||
|
@ -45,7 +45,7 @@ export class RdDPossession {
|
||||
defender: defender,
|
||||
targetToken: Targets.extractTokenData(target)
|
||||
};
|
||||
if (attacker.isCreature()) {
|
||||
if (attacker.isCreatureEntite()) {
|
||||
RdDItemCompetenceCreature.setRollDataCreature(rollData)
|
||||
}
|
||||
|
||||
|
@ -14,7 +14,7 @@ const levelDown = [
|
||||
{ level: -15, score: 1, norm: 1, sign: 0, part: 0, epart: 2, etotal: 10 },
|
||||
{ level: -16, score: 1, norm: 1, sign: 0, part: 0, epart: 0, etotal: 2 }
|
||||
];
|
||||
const levelImpossible = { score: 0, norm:0, sign: 0, part: 0, epart: 0, etotal: 1 };
|
||||
const levelImpossible = { score: 0, norm: 0, sign: 0, part: 0, epart: 0, etotal: 1 };
|
||||
|
||||
const reussites = [
|
||||
{ code: "etotal", isPart: false, isSign: false, isSuccess: false, isEchec: true, isEPart: true, isETotal: true, ptTache: -4, ptQualite: -6, quality: "Echec total", condition: (target, roll) => roll >= target.etotal && roll <= 100 },
|
||||
@ -42,6 +42,44 @@ export class RdDResolutionTable {
|
||||
return table;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static computeChances(carac, level) {
|
||||
if (level < -16) {
|
||||
return levelImpossible;
|
||||
}
|
||||
if (level < -10) {
|
||||
return levelDown.find(it => it.level == level);
|
||||
}
|
||||
const percentage = RdDResolutionTable.computePercentage(carac, level);
|
||||
return this._computeCell(level, percentage);
|
||||
}
|
||||
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static _computeRow(caracValue) {
|
||||
let dataRow = [
|
||||
this._computeCell(-10, Math.max(Math.floor(caracValue / 4), 1)),
|
||||
this._computeCell(-9, Math.max(Math.floor(caracValue / 2), 1))
|
||||
]
|
||||
for (var diff = -8; diff <= 22; diff++) {
|
||||
dataRow[diff + 10] = this._computeCell(diff, RdDResolutionTable.computePercentage(caracValue, diff));
|
||||
}
|
||||
return dataRow;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static _computeCell(niveau, percentage) {
|
||||
return {
|
||||
niveau: niveau,
|
||||
score: percentage,
|
||||
norm: Math.min(99, percentage),
|
||||
sign: this._reussiteSignificative(percentage),
|
||||
part: this._reussitePart(percentage),
|
||||
epart: this._echecParticulier(percentage),
|
||||
etotal: this._echecTotal(percentage)
|
||||
};
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static getResultat(code) {
|
||||
let resultat = reussites.find(r => code == r.code);
|
||||
@ -51,17 +89,6 @@ export class RdDResolutionTable {
|
||||
return resultat;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static explain(rolled) {
|
||||
let message = "<br>Jet : <strong>" + rolled.roll + "</strong> sur " + rolled.score + "% ";
|
||||
if (rolled.caracValue != undefined && rolled.finalLevel != undefined) {
|
||||
message += (rolled.diviseurSignificative > 1 ? `(1/${rolled.diviseurSignificative} de ` : "(")
|
||||
+ rolled.caracValue + " à " + Misc.toSignedString(rolled.finalLevel) + ") ";
|
||||
}
|
||||
message += '<strong>' + rolled.quality + '</strong>'
|
||||
return message;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static async displayRollData(rollData, actor = undefined, template = 'chat-resultat-general.html') {
|
||||
return await ChatUtility.createChatWithRollMode(actor?.userName ?? game.user.name, {
|
||||
@ -82,8 +109,8 @@ export class RdDResolutionTable {
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static async roll(caracValue, finalLevel, rollData = {}){
|
||||
let chances = this.computeChances(caracValue, finalLevel);
|
||||
static async roll(caracValue, finalLevel, rollData = {}) {
|
||||
let chances = duplicate(this.computeChances(caracValue, finalLevel));
|
||||
this._updateChancesWithBonus(chances, rollData.bonus, finalLevel);
|
||||
this._updateChancesFactor(chances, rollData.diviseurSignificative);
|
||||
chances.showDice = rollData.showDice;
|
||||
@ -95,7 +122,7 @@ export class RdDResolutionTable {
|
||||
rolled.bonus = rollData.bonus;
|
||||
rolled.factorHtml = Misc.getFractionHtml(rollData.diviseurSignificative);
|
||||
|
||||
if (ReglesOptionelles.isUsing("afficher-colonnes-reussite")){
|
||||
if (ReglesOptionelles.isUsing("afficher-colonnes-reussite")) {
|
||||
rolled.niveauNecessaire = this.findNiveauNecessaire(caracValue, rolled.roll);
|
||||
rolled.ajustementNecessaire = rolled.niveauNecessaire - finalLevel;
|
||||
}
|
||||
@ -103,13 +130,24 @@ export class RdDResolutionTable {
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static findNiveauNecessaire(caracValue, rollValue) {
|
||||
for (let cell of this.resolutionTable[caracValue]) {
|
||||
if ( rollValue <= cell.norm) {
|
||||
return cell.niveau;
|
||||
}
|
||||
static findNiveauNecessaire(carac, rolled) {
|
||||
if (carac == 0) {
|
||||
return NaN;
|
||||
}
|
||||
return 16; // Dummy default
|
||||
if (rolled >= carac){
|
||||
const upper = Math.ceil(rolled/carac);
|
||||
return 2*upper -10
|
||||
}
|
||||
if (rolled > Math.floor(carac/2)) {
|
||||
return -8
|
||||
}
|
||||
if (rolled > Math.floor(carac/4)) {
|
||||
return -9
|
||||
}
|
||||
if (rolled > 1) {
|
||||
return -10
|
||||
}
|
||||
return -11;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
@ -122,7 +160,7 @@ export class RdDResolutionTable {
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static _updateChancesWithBonus(chances, bonus, finalLevel) {
|
||||
if (bonus && finalLevel>-11) {
|
||||
if (bonus && finalLevel > -11) {
|
||||
let newScore = Number(chances.score) + bonus;
|
||||
mergeObject(chances, this._computeCell(undefined, newScore), { overwrite: true });
|
||||
}
|
||||
@ -142,21 +180,19 @@ export class RdDResolutionTable {
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static async rollChances(chances, diviseur, forceDiceResult = -1) {
|
||||
chances.forceDiceResult = forceDiceResult <= 0 || forceDiceResult > 100 ? undefined : {total: forceDiceResult};
|
||||
chances.roll = await RdDDice.rollTotal( "1d100", chances);
|
||||
chances.forceDiceResult = forceDiceResult <= 0 || forceDiceResult > 100 ? undefined : { total: forceDiceResult };
|
||||
chances.roll = await RdDDice.rollTotal("1d100", chances);
|
||||
mergeObject(chances, this.computeReussite(chances, chances.roll, diviseur), { overwrite: true });
|
||||
return chances;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static computeChances(caracValue, difficulte) {
|
||||
if (difficulte < -16) {
|
||||
return duplicate(levelImpossible);
|
||||
}
|
||||
if (difficulte < -10) {
|
||||
return duplicate(levelDown.find(levelData => levelData.level == difficulte));
|
||||
}
|
||||
return duplicate(RdDResolutionTable.resolutionTable[caracValue][difficulte + 10]);
|
||||
static computePercentage(carac, diff) {
|
||||
if (diff < -16) return 0
|
||||
if (diff < -10) return 1
|
||||
if (diff == -10) return Math.max(Math.floor(carac / 4), 1)
|
||||
if (diff == -9) return Math.max(Math.floor(carac / 2), 1)
|
||||
return Math.max(Math.floor(carac * (diff + 10) / 2), 1);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
@ -213,31 +249,6 @@ export class RdDResolutionTable {
|
||||
return reussite;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static _computeRow(caracValue) {
|
||||
let dataRow = [
|
||||
this._computeCell(-10, Math.max(Math.floor(caracValue / 4), 1)),
|
||||
this._computeCell(-9, Math.max(Math.floor(caracValue / 2), 1))
|
||||
]
|
||||
for (var diff = -8; diff <= 22; diff++) {
|
||||
dataRow[diff + 10] = this._computeCell(diff, Math.max(Math.floor(caracValue * (diff + 10) / 2), 1));
|
||||
}
|
||||
return dataRow;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static _computeCell(niveau, percentage) {
|
||||
return {
|
||||
niveau: niveau,
|
||||
score: percentage,
|
||||
norm: Math.min(99, percentage),
|
||||
sign: this._reussiteSignificative(percentage),
|
||||
part: this._reussitePart(percentage),
|
||||
epart: this._echecParticulier(percentage),
|
||||
etotal: this._echecTotal(percentage)
|
||||
};
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static _reussiteSignificative(percentage) {
|
||||
return Math.floor(percentage / 2);
|
||||
@ -261,92 +272,34 @@ export class RdDResolutionTable {
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static buildHTMLResults(caracValue, levelValue) {
|
||||
if (caracValue == undefined || isNaN(caracValue)) caracValue = 10;
|
||||
if (levelValue == undefined || isNaN(levelValue)) levelValue = 0;
|
||||
|
||||
let cell = this.computeChances(caracValue, levelValue);
|
||||
cell.epart = cell.epart > 99 ? 'N/A' : cell.epart;
|
||||
cell.etotal = cell.etotal > 100 ? 'N/A' : cell.etotal;
|
||||
cell.score = Math.min(cell.score, 99);
|
||||
|
||||
return `
|
||||
<span class="table-proba-reussite competence-label">
|
||||
Particulière: <span class="rdd-roll-part">${cell.part}</span>
|
||||
- Significative: <span class="rdd-roll-sign">${cell.sign}</span>
|
||||
- Réussite: <span class="rdd-roll-norm">${cell.score}</span>
|
||||
- Echec Particulier: <span class="rdd-roll-epart">${cell.epart}</span>
|
||||
- Echec Total: <span class="rdd-roll-etotal">${cell.etotal}</span>
|
||||
</span>
|
||||
`
|
||||
static subTable(carac, level, delta = { carac: 2, level: 5}) {
|
||||
return {
|
||||
carac,
|
||||
level,
|
||||
minCarac: carac - (delta?.carac ?? 2),
|
||||
maxCarac: carac + (delta?.carac ?? 2),
|
||||
minLevel: level - (delta?.level ?? 5),
|
||||
maxLevel: level + (delta?.level ?? 5)
|
||||
};
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static buildHTMLTableExtract(caracValue, levelValue) {
|
||||
return this.buildHTMLTable(caracValue, levelValue, caracValue - 2, caracValue + 2, levelValue - 5, levelValue + 5)
|
||||
}
|
||||
|
||||
static buildHTMLTable(caracValue, levelValue, minCarac = 1, maxCarac = 21, minLevel = -10, maxLevel = 11) {
|
||||
return this._buildHTMLTable(caracValue, levelValue, minCarac, maxCarac, minLevel, maxLevel)
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static _buildHTMLTable(caracValue, levelValue, minCarac, maxCarac, minLevel, maxLevel) {
|
||||
let countColonnes = maxLevel - minLevel;
|
||||
static async buildHTMLTable({ carac: carac, level: level, minCarac = 1, maxCarac = 21, minLevel = -10, maxLevel = 11 }) {
|
||||
let colonnes = maxLevel - minLevel;
|
||||
minCarac = Math.max(minCarac, 1);
|
||||
maxCarac = Math.min(maxCarac, caracMaximumResolution);
|
||||
maxCarac = Math.min(maxCarac, minCarac + 20);
|
||||
minLevel = Math.max(minLevel, -10);
|
||||
maxLevel = Math.max(Math.min(maxLevel, 22), minLevel + countColonnes);
|
||||
|
||||
let table = $("<table class='table-resolution'/>")
|
||||
.append(this._buildHTMLHeader(RdDResolutionTable.resolutionTable[0], minLevel, maxLevel));
|
||||
|
||||
for (var rowIndex = minCarac; rowIndex <= maxCarac; rowIndex++) {
|
||||
table.append(this._buildHTMLRow(RdDResolutionTable.resolutionTable[rowIndex], rowIndex, caracValue, levelValue, minLevel, maxLevel));
|
||||
}
|
||||
table.append("</table>");
|
||||
return table;
|
||||
maxLevel = Math.max(Math.min(maxLevel, 30), minLevel + colonnes);
|
||||
return await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/resolution-table.html', {
|
||||
carac: carac,
|
||||
difficulte: level,
|
||||
min: minLevel,
|
||||
rows: RdDResolutionTable.incrementalArray(minCarac, maxCarac),
|
||||
cols: RdDResolutionTable.incrementalArray(minLevel, maxLevel)
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static _buildHTMLHeader(dataRow, minLevel, maxLevel) {
|
||||
let tr = $("<tr/>");
|
||||
|
||||
if (minLevel > -8) {
|
||||
tr.append($("<th class='table-resolution-level'/>").text("-8"))
|
||||
}
|
||||
if (minLevel > -7) {
|
||||
tr.append($("<th class='table-resolution-level'/>").text("..."));
|
||||
}
|
||||
for (let difficulte = minLevel; difficulte <= maxLevel; difficulte++) {
|
||||
tr.append($("<th class='table-resolution-level'/>").text(Misc.toSignedString(difficulte)));
|
||||
}
|
||||
return tr;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static _buildHTMLRow(dataRow, rowIndex, caracValue, levelValue, minLevel, maxLevel) {
|
||||
let tr = $("<tr/>");
|
||||
let max = maxLevel;
|
||||
|
||||
if (minLevel > -8) {
|
||||
let score = dataRow[-8 + 10].score;
|
||||
tr.append($("<td class='table-resolution-carac'/>").text(score))
|
||||
}
|
||||
if (minLevel > -7) {
|
||||
tr.append($("<td/>"))
|
||||
}
|
||||
for (let difficulte = minLevel; difficulte <= max; difficulte++) {
|
||||
let td = $("<td/>");
|
||||
let score = dataRow[difficulte + 10].score;
|
||||
if (rowIndex == caracValue && levelValue == difficulte) {
|
||||
td.addClass('table-resolution-target');
|
||||
} else if (difficulte == -8) {
|
||||
td.addClass('table-resolution-carac');
|
||||
}
|
||||
tr.append(td.text(score));
|
||||
}
|
||||
return tr;
|
||||
static incrementalArray(min, max) {
|
||||
return Array.from(Array(max-min+1).keys()).map(i=>i+min)
|
||||
}
|
||||
|
||||
}
|
@ -1,4 +1,5 @@
|
||||
import { ENTITE_BLURETTE, ENTITE_INCARNE} from "./constants.js";
|
||||
import { ENTITE_BLURETTE, ENTITE_INCARNE } from "./constants.js";
|
||||
import { RdDUtility } from "./rdd-utility.js";
|
||||
|
||||
/**
|
||||
* Extend the base Dialog entity by defining a custom window to perform roll.
|
||||
@ -6,32 +7,37 @@ import { ENTITE_BLURETTE, ENTITE_INCARNE} from "./constants.js";
|
||||
*/
|
||||
export class RdDEncaisser extends Dialog {
|
||||
|
||||
static async encaisser(actor) {
|
||||
let html = await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/dialog-roll-encaisser.html',
|
||||
{ ajustementsEncaissement: RdDUtility.getAjustementsEncaissement() }
|
||||
);
|
||||
new RdDEncaisser(html, actor).render(true);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
constructor(html, actor) {
|
||||
// Common conf
|
||||
let buttons = {};
|
||||
if (!actor.isEntite()){
|
||||
buttons = {
|
||||
let dialogConf = {
|
||||
title: "Jet d'Encaissement",
|
||||
content: html,
|
||||
}
|
||||
|
||||
if (!actor.isEntite()) {
|
||||
dialogConf.default = "mortel";
|
||||
dialogConf.buttons = {
|
||||
"mortel": { label: "Mortel", callback: html => this.performEncaisser("mortel") },
|
||||
"non-mortel": { label: "Non-mortel", callback: html => this.performEncaisser("non-mortel") },
|
||||
"sonne": { label: "Sonné", callback: html => this.actor.setSonne() },
|
||||
};
|
||||
}
|
||||
else if (actor.isEntite([ENTITE_BLURETTE, ENTITE_INCARNE])){
|
||||
buttons = {
|
||||
"cauchemar": { label: "cauchemar", callback: html => this.performEncaisser("cauchemar") }
|
||||
else if (actor.isEntite([ENTITE_BLURETTE, ENTITE_INCARNE])) {
|
||||
dialogConf.default = "cauchemar"
|
||||
dialogConf.buttons = {
|
||||
"cauchemar": { label: "Cauchemar", callback: html => this.performEncaisser("cauchemar") }
|
||||
}
|
||||
}
|
||||
|
||||
let dialogConf = {
|
||||
title: "Jet d'Encaissement",
|
||||
content: html,
|
||||
buttons: buttons,
|
||||
default: "mortel"
|
||||
}
|
||||
|
||||
let dialogOptions = {
|
||||
classes: ["rdddialog"],
|
||||
classes: ["rdd-roll-dialog"],
|
||||
width: 320,
|
||||
height: 'fit-content'
|
||||
}
|
||||
@ -44,7 +50,18 @@ export class RdDEncaisser extends Dialog {
|
||||
this.encaisserSpecial = "aucun";
|
||||
}
|
||||
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
this.html = html;
|
||||
|
||||
this.html.find('[name="modificateurDegats"]').val("0");
|
||||
this.html.find('[name="modificateurDegats"]').change((event) => {
|
||||
this.modifier = event.currentTarget.value; // Update the selected bonus/malus
|
||||
});
|
||||
this.html.find('[name="encaisserSpecial"]').change((event) => {
|
||||
this.encaisserSpecial = event.currentTarget.value; // Update the selected bonus/malus
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
performEncaisser(mortalite) {
|
||||
@ -58,22 +75,4 @@ export class RdDEncaisser extends Dialog {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
|
||||
// Setup everything onload
|
||||
$(function () {
|
||||
$("#modificateurDegats").val("0");
|
||||
});
|
||||
|
||||
html.find('#modificateurDegats').change((event) => {
|
||||
this.modifier = event.currentTarget.value; // Update the selected bonus/malus
|
||||
});
|
||||
html.find('#encaisserSpecial').change((event) => {
|
||||
this.encaisserSpecial = event.currentTarget.value; // Update the selected bonus/malus
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -13,47 +13,33 @@ export class RdDRollDialogEthylisme extends Dialog {
|
||||
title: "Test d'éthylisme",
|
||||
content: html,
|
||||
default: "rollButton",
|
||||
buttons: { "rollButton": { label: "Test d'éthylisme", callback: html => this.onButton(html) } }
|
||||
buttons: { "rollButton": { label: "Test d'éthylisme", callback: html => onRoll(this.rollData) } }
|
||||
};
|
||||
let dialogOptions = { classes: ["rdddialog"], width: 400, height: 'fit-content', 'z-index': 99999 }
|
||||
let dialogOptions = { classes: ["rdd-roll-dialog"], width: 400, height: 'fit-content', 'z-index': 99999 }
|
||||
super(dialogConf, dialogOptions)
|
||||
|
||||
//console.log("ETH", rollData);
|
||||
this.onRoll = onRoll;
|
||||
this.rollData = rollData;
|
||||
this.actor = actor;
|
||||
}
|
||||
|
||||
async onButton(html) {
|
||||
this.onRoll(this.rollData);
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
this.html = html;
|
||||
this.bringToTop();
|
||||
|
||||
this.html.find(".force-alcool").change((event) => {
|
||||
this.rollData.forceAlcool = Misc.toInt(event.currentTarget.value);
|
||||
this.updateRollResult();
|
||||
});
|
||||
|
||||
this.html.find(".force-alcool").val(Misc.toInt(this.rollData.forceAlcool));
|
||||
this.updateRollResult();
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
|
||||
this.bringToTop(); // Ensure top level
|
||||
// Get the rollData stuff
|
||||
var rollData = this.rollData;
|
||||
var dialog = this;
|
||||
|
||||
// Setup everything onload
|
||||
$(function () {
|
||||
$("#forceAlcool").val(Misc.toInt(rollData.forceAlcool));
|
||||
dialog.updateRollResult();
|
||||
});
|
||||
|
||||
// Update !
|
||||
html.find('#forceAlcool').change((event) => {
|
||||
rollData.forceAlcool = Misc.toInt(event.currentTarget.value); // Update the selected bonus/malus
|
||||
dialog.updateRollResult();
|
||||
});
|
||||
}
|
||||
async updateRollResult() {
|
||||
|
||||
// Mise à jour valeurs
|
||||
$("#roll-param").text(this.rollData.vie + " / " + Misc.toSignedString(Number(this.rollData.etat) + Number(this.rollData.forceAlcool) + this.rollData.diffNbDoses));
|
||||
$(".table-resolution").remove();
|
||||
this.html.find(".roll-ethylisme").text(this.rollData.vie + " / " + Misc.toSignedString(Number(this.rollData.etat) + Number(this.rollData.forceAlcool) + this.rollData.diffNbDoses));
|
||||
this.html.find(".table-resolution").remove();
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -9,12 +9,19 @@ const titleTableDeResolution = 'Table de résolution';
|
||||
/* -------------------------------------------- */
|
||||
export class RdDRollResolutionTable extends Dialog {
|
||||
|
||||
static resolutionTable = undefined;
|
||||
/* -------------------------------------------- */
|
||||
static async open(rollData = {}) {
|
||||
RdDRollResolutionTable._setDefaultOptions(rollData);
|
||||
let html = await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/dialog-roll-resolution.html', rollData);
|
||||
const dialog = new RdDRollResolutionTable(rollData, html);
|
||||
dialog.render(true);
|
||||
static async open() {
|
||||
if (RdDRollResolutionTable.resolutionTable == undefined) {
|
||||
const rollData = {}
|
||||
RdDRollResolutionTable._setDefaultOptions(rollData);
|
||||
let html = await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/dialog-roll-resolution.html', rollData);
|
||||
RdDRollResolutionTable.resolutionTable = new RdDRollResolutionTable(rollData, html);
|
||||
RdDRollResolutionTable.resolutionTable.render(true);
|
||||
}
|
||||
else{
|
||||
RdDRollResolutionTable.resolutionTable.bringToTop();
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
@ -53,11 +60,40 @@ export class RdDRollResolutionTable extends Dialog {
|
||||
'lancer-fermer': { label: 'Lancer les dés et fermer', callback: html => this.onLancerFermer() }
|
||||
}
|
||||
};
|
||||
super(conf, { classes: ["rdddialog"], width: 800, height: 'fit-content', 'z-index': 99999 });
|
||||
super(conf, { classes: ["rdd-roll-dialog"], top: 50, width: 'fit-content', height: 'fit-content', 'z-index': 99999 });
|
||||
|
||||
this.rollData = rollData;
|
||||
}
|
||||
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
this.html = html;
|
||||
this.bringToTop();
|
||||
|
||||
|
||||
this.html.find("[name='diffLibre']").val(Misc.toInt(this.rollData.diffLibre));
|
||||
this.html.find("[name='diffConditions']").val(Misc.toInt(this.rollData.diffConditions));
|
||||
this.updateRollResult();
|
||||
|
||||
this.html.find('.lancer-table-resolution').click((event) => {
|
||||
this.onLancer();
|
||||
});
|
||||
// Update !
|
||||
this.html.find("[name='diffLibre']").change((event) => {
|
||||
this.rollData.diffLibre = Misc.toInt(event.currentTarget.value);
|
||||
this.updateRollResult();
|
||||
});
|
||||
this.html.find("[name='diffConditions']").change((event) => {
|
||||
this.rollData.diffConditions = Misc.toInt(event.currentTarget.value);
|
||||
this.updateRollResult();
|
||||
});
|
||||
this.html.find("[name='carac']").change((event) => {
|
||||
let caracKey = event.currentTarget.value;
|
||||
this.rollData.selectedCarac = this.rollData.carac[caracKey];
|
||||
this.updateRollResult();
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async onLancer() {
|
||||
await RdDResolutionTable.rollData(this.rollData);
|
||||
@ -72,65 +108,36 @@ export class RdDRollResolutionTable extends Dialog {
|
||||
await RdDResolutionTable.displayRollData(this.rollData);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
|
||||
this.bringToTop();
|
||||
|
||||
var dialog = this;
|
||||
|
||||
// Setup everything onload
|
||||
function onLoad(){
|
||||
$("#diffLibre").val(Misc.toInt(dialog.rollData.diffLibre));
|
||||
$("#diffConditions").val(Misc.toInt(dialog.rollData.diffConditions));
|
||||
dialog.updateRollResult();
|
||||
}
|
||||
$(function () { onLoad();});
|
||||
html.find('#lancer').click((event) => {
|
||||
this.onLancer();
|
||||
});
|
||||
// Update !
|
||||
html.find('#diffLibre').change((event) => {
|
||||
this.rollData.diffLibre = Misc.toInt(event.currentTarget.value);
|
||||
this.updateRollResult();
|
||||
});
|
||||
html.find('#diffConditions').change((event) => {
|
||||
this.rollData.diffConditions = Misc.toInt(event.currentTarget.value);
|
||||
this.updateRollResult();
|
||||
});
|
||||
html.find('#carac').change((event) => {
|
||||
let caracKey = event.currentTarget.value;
|
||||
this.rollData.selectedCarac = this.rollData.carac[caracKey];
|
||||
this.updateRollResult();
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async updateRollResult() {
|
||||
let rollData = this.rollData;
|
||||
rollData.caracValue = parseInt(rollData.selectedCarac.value)
|
||||
rollData.finalLevel = this._computeFinalLevel(rollData);
|
||||
|
||||
const htmlTable = await RdDResolutionTable.buildHTMLTable({
|
||||
carac: rollData.caracValue,
|
||||
level: rollData.finalLevel,
|
||||
maxCarac: 20,
|
||||
maxLevel: 10
|
||||
});
|
||||
|
||||
// Mise à jour valeurs
|
||||
$("#carac").val(rollData.caracValue);
|
||||
$("#roll-param").text(rollData.selectedCarac.value + " / " + Misc.toSignedString(rollData.finalLevel));
|
||||
$(".table-resolution").remove();
|
||||
$(".table-proba-reussite").remove();
|
||||
$("#tableResolution").append(RdDResolutionTable.buildHTMLTable(rollData.caracValue, rollData.finalLevel));
|
||||
$("#tableProbaReussite").append(RdDResolutionTable.buildHTMLResults(rollData.caracValue, rollData.finalLevel));
|
||||
this.html.find("[name='carac']").val(rollData.caracValue);
|
||||
this.html.find(".roll-param-resolution").text(rollData.selectedCarac.value + " / " + Misc.toSignedString(rollData.finalLevel));
|
||||
this.html.find("div.placeholder-resolution").empty().append(htmlTable)
|
||||
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
_computeFinalLevel(rollData) {
|
||||
const diffConditions = Misc.toInt(rollData.diffConditions);
|
||||
const diffLibre = this._computeDiffLibre(rollData);
|
||||
const diffLibre = Misc.toInt(rollData.diffLibre);
|
||||
|
||||
return diffLibre + diffConditions;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
_computeDiffLibre(rollData) {
|
||||
return Misc.toInt(rollData.diffLibre);
|
||||
async close() {
|
||||
await super.close();
|
||||
RdDRollResolutionTable.resolutionTable = undefined;
|
||||
}
|
||||
}
|
||||
|
@ -16,24 +16,17 @@ import { ReglesOptionelles } from "./settings/regles-optionelles.js";
|
||||
export class RdDRoll extends Dialog {
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static async create(actor, rollData, dialogConfig, ...actions) {
|
||||
|
||||
if (actor.isRollWindowsOpened()) {
|
||||
ui.notifications.warn("Vous avez déja une fenêtre de Test ouverte, il faut la fermer avant d'en ouvrir une autre.")
|
||||
return;
|
||||
}
|
||||
actor.setRollWindowsOpened(true);
|
||||
|
||||
RdDRoll._ensureCorrectActions(actions);
|
||||
static async create(actor, rollData, dialogConfig, action) {
|
||||
RdDRoll._ensureCorrectAction(action);
|
||||
RdDRoll._setDefaultOptions(actor, rollData);
|
||||
|
||||
const html = await renderTemplate(dialogConfig.html, rollData);
|
||||
|
||||
let options = { classes: ["rdddialog"], width: 600, height: 'fit-content', 'z-index': 99999 };
|
||||
if (dialogConfig.options) {
|
||||
mergeObject(options, dialogConfig.options, { overwrite: true })
|
||||
let options = { classes: ["rdd-roll-dialog"], width: 600, height: 'fit-content', 'z-index': 99999, close: html => {} };
|
||||
if (dialogConfig.close) {
|
||||
options.close = dialogConfig.close;
|
||||
}
|
||||
return new RdDRoll(actor, rollData, html, options, actions, dialogConfig.close);
|
||||
return new RdDRoll(actor, rollData, html, options, action);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
@ -67,7 +60,7 @@ export class RdDRoll extends Dialog {
|
||||
forceDiceResult: -1
|
||||
}
|
||||
// Mini patch :Ajout du rêve actuel
|
||||
if ( actor.system.type == "personnage") {
|
||||
if (actor.system.type == "personnage") {
|
||||
defaultRollData.carac["reve-actuel"] = actor.system.reve.reve
|
||||
}
|
||||
|
||||
@ -79,6 +72,7 @@ export class RdDRoll extends Dialog {
|
||||
|
||||
RollDataAjustements.calcul(rollData, actor);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static getDiviseurSignificative(rollData) {
|
||||
let facteurSign = 1;
|
||||
@ -97,171 +91,132 @@ export class RdDRoll extends Dialog {
|
||||
return facteurSign;
|
||||
}
|
||||
|
||||
|
||||
/* -------------------------------------------- */
|
||||
static _ensureCorrectActions(actions) {
|
||||
if (actions.length == 0) {
|
||||
throw 'No action defined';
|
||||
static _ensureCorrectAction(action) {
|
||||
if (action.callbacks == undefined) {
|
||||
console.warn('No callback defined for ', action.name);
|
||||
action.callbacks = [{ action: r => console.warn(action.name, r) }];
|
||||
}
|
||||
actions.forEach(action => {
|
||||
if (action.callbacks == undefined) {
|
||||
action.callbacks = [{ action: r => console.log(action.name, r) }];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
constructor(actor, rollData, html, options, actions, close = undefined) {
|
||||
constructor(actor, rollData, html, options, action) {
|
||||
let conf = {
|
||||
title: actions[0].label,
|
||||
title: action.label,
|
||||
content: html,
|
||||
buttons: {},
|
||||
default: actions[0].name,
|
||||
close: close
|
||||
};
|
||||
for (let action of actions) {
|
||||
conf.buttons[action.name] = {
|
||||
label: action.label, callback: html => {
|
||||
this.rollData.canClose = true;
|
||||
this.onAction(action, html)
|
||||
buttons: {
|
||||
"onAction": {
|
||||
label: action.label, callback: html => {
|
||||
this.rollData.canClose = true;
|
||||
this.onAction(action)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
},
|
||||
default: "onAction",
|
||||
close: options.close
|
||||
};
|
||||
super(conf, options);
|
||||
|
||||
this.actor = actor;
|
||||
this.rollData = rollData;
|
||||
}
|
||||
|
||||
close() {
|
||||
if (this.rollData.canClose) {
|
||||
this.actor.setRollWindowsOpened(false);
|
||||
return super.close();
|
||||
}
|
||||
ui.notifications.info("Vous devez faire ce jet de dés!");
|
||||
}
|
||||
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async onAction(action, html) {
|
||||
this.rollData.forceDiceResult = Number.parseInt($('#force-dice-result').val()) ?? -1;
|
||||
await RdDResolutionTable.rollData(this.rollData);
|
||||
console.log("RdDRoll -=>", this.rollData, this.rollData.rolled);
|
||||
this.actor.setRollWindowsOpened(false);
|
||||
if (action.callbacks)
|
||||
for (let callback of action.callbacks) {
|
||||
if (callback.condition == undefined || callback.condition(this.rollData)) {
|
||||
await callback.action(this.rollData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
activateListeners(html) {
|
||||
super.activateListeners(html);
|
||||
|
||||
this.html = html;
|
||||
this.bringToTop();
|
||||
|
||||
var dialog = this;
|
||||
console.log('RdDRoll.activateListeners', this.rollData);
|
||||
|
||||
function onLoad() {
|
||||
let rollData = dialog.rollData;
|
||||
console.log('Ouverture RdDRoll', rollData);
|
||||
// Update html, according to rollData
|
||||
if (rollData.competence) {
|
||||
const defaut_carac = rollData.competence.system.defaut_carac
|
||||
// Set the default carac from the competence item
|
||||
rollData.selectedCarac = rollData.carac[defaut_carac];
|
||||
$("#carac").val(defaut_carac);
|
||||
}
|
||||
if (rollData.selectedSort) {
|
||||
dialog.setSelectedSort(rollData.selectedSort);
|
||||
$(".draconic").val(rollData.selectedSort.system.listIndex); // Uniquement a la selection du sort, pour permettre de changer
|
||||
}
|
||||
RdDItemSort.setCoutReveReel(rollData.selectedSort);
|
||||
$("#diffLibre").val(Misc.toInt(rollData.diffLibre));
|
||||
$("#diffConditions").val(Misc.toInt(rollData.diffConditions));
|
||||
dialog.updateRollResult();
|
||||
// Update html, according to rollData
|
||||
if (this.rollData.competence) {
|
||||
const defaut_carac = this.rollData.competence.system.defaut_carac
|
||||
// Set the default carac from the competence item
|
||||
this.rollData.selectedCarac = this.rollData.carac[defaut_carac];
|
||||
this.html.find("[name='carac']").val(defaut_carac);
|
||||
}
|
||||
if (this.rollData.selectedSort) {
|
||||
this.setSelectedSort(this.rollData.selectedSort);
|
||||
this.html.find(".draconic").val(this.rollData.selectedSort.system.listIndex); // Uniquement a la selection du sort, pour permettre de changer
|
||||
}
|
||||
RdDItemSort.setCoutReveReel(this.rollData.selectedSort);
|
||||
this.html.find("[name='diffLibre']").val(Misc.toInt(this.rollData.diffLibre));
|
||||
this.html.find("[name='diffConditions']").val(Misc.toInt(this.rollData.diffConditions));
|
||||
this.updateRollResult(html);
|
||||
|
||||
// Setup everything onload
|
||||
$(function () { onLoad(); });
|
||||
|
||||
// Update !
|
||||
html.find('#diffLibre').change((event) => {
|
||||
this.html.find("[name='diffLibre']").change((event) => {
|
||||
this.rollData.diffLibre = Misc.toInt(event.currentTarget.value); // Update the selected bonus/malus
|
||||
this.updateRollResult();
|
||||
this.updateRollResult(html);
|
||||
});
|
||||
html.find('#diffConditions').change((event) => {
|
||||
this.html.find("[name='diffConditions']").change((event) => {
|
||||
this.rollData.diffConditions = Misc.toInt(event.currentTarget.value); // Update the selected bonus/malus
|
||||
this.updateRollResult();
|
||||
this.updateRollResult(html);
|
||||
});
|
||||
html.find('#force-dice-result').change((event) => {
|
||||
this.html.find("[name='force-dice-result']").change((event) => {
|
||||
this.rollData.forceDiceResult = Misc.toInt(event.currentTarget.value);
|
||||
});
|
||||
html.find('#carac').change((event) => {
|
||||
this.html.find("[name='carac']").change((event) => {
|
||||
let caracKey = event.currentTarget.value;
|
||||
this.rollData.selectedCarac = this.rollData.carac[caracKey]; // Update the selectedCarac
|
||||
this.updateRollResult();
|
||||
this.updateRollResult(html);
|
||||
});
|
||||
html.find('.roll-draconic').change((event) => {
|
||||
this.html.find('.roll-draconic').change((event) => {
|
||||
let draconicKey = Misc.toInt(event.currentTarget.value);
|
||||
this.rollData.competence = this.rollData.draconicList[draconicKey]; // Update the selectedCarac
|
||||
this.updateRollResult();
|
||||
this.updateRollResult(html);
|
||||
});
|
||||
html.find('.roll-sort').change((event) => {
|
||||
this.html.find('.roll-sort').change((event) => {
|
||||
let sortKey = Misc.toInt(event.currentTarget.value);
|
||||
this.setSelectedSort(this.rollData.sortList[sortKey]);
|
||||
this.updateRollResult();
|
||||
$("#diffLibre").val(this.rollData.diffLibre);
|
||||
this.updateRollResult(html);
|
||||
this.html.find("[name='diffLibre']").val(this.rollData.diffLibre);
|
||||
});
|
||||
html.find('.roll-carac-competence').change((event) => {
|
||||
this.html.find('.roll-carac-competence').change((event) => {
|
||||
const competence = event.currentTarget.value;
|
||||
this.rollData.competence = this.rollData.competences.find(it => it.name == competence);
|
||||
this.updateRollResult();
|
||||
this.updateRollResult(html);
|
||||
});
|
||||
html.find('.roll-signedraconique').change((event) => {
|
||||
this.html.find('.roll-signedraconique').change((event) => {
|
||||
let sortKey = Misc.toInt(event.currentTarget.value);
|
||||
this.setSelectedSigneDraconique(this.rollData.signes[sortKey]);
|
||||
this.updateRollResult();
|
||||
this.updateRollResult(html);
|
||||
});
|
||||
html.find('#ptreve-variable').change((event) => {
|
||||
this.html.find("[name='ptreve-variable']").change((event) => {
|
||||
let ptreve = Misc.toInt(event.currentTarget.value);
|
||||
this.rollData.selectedSort.system.ptreve_reel = ptreve;
|
||||
console.log("RdDRollSelectDialog - Cout reve", ptreve);
|
||||
this.updateRollResult();
|
||||
this.updateRollResult(html);
|
||||
});
|
||||
html.find("[name='coupsNonMortels']").change((event) => {
|
||||
this.html.find("[name='coupsNonMortels']").change((event) => {
|
||||
this.rollData.dmg.mortalite = event.currentTarget.checked ? "non-mortel" : "mortel";
|
||||
this.updateRollResult();
|
||||
this.updateRollResult(html);
|
||||
});
|
||||
html.find('.cuisine-proportions').change((event) => {
|
||||
this.html.find('.cuisine-proportions').change((event) => {
|
||||
this.rollData.proportions = Number(event.currentTarget.value);
|
||||
this.updateRollResult();
|
||||
this.updateRollResult(html);
|
||||
});
|
||||
html.find('.select-by-name').change((event) => {
|
||||
this.html.find('.select-by-name').change((event) => {
|
||||
const attribute = event.currentTarget.attributes['name'].value;
|
||||
this.rollData[attribute] = event.currentTarget.value;
|
||||
this.updateRollResult();
|
||||
this.updateRollResult(html);
|
||||
});
|
||||
html.find('.checkbox-by-name').change((event) => {
|
||||
this.html.find('.checkbox-by-name').change((event) => {
|
||||
const attribute = event.currentTarget.attributes['name'].value;
|
||||
this.rollData[attribute] = event.currentTarget.checked;
|
||||
this.updateRollResult();
|
||||
this.updateRollResult(html);
|
||||
});
|
||||
html.find('input.use-encTotal').change((event) => {
|
||||
this.html.find('input.use-encTotal').change((event) => {
|
||||
this.rollData.use.encTotal = event.currentTarget.checked;
|
||||
this.updateRollResult();
|
||||
this.updateRollResult(html);
|
||||
});
|
||||
html.find('input.use-surenc').change((event) => {
|
||||
this.html.find('input.use-surenc').change((event) => {
|
||||
this.rollData.use.surenc = event.currentTarget.checked;
|
||||
this.updateRollResult();
|
||||
this.updateRollResult(html);
|
||||
});
|
||||
html.find('.appel-moral').click((event) => { /* l'appel au moral, qui donne un bonus de +1 */
|
||||
this.html.find('.appel-moral').click((event) => { /* l'appel au moral, qui donne un bonus de +1 */
|
||||
this.rollData.use.moral = !this.rollData.use.moral;
|
||||
const appelMoral = html.find('.icon-appel-moral')[0];
|
||||
const tooltip = html.find('.tooltipAppelAuMoralText')[0];
|
||||
const appelMoral = this.html.find('.icon-appel-moral')[0];
|
||||
const tooltip = this.html.find('.tooltipAppelAuMoralText')[0];
|
||||
if (this.rollData.use.moral) {
|
||||
if (this.rollData.moral > 0) {
|
||||
tooltip.innerHTML = "Appel au moral";
|
||||
@ -274,16 +229,36 @@ export class RdDRoll extends Dialog {
|
||||
tooltip.innerHTML = "Sans appel au moral";
|
||||
appelMoral.src = "/systems/foundryvtt-reve-de-dragon/icons/moral-neutre.svg";
|
||||
}
|
||||
this.updateRollResult();
|
||||
this.updateRollResult(html);
|
||||
});
|
||||
// Section Méditation
|
||||
html.find('.conditionMeditation').change((event) => {
|
||||
let condition = event.currentTarget.attributes['id'].value;
|
||||
this.html.find('.conditionMeditation').change((event) => {
|
||||
let condition = event.currentTarget.attributes['name'].value;
|
||||
this.rollData.conditionMeditation[condition] = event.currentTarget.checked;
|
||||
this.updateRollResult();
|
||||
this.updateRollResult(html);
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
close() {
|
||||
if (this.rollData.canClose) {
|
||||
return super.close();
|
||||
}
|
||||
ui.notifications.info("Vous devez faire ce jet de dés!");
|
||||
}
|
||||
|
||||
async onAction(action) {
|
||||
this.rollData.forceDiceResult = Number.parseInt(this.html.find("[name='force-dice-result']").val()) ?? -1;
|
||||
await RdDResolutionTable.rollData(this.rollData);
|
||||
console.log("RdDRoll -=>", this.rollData, this.rollData.rolled);
|
||||
if (action.callbacks)
|
||||
for (let callback of action.callbacks) {
|
||||
if (callback.condition == undefined || callback.condition(this.rollData)) {
|
||||
await callback.action(this.rollData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async setSelectedSort(sort) {
|
||||
this.rollData.selectedSort = sort; // Update the selectedCarac
|
||||
this.rollData.competence = RdDItemCompetence.getVoieDraconic(this.rollData.draconicList, sort.system.draconic);
|
||||
@ -291,31 +266,31 @@ export class RdDRoll extends Dialog {
|
||||
this.rollData.diffLibre = RdDItemSort.getDifficulte(sort, -7);
|
||||
RdDItemSort.setCoutReveReel(sort);
|
||||
const htmlSortDescription = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/partial-description-sort.html", { sort: sort });
|
||||
$(".sort-ou-rituel").text(sort.system.isrituel ? "rituel" : "sort");
|
||||
$(".bonus-case").text(`${this.rollData.bonus}%`);
|
||||
$(".details-sort").remove();
|
||||
$(".description-sort").append(htmlSortDescription);
|
||||
$(".roll-draconic").val(sort.system.listIndex);
|
||||
$(".div-sort-difficulte-fixe").text(Misc.toSignedString(sort.system.difficulte));
|
||||
$(".div-sort-ptreve-fixe").text(sort.system.ptreve);
|
||||
this.html.find(".sort-ou-rituel").text(sort.system.isrituel ? "rituel" : "sort");
|
||||
this.html.find(".bonus-case").text(`${this.rollData.bonus}%`);
|
||||
this.html.find(".placeholder-description-sort").children().remove();
|
||||
this.html.find(".placeholder-description-sort").append(htmlSortDescription);
|
||||
this.html.find(".roll-draconic").val(sort.system.listIndex);
|
||||
this.html.find(".div-sort-difficulte-fixe").text(Misc.toSignedString(sort.system.difficulte));
|
||||
this.html.find(".div-sort-ptreve-fixe").text(sort.system.ptreve);
|
||||
const diffVariable = RdDItemSort.isDifficulteVariable(sort);
|
||||
const coutVariable = RdDItemSort.isCoutVariable(sort);
|
||||
|
||||
HtmlUtility._showControlWhen($(".div-sort-non-rituel"), !sort.system.isrituel);
|
||||
HtmlUtility._showControlWhen($(".div-sort-difficulte-var"), diffVariable);
|
||||
HtmlUtility._showControlWhen($(".div-sort-difficulte-fixe"), !diffVariable);
|
||||
HtmlUtility._showControlWhen($(".div-sort-ptreve-var"), coutVariable);
|
||||
HtmlUtility._showControlWhen($(".div-sort-ptreve-fixe"), !coutVariable);
|
||||
HtmlUtility._showControlWhen(this.html.find(".div-sort-non-rituel"), !sort.system.isrituel);
|
||||
HtmlUtility._showControlWhen(this.html.find(".div-sort-difficulte-var"), diffVariable);
|
||||
HtmlUtility._showControlWhen(this.html.find(".div-sort-difficulte-fixe"), !diffVariable);
|
||||
HtmlUtility._showControlWhen(this.html.find(".div-sort-ptreve-var"), coutVariable);
|
||||
HtmlUtility._showControlWhen(this.html.find(".div-sort-ptreve-fixe"), !coutVariable);
|
||||
}
|
||||
|
||||
async setSelectedSigneDraconique(signe){
|
||||
async setSelectedSigneDraconique(signe) {
|
||||
this.rollData.signe = signe;
|
||||
this.rollData.diffLibre = signe.system.difficulte,
|
||||
$(".signe-difficulte").text(Misc.toSignedString(this.rollData.diffLibre));
|
||||
$(".signe-difficulte").text(Misc.toSignedString(this.rollData.diffLibre));
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async updateRollResult() {
|
||||
async updateRollResult(html) {
|
||||
let rollData = this.rollData;
|
||||
|
||||
rollData.dmg = rollData.attackerRoll?.dmg ?? RdDBonus.dmg(rollData, this.actor.getBonusDegat())
|
||||
@ -325,39 +300,35 @@ export class RdDRoll extends Dialog {
|
||||
rollData.use.appelAuMoral = this.actor.isPersonnage() && RdDCarac.isActionPhysique(rollData.selectedCarac);
|
||||
let dmgText = Misc.toSignedString(rollData.dmg.total);
|
||||
|
||||
switch (rollData.mortalite){
|
||||
case 'non-mortel': dmgText = `(${dmgText}) non-mortel`; break;
|
||||
case 'empoignade': dmgText = `empoignade`; break;
|
||||
switch (rollData.mortalite) {
|
||||
case 'non-mortel': dmgText = `(${dmgText}) non-mortel`; break;
|
||||
case 'empoignade': dmgText = `empoignade`; break;
|
||||
}
|
||||
|
||||
RollDataAjustements.calcul(rollData, this.actor);
|
||||
rollData.finalLevel = this._computeFinalLevel(rollData);
|
||||
|
||||
HtmlUtility._showControlWhen($(".use-encTotal"), rollData.ajustements.encTotal.visible && RdDCarac.isAgiliteOuDerivee(rollData.selectedCarac));
|
||||
HtmlUtility._showControlWhen($(".use-surenc"), rollData.ajustements.surenc.visible && RdDCarac.isActionPhysique(rollData.selectedCarac));
|
||||
HtmlUtility._showControlWhen($(".utilisation-moral"), rollData.use.appelAuMoral);
|
||||
HtmlUtility._showControlWhen($(".diffMoral"), rollData.ajustements.moralTotal.used);
|
||||
HtmlUtility._showControlWhen($(".divAppelAuMoral"), rollData.use.appelAuMoral);
|
||||
HtmlUtility._showControlWhen($("#etat-general"), !RdDCarac.isIgnoreEtatGeneral(rollData));
|
||||
HtmlUtility._showControlWhen($("#ajust-astrologique"), RdDResolutionTable.isAjustementAstrologique(rollData));
|
||||
const resolutionTable = await RdDResolutionTable.buildHTMLTable(RdDResolutionTable.subTable(rollData.caracValue, rollData.finalLevel))
|
||||
const adjustements = await this.buildAjustements(rollData);
|
||||
|
||||
HtmlUtility._showControlWhen(this.html.find(".use-encTotal"), rollData.ajustements.encTotal.visible && RdDCarac.isAgiliteOuDerivee(rollData.selectedCarac));
|
||||
HtmlUtility._showControlWhen(this.html.find(".use-surenc"), rollData.ajustements.surenc.visible && RdDCarac.isActionPhysique(rollData.selectedCarac));
|
||||
HtmlUtility._showControlWhen(this.html.find(".utilisation-moral"), rollData.use.appelAuMoral);
|
||||
HtmlUtility._showControlWhen(this.html.find(".diffMoral"), rollData.ajustements.moralTotal.used);
|
||||
HtmlUtility._showControlWhen(this.html.find(".divAppelAuMoral"), rollData.use.appelAuMoral);
|
||||
|
||||
// Mise à jour valeurs
|
||||
$(".dialog-roll-title").text(this._getTitle(rollData));
|
||||
$("[name='coupsNonMortels']").prop('checked', rollData.mortalite == 'non-mortel');
|
||||
$(".dmg-arme-actor").text(dmgText);
|
||||
$('.table-ajustement').remove();
|
||||
$(".table-resolution").remove();
|
||||
$(".table-proba-reussite").remove();
|
||||
$("#tableAjustements").append(await this.buildAjustements(rollData));
|
||||
$("#tableResolution").append(RdDResolutionTable.buildHTMLTableExtract(rollData.caracValue, rollData.finalLevel));
|
||||
$("#tableProbaReussite").append(RdDResolutionTable.buildHTMLResults(rollData.caracValue, rollData.finalLevel));
|
||||
this.html.find(".dialog-roll-title").text(this._getTitle(rollData));
|
||||
this.html.find("[name='coupsNonMortels']").prop('checked', rollData.mortalite == 'non-mortel');
|
||||
this.html.find(".dmg-arme-actor").text(dmgText);
|
||||
this.html.find("div.placeholder-ajustements").empty().append(adjustements);
|
||||
this.html.find("div.placeholder-resolution").empty().append(resolutionTable)
|
||||
}
|
||||
|
||||
|
||||
/* -------------------------------------------- */
|
||||
async buildAjustements(rollData) {
|
||||
const html = await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/partial-roll-ajustements.html`, rollData);
|
||||
return html;
|
||||
return await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/partial-roll-ajustements.html`, rollData);
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
@ -375,23 +346,11 @@ export class RdDRoll extends Dialog {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
_computeDiffLibre(rollData) {
|
||||
let diffLibre = Misc.toInt(rollData.diffLibre);
|
||||
if (rollData.draconicList && rollData.selectedSort) {
|
||||
return RdDItemSort.getDifficulte(rollData.selectedSort, diffLibre);
|
||||
}
|
||||
return diffLibre;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
_computeMalusArmure(rollData) {
|
||||
let malusArmureValue = 0;
|
||||
if (rollData.malusArmureValue && (rollData.selectedCarac.label == "Agilité" || rollData.selectedCarac.label == "Dérobée")) {
|
||||
$("#addon-message").text("Malus armure appliqué : " + rollData.malusArmureValue);
|
||||
malusArmureValue = rollData.malusArmureValue;
|
||||
} else {
|
||||
$("#addon-message").text("");
|
||||
}
|
||||
return malusArmureValue;
|
||||
}
|
||||
|
@ -95,8 +95,9 @@ export class RdDRollTables {
|
||||
const row = await table.getRandom(itemFrequence, filter);
|
||||
if (row) {
|
||||
await CompendiumTableHelpers.tableRowToChatMessage(row, type);
|
||||
return row.document;
|
||||
}
|
||||
return row;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- */
|
||||
|