c8a5526a5f
Les tokens non liés à l'acteur peuvent maintenant vendre de l'équipement L'équipement n'est pas enlevé de la fiche synthétique du token, l'argent n'est pas ajouté non plus.
4104 lines
152 KiB
JavaScript
4104 lines
152 KiB
JavaScript
import { RdDUtility } from "./rdd-utility.js";
|
|
import { TMRUtility } from "./tmr-utility.js";
|
|
import { RdDRollDialogEthylisme } from "./rdd-roll-ethylisme.js";
|
|
import { RdDRoll } from "./rdd-roll.js";
|
|
import { RdDTMRDialog } from "./rdd-tmr-dialog.js";
|
|
import { Misc } from "./misc.js";
|
|
import { RdDAstrologieJoueur } from "./rdd-astrologie-joueur.js";
|
|
import { RdDResolutionTable } from "./rdd-resolution-table.js";
|
|
import { RdDDice } from "./rdd-dice.js";
|
|
import { RdDRollTables } from "./rdd-rolltables.js";
|
|
import { ChatUtility } from "./chat-utility.js";
|
|
import { RdDItemSort } from "./item-sort.js";
|
|
import { Grammar } from "./grammar.js";
|
|
import { RdDEncaisser } from "./rdd-roll-encaisser.js";
|
|
import { RdDCombat } from "./rdd-combat.js";
|
|
import { RdDAudio } from "./rdd-audio.js";
|
|
import { RdDItemCompetence } from "./item-competence.js";
|
|
import { RdDItemArme } from "./item-arme.js";
|
|
import { RdDAlchimie } from "./rdd-alchimie.js";
|
|
import { StatusEffects } from "./status-effects.js";
|
|
import { RdDItemCompetenceCreature } from "./item-competencecreature.js";
|
|
import { RdDItemSigneDraconique } from "./item-signedraconique.js";
|
|
import { ReglesOptionelles } from "./regles-optionelles.js";
|
|
import { TMRRencontres } from "./tmr-rencontres.js";
|
|
import { Poetique } from "./poetique.js";
|
|
import { EffetsDraconiques } from "./tmr/effets-draconiques.js";
|
|
import { Draconique } from "./tmr/draconique.js";
|
|
import { RdDCarac } from "./rdd-carac.js";
|
|
import { Monnaie } from "./item-monnaie.js";
|
|
import { DialogConsommer } from "./dialog-item-consommer.js";
|
|
import { DialogFabriquerPotion } from "./dialog-fabriquer-potion.js";
|
|
import { RollDataAjustements } from "./rolldata-ajustements.js";
|
|
import { DialogItemAchat } from "./dialog-item-achat.js";
|
|
import { RdDItem } from "./item.js";
|
|
|
|
|
|
/* -------------------------------------------- */
|
|
/**
|
|
* Extend the base Actor entity by defining a custom roll data structure which is ideal for the Simple system.
|
|
* @extends {Actor}
|
|
*/
|
|
export class RdDActor extends Actor {
|
|
/* -------------------------------------------- */
|
|
static init() {
|
|
Hooks.on("deleteActiveEffect", (effect, options, userId) => RdDActor.getParentActor(effect)?.onDeleteActiveEffect(effect, options));
|
|
Hooks.on("createActiveEffect", (effect, options, userId) => RdDActor.getParentActor(effect)?.onCreateActiveEffect(effect, options));
|
|
|
|
Hooks.on("preUpdateItem", (item, change, options, id) => RdDActor.getParentActor(item)?.onPreUpdateItem(item, change, options, id));
|
|
Hooks.on("createItem", (item, options, id) => RdDActor.getParentActor(item)?.onCreateItem(item, options, id));
|
|
Hooks.on("deleteItem", (item, options, id) => RdDActor.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 RdDActor.onRemoteActorCall(sockmsg.data);
|
|
case "msg_reset_nombre_astral":
|
|
console.log("RESET ASTRAL", game.user.character);
|
|
game.user.character.resetNombreAstral();
|
|
return;
|
|
}
|
|
}
|
|
|
|
static remoteActorCall(data) {
|
|
if (Misc.isElectedUser()) {
|
|
RdDActor.onRemoteActorCall(data);
|
|
}
|
|
else {
|
|
game.socket.emit("system.foundryvtt-reve-de-dragon", { msg: "msg_remote_actor_call", data: data });
|
|
}
|
|
}
|
|
|
|
static onRemoteActorCall(data) {
|
|
if (Misc.isElectedUser()) { // Seul le joueur choisi effectue l'appel
|
|
const actor = game.actors.get(data?.actorId);
|
|
if (!actor) {
|
|
console.info("RdDActor.onRemoteActorCall: Pas d'Actor disponible ", data);
|
|
}
|
|
else {
|
|
const args = data.args;
|
|
console.info(`RdDActor.onRemoteActorCall: pour l'Actor ${data.actorId}, appel de RdDActor.${data.method}(`, ...args, ')');
|
|
actor[data.method](...args);
|
|
}
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
static getParentActor(document) {
|
|
return document?.parent instanceof Actor ? document.parent : undefined
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
/**
|
|
* Override the create() function to provide additional RdD functionality.
|
|
*
|
|
* This overrided create() function adds initial items
|
|
* Namely: Basic skills, money,
|
|
*
|
|
* @param {Object} actorData Barebones actor data which this function adds onto.
|
|
* @param {Object} options (Unused) Additional options which customize the creation workflow.
|
|
*
|
|
*/
|
|
|
|
static async create(actorData, options) {
|
|
// Case of compendium global import
|
|
if (actorData instanceof Array) {
|
|
return super.create(actorData, options);
|
|
}
|
|
|
|
const isPersonnage = actorData.type == "personnage";
|
|
// If the created actor has items (only applicable to duplicated actors) bypass the new actor creation logic
|
|
if (actorData.items) {
|
|
let actor = await super.create(actorData, options);
|
|
if (isPersonnage) {
|
|
await actor.checkMonnaiePresence(actorData.items);
|
|
}
|
|
return actor;
|
|
}
|
|
|
|
const competences = await RdDUtility.loadCompendium(RdDItemCompetence.actorCompendium(actorData.type));
|
|
actorData.items = competences.map(i => i.toObject());
|
|
if (isPersonnage) {
|
|
actorData.items = actorData.items.concat(Monnaie.monnaiesData());
|
|
}
|
|
return super.create(actorData, options);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
prepareData() {
|
|
super.prepareData();
|
|
const actorData = this.data;
|
|
|
|
// Dynamic computing fields
|
|
this.encTotal = 0;
|
|
this.prixTotalEquipement = 0;
|
|
|
|
/*
|
|
// Auto-resize token
|
|
if (this.isToken) {
|
|
let tokenSize = actorData.data.carac.taille.value/10;
|
|
this.token.update({height: tokenSize, width: tokenSize } );
|
|
}*/
|
|
|
|
// Make separate methods for each Actor type (character, npc, etc.) to keep
|
|
// things organized.
|
|
if (actorData.type === 'personnage') this._prepareCharacterData(actorData);
|
|
if (actorData.type === 'creature') this._prepareCreatureData(actorData);
|
|
if (actorData.type === 'vehicule') this._prepareVehiculeData(actorData);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
setRollWindowsOpened(flag) {
|
|
this.rollWindowsOpened = flag;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
isRollWindowsOpened() {
|
|
return this.rollWindowsOpened;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
_prepareCreatureData(actorData) {
|
|
this.computeEncombrementTotalEtMalusArmure();
|
|
this.computeEtatGeneral();
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
_prepareVehiculeData(actorData) {
|
|
this.computeEncombrementTotalEtMalusArmure();
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
/**
|
|
* Prepare Character type specific data
|
|
*/
|
|
async _prepareCharacterData(actorData) {
|
|
// Initialize empty items
|
|
RdDCarac.computeCarac(actorData.data);
|
|
this.computeIsHautRevant();
|
|
await this.cleanupConteneurs();
|
|
await this.computeEncombrementTotalEtMalusArmure();
|
|
this.computePrixTotalEquipement();
|
|
this.computeEtatGeneral();
|
|
// Sanity check
|
|
await this.checkMonnaiePresence(actorData.items);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async cleanupConteneurs() {
|
|
let updates = this.listItemsData('conteneur')
|
|
.filter(c => c.data.contenu.filter(id => this.getObjet(id) == undefined).length > 0)
|
|
.map(c => { return { _id: c._id, 'data.contenu': c.data.contenu.filter(id => this.getObjet(id) != undefined) } });
|
|
if (updates.length > 0) {
|
|
await this.updateEmbeddedDocuments("Item", updates)
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async checkMonnaiePresence(items) { // Ajout opportuniste si les pièces n'existent pas.
|
|
if (!items) return; // Sanity check during import
|
|
let manquantes = Monnaie.monnaiesManquantes(items);
|
|
//console.log("Manque : ", manquantes);
|
|
if (manquantes.length > 0) {
|
|
await this.createEmbeddedDocuments('Item', manquantes, { renderSheet: false });
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
isCreature() {
|
|
return this.data.type == 'creature' || this.data.type == 'entite';
|
|
}
|
|
/* -------------------------------------------- */
|
|
isPersonnage() {
|
|
return this.data.type == 'personnage';
|
|
}
|
|
/* -------------------------------------------- */
|
|
isHautRevant() {
|
|
return this.isPersonnage() && Misc.templateData(this).attributs.hautrevant.value != ""
|
|
}
|
|
/* -------------------------------------------- */
|
|
getFatigueActuelle() {
|
|
if (ReglesOptionelles.isUsing("appliquer-fatigue") && this.isPersonnage()) {
|
|
return Misc.toInt(Misc.templateData(this).sante.fatigue?.value);
|
|
}
|
|
return 0;
|
|
}
|
|
/* -------------------------------------------- */
|
|
getFatigueMax() {
|
|
if (!this.isPersonnage()) {
|
|
return 1;
|
|
}
|
|
return Misc.toInt(Misc.templateData(this).sante.fatigue?.max);
|
|
}
|
|
/* -------------------------------------------- */
|
|
getReveActuel() {
|
|
const templateData = Misc.templateData(this);
|
|
return Misc.toInt(templateData.reve?.reve?.value ?? templateData.carac.reve.value);
|
|
}
|
|
/* -------------------------------------------- */
|
|
getChanceActuel() {
|
|
return Misc.toInt(Misc.templateData(this).compteurs.chance?.value ?? 10);
|
|
}
|
|
/* -------------------------------------------- */
|
|
getTaille() {
|
|
return Misc.toInt(Misc.templateData(this).carac.taille?.value);
|
|
}
|
|
/* -------------------------------------------- */
|
|
getForce() {
|
|
if (this.isEntiteCauchemar()) {
|
|
return Misc.toInt(Misc.templateData(this).carac.reve?.value);
|
|
}
|
|
return Misc.toInt(Misc.templateData(this).carac.force?.value);
|
|
}
|
|
/* -------------------------------------------- */
|
|
getAgilite() {
|
|
switch (this.data.type) {
|
|
case 'personnage': return Misc.toInt(Misc.templateData(this).carac.agilite?.value);
|
|
case 'creature': return Misc.toInt(Misc.templateData(this).carac.force?.value);
|
|
case 'entite': return Misc.toInt(Misc.templateData(this).carac.reve?.value);
|
|
}
|
|
return 10;
|
|
}
|
|
/* -------------------------------------------- */
|
|
getChance() {
|
|
return Misc.toInt(Misc.templateData(this).carac.chance?.value ?? 10);
|
|
}
|
|
getMoralTotal() {
|
|
return Misc.toInt(Misc.templateData(this).compteurs.moral?.value);
|
|
}
|
|
/* -------------------------------------------- */
|
|
getBonusDegat() {
|
|
// TODO: gérer séparation et +dom créature/entité indépendament de la compétence
|
|
return Misc.toInt(Misc.templateData(this).attributs.plusdom.value);
|
|
}
|
|
/* -------------------------------------------- */
|
|
getProtectionNaturelle() {
|
|
return Misc.toInt(Misc.templateData(this).attributs.protection.value);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
getEtatGeneral(options = { ethylisme: false }) {
|
|
const tplData = Misc.templateData(this);
|
|
let etatGeneral = Misc.toInt(tplData.compteurs.etat?.value);
|
|
if (options.ethylisme) {
|
|
// Pour les jets d'Ethylisme, on ignore le degré d'éthylisme (p.162)
|
|
etatGeneral -= Math.min(0, tplData.compteurs.ethylisme.value);
|
|
}
|
|
return etatGeneral;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
getMalusArmure() {
|
|
return Misc.toInt(Misc.templateData(this).attributs?.malusarmure?.value);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
getEncTotal() {
|
|
return Math.floor(this.encTotal ?? 0);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
getPrixTotalEquipement() {
|
|
return Math.floor(Misc.templateData(this).prixTotalEquipement ?? 0);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
getSurenc() {
|
|
return Misc.templateData(this).compteurs.surenc?.value ?? 0;
|
|
}
|
|
/* -------------------------------------------- */
|
|
getCompetence(name) {
|
|
return RdDItemCompetence.findCompetence(this.data.items, name);
|
|
}
|
|
/* -------------------------------------------- */
|
|
getObjet(id) {
|
|
return id ? this.data.items.find(it => it.id == id) : undefined;
|
|
}
|
|
listItemsData(type) {
|
|
return this.filterItemsData(it => it.type == type);
|
|
}
|
|
filterItemsData(filter) {
|
|
return this.data.items.map(it => Misc.data(it)).filter(filter);
|
|
}
|
|
filterItems(filter) {
|
|
return this.data.items.filter(it => filter(Misc.data(it)));
|
|
}
|
|
getItemOfType(id, type) {
|
|
if (id && type) {
|
|
let itemById = this.data.items.find(it => it.id == id);
|
|
const itemData = Misc.data(itemById);
|
|
if (itemData.type == type) {
|
|
return itemById;
|
|
}
|
|
}
|
|
return undefined;
|
|
}
|
|
getMonnaie(id) {
|
|
return this.getItemOfType(id, 'monnaie');
|
|
}
|
|
|
|
getTache(id) {
|
|
return this.getItemOfType(id, 'tache');
|
|
}
|
|
getMeditation(id) {
|
|
return this.getItemOfType(id, 'meditation');
|
|
}
|
|
getChant(id) {
|
|
return this.getItemOfType(id, 'chant');
|
|
}
|
|
getDanse(id) {
|
|
return this.getItemOfType(id, 'danse');
|
|
}
|
|
getMusique(id) {
|
|
return this.getItemOfType(id, 'musique');
|
|
}
|
|
getOeuvre(id, type = 'oeuvre') {
|
|
return this.getItemOfType(id, type);
|
|
}
|
|
getJeu(id) {
|
|
return this.getItemOfType(id, 'jeu');
|
|
}
|
|
getRecetteCuisine(id) {
|
|
return this.getItemOfType(id, 'recettecuisine');
|
|
}
|
|
/* -------------------------------------------- */
|
|
getDraconicList() {
|
|
return this.items.filter(it => Misc.data(it).type == 'competence' && Misc.templateData(it).categorie == 'draconic')
|
|
.sort(Misc.descending(it => Misc.templateData(it).niveau));
|
|
}
|
|
/* -------------------------------------------- */
|
|
getBestDraconic() {
|
|
const list = this.getDraconicList();
|
|
if (list.length == 0) {
|
|
return { name: "Aucun", data: { name: "Aucun", data: { niveau: 0 } } };
|
|
}
|
|
return duplicate(list[0]);
|
|
}
|
|
getDemiReve() {
|
|
return Misc.templateData(this).reve.tmrpos.coord;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async verifierPotionsEnchantees() {
|
|
let potionsEnchantees = this.filterItemsData(it => it.type == 'potion' && it.data.magique);
|
|
for (let potion of potionsEnchantees) {
|
|
if (!potion.prpermanent) {
|
|
console.log(potion);
|
|
let newPr = (potion.data.pr > 0) ? potion.data.pr - 1 : 0;
|
|
let update = { _id: potion._id, 'data.pr': newPr };
|
|
const updated = await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
|
|
|
|
let messageData = {
|
|
pr: newPr,
|
|
alias: this.name,
|
|
potionName: potion.name,
|
|
potionImg: potion.img
|
|
}
|
|
ChatMessage.create({
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
|
|
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-potionenchantee-chateaudormant.html`, messageData)
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async deleteSortReserve(sortReserve) {
|
|
let reserve = duplicate(Misc.templateData(this).reve.reserve);
|
|
let tmr = TMRUtility.getTMR(sortReserve.coord);
|
|
let index = reserve.list.findIndex(tmr.type == 'fleuve'
|
|
? sort => (TMRUtility.getTMR(sort.coord).type == 'fleuve' && sort.sort.name == sortReserve.sort.name)
|
|
: sort => (sort.coord == sortReserve.coord && sort.sort.name == sortReserve.sort.name)
|
|
);
|
|
if (index >= 0) {
|
|
reserve.list.splice(index, 1);
|
|
await this.update({ "data.reve.reserve": reserve });
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
getSurprise(isCombat = undefined) {
|
|
let niveauSurprise = Array.from(this.effects?.values() ?? [])
|
|
.map(effect => StatusEffects.valeurSurprise(effect.data, isCombat))
|
|
.reduce(Misc.sum(), 0);
|
|
if (niveauSurprise > 1) {
|
|
return 'totale';
|
|
}
|
|
if (niveauSurprise == 1 || this.getSonne()) {
|
|
return 'demi';
|
|
}
|
|
return '';
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async dormirChateauDormant() {
|
|
let message = {
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(this.name),
|
|
content: ""
|
|
};
|
|
|
|
const blessures = duplicate(Misc.templateData(this).blessures);
|
|
await this._recupererBlessures(message, "legere", blessures.legeres.liste.filter(b => b.active), []);
|
|
await this._recupererBlessures(message, "grave", blessures.graves.liste.filter(b => b.active), blessures.legeres.liste);
|
|
await this._recupererBlessures(message, "critique", blessures.critiques.liste.filter(b => b.active), blessures.graves.liste);
|
|
await this.update({ "data.blessures": blessures });
|
|
await this._recupererVie(message);
|
|
await this.jetDeMoral('neutre');
|
|
await this._recupereChance();
|
|
await this.transformerStress();
|
|
await this.retourSeuilDeReve(message);
|
|
this.bonusRecuperationPotion = 0; // Reset potion
|
|
await this.retourSust(message);
|
|
await this.verifierPotionsEnchantees();
|
|
message.content = `A la fin Chateau Dormant, ${message.content}<br>Un nouveau jour se lève`;
|
|
ChatMessage.create(message);
|
|
this.sheet.render(true);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _recupereChance() {
|
|
// On ne récupère un point de chance que si aucun appel à la chance dans la journée
|
|
if (this.getChanceActuel() < this.getChance() && !this.getFlag('foundryvtt-reve-de-dragon', 'utilisationChance')) {
|
|
await this.chanceActuelleIncDec(1);
|
|
}
|
|
// Nouveau jour, suppression du flag
|
|
await this.unsetFlag('foundryvtt-reve-de-dragon', 'utilisationChance');
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _recupererBlessures(message, type, liste, moindres) {
|
|
if (!this.bonusRecuperationPotion) this.bonusRecuperationPotion = 0;
|
|
let count = 0;
|
|
const definitions = RdDUtility.getDefinitionsBlessures();
|
|
let definition = definitions.find(d => d.type == type);
|
|
for (let blessure of liste) {
|
|
if (blessure.jours >= definition.facteur) {
|
|
let rolled = await this._jetRecuperationConstitution(Misc.toInt(blessure.soins_complets) + this.bonusRecuperationPotion, message);
|
|
blessure.soins_complets = 0;
|
|
if (rolled.isSuccess && this._retrograderBlessure(type, blessure, moindres)) {
|
|
message.content += ` -- une blessure ${type} cicatrise`;
|
|
count++;
|
|
}
|
|
else if (rolled.isETotal) {
|
|
message.content += ` -- une blessure ${type} s'infecte (temps de guérison augmenté de ${definition.facteur} jours, perte de vie)`;
|
|
blessure.jours = 0;
|
|
await this.santeIncDec("vie", -1);
|
|
}
|
|
else {
|
|
message.content += ` -- une blessure ${type} reste stable`;
|
|
}
|
|
}
|
|
else {
|
|
blessure.jours++;
|
|
}
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
_retrograderBlessure(type, blessure, blessuresMoindres) {
|
|
if (type != "legere") {
|
|
let retrograde = blessuresMoindres.find(b => !b.active);
|
|
if (!retrograde) {
|
|
return false;
|
|
}
|
|
mergeObject(retrograde, { "active": true, "premiers_soins": 0, "soins_complets": 0, "jours": 0, "loc": blessure.loc });
|
|
}
|
|
this._supprimerBlessure(blessure);
|
|
return true;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
_supprimerBlessure(blessure) {
|
|
mergeObject(blessure, { "active": false, "premiers_soins": 0, "soins_complets": 0, "jours": 0, "loc": "" });
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _recupererVie(message) {
|
|
const tData = Misc.templateData(this);
|
|
let blessures = [].concat(tData.blessures.legeres.liste).concat(tData.blessures.graves.liste).concat(tData.blessures.critiques.liste);
|
|
let nbBlessures = blessures.filter(b => b.active);
|
|
let vieManquante = tData.sante.vie.max - tData.sante.vie.value;
|
|
if (nbBlessures == 0 && vieManquante > 0) {
|
|
let bonusSoins = 0;
|
|
for (let b of blessures) {
|
|
bonusSoins = Math.max(bonusSoins, Misc.toInt(b.soins_complets));
|
|
}
|
|
let rolled = await this._jetRecuperationConstitution(bonusSoins, message)
|
|
if (rolled.isSuccess) {
|
|
const gain = Math.min(rolled.isPart ? 2 : 1, vieManquante);
|
|
message.content += " -- récupération de vie: " + gain;
|
|
await this.santeIncDec("vie", gain);
|
|
}
|
|
else if (rolled.isETotal) {
|
|
message.content += " -- perte de vie: 1";
|
|
await this.santeIncDec("vie", -1);
|
|
}
|
|
else {
|
|
message.content += " -- vie stationnaire ";
|
|
}
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _jetRecuperationConstitution(bonusSoins, message = undefined) {
|
|
const tData = Misc.templateData(this);
|
|
let difficulte = Misc.toInt(bonusSoins) + Math.min(0, tData.sante.vie.value - tData.sante.vie.max);
|
|
let rolled = await RdDResolutionTable.roll(tData.carac.constitution.value, difficulte);
|
|
if (message) {
|
|
message.content += RdDResolutionTable.explain(rolled).replace(/Jet :/, "Constitution :");
|
|
}
|
|
return rolled;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async remiseANeuf() {
|
|
let message = {
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(this.name),
|
|
content: "Remise à neuf de " + this.name
|
|
};
|
|
const actorData = Misc.data(this);
|
|
if (this.isEntiteCauchemar()) {
|
|
await this.santeIncDec("endurance", actorData.data.sante.endurance.max - actorData.data.sante.endurance.value);
|
|
}
|
|
else {
|
|
|
|
if (actorData.data.blessures) {
|
|
const blessures = duplicate(actorData.data.blessures);
|
|
for (let listeBlessures of [blessures.legeres.liste, blessures.graves.liste, blessures.critiques.liste]) {
|
|
for (let blessure of listeBlessures) {
|
|
this._supprimerBlessure(blessure);
|
|
}
|
|
}
|
|
await this.update({ "data.blessures": blessures });
|
|
}
|
|
if (this.isPersonnage()) {
|
|
await this.setEthylisme(1);
|
|
}
|
|
|
|
await this.santeIncDec("vie", actorData.data.sante.vie.max - actorData.data.sante.vie.value);
|
|
await this.santeIncDec("endurance", actorData.data.sante.endurance.max - actorData.data.sante.endurance.value);
|
|
if (ReglesOptionelles.isUsing("appliquer-fatigue") && actorData.data.sante.fatigue) {
|
|
await this.update({ "data.sante.fatigue.value": 0 });
|
|
}
|
|
}
|
|
ChatMessage.create(message);
|
|
this.sheet.render(true);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async dormir(heures) {
|
|
let message = {
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(this.name),
|
|
content: `${this.name}: Vous dormez ${heures == 1 ? 'une' : heures} heure${heures == 1 ? '' : 's'}.`
|
|
};
|
|
await this.recupereEndurance(message);
|
|
for (let i = 0; i < heures; i++) {
|
|
await this._recupererEthylisme(message);
|
|
await this.recupererFatigue(message);
|
|
await this.recuperationReve(message, 1);
|
|
if (EffetsDraconiques.isDonDoubleReve(this)) {
|
|
await this.recuperationReve(message, 2);
|
|
}
|
|
}
|
|
ChatMessage.create(message);
|
|
this.sheet.render(true);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _recupererEthylisme(message) {
|
|
let ethylisme = duplicate(Misc.templateData(this).compteurs.ethylisme);
|
|
ethylisme.nb_doses = 0;
|
|
ethylisme.jet_moral = false;
|
|
if (ethylisme.value < 1) {
|
|
ethylisme.value = Math.min(ethylisme.value + 1, 1);
|
|
if (ethylisme.value <= 0) {
|
|
message.content += `Vous dégrisez un peu (${RdDUtility.getNomEthylisme(ethylisme.value)}). `;
|
|
}
|
|
}
|
|
await this.update({ "data.compteurs.ethylisme": ethylisme });
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async recupereEndurance(message) {
|
|
const manquant = this._computeEnduranceMax() - Misc.templateData(this).sante.endurance.value;
|
|
if (manquant > 0) {
|
|
await this.santeIncDec("endurance", manquant);
|
|
message.content += "Vous récuperez " + manquant + " points d'endurance. ";
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async recupererFatigue(message) {
|
|
if (ReglesOptionelles.isUsing("appliquer-fatigue")) {
|
|
let fatigue = Misc.templateData(this).sante.fatigue.value;
|
|
const fatigueMin = this._computeFatigueMin();
|
|
if (fatigue <= fatigueMin) {
|
|
message.content += "Vous êtes déjà reposé. ";
|
|
return;
|
|
}
|
|
fatigue = Math.max(fatigueMin, this._calculRecuperationSegment(fatigue));
|
|
await this.update({ "data.sante.fatigue.value": fatigue });
|
|
if (fatigue == 0) {
|
|
message.content += "Vous êtes complêtement reposé. ";
|
|
}
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
_calculRecuperationSegment(actuel) {
|
|
const segments = RdDUtility.getSegmentsFatigue(Misc.templateData(this).sante.endurance.max);
|
|
let cumul = 0;
|
|
let i;
|
|
for (i = 0; i < 11; i++) {
|
|
cumul += segments[i];
|
|
let diff = cumul - actuel;
|
|
if (diff >= 0) {
|
|
const limit2Segments = Math.floor(segments[i] / 2);
|
|
if (diff > limit2Segments && i > 0) {
|
|
cumul -= segments[i - 1]; // le segment est à moins de la moitié, il est récupéré
|
|
}
|
|
cumul -= segments[i];
|
|
break;
|
|
}
|
|
};
|
|
return cumul;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async recuperationReve(message, demiHeure) {
|
|
const seuil = Misc.templateData(this).reve.seuil.value;
|
|
const reveActuel = this.getReveActuel();
|
|
if (reveActuel >= seuil) {
|
|
if (demiHeure == 1) {
|
|
message.content += `Vous avez suffisament rêvé, au delà de votre seuil. `;
|
|
}
|
|
}
|
|
else {
|
|
let deRecuperation = await RdDDice.rollTotal("1dr");
|
|
console.log("recuperationReve", deRecuperation);
|
|
if (deRecuperation >= 7) {
|
|
// Rêve de Dragon !
|
|
message.content += `Vous faites un <strong>Rêve de Dragon</strong> de ${deRecuperation} Points de rêve! `;
|
|
await this.combattreReveDeDragon(deRecuperation);
|
|
}
|
|
else {
|
|
message.content += `Vous récupérez ${deRecuperation} Points de rêve. `;
|
|
await this.reveActuelIncDec(deRecuperation);
|
|
}
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async retourSeuilDeReve(message) {
|
|
const seuil = Misc.templateData(this).reve.seuil.value;
|
|
const reveActuel = this.getReveActuel();
|
|
if (reveActuel > seuil) {
|
|
message.content += `<br>Votre rêve redescend vers son seuil naturel (${seuil}, nouveau rêve actuel ${(reveActuel - 1)})`;
|
|
await this.reveActuelIncDec(-1);
|
|
}
|
|
}
|
|
|
|
async retourSust(message) {
|
|
const tplData = Misc.templateData(this);
|
|
const sustNeeded = tplData.attributs.sust.value;
|
|
const sustConsomme = tplData.compteurs.sust.value;
|
|
const eauConsomme = tplData.compteurs.eau.value;
|
|
if (game.settings.get("foundryvtt-reve-de-dragon", "appliquer-famine-soif").includes('famine') && sustConsomme < sustNeeded) {
|
|
const perte = sustConsomme < Math.min(0.5, sustNeeded) ? 3 : (sustConsomme <= (sustNeeded / 2) ? 2 : 1);
|
|
message.content += `<br>Vous ne vous êtes sustenté que de ${sustConsomme} pour un appétit de ${sustNeeded}, vous avez faim!
|
|
La famine devrait vous faire ${perte} points d'endurance non récupérables, notez le cumul de côté et ajustez l'endurance`;
|
|
}
|
|
|
|
if (game.settings.get("foundryvtt-reve-de-dragon", "appliquer-famine-soif").includes('soif') && eauConsomme < sustNeeded) {
|
|
const perte = eauConsomme < Math.min(0.5, sustNeeded) ? 12 : (eauConsomme <= (sustNeeded / 2) ? 6 : 3);
|
|
message.content += `<br>Vous n'avez bu que ${eauConsomme} doses de liquide pour une soif de ${sustNeeded}, vous avez soif!
|
|
La soif devrait vous faire ${perte} points d'endurance non récupérables, notez le cumul de côté et ajustez l'endurance`;
|
|
}
|
|
await this.updateCompteurValue('sust', 0);
|
|
await this.updateCompteurValue('eau', 0);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async combattreReveDeDragon(force) {
|
|
let rollData = {
|
|
actor: this,
|
|
competence: duplicate(this.getBestDraconic()),
|
|
canClose: false,
|
|
rencontre: duplicate(TMRRencontres.getRencontre('rdd')),
|
|
tmr: true,
|
|
use: { libre: false, conditions: false },
|
|
forceCarac: { 'reve-actuel': { label: "Rêve Actuel", value: this.getReveActuel() } }
|
|
}
|
|
rollData.rencontre.force = force;
|
|
rollData.competence.data.defaut_carac = 'reve-actuel';
|
|
|
|
const dialog = await RdDRoll.create(this, rollData,
|
|
{
|
|
html: 'systems/foundryvtt-reve-de-dragon/templates/dialog-roll-reve-de-dragon.html',
|
|
options: { height: 400 }
|
|
},
|
|
{
|
|
name: 'maitrise',
|
|
label: 'Maîtriser le Rêve de Dragon',
|
|
callbacks: [
|
|
this.createCallbackExperience(),
|
|
{ action: r => this.resultCombatReveDeDragon(r) }
|
|
]
|
|
}
|
|
);
|
|
dialog.render(true);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async resultCombatReveDeDragon(rollData) {
|
|
rollData.queues = [];
|
|
if (rollData.rolled.isEchec) {
|
|
rollData.queues.push(Misc.data(await this.ajouterQueue()));
|
|
}
|
|
if (rollData.rolled.isETotal) {
|
|
rollData.queues.push(Misc.data(await this.ajouterQueue()));
|
|
}
|
|
if (rollData.rolled.isSuccess) {
|
|
await this.updatePointDeSeuil();
|
|
await this.reveActuelIncDec(rollData.rencontre.force);
|
|
}
|
|
if (rollData.rolled.isPart) {
|
|
// TODO: un dialogue pour demander le type de tête?
|
|
rollData.tete = true;
|
|
}
|
|
rollData.poesie = await Poetique.getExtrait();
|
|
|
|
ChatMessage.create({
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
|
|
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-resultat-reve-de-dragon.html`, rollData)
|
|
});
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async sortMisEnReserve(rollData, sort) {
|
|
let reserve = duplicate(Misc.templateData(this).reve.reserve.list);
|
|
reserve.push({ coord: rollData.tmr.coord, sort: sort, draconic: duplicate(rollData.competence) });
|
|
await this.update({ "data.reve.reserve.list": reserve });
|
|
this.currentTMR.updateTokens();
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async updateCarac(caracName, caracValue) {
|
|
if (caracName == "force") {
|
|
if (Number(caracValue) > this.getTaille() + 4) {
|
|
ui.notifications.warn("Votre FORCE doit être au maximum de TAILLE+4");
|
|
return;
|
|
}
|
|
}
|
|
const tplData = Misc.templateData(this);
|
|
if (caracName == "reve") {
|
|
if (caracValue > Misc.toInt(tplData.reve.seuil.value)) {
|
|
this.setPointsDeSeuil(caracValue);
|
|
}
|
|
}
|
|
if (caracName == "chance") {
|
|
if (caracValue > Misc.toInt(tplData.compteurs.chance.value)) {
|
|
this.setPointsDeChance(caracValue);
|
|
}
|
|
}
|
|
await this.update({ [`data.carac.${caracName}.value`]: caracValue });
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async updateCaracXP(caracName, caracXP) {
|
|
if (caracName == 'Taille') {
|
|
return;
|
|
}
|
|
// if ( isNaN(caracXP) || typeof(caracXP) != 'number') caracXP = 0;
|
|
//await this.update({ [`data.carac.${caracName}.xp`]: caracXP });
|
|
this.checkCaracXP(caracName);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async updateCaracXPAuto(caracName) {
|
|
if (caracName == 'Taille') {
|
|
return;
|
|
}
|
|
let carac = RdDActor._findCaracByName(Misc.templateData(this).carac, caracName);
|
|
if (carac) {
|
|
carac = duplicate(carac);
|
|
let xp = Number(carac.xp);
|
|
let value = Number(carac.value);
|
|
while (xp >= RdDCarac.getCaracNextXp(value) && xp > 0) {
|
|
xp -= RdDCarac.getCaracNextXp(value);
|
|
value++;
|
|
}
|
|
carac.xp = xp;
|
|
carac.value = value;
|
|
await this.update({ [`data.carac.${caracName}`]: carac });
|
|
this.updateExperienceLog("Carac +", xp, caracName + " passée à " + value);
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async updateCompetenceXPAuto(compName) {
|
|
let competence = this.getCompetence(compName);
|
|
if (competence) {
|
|
let compData = Misc.data(competence);
|
|
let xp = Number(compData.data.xp);
|
|
let niveau = Number(compData.data.niveau);
|
|
while (xp >= RdDItemCompetence.getCompetenceNextXp(niveau) && xp > 0) {
|
|
xp -= RdDItemCompetence.getCompetenceNextXp(niveau);
|
|
niveau++;
|
|
}
|
|
competence.update({
|
|
"data.xp": xp,
|
|
"data.niveau": niveau,
|
|
});
|
|
this.updateExperienceLog("Compétence +", xp, compName + " passée à " + niveau);
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async updateCreatureCompetence(compName, fieldName, compValue) {
|
|
let comp = this.getCompetence(compName);
|
|
if (comp) {
|
|
const update = { _id: comp.id }
|
|
if (fieldName == "niveau")
|
|
update['data.niveau'] = compValue;
|
|
else if (fieldName == "dommages")
|
|
update['data.dommages'] = compValue;
|
|
else
|
|
update['data.carac_value'] = compValue;
|
|
const updated = await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async updateCompetence(compName, compValue) {
|
|
let comp = this.getCompetence(compName);
|
|
if (comp) {
|
|
let troncList = RdDItemCompetence.isTronc(compName);
|
|
let nouveauNiveau = compValue ?? RdDItemCompetence.getNiveauBase(Misc.data(comp).data.categorie);
|
|
if (troncList) {
|
|
let message = "Vous avez modifié une compétence 'tronc'. Vérifiez que les compétences suivantes évoluent ensemble jusqu'au niveau 0 : ";
|
|
for (let troncName of troncList) {
|
|
message += "<br>" + troncName;
|
|
}
|
|
ChatMessage.create({
|
|
whisper: ChatMessage.getWhisperRecipients(game.user.name),
|
|
content: message
|
|
});
|
|
}
|
|
const update = { _id: comp.id, 'data.niveau': nouveauNiveau };
|
|
await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
|
|
} else {
|
|
console.log("Competence not found", compName);
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async updateCompetenceXP(compName, newXp) {
|
|
let comp = this.getCompetence(compName);
|
|
if (comp) {
|
|
if ( isNaN(newXp) || typeof(newXp) != 'number') newXp = 0;
|
|
this.checkCompetenceXP(compName, newXp);
|
|
const update = { _id: comp.id, 'data.xp': newXp };
|
|
await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
|
|
this.updateExperienceLog("XP", newXp, "XP modifié en " + compName);
|
|
} else {
|
|
console.log("Competence not found", compName);
|
|
}
|
|
RdDUtility.checkThanatosXP(compName);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async updateCompetenceXPSort(compName, compValue) {
|
|
let comp = this.getCompetence(compName);
|
|
if (comp) {
|
|
if ( isNaN(compValue) || typeof(compValue) != 'number') compValue = 0;
|
|
const update = { _id: comp.id, 'data.xp_sort': compValue };
|
|
await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
|
|
this.updateExperienceLog("XP Sort", compValue, "XP modifié en sort de " + compName);
|
|
} else {
|
|
console.log("Competence not found", compName);
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async updateCompetenceArchetype(compName, compValue) {
|
|
let comp = this.getCompetence(compName);
|
|
if (comp) {
|
|
compValue = compValue ?? 0;
|
|
const update = { _id: comp.id, 'data.niveau_archetype': compValue };
|
|
await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
|
|
} else {
|
|
console.log("Competence not found", compName);
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async updateExperienceLog(modeXP, valeurXP, raisonXP = 'Inconnue') {
|
|
let d = new Date();
|
|
console.log(modeXP, valeurXP, raisonXP);
|
|
let expLog = duplicate((Misc.templateData(this)).experiencelog);
|
|
expLog.push({
|
|
mode: Misc.upperFirst(modeXP), valeur: valeurXP, raison: Misc.upperFirst(raisonXP),
|
|
daterdd: game.system.rdd.calendrier.getDateFromIndex(), datereel: `${d.getDate()}/${d.getMonth() + 1}/${d.getFullYear()}`
|
|
});
|
|
await this.update({ [`data.experiencelog`]: expLog });
|
|
console.log("Add XP log", expLog);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async updateCompteurValue(fieldName, fieldValue, raison = 'Inconnue') {
|
|
await this.update({ [`data.compteurs.${fieldName}.value`]: fieldValue });
|
|
if (fieldName == 'stress') {
|
|
await this.updateExperienceLog('stress', fieldValue, raison);
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async addCompteurValue(fieldName, fieldValue, raison = 'Inconnue') {
|
|
let oldValue = (Misc.templateData(this)).compteurs[fieldName].value;
|
|
await this.update({ [`data.compteurs.${fieldName}.value`]: Number(oldValue) + Number(fieldValue) });
|
|
if (fieldName == 'stress') {
|
|
await this.updateExperienceLog('stress', fieldValue, raison);
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async updateAttributeValue(fieldName, fieldValue) {
|
|
await this.update({ [`data.attributs.${fieldName}.value`]: fieldValue });
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
_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 Misc.templateData(item).contenu) {
|
|
let subObjet = this.getObjet(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 = Misc.templateData(objet);
|
|
if (objet.type != 'conteneur') {
|
|
return Number(tplData.encombrement) * Number(tplData.quantite);
|
|
}
|
|
const encContenus = tplData.contenu.map(idContenu => this.getRecursiveEnc(this.getObjet(idContenu)));
|
|
return encContenus.reduce(Misc.sum(), 0)
|
|
+ Number(tplData.encombrement) /* TODO? Number(tplData.quantite) -- on pourrait avoir plusieurs conteneurs...*/
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
buildSubConteneurObjetList(conteneurId, deleteList) {
|
|
let conteneur = this.getObjet(conteneurId);
|
|
if (conteneur?.type == 'conteneur') { // Si c'est un conteneur
|
|
for (let subId of Misc.templateData(conteneur).contenu) {
|
|
let subObj = this.getObjet(subId);
|
|
if (subObj) {
|
|
if (subObj.type == 'conteneur') {
|
|
this.buildSubConteneurObjetList(subId, deleteList);
|
|
}
|
|
deleteList.push({ id: subId, conteneurId: conteneurId });
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async deleteAllConteneur(itemId) {
|
|
let list = [];
|
|
list.push({ id: itemId, conteneurId: undefined }); // Init list
|
|
this.buildSubConteneurObjetList(itemId, list);
|
|
await this.deleteEmbeddedDocuments('Item', list.map(it => it.id));
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
/** Supprime un item d'un conteneur, sur la base
|
|
* de leurs ID */
|
|
async enleverDeConteneur(item, conteneur, objetVersConteneur) {
|
|
if (conteneur?.isConteneur()) {
|
|
let data2use = duplicate(Misc.data(conteneur));
|
|
let contenu = data2use.data.contenu;
|
|
let index = contenu.indexOf(item.id);
|
|
while (index >= 0) { // Force cleanup, itemId is unique
|
|
contenu.splice(index, 1);
|
|
index = contenu.indexOf(item.id);
|
|
}
|
|
item.data.estContenu = false;
|
|
await this.updateEmbeddedDocuments('Item', [data2use]);
|
|
delete objetVersConteneur[item.id];
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
/** Ajoute un item dans un conteneur, sur la base
|
|
* de leurs ID */
|
|
async ajouterDansConteneur(item, conteneur, objetVersConteneur) {
|
|
if (conteneur?.isConteneur()) {
|
|
let data2use = duplicate(Misc.data(conteneur));
|
|
data2use.data.contenu.push(item.id);
|
|
item.data.estContenu = true;
|
|
await this.updateEmbeddedDocuments('Item', [data2use]);
|
|
objetVersConteneur[item.id] = conteneur.id;
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
/** Fonction de remise à plat de l'équipement (ie vide les champs 'contenu') */
|
|
async nettoyerConteneurs() {
|
|
const corrections = [];
|
|
for (let item of this.items) {
|
|
let itemData = Misc.data(item);
|
|
if (itemData.estContenu) {
|
|
itemData.estContenu = undefined;
|
|
}
|
|
if (itemData.type == 'conteneur' && itemData.data.contenu.length > 0) {
|
|
corrections.push({ _id: itemData._id, 'data.contenu': [] });
|
|
}
|
|
}
|
|
if (corrections.length > 0) {
|
|
await this.updateEmbeddedDocuments('Item', corrections);
|
|
}
|
|
}
|
|
|
|
async processDropItem(event, dragData, objetVersConteneur) {
|
|
console.log("DRAG", this.id, dragData);
|
|
const itemId = dragData.id || dragData.data._id;
|
|
if (dragData.actorId && dragData.actorId != this.id) {
|
|
console.log("Moving objects", dragData);
|
|
this.moveItemsBetweenActors(itemId, dragData.actorId);
|
|
return false;
|
|
}
|
|
let result = true;
|
|
const destId = $(event.target).parents(".item").attr("data-item-id");
|
|
const item = this.getObjet(itemId);
|
|
if (item?.isEquipement() && dragData.actorId == this.id) {
|
|
// rangement
|
|
const srcId = objetVersConteneur[itemId];
|
|
if (srcId != destId && itemId != destId) { // déplacement de l'objet
|
|
const dest = this.getObjet(destId);
|
|
const src = this.getObjet(srcId);
|
|
// changer de conteneur
|
|
if (this.conteneurPeutContenir(dest, item)) {
|
|
await this.enleverDeConteneur(item, src, objetVersConteneur);
|
|
await this.ajouterDansConteneur(item, dest, objetVersConteneur);
|
|
}
|
|
else if (dest?.isEquipementSimilaire(item)) {
|
|
await this.regrouperEquipementsSimilaires(item, dest);
|
|
result = false;
|
|
}
|
|
}
|
|
}
|
|
await this.computeEncombrementTotalEtMalusArmure();
|
|
return result;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
conteneurPeutContenir(dest, item) {
|
|
if (!dest) {
|
|
return true;
|
|
}
|
|
if (!dest.isConteneur()) {
|
|
return false;
|
|
}
|
|
const destData = Misc.data(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.data.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.data.capacite) < encContenu + newEnc) {
|
|
ui.notifications.warn(
|
|
`Le conteneur ${dest.name} a une capacité de ${destData.data.capacite}, et contient déjà ${encContenu}.
|
|
Impossible d'y ranger: ${item.name} d'encombrement ${newEnc}!`);
|
|
return false;
|
|
}
|
|
return true;
|
|
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
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
|
|
|
|
let itemMap = {};
|
|
for (let item of itemsList) {
|
|
let srcItem = sourceActor.data.items.find(subItem => subItem._id == item.id);
|
|
let newItem = await this.createEmbeddedDocuments('Item', [duplicate(srcItem)]);
|
|
console.log('New object', newItem, srcItem);
|
|
itemMap[srcItem._id] = newItem._id; // Pour garder le lien ancien / nouveau
|
|
}
|
|
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.getObjet(newConteneurId);
|
|
|
|
let newItemId = itemMap[item.id]; // Get newItem
|
|
|
|
console.log('New conteneur filling!', newConteneur, newItemId, item);
|
|
let contenu = duplicate(Misc.templateData(newConteneur).contenu);
|
|
contenu.push(newItemId);
|
|
await this.updateEmbeddedDocuments('Item', [{ _id: newConteneurId, 'data.contenu': contenu }]);
|
|
}
|
|
}
|
|
for (let item of itemsList) {
|
|
await sourceActor.deleteEmbeddedDocuments('Item', [item.id]);
|
|
}
|
|
}
|
|
|
|
async regrouperEquipementsSimilaires(item, dest) {
|
|
await dest.quantiteIncDec(Misc.templateData(item).quantite);
|
|
await item.delete();
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
detectSurEncombrement() {
|
|
return Math.max(0, Math.ceil(Number(this.encTotal) - this.getEncombrementMax()));
|
|
}
|
|
|
|
getEncombrementMax() {
|
|
return (this.data.type == 'vehicule')
|
|
? Misc.templateData(this).capacite_encombrement
|
|
: Misc.templateData(this).attributs.encombrement.value;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
computeIsHautRevant() {
|
|
if (this.isPersonnage()) {
|
|
Misc.templateData(this).attributs.hautrevant.value = this.hasItemNamed('tete', 'don de haut-reve')
|
|
? "Haut rêvant"
|
|
: "";
|
|
}
|
|
}
|
|
|
|
hasItemNamed(type, name) {
|
|
name = Grammar.toLowerCaseNoAccent(name);
|
|
return this.listItemsData(type).find(it => Grammar.toLowerCaseNoAccent(it.name) == name);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async computeEncombrementTotalEtMalusArmure() {
|
|
await this.computeMalusArmure();
|
|
return this.computeEncombrement();
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
computeEncombrement() {
|
|
this.encTotal = this.items.map(it => it.getEncTotal()).reduce(Misc.sum(), 0);
|
|
return this.encTotal;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async computeMalusArmure() {
|
|
const newMalusArmure = this.filterItemsData(it => it.type == 'armure' && it.data.equipe)
|
|
.map(it => it.data.malus ?? 0)
|
|
.reduce(Misc.sum(), 0);
|
|
// Mise à jour éventuelle du malus armure
|
|
if (newMalusArmure && Misc.templateData(this).attributs?.malusarmure?.value != newMalusArmure) {
|
|
await this.updateAttributeValue("malusarmure", newMalusArmure);
|
|
}
|
|
return newMalusArmure;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
computePrixTotalEquipement() {
|
|
this.prixTotalEquipement = this.filterItemsData(it => it.data.prixTotal)
|
|
.map(it => it.data.prixTotal ?? 0)
|
|
.reduce(Misc.sum(), 0);
|
|
// Mise à jour valeur totale de l'équipement
|
|
return this.prixTotalEquipement;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
computeResumeBlessure(blessures = undefined) {
|
|
blessures = blessures ?? Misc.templateData(this).blessures;
|
|
let nbLegeres = this.countBlessures(blessures.legeres.liste);
|
|
let nbGraves = this.countBlessures(blessures.graves.liste);
|
|
let nbCritiques = this.countBlessures(blessures.critiques.liste);
|
|
|
|
let resume = "Blessures:";
|
|
if (nbCritiques > 0 || nbGraves > 0 || nbLegeres > 0) {
|
|
if (nbLegeres > 0) {
|
|
resume += " " + nbLegeres + " légère" + (nbLegeres > 1 ? "s" : "");
|
|
}
|
|
if (nbGraves > 0) {
|
|
if (nbLegeres > 0)
|
|
resume += ",";
|
|
resume += " " + nbGraves + " grave" + (nbGraves > 1 ? "s" : "");
|
|
}
|
|
if (nbCritiques > 0) {
|
|
if (nbGraves > 0 || nbLegeres > 0)
|
|
resume += ",";
|
|
resume += " une CRITIQUE !";
|
|
}
|
|
}
|
|
else {
|
|
resume = "Aucune blessure";
|
|
}
|
|
return resume;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
computeEtatGeneral() {
|
|
const actorData = Misc.data(this);
|
|
|
|
// Pas d'état général pour les entités forçage à 0
|
|
if (this.data.type == 'entite') {
|
|
actorData.data.compteurs.etat.value = 0;
|
|
return;
|
|
}
|
|
// Pour les autres
|
|
let state = - (actorData.data.sante.vie.max - actorData.data.sante.vie.value);
|
|
if (ReglesOptionelles.isUsing("appliquer-fatigue") && actorData.data.sante.fatigue) {
|
|
state += RdDUtility.currentFatigueMalus(actorData.data.sante.fatigue.value, actorData.data.sante.endurance.max);
|
|
}
|
|
// Ajout de l'éthylisme
|
|
state += Math.min(0, (actorData.data.compteurs.ethylisme?.value ?? 0));
|
|
|
|
actorData.data.compteurs.etat.value = state;
|
|
if (actorData.data.compteurs?.surenc) {
|
|
actorData.data.compteurs.surenc.value = - this.detectSurEncombrement();
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async ajouterRefoulement(value = 1) {
|
|
let refoulement = Misc.templateData(this).reve.refoulement.value + value;
|
|
let total = await RdDDice.rollTotal("1d20");
|
|
if (total <= refoulement) {
|
|
refoulement = 0;
|
|
await this.ajouterSouffle({ chat: true });
|
|
}
|
|
await this.update({ "data.reve.refoulement.value": refoulement });
|
|
return refoulement == 0 ? "souffle" : "none";
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async ajouterSouffle(options = { chat: false }) {
|
|
let souffle = Misc.data(await RdDRollTables.getSouffle());
|
|
souffle._id = undefined; //TBC
|
|
await this.createEmbeddedDocuments('Item', [souffle]);
|
|
if (options.chat) {
|
|
ChatMessage.create({
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
|
|
content: this.name + " subit un Souffle de Dragon : " + souffle.name
|
|
});
|
|
}
|
|
return souffle;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async ajouterQueue(options = { chat: false }) {
|
|
let queue;
|
|
if (Misc.data(this).data.reve.reve.thanatosused) {
|
|
queue = Misc.data(await RdDRollTables.getOmbre());
|
|
await this.update({ "data.reve.reve.thanatosused": false });
|
|
}
|
|
else {
|
|
queue = Misc.data(await RdDRollTables.getQueue());
|
|
}
|
|
await this.createEmbeddedDocuments('Item', [queue]);
|
|
if (options.chat) {
|
|
ChatMessage.create({
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
|
|
content: this.name + " subit une Queue de Dragon : " + queue.name
|
|
});
|
|
}
|
|
return queue;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async cacheTMR() {
|
|
await this.update({ 'data.reve.tmrpos.cache': true });
|
|
}
|
|
async montreTMR() {
|
|
await this.update({ 'data.reve.tmrpos.cache': false });
|
|
}
|
|
isTMRCache() {
|
|
return this.data.data.reve.tmrpos.cache;
|
|
}
|
|
/* -------------------------------------------- */
|
|
async cacheTMRetMessage() {
|
|
await this.reinsertionAleatoire("Action MJ");
|
|
await this.cacheTMR();
|
|
game.socket.emit("system.foundryvtt-reve-de-dragon", {
|
|
msg: "msg_tmr_move", data: {
|
|
actorId: this.data._id,
|
|
tmrPos: this.data.data.reve.tmrpos
|
|
}
|
|
});
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async afficheTMRetMessage() {
|
|
await this.montreTMR();
|
|
game.socket.emit("system.foundryvtt-reve-de-dragon", {
|
|
msg: "msg_tmr_move", data: {
|
|
actorId: this.data._id,
|
|
tmrPos: this.data.data.reve.tmrpos
|
|
}
|
|
});
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async reinsertionAleatoire(raison) {
|
|
ChatMessage.create({
|
|
content: `${raison} : ré-insertion aléatoire.`,
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name)
|
|
});
|
|
const innaccessible = this.buildTMRInnaccessible();
|
|
let tmr = await TMRUtility.getTMRAleatoire(tmr => !innaccessible.includes(tmr.coord));
|
|
this.updateCoordTMR(tmr.coord);
|
|
this.cacheTMR();
|
|
return tmr;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
buildTMRInnaccessible() {
|
|
const tmrInnaccessibles = this.filterItemsData(it => Draconique.isCaseTMR(it) &&
|
|
EffetsDraconiques.isInnaccessible(it));
|
|
return tmrInnaccessibles.map(it => it.data.coord);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
getTMRRencontres() {
|
|
return Misc.templateData(this).reve.rencontre.list;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async deleteTMRRencontreAtPosition() {
|
|
let rencontres = this.getTMRRencontres();
|
|
let newRencontres = rencontres.filter(it => it.coord != this.getDemiReve());
|
|
if (newRencontres.length != rencontres.length) {
|
|
await this.update({ "data.reve.rencontre.list": newRencontres });
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async addTMRRencontre(currentRencontre) {
|
|
let rencontres = this.getTMRRencontres();
|
|
let newRencontres = rencontres.filter(it => it.coord != this.getDemiReve());
|
|
if (newRencontres.length == rencontres.length) {
|
|
newRencontres.push(currentRencontre);
|
|
await this.update({ "data.reve.rencontre.list": newRencontres });
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async deleteTMRRencontre(rencontreKey) {
|
|
let list = duplicate(Misc.templateData(this).reve.rencontre.list);
|
|
let newList = [];
|
|
for (let i = 0; i < list.length; i++) {
|
|
if (i != rencontreKey)
|
|
newList.push(list[i]);
|
|
}
|
|
await this.update({ "data.reve.rencontre.list": newList });
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async updateCoordTMR(coord) {
|
|
//console.log("UPDATE TMR", coord);
|
|
await this.update({ "data.reve.tmrpos.coord": coord });
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async reveActuelIncDec(value) {
|
|
let mydata = Misc.templateData(this);
|
|
let reve = Math.max(mydata.reve.reve.value + value, 0);
|
|
await this.update({ "data.reve.reve.value": reve });
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async updatePointDeSeuil(value = 1) {
|
|
const seuil = Misc.toInt(Misc.templateData(this).reve.seuil.value);
|
|
const reve = Misc.toInt(Misc.templateData(this).carac.reve.value);
|
|
if (seuil < reve) {
|
|
await this.setPointsDeSeuil(Math.min(seuil + value, reve));
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async setPointsDeSeuil(seuil) {
|
|
await this.update({ "data.reve.seuil.value": seuil });
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async setPointsDeChance(chance) {
|
|
await this.updateCompteurValue("chance", chance);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
getSonne() {
|
|
let data = Misc.templateData(this);
|
|
return !this.isEntiteCauchemar() && (data.sante?.sonne?.value ?? false);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
getSonneRound() {
|
|
return !this.isEntiteCauchemar() && (Misc.templateData(this).sante.sonne?.round ?? false);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async verifierSonneRound(round) {
|
|
if (this.getSonne()) {
|
|
if (round > this.getSonneRound() + 1) {
|
|
await this.setSonne(false, -1); // Nettoyer l'état sonné
|
|
ChatMessage.create({ content: `${this.name} n'est plus sonné ce round !` });
|
|
}
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async setSonne(sonne = true) {
|
|
if (this.isEntiteCauchemar()) {
|
|
return;
|
|
}
|
|
let round = (sonne && game.combat) ? game.combat.current.round : -1; // Sauvegarde du round de sonné en cas de combat
|
|
await this.setStatusSonne(sonne);
|
|
await this.setStateSonne(sonne, round);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async setStateSonne(sonne, round = -1) {
|
|
if (this.isEntiteCauchemar()) {
|
|
return;
|
|
}
|
|
let sonneData = duplicate(Misc.templateData(this).sante.sonne);
|
|
sonneData.value = sonne;
|
|
sonneData.round = round;
|
|
await this.update({ "data.sante.sonne": sonneData });
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
getSConst() {
|
|
if (this.isEntiteCauchemar()) {
|
|
return 0;
|
|
}
|
|
return RdDCarac.calculSConst(Misc.templateData(this).carac.constitution.value);
|
|
}
|
|
|
|
|
|
async ajoutXpConstitution(xp) {
|
|
await this.update({ "data.carac.constitution.xp": Misc.toInt(Misc.templateData(this).carac.constitution.xp) + xp });
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
countBlessures(blessuresListe) {
|
|
return blessuresListe.filter(b => b.active).length
|
|
}
|
|
/* -------------------------------------------- */
|
|
countBlessuresByName(name) {
|
|
return this.countBlessures(Misc.templateData(this).blessures[name].liste);
|
|
}
|
|
|
|
|
|
/* -------------------------------------------- */
|
|
async testSiSonne(sante, endurance) {
|
|
const result = await this._jetEndurance(endurance);
|
|
if (result.roll.total == 1) {
|
|
ChatMessage.create({ content: await this._gainXpConstitutionJetEndurance() });
|
|
}
|
|
sante.sonne.value ||= result.sonne;
|
|
return result;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async jetEndurance() {
|
|
const actorData = Misc.data(this);
|
|
const endurance = actorData.data.sante.endurance.value;
|
|
|
|
const result = await this._jetEndurance(actorData.data.sante.endurance.value)
|
|
const message = {
|
|
content: "Jet d'Endurance : " + result.roll.total + " / " + endurance + "<br>",
|
|
whisper: ChatMessage.getWhisperRecipients(game.user.name)
|
|
};
|
|
if (result.sonne) {
|
|
message.content += `${this.name} a échoué son Jet d'Endurance et devient Sonné`;
|
|
}
|
|
else if (result.roll.total == 1) {
|
|
message.content += await this._gainXpConstitutionJetEndurance();
|
|
}
|
|
else {
|
|
message.content += `${this.name} a réussi son Jet d'Endurance !`;
|
|
}
|
|
|
|
ChatMessage.create(message);
|
|
}
|
|
|
|
async _gainXpConstitutionJetEndurance() {
|
|
await this.ajoutXpConstitution(1); // +1 XP !
|
|
return `${this.name} a obtenu 1 sur son Jet d'Endurance et a gagné 1 point d'Expérience en Constitution. Ce point d'XP a été ajouté automatiquement.`;
|
|
}
|
|
|
|
async _jetEndurance(endurance) {
|
|
const roll = await RdDDice.roll("1d20", { showDice: true });
|
|
let result = {
|
|
roll: roll,
|
|
sonne: roll.total > endurance || roll.total == 20 // 20 is always a failure
|
|
}
|
|
if (result.sonne) {
|
|
await this.setSonne();
|
|
}
|
|
return result;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async jetVie() {
|
|
let roll = await RdDDice.roll("1d20", { showDice: true });
|
|
const actorData = Misc.data(this);
|
|
let msgText = "Jet de Vie : " + roll.total + " / " + actorData.data.sante.vie.value + "<br>";
|
|
if (roll.total <= actorData.data.sante.vie.value) {
|
|
msgText += "Jet réussi, pas de perte de point de vie (prochain jet dans 1 round pour 1 critique, SC minutes pour une grave)";
|
|
if (roll.total == 1) {
|
|
msgText += "La durée entre 2 jets de vie est multipliée par 20 (20 rounds pour une critique, SCx20 minutes pour une grave)";
|
|
}
|
|
} else {
|
|
msgText += "Jet échoué, vous perdez 1 point de vie";
|
|
await this.santeIncDec("vie", -1);
|
|
if (roll.total == 20) {
|
|
msgText += "Votre personnage est mort !!!!!";
|
|
}
|
|
}
|
|
const message = {
|
|
content: msgText,
|
|
whisper: ChatMessage.getWhisperRecipients(game.user.name)
|
|
};
|
|
ChatMessage.create(message);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async santeIncDec(name, inc, options = { isCritique: false, ethylisme: false }) {
|
|
if (name == 'fatigue' && !ReglesOptionelles.isUsing("appliquer-fatigue")) {
|
|
return;
|
|
}
|
|
const sante = duplicate(Misc.templateData(this).sante);
|
|
let compteur = sante[name];
|
|
if (!compteur) {
|
|
return;
|
|
}
|
|
let result = {
|
|
sonne: false,
|
|
};
|
|
|
|
let minValue = name == "vie" ? -this.getSConst() - 1 : 0;
|
|
|
|
result.newValue = Math.max(minValue, Math.min(compteur.value + inc, compteur.max));
|
|
//console.log("New value ", inc, minValue, result.newValue);
|
|
let fatigue = 0;
|
|
if (name == "endurance" && !this.isEntiteCauchemar()) {
|
|
if (result.newValue == 0 && inc < 0 && !options.isCritique) { // perte endurance et endurance devient 0 (sauf critique) -> -1 vie
|
|
sante.vie.value--;
|
|
result.perteVie = true;
|
|
}
|
|
result.newValue = Math.max(0, result.newValue);
|
|
if (inc > 0) { // le max d'endurance s'applique seulement à la récupération
|
|
result.newValue = Math.min(result.newValue, this._computeEnduranceMax())
|
|
}
|
|
const perte = compteur.value - result.newValue;
|
|
result.perte = perte;
|
|
if (perte > 1 && !options.ethylisme) {
|
|
// Peut-être sonné si 2 points d'endurance perdus d'un coup
|
|
const testIsSonne = await this.testSiSonne(sante, result.newValue);
|
|
result.sonne = testIsSonne.sonne;
|
|
result.jetEndurance = testIsSonne.roll.total;
|
|
} else if (inc > 0) {
|
|
await this.setSonne(false);
|
|
sante.sonne.value = false;
|
|
}
|
|
if (sante.fatigue && inc < 0) { // Each endurance lost -> fatigue lost
|
|
fatigue = perte;
|
|
}
|
|
}
|
|
compteur.value = result.newValue;
|
|
//console.log(name, inc, data.value, result.newValue, minValue, data.max);
|
|
// If endurance lost, then the same amount of fatigue cannot be recovered
|
|
if (ReglesOptionelles.isUsing("appliquer-fatigue") && sante.fatigue && fatigue > 0) {
|
|
sante.fatigue.value = Math.max(sante.fatigue.value + fatigue, this._computeFatigueMin());
|
|
}
|
|
await this.update({ "data.sante": sante });
|
|
if (this.isDead()) {
|
|
await this.addStatusEffectById('dead');
|
|
}
|
|
return result;
|
|
}
|
|
|
|
isDead() {
|
|
return !this.isEntiteCauchemar() && Misc.templateData(this).sante.vie.value < -this.getSConst()
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
_computeFatigueMin() {
|
|
return Misc.templateData(this).sante.endurance.max - Misc.templateData(this).sante.endurance.value;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
_computeEnduranceMax() {
|
|
const actorData = Misc.data(this);
|
|
let blessures = actorData.data.blessures;
|
|
let diffVie = actorData.data.sante.vie.max - actorData.data.sante.vie.value;
|
|
let maxEndVie = actorData.data.sante.endurance.max - (diffVie * 2);
|
|
let nbGraves = this.countBlessures(blessures.graves.liste);
|
|
let nbCritiques = this.countBlessures(blessures.critiques.liste);
|
|
let maxEndGraves = Math.floor(actorData.data.sante.endurance.max / (2 * nbGraves));
|
|
let maxEndCritiques = nbCritiques > 0 ? 1 : actorData.data.sante.endurance.max;
|
|
return Math.max(0, Math.min(maxEndVie, maxEndGraves, maxEndCritiques));
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async manageBlessureFromSheet(gravite, index) {
|
|
let listBlessures = duplicate(Misc.templateData(this).blessures);
|
|
let blessure = listBlessures[gravite + "s"].liste[index];
|
|
blessure.active = !blessure.active;
|
|
if (!blessure.active) {
|
|
this._supprimerBlessure(blessure);
|
|
}
|
|
await this.update({ 'data.blessures': listBlessures });
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async setDataBlessureFromSheet(gravite, index, psoins, pcomplets, jours, loc) {
|
|
let listBlessures = duplicate(Misc.templateData(this).blessures);
|
|
let blessure = listBlessures[gravite + "s"].liste[index];
|
|
blessure.premiers_soins = psoins;
|
|
blessure.soins_complets = pcomplets;
|
|
blessure.jours = jours;
|
|
blessure.loc = loc;
|
|
await this.update({ 'data.blessures': listBlessures });
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async jetDeMoral(situation, messageReussi = undefined, messageManque = undefined) {
|
|
let jetMoral = await this._jetMoral(situation)
|
|
|
|
let defaultMessage = `Vous ${jetMoral.ajustement > 0 ? "gagnez du moral" : jetMoral.ajustement < 0 ? "perdez du moral" : "gardez votre moral"}.`;
|
|
let finMessage = jetMoral.succes ? (messageReussi != undefined ? messageReussi : defaultMessage) : (messageManque != undefined ? messageManque : defaultMessage);
|
|
let message = `Jet de moral ${jetMoral.succes ? "réussi" : "manqué"} en situation ${situation} (${jetMoral.jet}/${jetMoral.difficulte}). <br/>${finMessage}`;
|
|
ChatMessage.create({
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
|
|
content: message
|
|
});
|
|
return jetMoral.ajustement;
|
|
}
|
|
|
|
async _jetMoral(situation) {
|
|
const moralActuel = Misc.toInt(Misc.templateData(this).compteurs.moral.value);
|
|
const jet = await RdDDice.rollTotal("1d20", { showDice: true });
|
|
const difficulte = 10 + moralActuel;
|
|
const succes = jet <= difficulte;
|
|
const jetMoral = {
|
|
actuel: moralActuel,
|
|
jet: jet,
|
|
situation: situation,
|
|
difficulte: difficulte,
|
|
succes: succes,
|
|
ajustement: this._calculAjustementMoral(succes, moralActuel, situation)
|
|
};
|
|
await this.moralIncDec(jetMoral.ajustement);
|
|
return jetMoral;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async moralIncDec(ajustementMoral) {
|
|
let tplData = Misc.templateData(this);
|
|
if (ajustementMoral != 0) {
|
|
let moral = Misc.toInt(tplData.compteurs.moral.value) + ajustementMoral
|
|
if (moral > 3) { // exaltation
|
|
const exaltation = Misc.toInt(tplData.compteurs.exaltation.value) + moral - 3;
|
|
await this.updateCompteurValue('exaltation', exaltation);
|
|
}
|
|
if (moral < -3) { // dissolution
|
|
const dissolution = Misc.toInt(tplData.compteurs.dissolution.value) + 3 - moral;
|
|
await this.updateCompteurValue('dissolution', dissolution);
|
|
}
|
|
moral = Math.max(-3, Math.min(moral, 3));
|
|
await this.updateCompteurValue('moral', moral);
|
|
}
|
|
return tplData.compteurs.moral.value;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
_calculAjustementMoral(succes, moral, situation) {
|
|
switch (situation) {
|
|
case 'heureux': case 'heureuse': return succes ? 1 : 0;
|
|
case 'malheureuse': case 'malheureux': return succes ? 0 : -1;
|
|
case 'neutre':
|
|
if (succes && moral <= 0) return 1;
|
|
if (!succes && moral > 0) return -1;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async setEthylisme(degre) {
|
|
let ethylisme = duplicate(Misc.templateData(this).compteurs.ethylisme);
|
|
ethylisme.value = degre;
|
|
ethylisme.nb_doses = 0;
|
|
if (degre == 1) {
|
|
ethylisme.jet_moral = false;
|
|
}
|
|
await this.update({ "data.compteurs.ethylisme": ethylisme });
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async jetEthylisme() {
|
|
const actorData = Misc.data(this);
|
|
let rollData = {
|
|
vie: actorData.data.sante.vie.max,
|
|
forceAlcool: 0,
|
|
etat: this.getEtatGeneral({ ethylisme: true }),
|
|
diffNbDoses: -Number(actorData.data.compteurs.ethylisme.nb_doses || 0),
|
|
finalLevel: 0,
|
|
diffConditions: 0,
|
|
ajustementsForce: CONFIG.RDD.difficultesLibres,
|
|
}
|
|
let html = await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/dialog-roll-ethylisme.html', rollData);
|
|
new RdDRollDialogEthylisme(html, rollData, this, r => this.saouler(r.forceAlcool)).render(true);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async actionItem(item) {
|
|
if (!item.getActionPrincipale()) return;
|
|
switch (Misc.data(item).type) {
|
|
case 'nourritureboisson': return await this.actionNourritureboisson(item);
|
|
case 'potion': return await this.actionPotion(item);
|
|
case 'livre': return await this.actionLire(item);
|
|
}
|
|
}
|
|
|
|
async actionNourritureboisson(item) {
|
|
const dialog = await DialogConsommer.create(this, item);
|
|
dialog.render(true);
|
|
}
|
|
|
|
async actionPotion(item) {
|
|
return await this.consommerPotion(item)
|
|
}
|
|
async actionLire(item) {
|
|
const tache = await this.creerTacheDepuisLivre(item, { renderSheet: false });
|
|
if (tache) {
|
|
await this.rollTache(tache.id);
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async consommer(item, choix) {
|
|
switch (Misc.data(item).type) {
|
|
case 'nourritureboisson':
|
|
return await this.consommerNourritureboisson(item, choix);
|
|
case 'potion':
|
|
return await this.consommerPotion(item)
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async consommerNourritureboisson(item, choix = { doses: 1, seForcer: false }) {
|
|
const itemData = Misc.data(item);
|
|
if (itemData.type != 'nourritureboisson') {
|
|
return;
|
|
}
|
|
if (choix.doses > itemData.data.quantite) {
|
|
ui.notifications.warn(`Il n'y a pas assez de ${itemData.name} pour manger ${choix.doses}`)
|
|
return;
|
|
}
|
|
const surmonteExotisme = await this.surmonterExotisme(item, choix);
|
|
if (!surmonteExotisme) {
|
|
ui.notifications.warn(`Vous n'arrivez pas à manger de ${itemData.name}`)
|
|
return;
|
|
}
|
|
await this.manger(item, choix.doses, { diminuerQuantite: false });
|
|
await this.boire(item, choix.doses, { diminuerQuantite: false });
|
|
await item.diminuerQuantite(choix.doses);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async manger(item, doses, options = { diminuerQuantite: true }) {
|
|
if (!item.getActionPrincipale()) return;
|
|
await this.apprecierCuisine(item);
|
|
const sust = Misc.templateData(item).sust;
|
|
if (sust > 0) {
|
|
await this.updateCompteurValue('sust', Misc.keepDecimals(Misc.templateData(this).compteurs.sust.value + sust * doses, 2));
|
|
}
|
|
await item.diminuerQuantite(doses, options);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async boire(item, doses, options = { diminuerQuantite: true }) {
|
|
if (!item.getActionPrincipale()) return;
|
|
const itemData = Misc.data(item);
|
|
const desaltere = itemData.data.desaltere;
|
|
if (desaltere > 0) {
|
|
await this.updateCompteurValue('eau', Misc.keepDecimals(Misc.templateData(this).compteurs.eau.value + desaltere * doses, 2));
|
|
}
|
|
if (item.isAlcool()) {
|
|
for (let i = 0; i < doses; i++) {
|
|
await this.saouler(itemData.data.force, item);
|
|
}
|
|
}
|
|
await item.diminuerQuantite(doses, options);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async saouler(forceAlcool, alcool = undefined) {
|
|
const actorData = Misc.data(this);
|
|
let ethylisme = duplicate(actorData.data.compteurs.ethylisme);
|
|
|
|
const etat = this.getEtatGeneral({ ethylisme: true });
|
|
const nbDoses = Number(actorData.data.compteurs.ethylisme.nb_doses || 0);
|
|
const ethylismeData = {
|
|
alias: actorData.name,
|
|
actor: actorData,
|
|
vie: actorData.data.sante.vie.max,
|
|
alcool: Misc.data(alcool),
|
|
jetVie: {
|
|
forceAlcool: forceAlcool,
|
|
nbDoses: nbDoses,
|
|
selectedCarac: actorData.data.sante.vie,
|
|
carac: actorData.data.carac,
|
|
caracValue: actorData.data.sante.vie.max,
|
|
finalLevel: etat + forceAlcool - nbDoses,
|
|
showDice: true
|
|
},
|
|
}
|
|
|
|
await RdDResolutionTable.rollData(ethylismeData.jetVie);
|
|
this._appliquerExperienceRollData(ethylismeData.jetVie);
|
|
RollDataAjustements.calcul(ethylismeData.jetVie, this);
|
|
if (ethylismeData.jetVie.rolled.isSuccess) {
|
|
ethylisme.nb_doses++;
|
|
} else {
|
|
ethylisme.value = Math.max(ethylisme.value - 1, -7);
|
|
ethylisme.nb_doses = 0;
|
|
|
|
let perte = await RdDDice.rollTotal("1d6", { showDice: true });
|
|
ethylismeData.perteEndurance = await this.santeIncDec("endurance", -perte, { ethylisme: true });
|
|
|
|
if (!ethylisme.jet_moral) {
|
|
ethylismeData.jetMoral = await this._jetMoral('heureuse');
|
|
if (ethylismeData.jetMoral.ajustement == 1) {
|
|
ethylismeData.moralAlcool = 'heureux';
|
|
ethylisme.jet_moral = true;
|
|
} else if (ethylisme.value == -1) {
|
|
ethylismeData.jetMoral.ajustement = -1;
|
|
ethylismeData.moralAlcool = 'triste';
|
|
ethylisme.jet_moral = true;
|
|
await this.moralIncDec(-1);
|
|
}
|
|
}
|
|
if (ethylisme.value < 0) {
|
|
// Qui a bu boira (p 164)
|
|
ethylismeData.jetVolonte = {
|
|
selectedCarac: actorData.data.carac.volonte,
|
|
caracValue: actorData.data.carac.volonte.value,
|
|
ethylisme: ethylisme.value,
|
|
finalLevel: ethylisme.value + actorData.data.compteurs.moral.value,
|
|
showDice: true
|
|
}
|
|
await RdDResolutionTable.rollData(ethylismeData.jetVolonte);
|
|
this._appliquerExperienceRollData(ethylismeData.jetVolonte);
|
|
RollDataAjustements.calcul(ethylismeData.jetVolonte, this);
|
|
}
|
|
}
|
|
ethylismeData.ajustementEthylique = ethylisme.value;
|
|
ethylismeData.nomEthylisme = RdDUtility.getNomEthylisme(ethylisme.value);
|
|
ethylismeData.doses = ethylisme.nb_doses;
|
|
|
|
await this.update({ 'data.compteurs.ethylisme': ethylisme });
|
|
await RdDResolutionTable.displayRollData(ethylismeData, this, 'chat-resultat-ethylisme.html');
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async apprecierCuisine(item) {
|
|
const cuisine = Misc.data(this.getCompetence('cuisine'));
|
|
const itemData = Misc.data(item);
|
|
const qualite = itemData.data.qualite;
|
|
if (cuisine && qualite > 0 && qualite > cuisine.data.niveau) {
|
|
const rolled = await this.rollCaracCompetence('gout', 'cuisine', qualite, { title: itemData.data.boisson ? "apprécie la boisson" : "apprécie le plat" });
|
|
if (rolled.isSuccess) {
|
|
await this.jetDeMoral('heureux');
|
|
}
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async surmonterExotisme(item, choix = {}) {
|
|
const itemData = Misc.data(item);
|
|
const exotisme = Math.min(itemData.data.exotisme, itemData.data.qualite, 0);
|
|
if (exotisme < 0) {
|
|
const rolled = await this.rollCaracCompetence('volonte', 'cuisine', exotisme, { title: `tente de surmonter l'exotisme de ${itemData.name}` });
|
|
if (rolled.isEchec) {
|
|
if (!choix.seForcer) {
|
|
return false;
|
|
}
|
|
await this.jetDeMoral('malheureux');
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async jetGoutCuisine() {
|
|
console.info('Jet de Gout/Cuisine');
|
|
return true;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async transformerStress() {
|
|
const actorData = Misc.data(this);
|
|
const stress = Misc.toInt(actorData.data.compteurs.stress.value);
|
|
if (stress <= 0) {
|
|
return;
|
|
}
|
|
|
|
const stressRoll = await this._stressRoll(this.getReveActuel());
|
|
|
|
const conversion = Math.floor(stress * stressRoll.factor / 100);
|
|
let dissolution = Math.max(0, Misc.toInt(actorData.data.compteurs.dissolution.value));
|
|
let exaltation = Math.max(0, Misc.toInt(actorData.data.compteurs.exaltation.value));
|
|
const annule = Math.min(dissolution, exaltation);
|
|
dissolution -= annule;
|
|
exaltation -= annule;
|
|
const perteDissolution = Math.max(0, Math.min(dissolution, conversion));
|
|
|
|
let stressRollData = {
|
|
alias: this.name,
|
|
selectedCarac: actorData.data.carac.reve,
|
|
rolled: stressRoll,
|
|
stress: stress,
|
|
perte: Math.min(conversion, stress),
|
|
convertis: conversion - perteDissolution,
|
|
xp: conversion - perteDissolution + exaltation,
|
|
dissolution: dissolution,
|
|
exaltation: exaltation
|
|
};
|
|
|
|
ChatMessage.create({
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
|
|
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-resultat-transformer-stress.html`, stressRollData)
|
|
});
|
|
|
|
let compteurs = duplicate(actorData.data.compteurs);
|
|
compteurs.stress.value = Math.max(stress - stressRollData.perte - 1, 0);
|
|
compteurs.experience.value += stressRollData.xp;
|
|
compteurs.dissolution.value = dissolution - perteDissolution;
|
|
compteurs.exaltation.value = 0;
|
|
await this.update({ "data.compteurs": compteurs });
|
|
|
|
this.updateExperienceLog('XP', stressRollData.xp, "Transformation du stress");
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _stressRoll(reveActuel) {
|
|
let result = await RdDResolutionTable.roll(reveActuel, 0);
|
|
if (result.isPart) {
|
|
result.second = await RdDResolutionTable.roll(reveActuel, 0);
|
|
}
|
|
result.factor = this._getFacteurStress(result);
|
|
return result;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
_getFacteurStress(stressRoll) {
|
|
switch (stressRoll.code) {
|
|
case "sign": return 75;
|
|
case "norm": return 50;
|
|
case "echec": return 20;
|
|
case "epart": return 10;
|
|
case "etotal": return 0;
|
|
case "part":
|
|
if (stressRoll.second.isSign) {
|
|
stressRoll.quality = "Double Particulière";
|
|
return 150;
|
|
}
|
|
return 100;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
createCallbackExperience() {
|
|
return {
|
|
condition: r => r.rolled.isPart && r.finalLevel < 0 && game.settings.get("core", "rollMode") != 'selfroll',
|
|
action: r => this.appliquerAjoutExperience(r, game.settings.get("core", "rollMode") != 'blindroll')
|
|
};
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
createCallbackAppelAuMoral() { /* Si l'appel au moral est utilisé, on l'affiche dans le chat et on diminue éventuellement le moral */
|
|
return {
|
|
condition: r => r.use.appelAuMoral && game.settings.get("core", "rollMode") != 'selfroll',
|
|
action: r => this._appliquerAppelMoral(r)
|
|
};
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async checkCaracXP(caracName, display = true) {
|
|
let carac = RdDActor._findCaracByName(Misc.templateData(this).carac, caracName);
|
|
if (carac && carac.xp > 0) {
|
|
const niveauSuivant = Number(carac.value) + 1;
|
|
let xpNeeded = RdDCarac.getCaracNextXp(niveauSuivant);
|
|
if (carac.xp >= xpNeeded) {
|
|
carac = duplicate(carac);
|
|
carac.value = niveauSuivant;
|
|
|
|
let checkXp = {
|
|
alias: this.name,
|
|
carac: caracName,
|
|
value: niveauSuivant,
|
|
xp: carac.xp
|
|
}
|
|
if (display) {
|
|
ChatUtility.createChatMessage(this.name, "default", {
|
|
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-actor-carac-xp.html`, checkXp)
|
|
});
|
|
}
|
|
return checkXp;
|
|
}
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async checkCompetenceXP(compName, newXP, display = true) {
|
|
let compData = Misc.data(this.getCompetence(compName));
|
|
if (compData && newXP && newXP == compData.data.xp) { // Si édition, mais sans changement XP
|
|
return;
|
|
}
|
|
newXP = (newXP) ? newXP : compData.data.xp;
|
|
if (compData && newXP > 0) {
|
|
let xpNeeded = RdDItemCompetence.getCompetenceNextXp(compData.data.niveau + 1);
|
|
if (newXP >= xpNeeded) {
|
|
let newCompData = duplicate(compData);
|
|
newCompData.data.niveau += 1;
|
|
newCompData.data.xp = newXP;
|
|
let checkXp = {
|
|
alias: this.name,
|
|
competence: newCompData.name,
|
|
niveau: newCompData.data.niveau,
|
|
xp: newCompData.data.xp,
|
|
archetype: newCompData.data.niveau_archetype,
|
|
archetypeWarning: newCompData.data.niveau > compData.data.niveau_archetype
|
|
}
|
|
if (display) {
|
|
ChatUtility.createChatMessage(this.name, "default", {
|
|
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-actor-competence-xp.html`, checkXp)
|
|
});
|
|
}
|
|
return checkXp;
|
|
}
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async appliquerAjoutExperience(rollData, display) {
|
|
if (!this.isPersonnage()) return;
|
|
let xpData = await this._appliquerExperience(rollData.rolled, rollData.selectedCarac.label, rollData.competence);
|
|
if (!xpData) {
|
|
return;
|
|
}
|
|
if (display) {
|
|
let message = {
|
|
whisher: ChatUtility.getWhisperRecipientsAndGMs(this.name),
|
|
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-actor-gain-xp.html`, xpData)
|
|
}
|
|
ChatMessage.create(message);
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _appliquerAppelMoral(rollData, display = true) {
|
|
if (!this.isPersonnage()) return;
|
|
if (!rollData.useMoral) return;
|
|
if (rollData.rolled.isEchec ||
|
|
(rollData.ajustements.diviseurSignificative && (rollData.rolled.roll * rollData.ajustements.diviseurSignificative > rollData.score))) {
|
|
rollData.perteMoralEchec = rollData.moral <= -3 ? 'dissolution' : 'perte';
|
|
rollData.moral = await this.moralIncDec(-1); /* L'appel au moral a échoué. Le personnage perd un point de moral */
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
filterSortList(sortList, coord) {
|
|
let tmr = TMRUtility.getTMR(coord);
|
|
let letfilteredList = []
|
|
for (let sort of sortList) {
|
|
//console.log(sort.name, sort.data.caseTMR.toLowerCase(), sort.data.caseTMRspeciale.toLowerCase(), coord.toLowerCase() );
|
|
if (sort.data.caseTMR.toLowerCase().includes('variable')) {
|
|
letfilteredList.push(sort);
|
|
} else if (sort.data.caseTMRspeciale.toLowerCase().includes('variable')) {
|
|
letfilteredList.push(sort);
|
|
} else if (sort.data.caseTMR.toLowerCase() == tmr.type) {
|
|
letfilteredList.push(sort);
|
|
} else if (sort.data.caseTMR.toLowerCase().includes('special') && sort.data.caseTMRspeciale.toLowerCase().includes(coord.toLowerCase())) {
|
|
letfilteredList.push(sort);
|
|
}
|
|
}
|
|
|
|
return letfilteredList;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
computeDraconicAndSortIndex(sortList) {
|
|
let draconicList = this.getDraconicList()
|
|
.map(it => {
|
|
it = duplicate(Misc.data(it))
|
|
it.data.defaut_carac = "reve";
|
|
return it;
|
|
});
|
|
for (let sort of sortList) {
|
|
let draconicsSort = this.getDraconicsSort(draconicList, sort).map(it => it.name);
|
|
for (let index = 0; index < draconicList.length && sort.data.listIndex == undefined; index++) {
|
|
if (draconicsSort.includes(draconicList[index].name)) {
|
|
sort.data.listIndex = index;
|
|
}
|
|
}
|
|
}
|
|
return draconicList;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
getDraconicsSort(draconicList, sort) {
|
|
//console.log(draconicList, bestDraconic, draconic, voie);
|
|
switch (Grammar.toLowerCaseNoAccent(sort.name)) {
|
|
case "lecture d'aura":
|
|
case "detection d'aura":
|
|
return draconicList;
|
|
case "annulation de magie":
|
|
return draconicList.filter(it => !Grammar.toLowerCaseNoAccent(Misc.data(it).name).includes('thanatos'));
|
|
}
|
|
return [RdDItemCompetence.getVoieDraconic(draconicList, sort.data.draconic)];
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async rollUnSort(coord) {
|
|
let sortList = duplicate(this.getSortList()); // Duplication car les pts de reve sont modifiés dans le sort
|
|
if (!sortList || sortList.length == 0) {
|
|
ui.notifications.info("Aucun sort disponible!");
|
|
return;
|
|
}
|
|
sortList = this.filterSortList(sortList, coord);
|
|
if (!sortList || sortList.length == 0) {
|
|
ui.notifications.info("Aucun sort disponible pour cette case !");
|
|
return;
|
|
}
|
|
if (EffetsDraconiques.isSortImpossible(this)) {
|
|
ui.notifications.error("Une queue ou un souffle vous empèche de lancer de sort!");
|
|
return;
|
|
}
|
|
if (this.currentTMR) this.currentTMR.minimize(); // Hide
|
|
|
|
let draconicList = this.computeDraconicAndSortIndex(sortList);
|
|
const actorData = Misc.data(this);
|
|
const reve = duplicate(actorData.data.carac.reve);
|
|
let rollData = {
|
|
carac: { 'reve': reve },
|
|
forceCarac: { 'reve': reve },
|
|
selectedCarac: reve,
|
|
draconicList: draconicList,
|
|
competence: draconicList[0],
|
|
sortList: sortList,
|
|
selectedSort: sortList[0],
|
|
tmr: TMRUtility.getTMR(coord),
|
|
diffLibre: RdDItemSort.getDifficulte(sortList[0], -7), // Per default at startup
|
|
coutreve: Array(30).fill().map((item, index) => 1 + index),
|
|
}
|
|
|
|
const dialog = await RdDRoll.create(this, rollData,
|
|
{
|
|
html: 'systems/foundryvtt-reve-de-dragon/templates/dialog-roll-sort.html',
|
|
options: { height: 600 },
|
|
close: html => { this.currentTMR.maximize() } // Re-display TMR
|
|
},
|
|
{
|
|
name: 'lancer-un-sort',
|
|
label: 'Lancer un sort',
|
|
callbacks: [
|
|
this.createCallbackExperience(),
|
|
{ action: r => this._rollUnSortResult(r) }
|
|
]
|
|
}
|
|
);
|
|
dialog.render(true);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
isRencontreSpeciale() { // Gestion queue/souffle 'Mauvaise Rencontre en Perpective'
|
|
let addMsg = "";
|
|
let rencSpecial = this.data.items.find(item => EffetsDraconiques.isMauvaiseRencontre(item));
|
|
if (rencSpecial) {
|
|
rencSpecial = Misc.data(rencSpecial); // To keep it
|
|
if (rencSpecial.type != 'souffle') {
|
|
this.deleteEmbeddedDocuments('Item', [rencSpecial._id]); // Suppression dans la liste des queues
|
|
addMsg = " La queue a été supprimée de votre fiche automatiquement";
|
|
} else {
|
|
addMsg = " Vous devez gérer manuellement le décompte de mauvaises rencontres manuellement.";
|
|
}
|
|
ChatMessage.create({
|
|
content: "Vous êtes sous le coup d'une Mauvaise Rencontre en Persective." + addMsg,
|
|
whisper: ChatMessage.getWhisperRecipients(game.user.name)
|
|
});
|
|
}
|
|
return rencSpecial;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
getTMRFatigue() { // Pour l'instant uniquement Inertie Draconique
|
|
let countInertieDraconique = EffetsDraconiques.countInertieDraconique(this);
|
|
if (countInertieDraconique > 0) {
|
|
ChatMessage.create({
|
|
content: `Vous êtes sous le coup d'Inertie Draconique : vous perdrez ${countInertieDraconique + 1} cases de Fatigue par déplacement au lieu d'une.`,
|
|
whisper: ChatMessage.getWhisperRecipients(game.user.name)
|
|
});
|
|
}
|
|
return countInertieDraconique + 1;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async checkSoufflePeage(tmr) {
|
|
let peage = this.data.items.find(item => EffetsDraconiques.isPeage(item));
|
|
if (peage && (tmr.type == 'pont' || tmr.type == 'cite')) {
|
|
await this.reveActuelIncDec(-1);
|
|
ChatMessage.create({
|
|
content: "Vous êtes sous le coup d'un Péage : l'entrée sur cette case vous a coûté 1 Point de Rêve (déduit automatiquement).",
|
|
whisper: ChatMessage.getWhisperRecipients(game.user.name)
|
|
});
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _rollUnSortResult(rollData) {
|
|
let rolled = rollData.rolled;
|
|
let selectedSort = rollData.selectedSort;
|
|
|
|
rollData.isSortReserve = rollData.mettreEnReserve && !selectedSort.data.isrituel;
|
|
rollData.show = {}
|
|
rollData.depenseReve = Number(selectedSort.data.ptreve_reel);
|
|
|
|
if (rollData.competence.name.includes('Thanatos')) { // Si Thanatos
|
|
await this.update({ "data.reve.reve.thanatosused": true });
|
|
}
|
|
let reveActuel = Misc.templateData(this).reve.reve.value;
|
|
if (rolled.isSuccess) { // Réussite du sort !
|
|
if (rolled.isPart) {
|
|
rollData.depenseReve = Math.max(Math.floor(rollData.depenseReve / 2), 1);
|
|
}
|
|
if (rollData.isSortReserve) {
|
|
rollData.depenseReve++;
|
|
}
|
|
if (reveActuel > rollData.depenseReve) {
|
|
// Incrémenter/gére le bonus de case
|
|
RdDItemSort.incrementBonusCase(this, selectedSort, rollData.tmr.coord);
|
|
|
|
if (rollData.isSortReserve) {
|
|
await this.sortMisEnReserve(rollData, selectedSort);
|
|
}
|
|
}
|
|
else {
|
|
rollData.depenseReve = 0;
|
|
rollData.show.reveInsuffisant = true;
|
|
mergeObject(rollData.rolled, RdDResolutionTable.getResultat("echec"), { overwrite: true });
|
|
}
|
|
} else {
|
|
if (rolled.isETotal) { // Echec total !
|
|
rollData.depenseReve = Math.min(reveActuel, Math.floor(rollData.depenseReve * 1.5))
|
|
// TODO: mise en réserve d'un échec total...
|
|
} else {
|
|
rollData.depenseReve = 0
|
|
}
|
|
}
|
|
|
|
reveActuel = Math.max(reveActuel - rollData.depenseReve, 0);
|
|
await this.update({ "data.reve.reve.value": reveActuel });
|
|
|
|
if (rollData.isSortReserve) {
|
|
this.currentTMR.maximize(); // Re-display TMR
|
|
} else {
|
|
this.currentTMR.close(); // Close TMR !
|
|
}
|
|
// Final chat message
|
|
RdDResolutionTable.displayRollData(rollData, this, 'chat-resultat-sort.html');
|
|
|
|
if (reveActuel == 0) { // 0 points de reve
|
|
ChatMessage.create({ content: this.name + " est réduit à 0 Points de Rêve, et tombe endormi !" });
|
|
closeTMR = true;
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async rollCarac(caracName) {
|
|
let rollData = { selectedCarac: this.getCaracByName(caracName) };
|
|
|
|
const dialog = await RdDRoll.create(this, rollData,
|
|
{ html: 'systems/foundryvtt-reve-de-dragon/templates/dialog-roll-carac.html' },
|
|
{
|
|
name: 'jet-' + caracName,
|
|
label: 'Jet ' + Grammar.apostrophe('de', rollData.selectedCarac.label),
|
|
callbacks: [
|
|
this.createCallbackExperience(),
|
|
this.createCallbackAppelAuMoral(),
|
|
{ action: r => this._onRollCaracResult(r) }
|
|
]
|
|
}
|
|
);
|
|
dialog.render(true);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _onRollCaracResult(rollData) {
|
|
// Final chat message
|
|
RdDResolutionTable.displayRollData(rollData, this, 'chat-resultat-general.html');
|
|
}
|
|
|
|
async rollCaracCompetence(caracName, compName, diff, options = { title: "" }) {
|
|
const carac = this.getCaracByName(caracName);
|
|
if (!carac) {
|
|
ui.notifications.warn(`${this.name} n'a pas de caractéristique correspondant à ${caracName}`)
|
|
return;
|
|
}
|
|
const competence = Misc.data(this.getCompetence(compName));
|
|
if (compName && !competence) {
|
|
ui.notifications.warn(`${this.name} n'a pas de compétence correspondant à ${compName}`)
|
|
return;
|
|
}
|
|
let rollData = {
|
|
alias: this.name,
|
|
caracValue: Number(carac.value),
|
|
selectedCarac: carac,
|
|
competence: competence,
|
|
finalLevel: (Misc.templateData(competence)?.niveau ?? 0) + diff,
|
|
diffLibre: diff,
|
|
showDice: true,
|
|
show: { title: options?.title ?? '' }
|
|
};
|
|
await RdDResolutionTable.rollData(rollData);
|
|
this._appliquerExperienceRollData(rollData);
|
|
RdDResolutionTable.displayRollData(rollData, this)
|
|
return rollData.rolled;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
_appliquerExperienceRollData(rollData) {
|
|
const callback = this.createCallbackExperience();
|
|
if (callback.condition(rollData)) {
|
|
callback.action(rollData);
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async rollCompetence(name) {
|
|
let rollData = { competence: Misc.data(this.getCompetence(name)) }
|
|
|
|
//console.log("COMP CREATURE", name, rollData, name);
|
|
if (rollData.competence.type == 'competencecreature') {
|
|
if (rollData.competence.data.iscombat) {
|
|
const arme = RdDItemCompetenceCreature.toArme(rollData.competence);
|
|
RdDCombat.createUsingTarget(this).attaque(rollData.competence, arme);
|
|
return;
|
|
}
|
|
//console.log("COMP CREATURE2");
|
|
// Fake competence pour créature
|
|
RdDItemCompetenceCreature.setRollDataCreature(rollData);
|
|
}
|
|
else {
|
|
rollData.carac = Misc.templateData(this).carac;
|
|
}
|
|
console.log("rollCompetence !!!", rollData);
|
|
|
|
const dialog = await RdDRoll.create(this, rollData, { html: 'systems/foundryvtt-reve-de-dragon/templates/dialog-competence.html' }, {
|
|
name: 'jet-competence',
|
|
label: 'Jet ' + Grammar.apostrophe('de', name),
|
|
callbacks: [
|
|
this.createCallbackExperience(),
|
|
this.createCallbackAppelAuMoral(),
|
|
{ action: r => this._competenceResult(r) }
|
|
]
|
|
});
|
|
dialog.render(true);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _competenceResult(rollData) {
|
|
RdDResolutionTable.displayRollData(rollData, this, 'chat-resultat-competence.html')
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async creerTacheDepuisLivre(item, options = { renderSheet: true }) {
|
|
const itemData = Misc.data(item);
|
|
const nomTache = "Lire " + itemData.name;
|
|
const filterTacheLecture = it => it.type == 'tache' && it.name == nomTache;
|
|
let tachesExistantes = this.filterItems(filterTacheLecture);
|
|
if (tachesExistantes.length == 0) {
|
|
const tache = {
|
|
name: nomTache, type: 'tache',
|
|
data: {
|
|
carac: 'intellect',
|
|
competence: 'Ecriture',
|
|
difficulte: itemData.data.difficulte,
|
|
periodicite: "60 minutes",
|
|
fatigue: 2,
|
|
points_de_tache: itemData.data.points_de_tache,
|
|
points_de_tache_courant: 0,
|
|
description: "Lecture du livre " + item.name + " - XP : " + itemData.data.xp + " - Compétences : " + itemData.data.competence
|
|
}
|
|
}
|
|
await this.createEmbeddedDocuments('Item', [tache], options);
|
|
tachesExistantes = this.filterItems(filterTacheLecture);
|
|
}
|
|
return tachesExistantes.length > 0 ? tachesExistantes[0] : undefined;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async rollTache(id) {
|
|
const actorData = Misc.data(this);
|
|
const tacheData = Misc.data(this.getTache(id));
|
|
const compData = Misc.data(this.getCompetence(tacheData.data.competence));
|
|
compData.data.defaut_carac = tacheData.data.carac; // Patch !
|
|
|
|
let rollData = {
|
|
competence: compData,
|
|
tache: tacheData,
|
|
diffLibre: tacheData.data.difficulte,
|
|
diffConditions: 0,
|
|
use: { libre: false, conditions: true },
|
|
carac: {}
|
|
};
|
|
rollData.carac[tacheData.data.carac] = duplicate(actorData.data.carac[tacheData.data.carac]); // Single carac
|
|
|
|
console.log("rollTache !!!", rollData);
|
|
|
|
const dialog = await RdDRoll.create(this, rollData, { html: 'systems/foundryvtt-reve-de-dragon/templates/dialog-competence.html' }, {
|
|
name: 'jet-competence',
|
|
label: 'Jet de Tâche ' + tacheData.name,
|
|
callbacks: [
|
|
this.createCallbackExperience(),
|
|
this.createCallbackAppelAuMoral(),
|
|
{ action: r => this._tacheResult(r) }
|
|
]
|
|
});
|
|
dialog.render(true);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _tacheResult(rollData) {
|
|
// Mise à jour de la tache
|
|
rollData.appliquerFatigue = ReglesOptionelles.isUsing("appliquer-fatigue");
|
|
rollData.tache = duplicate(rollData.tache);
|
|
rollData.tache.data.points_de_tache_courant += rollData.rolled.ptTache;
|
|
if (rollData.rolled.isETotal) {
|
|
rollData.tache.data.difficulte--;
|
|
}
|
|
this.updateEmbeddedDocuments('Item', [rollData.tache]);
|
|
this.santeIncDec("fatigue", rollData.tache.data.fatigue);
|
|
|
|
RdDResolutionTable.displayRollData(rollData, this, 'chat-resultat-tache.html');
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _rollArt(artData, selected, oeuvre, callBackResult = r => this._resultArt(r)) {
|
|
const actorData = Misc.data(this);
|
|
mergeObject(artData,
|
|
{
|
|
oeuvre: oeuvre,
|
|
art: oeuvre.type,
|
|
competence: duplicate(Misc.data(this.getCompetence(artData.compName ?? oeuvre.data.competence ?? artData.art))),
|
|
diffLibre: - (oeuvre.data.niveau ?? 0),
|
|
diffConditions: 0,
|
|
use: { libre: false, conditions: true },
|
|
selectedCarac: duplicate(actorData.data.carac[selected])
|
|
},
|
|
{ overwrite: false });
|
|
artData.competence.data.defaut_carac = selected;
|
|
if (!artData.forceCarac) {
|
|
artData.forceCarac = {};
|
|
artData.forceCarac[selected] = duplicate(actorData.data.carac[selected]);
|
|
}
|
|
|
|
console.log("rollArt !!!", artData);
|
|
|
|
const dialog = await RdDRoll.create(this, artData,
|
|
{
|
|
html: `systems/foundryvtt-reve-de-dragon/templates/dialog-roll-${oeuvre.type}.html`,
|
|
options: { height: 500, }
|
|
},
|
|
{
|
|
name: `jet-${artData.art}`,
|
|
label: `${artData.verbe} ${oeuvre.name}`,
|
|
callbacks: [
|
|
this.createCallbackExperience(),
|
|
this.createCallbackAppelAuMoral(),
|
|
{ action: r => callBackResult(r) }
|
|
]
|
|
});
|
|
dialog.render(true);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _resultArt(artData) {
|
|
const baseQualite = (artData.rolled.isSuccess ? artData.oeuvre.data.niveau : artData.competence.data.niveau);
|
|
artData.qualiteFinale = Math.min(baseQualite, artData.oeuvre.data.niveau) + artData.rolled.ptQualite;
|
|
|
|
RdDResolutionTable.displayRollData(artData, this.name, `chat-resultat-${artData.art}.html`);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async rollChant(id) {
|
|
const artData = { art: 'chant', verbe: 'Chanter' };
|
|
const oeuvre = duplicate(this.getChant(id));
|
|
await this._rollArt(artData, "ouie", oeuvre);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async rollDanse(id) {
|
|
const actorData = Misc.data(this);
|
|
const artData = { art: 'danse', verbe: 'Danser', forceCarac: {} };
|
|
const oeuvre = duplicate(this.getItemOfType(id, artData.art));
|
|
if (oeuvre.data.agilite) {
|
|
artData.forceCarac['agilite'] = duplicate(actorData.data.carac.agilite);
|
|
}
|
|
if (oeuvre.data.apparence) {
|
|
artData.forceCarac['apparence'] = duplicate(actorData.data.carac.apparence);
|
|
}
|
|
const selectedCarac = this._getCaracDanse(oeuvre);
|
|
await this._rollArt(artData, selectedCarac, oeuvre);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
_getCaracDanse(oeuvre) {
|
|
if (oeuvre.data.agilite) { return "agilite"; }
|
|
else if (oeuvre.data.apparence) { return "apparence"; }
|
|
const compData = Misc.data(this.getCompetence(oeuvre.data.competence));
|
|
return compData.data.defaut_carac;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async rollMusique(id) {
|
|
const artData = { art: 'musique', verbe: 'Jouer' };
|
|
const oeuvre = Misc.data(this.getItemOfType(id, artData.art));
|
|
await this._rollArt(artData, "ouie", oeuvre);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async rollRecetteCuisine(id) {
|
|
const oeuvre = Misc.data(this.getRecetteCuisine(id));
|
|
const artData = {
|
|
verbe: 'Cuisiner',
|
|
compName: 'cuisine',
|
|
proportions: 1,
|
|
ajouterEquipement: false
|
|
};
|
|
await this._rollArt(artData, 'odoratgout', oeuvre, r => this._resultRecetteCuisine(r));
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _resultRecetteCuisine(artData) {
|
|
const baseQualite = (artData.rolled.isSuccess ? artData.oeuvre.data.niveau : artData.competence.data.niveau);
|
|
const sust = artData.oeuvre.data.sust * artData.proportions;
|
|
artData.qualiteFinale = Math.min(baseQualite, artData.oeuvre.data.niveau) + artData.rolled.ptQualite;
|
|
artData.exotismeFinal = Math.min(Math.min(artData.qualiteFinale, artData.oeuvre.data.exotisme ?? 0), 0);
|
|
console.log("OEUVRE", artData.art, artData)
|
|
const platCuisine = {
|
|
name: artData.oeuvre.name,
|
|
type: 'nourritureboisson',
|
|
img: 'systems/foundryvtt-reve-de-dragon/icons/objets/provision_cuite.webp',
|
|
data: {
|
|
"description": artData.oeuvre.data.description,
|
|
"sust": Math.min(sust, 1),
|
|
"qualite": artData.qualiteFinale,
|
|
"exotisme": artData.exotismeFinal,
|
|
"encombrement": 0.1,
|
|
"quantite": Math.max(1, Math.floor(sust)),
|
|
"cout": Math.max(artData.qualiteFinale) * 0.01
|
|
}
|
|
};
|
|
if (artData.ajouterEquipement) {
|
|
await this.createEmbeddedDocuments('Item', [platCuisine]);
|
|
ui.notifications.info(`${platCuisine.data.quantite} rations de ${platCuisine.name} ont été ajoutés à votre équipement`);
|
|
}
|
|
artData.platCuisine = platCuisine;
|
|
RdDResolutionTable.displayRollData(artData, this.name, `chat-resultat-${artData.art}.html`);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async rollJeu(id) {
|
|
const actorData = Misc.data(this);
|
|
const oeuvre = Misc.data(this.getJeu(id));
|
|
|
|
const listCarac = oeuvre.data.caraccomp.toLowerCase().split(/[.,:\/-]/).map(it => it.trim());
|
|
const carac = listCarac.length > 0 ? listCarac[0] : 'chance'
|
|
const artData = {
|
|
art: 'jeu', verbe: 'Jeu',
|
|
use: { libre: true, conditions: true, },
|
|
competence: duplicate(Misc.data(this.getCompetence('jeu'))),
|
|
forceCarac: {}
|
|
};
|
|
listCarac.forEach(c => artData.forceCarac[c] = actorData.data.carac[c]);
|
|
artData.competence.data.niveauReel = artData.competence.data.niveau;
|
|
artData.competence.data.niveau = Math.max(artData.competence.data.niveau, oeuvre.data.base);
|
|
await this._rollArt(artData, carac, oeuvre);
|
|
}
|
|
|
|
async rollOeuvre(id) {
|
|
const artData = { art: 'oeuvre', verbe: 'Interpréter' };
|
|
const oeuvre = duplicate(this.getItemOfType(id, artData.art));
|
|
await this._rollArt(artData, oeuvre.data.default_carac, oeuvre);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async rollMeditation(id) {
|
|
const meditation = duplicate(Misc.data(this.getMeditation(id)));
|
|
const competence = duplicate(Misc.data(this.getCompetence(meditation.data.competence)));
|
|
competence.data.defaut_carac = "intellect"; // Meditation = toujours avec intellect
|
|
let meditationData = {
|
|
competence: competence,
|
|
meditation: meditation,
|
|
conditionMeditation: { isHeure: false, isVeture: false, isComportement: false, isPurification: false },
|
|
diffConditions: 0,
|
|
use: { libre: false, conditions: true, },
|
|
carac: { "intellect": Misc.templateData(this).carac.intellect }
|
|
};
|
|
|
|
const dialog = await RdDRoll.create(this, meditationData,
|
|
{
|
|
html: 'systems/foundryvtt-reve-de-dragon/templates/dialog-roll-meditation.html',
|
|
options: { height: 575, }
|
|
},
|
|
{
|
|
name: 'jet-meditation',
|
|
label: "Jet de méditation",
|
|
callbacks: [
|
|
this.createCallbackExperience(),
|
|
{ condition: r => r.rolled.isEPart, action: r => this._meditationEPart(r) },
|
|
{ action: r => this._meditationResult(r) }
|
|
]
|
|
});
|
|
dialog.render(true);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _meditationResult(meditationData) {
|
|
this.santeIncDec("fatigue", 2);
|
|
|
|
const signeData = RdDItemSigneDraconique.prepareSigneDraconiqueMeditation(meditationData.meditation, meditationData.rolled)
|
|
if (signeData) {
|
|
await this.createEmbeddedDocuments("Item", [signeData]);
|
|
}
|
|
|
|
RdDResolutionTable.displayRollData(meditationData, this.name, 'chat-resultat-meditation.html');
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
_meditationEPart(meditationData) {
|
|
this.updateEmbeddedDocuments('Item', [{ _id: meditation._id, 'data.malus': meditationData.meditation.data.malus - 1 }]);
|
|
}
|
|
|
|
|
|
/* -------------------------------------------- */
|
|
_getSignesDraconiques(coord) {
|
|
const type = TMRUtility.getTMRType(coord);
|
|
return this.listItemsData("signedraconique").filter(it => it.data.typesTMR.includes(type));
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
isResonanceSigneDraconique(coord) {
|
|
return this._getSignesDraconiques(coord).length > 0;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async rollLireSigneDraconique(coord) {
|
|
if (!this.isHautRevant()) {
|
|
ui.notifications.info("Seul un haut rêvant peut lire un signe draconique!");
|
|
return;
|
|
}
|
|
let signes = this._getSignesDraconiques(coord);
|
|
if (signes.length == 0) {
|
|
ui.notifications.info(`Aucun signe draconiques en ${coord} !`);
|
|
return;
|
|
}
|
|
if (this.currentTMR) this.currentTMR.minimize(); // Hide
|
|
|
|
let draconicList = this.getDraconicList()
|
|
.map(draconic => duplicate(Misc.data(draconic)))
|
|
.map(draconic => { draconic.data.defaut_carac = "intellect"; return draconic; });
|
|
|
|
const intellect = Misc.templateData(this).carac.intellect;
|
|
let rollData = {
|
|
carac: { 'intellect': intellect },
|
|
selectedCarac: intellect,
|
|
competence: draconicList[0],
|
|
draconicList: draconicList,
|
|
signe: signes[0],
|
|
signes: signes,
|
|
tmr: TMRUtility.getTMR(coord),
|
|
diffLibre: Misc.data(signes[0]).data.difficulte,
|
|
}
|
|
|
|
const dialog = await RdDRoll.create(this, rollData,
|
|
{
|
|
html: 'systems/foundryvtt-reve-de-dragon/templates/dialog-roll-signedraconique.html',
|
|
options: { height: 600 },
|
|
close: html => { this.currentTMR.maximize() } // Re-display TMR
|
|
},
|
|
{
|
|
name: 'lire-signe-draconique',
|
|
label: 'Lire le signe draconique',
|
|
callbacks: [
|
|
this.createCallbackExperience(),
|
|
{ action: r => this._rollLireSigneDraconique(r) }
|
|
]
|
|
}
|
|
);
|
|
dialog.render(true);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _rollLireSigneDraconique(rollData) {
|
|
const compData = rollData.competence;
|
|
if (!RdDItemCompetence.isDraconic(compData)) {
|
|
ui.notifications.error(`La compétence ${compData.name} n'est pas une compétence draconique`);
|
|
return;
|
|
}
|
|
rollData.xpSort = RdDItemSigneDraconique.getXpSortSigneDraconique(rollData.rolled.code, rollData.signe);
|
|
if (rollData.xpSort > 0) {
|
|
await this.updateEmbeddedDocuments("Item", [{ _id: compData._id, 'data.xp_sort': Misc.toInt(compData.data.xp_sort) + rollData.xpSort }]);
|
|
}
|
|
await this.deleteEmbeddedDocuments("Item", [rollData.signe._id]);
|
|
RdDResolutionTable.displayRollData(rollData, this.name, 'chat-resultat-lecture-signedraconique.html');
|
|
this.currentTMR.close();
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async rollAppelChance(onSuccess = () => { }, onEchec = () => { }) {
|
|
// Stocke si utilisation de la chance
|
|
let rollData = { selectedCarac: this.getCaracByName('chance-actuelle'), surprise: '' };
|
|
const dialog = await RdDRoll.create(this, rollData,
|
|
{ html: 'systems/foundryvtt-reve-de-dragon/templates/dialog-roll-carac.html' },
|
|
{
|
|
name: 'appelChance',
|
|
label: 'Appel à la chance',
|
|
callbacks: [
|
|
this.createCallbackExperience(),
|
|
{ action: r => this._appelChanceResult(r, onSuccess, onEchec) },
|
|
]
|
|
}
|
|
);
|
|
dialog.render(true);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _appelChanceResult(rollData, onSuccess = () => { }, onEchec = () => { }) {
|
|
await RdDResolutionTable.displayRollData(rollData, this, 'chat-resultat-appelchance.html')
|
|
if (rollData.rolled.isSuccess) {
|
|
await this.setFlag('foundryvtt-reve-de-dragon', 'utilisationChance', true);
|
|
await this.chanceActuelleIncDec(-1);
|
|
onSuccess();
|
|
}
|
|
else {
|
|
onEchec();
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async chanceActuelleIncDec(value) {
|
|
const chance = Math.min(this.getChance(), Math.max(this.getChanceActuel() + value, 0));
|
|
await this.updateCompteurValue("chance", chance);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async appelDestinee(onSuccess = () => { }, onEchec = () => { }) {
|
|
let destinee = Misc.templateData(this).compteurs.destinee?.value ?? 0;
|
|
if (destinee > 0) {
|
|
ChatMessage.create({ content: `<span class="rdd-roll-part">${this.name} a fait appel à la Destinée !</span>` });
|
|
destinee--;
|
|
await this.updateCompteurValue("destinee", destinee);
|
|
onSuccess();
|
|
}
|
|
else {
|
|
onEchec();
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
ajustementAstrologique() {
|
|
if (this.isCreature()) {
|
|
return 0;
|
|
}
|
|
const actorData = Misc.data(this);
|
|
// selon l'heure de naissance...
|
|
return game.system.rdd.calendrier.getAjustementAstrologique(actorData.data.heure, this.name);
|
|
}
|
|
/* -------------------------------------------- */
|
|
checkDesirLancinant() {
|
|
let queue = this.filterItemsData(it => it.type == 'queue' || it.type == 'ombre')
|
|
.filter(it => Grammar.toLowerCaseNoAccent(it.name).includes('desir lancinant'));
|
|
return (queue.length > 0);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _appliquerExperience(rolled, caracName, competence) {
|
|
if (!this.isPersonnage()) return;
|
|
// Pas d'XP
|
|
if (!rolled.isPart || rolled.finalLevel >= 0) {
|
|
return undefined;
|
|
}
|
|
if (this.checkDesirLancinant()) {
|
|
// Cas de désir lancinant, pas d'expérience sur particulière
|
|
ChatMessage.create({
|
|
content: `Vous souffrez au moins d'un Désir Lancinant, vous ne pouvez pas gagner d'expérience sur une Particulière tant que le désir n'est pas assouvi`,
|
|
whisper: ChatMessage.getWhisperRecipients(game.user.name)
|
|
});
|
|
return undefined;
|
|
}
|
|
if (caracName == 'Vie') caracName = 'constitution';
|
|
if (caracName == 'derobee') caracName = 'agilite';
|
|
if (caracName == 'reve-actuel') caracName = 'reve';
|
|
|
|
let xp = Math.abs(rolled.finalLevel);
|
|
// impair: arrondi inférieur en carac
|
|
let xpCarac = competence ? Math.floor(xp / 2) : Math.max(Math.floor(xp / 2), 1);
|
|
|
|
let xpData = {
|
|
alias: this.name,
|
|
caracName: caracName, xpCarac: xpCarac,
|
|
competence: competence, xpCompetence: competence ? xp - xpCarac : 0
|
|
};
|
|
|
|
await this._xpCompetence(xpData);
|
|
await this._xpCarac(xpData);
|
|
return xpData;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _xpCompetence(xpData) {
|
|
if (xpData.competence) {
|
|
const newXp = Misc.toInt(xpData.competence.data.xp) + xpData.xpCompetence;
|
|
let update = { _id: xpData.competence._id, 'data.xp': newXp };
|
|
await this.updateEmbeddedDocuments('Item', [update]);
|
|
xpData.checkComp = await this.checkCompetenceXP(xpData.competence.name, undefined, false);
|
|
this.updateExperienceLog("XP", xpData.xp, "XP gagné en " + xpData.competence.name);
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async _xpCarac(xpData) {
|
|
if (xpData.xpCarac > 0) {
|
|
let carac = duplicate(Misc.templateData(this).carac);
|
|
let selectedCarac = RdDActor._findCaracByName(carac, xpData.caracName);
|
|
if (!selectedCarac.derivee) {
|
|
selectedCarac.xp = Misc.toInt(selectedCarac.xp) + xpData.xpCarac;
|
|
await this.update({ "data.carac": carac });
|
|
xpData.checkCarac = await this.checkCaracXP(selectedCarac.label, false);
|
|
this.updateExperienceLog("XP", xpData.xpCarac, "XP gagné en " + xpData.caracName);
|
|
} else {
|
|
xpData.caracRepartitionManuelle = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async resetNombreAstral(data) {
|
|
let toDelete = this.listItemsData('nombreastral');
|
|
const deletions = toDelete.map(it => it._id);
|
|
await this.deleteEmbeddedDocuments("Item", deletions);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async ajouteNombreAstral(data) {
|
|
// Gestion expérience (si existante)
|
|
data.competence = Misc.data(this.getCompetence("astrologie"));
|
|
data.selectedCarac = Misc.templateData(this).carac["vue"];
|
|
this.appliquerAjoutExperience(data, false);
|
|
|
|
// Ajout du nombre astral
|
|
const item = {
|
|
name: "Nombre Astral", type: "nombreastral", data:
|
|
{ value: data.nbAstral, istrue: data.isvalid, jourindex: Number(data.date), jourlabel: game.system.rdd.calendrier.getDateFromIndex(Number(data.date)) }
|
|
};
|
|
await this.createEmbeddedDocuments("Item", [item]);
|
|
|
|
// Suppression des anciens nombres astraux
|
|
let toDelete = this.listItemsData('nombreastral').filter(it => it.data.jourindex < game.system.rdd.calendrier.getCurrentDayIndex());
|
|
const deletions = toDelete.map(it => it._id);
|
|
await this.deleteEmbeddedDocuments("Item", deletions);
|
|
|
|
// Affichage Dialog
|
|
this.astrologieNombresAstraux();
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async astrologieNombresAstraux() {
|
|
// Afficher l'interface spéciale
|
|
const astrologieDialog = await RdDAstrologieJoueur.create(this, {});
|
|
astrologieDialog.render(true);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
getCaracByName(caracName) {
|
|
switch (Grammar.toLowerCaseNoAccent(caracName)) {
|
|
case 'reve-actuel': case 'reve actuel':
|
|
return {
|
|
label: 'Rêve actuel',
|
|
value: this.getReveActuel(),
|
|
type: "number"
|
|
};
|
|
case 'chance-actuelle': case 'chance-actuelle':
|
|
return {
|
|
label: 'Chance actuelle',
|
|
value: this.getChanceActuel(),
|
|
type: "number"
|
|
};
|
|
}
|
|
return RdDActor._findCaracByName(Misc.templateData(this).carac, caracName);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
static _findCaracByName(carac, name) {
|
|
name = Grammar.toLowerCaseNoAccent(name);
|
|
switch (name) {
|
|
case 'reve-actuel': case 'rêve actuel':
|
|
return carac.reve;
|
|
case 'chance-actuelle': case 'chance actuelle':
|
|
return carac.chance;
|
|
}
|
|
const keys = Object.entries(carac)
|
|
.filter(it => it[0].includes(name) || Grammar.toLowerCaseNoAccent(it[1].label).includes(name))
|
|
.map(it => it[0]);
|
|
if (keys.length > 1) {
|
|
const names = keys.reduce((a, b) => `${a}<br>${b}`);
|
|
ui.notifications.info(`Plusieurs caractéristiques possibles:<br>${names}<br>La première sera choisie.`);
|
|
}
|
|
if (keys.length > 0) {
|
|
return carac[keys[0]];
|
|
}
|
|
return undefined; // Per default
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
getSortList() {
|
|
return this.listItemsData("sort");
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
countMonteeLaborieuse() { // Return +1 par queue/ombre/souffle Montée Laborieuse présente
|
|
let countMonteeLaborieuse = this.filterItemsData(it => EffetsDraconiques.isMonteeLaborieuse(it)).length;
|
|
if (countMonteeLaborieuse > 0) {
|
|
ChatMessage.create({
|
|
content: `Vous êtes sous le coup d'une Montée Laborieuse : vos montées en TMR coûtent ${countMonteeLaborieuse} Point de Rêve de plus.`,
|
|
whisper: ChatMessage.getWhisperRecipients(game.user.name)
|
|
});
|
|
}
|
|
return countMonteeLaborieuse;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
refreshTMRView(tmrData) {
|
|
if (this.currentTMR) {
|
|
this.currentTMR.externalRefresh(tmrData)
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async displayTMR(mode = "normal") {
|
|
if (this.tmrApp) {
|
|
ui.notifications.warn("Vous êtes déja dans les TMR....");
|
|
return
|
|
}
|
|
let demiReve = this.listeEffets(it => it.label == "Demi-rêve");
|
|
if (mode != 'visu' && demiReve.length > 0) {
|
|
ui.notifications.warn("Le joueur ou le MJ est déja dans les Terres Médianes avec ce personnage ! Visualisation uniquement");
|
|
mode = "visu"; // bascule le mode en visu automatiquement
|
|
}
|
|
|
|
let isRapide = mode == "rapide";
|
|
if (mode != "visu") {
|
|
let minReveValue = (isRapide && !EffetsDraconiques.isDeplacementAccelere(this) ? 3 : 2) + this.countMonteeLaborieuse();
|
|
if (this.getReveActuel() < minReveValue) {
|
|
ChatMessage.create({
|
|
content: `Vous n'avez les ${minReveValue} Points de Reve nécessaires pour monter dans les Terres Médianes`,
|
|
whisper: ChatMessage.getWhisperRecipients(game.user.name)
|
|
});
|
|
return;
|
|
}
|
|
await this.setStatusDemiReve(true);
|
|
}
|
|
|
|
const actorData = Misc.data(this);
|
|
const fatigue = actorData.data.sante.fatigue.value;
|
|
const endurance = actorData.data.sante.endurance.max;
|
|
let tmrFormData = {
|
|
mode: mode,
|
|
fatigue: RdDUtility.calculFatigueHtml(fatigue, endurance),
|
|
draconic: this.getDraconicList(),
|
|
sort: this.getSortList(),
|
|
signes: this.listItemsData("signedraconique"),
|
|
caracReve: actorData.data.carac.reve.value,
|
|
pointsReve: this.getReveActuel(),
|
|
isRapide: isRapide
|
|
}
|
|
|
|
let html = await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/dialog-tmr.html', tmrFormData);
|
|
this.currentTMR = await RdDTMRDialog.create(html, this, tmrFormData);
|
|
this.currentTMR.render(true);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
rollArme(compName, armeName = undefined) {
|
|
let arme = armeName ? this.data.items.find(it => Misc.data(it).name == armeName && RdDItemArme.isArme(it)) : undefined;
|
|
let competence = Misc.data(this.getCompetence(compName));
|
|
|
|
if (arme || armeName || (competence.type == 'competencecreature' && competence.data.iscombat)) {
|
|
RdDCombat.createUsingTarget(this)?.attaque(competence, arme);
|
|
} else {
|
|
this.rollCompetence(competence.name);
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
_getTarget() {
|
|
if (game.user.targets && game.user.targets.size == 1) {
|
|
for (let target of game.user.targets) {
|
|
return target;
|
|
}
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
getArmeParade(armeParadeId) {
|
|
const item = armeParadeId ? this.getEmbeddedDocument('Item', armeParadeId) : undefined;
|
|
return RdDItemArme.getArmeData(item);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
verifierForceMin(itemData) {
|
|
const actorData = Misc.data(this);
|
|
if (itemData.type == 'arme' && itemData.data.force > actorData.data.carac.force.value) {
|
|
ChatMessage.create({
|
|
content: `<strong>${this.name} s'est équipé(e) de l'arme ${itemData.name}, mais n'a pas une force suffisante pour l'utiliser normalement </strong>
|
|
(${itemData.data.force} nécessaire pour une Force de ${actorData.data.carac.force.value})`
|
|
});
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async equiperObjet(itemID) {
|
|
let item = this.getEmbeddedDocument('Item', itemID);
|
|
let itemData = Misc.data(item);
|
|
if (itemData?.data) {
|
|
const isEquipe = !itemData.data.equipe;
|
|
let update = { _id: item.id, "data.equipe": isEquipe };
|
|
await this.updateEmbeddedDocuments('Item', [update]);
|
|
this.computeEncombrementTotalEtMalusArmure(); // Mise à jour encombrement
|
|
this.computePrixTotalEquipement(); // Mis à jour du prix total de l'équipement
|
|
if (isEquipe)
|
|
this.verifierForceMin(itemData);
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async computeArmure(attackerRoll) {
|
|
let dmg = (attackerRoll.dmg.dmgArme ?? 0) + (attackerRoll.dmg.dmgActor ?? 0);
|
|
let armeData = attackerRoll.arme;
|
|
let protection = 0;
|
|
const armures = this.items.map(it => Misc.data(it))
|
|
.filter(it => it.type == "armure" && it.data.equipe);
|
|
for (const itemData of armures) {
|
|
protection += await RdDDice.rollTotal(itemData.data.protection.toString());
|
|
if (dmg > 0) {
|
|
this._deteriorerArmure(itemData, dmg);
|
|
dmg = 0;
|
|
}
|
|
}
|
|
const penetration = Misc.toInt(armeData?.data.penetration ?? 0);
|
|
protection = Math.max(protection - penetration, 0);
|
|
protection += this.getProtectionNaturelle();
|
|
// Gestion des cas particuliers sur la fenêtre d'encaissement
|
|
if (attackerRoll.dmg.encaisserSpecial && attackerRoll.dmg.encaisserSpecial == "noarmure") {
|
|
protection = 0;
|
|
}
|
|
if (attackerRoll.dmg.encaisserSpecial && attackerRoll.dmg.encaisserSpecial == "chute" && Number(protection) > 2) {
|
|
protection = 2;
|
|
}
|
|
console.log("Final protect", protection, attackerRoll);
|
|
return protection;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
_deteriorerArmure(item, dmg) {
|
|
if (!ReglesOptionelles.isUsing('deteriorationArmure')) {
|
|
return;
|
|
}
|
|
let itemData = duplicate(Misc.data(item));
|
|
itemData.data.deterioration = (itemData.data.deterioration ?? 0) + dmg;
|
|
if (itemData.data.deterioration >= 10) {
|
|
itemData.data.deterioration = 0;
|
|
let res = /\d+/.exec(itemData.data.protection);
|
|
if (!res) {
|
|
itemData.data.protection = "1d" + itemData.data.protection;
|
|
}
|
|
else if (res = /(\d+d\d+)(\-\d+)?/.exec(itemData.data.protection)) {
|
|
let malus = Misc.toInt(res[2]) - 1;
|
|
itemData.data.protection = res[1] + malus;
|
|
}
|
|
else {
|
|
ui.notifications.warn(`La valeur d'armure de votre ${item.name} est incorrecte`);
|
|
}
|
|
ChatMessage.create({ content: "Votre armure s'est détériorée, elle protège maintenant de " + itemData.data.protection });
|
|
}
|
|
this.updateEmbeddedDocuments('Item', [itemData]);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async encaisser() {
|
|
let data = { ajustementsEncaissement: RdDUtility.getAjustementsEncaissement() };
|
|
let html = await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/dialog-roll-encaisser.html', data);
|
|
new RdDEncaisser(html, this).render(true);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async encaisserDommages(rollData, attacker = undefined, defenderRoll = undefined) {
|
|
if (attacker && !await attacker.accorder(this, 'avant-encaissement')) {
|
|
return;
|
|
}
|
|
|
|
console.log("encaisserDommages", rollData)
|
|
|
|
let santeOrig = duplicate(Misc.templateData(this).sante);
|
|
let encaissement = await this.jetEncaissement(rollData);
|
|
|
|
this.ajouterBlessure(encaissement); // Will upate the result table
|
|
const perteVie = this.isEntiteCauchemar()
|
|
? { newValue: 0 }
|
|
: await this.santeIncDec("vie", - encaissement.vie);
|
|
const perteEndurance = await this.santeIncDec("endurance", -encaissement.endurance, { critiques: encaissement.critiques > 0 });
|
|
|
|
this.computeEtatGeneral();
|
|
|
|
const actorData = Misc.data(this);
|
|
mergeObject(encaissement, {
|
|
alias: this.name,
|
|
hasPlayerOwner: this.hasPlayerOwner,
|
|
resteEndurance: actorData.data.sante.endurance.value,
|
|
sonne: perteEndurance.sonne,
|
|
jetEndurance: perteEndurance.jetEndurance,
|
|
endurance: santeOrig.endurance.value - perteEndurance.newValue,
|
|
vie: this.isEntiteCauchemar() ? 0 : (santeOrig.vie.value - perteVie.newValue),
|
|
show: defenderRoll?.show ?? {}
|
|
});
|
|
|
|
ChatUtility.createChatWithRollMode(this.name, {
|
|
roll: encaissement.roll,
|
|
content: await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/chat-resultat-encaissement.html', encaissement)
|
|
});
|
|
|
|
if (!encaissement.hasPlayerOwner && encaissement.endurance != 0) {
|
|
encaissement = duplicate(encaissement);
|
|
encaissement.isGM = true;
|
|
ChatMessage.create({
|
|
whisper: ChatMessage.getWhisperRecipients("GM"),
|
|
content: await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/chat-resultat-encaissement.html', encaissement)
|
|
});
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async jetEncaissement(rollData) {
|
|
const roll = await RdDDice.roll("2d10", { showDice: true });
|
|
|
|
const armure = await this.computeArmure(rollData);
|
|
const jetTotal = roll.total + rollData.dmg.total - armure;
|
|
|
|
let encaissement = RdDUtility.selectEncaissement(jetTotal, rollData.dmg.mortalite)
|
|
let over20 = Math.max(jetTotal - 20, 0);
|
|
encaissement.dmg = rollData.dmg;
|
|
encaissement.dmg.loc = rollData.dmg.loc ?? await RdDUtility.getLocalisation(this.data.type);
|
|
encaissement.dmg.loc.label = encaissement.dmg.loc.label ?? 'Corps;'
|
|
encaissement.roll = roll;
|
|
encaissement.armure = armure;
|
|
encaissement.total = jetTotal;
|
|
encaissement.vie = await RdDActor._evaluatePerte(encaissement.vie, over20);
|
|
encaissement.endurance = await RdDActor._evaluatePerte(encaissement.endurance, over20);
|
|
encaissement.penetration = rollData.arme?.data.penetration ?? 0;
|
|
|
|
return encaissement;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
static async _evaluatePerte(formula, over20) {
|
|
let perte = new Roll(formula, { over20: over20 });
|
|
await perte.evaluate({ async: true });
|
|
return perte.total;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
ajouterBlessure(encaissement) {
|
|
const actorData = Misc.data(this);
|
|
if (actorData.type == 'entite') return; // Une entité n'a pas de blessures
|
|
if (encaissement.legeres + encaissement.graves + encaissement.critiques == 0) return;
|
|
|
|
const endActuelle = Number(actorData.data.sante.endurance.value);
|
|
let blessures = duplicate(actorData.data.blessures);
|
|
|
|
let count = encaissement.legeres;
|
|
// Manage blessures
|
|
while (count > 0) {
|
|
let legere = blessures.legeres.liste.find(it => !it.active);
|
|
if (legere) {
|
|
this._setBlessure(legere, encaissement);
|
|
count--;
|
|
}
|
|
else {
|
|
encaissement.graves += count;
|
|
encaissement.legeres -= count;
|
|
break;
|
|
}
|
|
}
|
|
|
|
count = encaissement.graves;
|
|
while (count > 0) {
|
|
let grave = blessures.graves.liste.find(it => !it.active);
|
|
if (grave) {
|
|
this._setBlessure(grave, encaissement);
|
|
count--;
|
|
}
|
|
else {
|
|
encaissement.critiques += count;
|
|
encaissement.graves -= count;
|
|
encaissement.endurance = -endActuelle;
|
|
encaissement.vie = -4;
|
|
break;
|
|
}
|
|
}
|
|
|
|
count = encaissement.critiques;
|
|
while (count > 0) {
|
|
let critique = blessures.critiques.liste[0];
|
|
if (!critique.active) {
|
|
this._setBlessure(critique, encaissement);
|
|
count--;
|
|
} else {
|
|
// TODO: status effect dead
|
|
this.addStatusEffectById('dead');
|
|
ChatMessage.create({
|
|
content: `<img class="chat-icon" src="icons/svg/skull.svg" alt="charge" />
|
|
<strong>${this.name} vient de succomber à une seconde blessure critique ! Que les Dragons gardent son Archétype en paix !</strong>`
|
|
});
|
|
encaissement.critiques -= count;
|
|
encaissement.mort = true;
|
|
break;
|
|
}
|
|
}
|
|
|
|
encaissement.endurance = Math.max(encaissement.endurance, -endActuelle);
|
|
this.update({ "data.blessures": blessures });
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
_setBlessure(blessure, encaissement) {
|
|
blessure.active = true;
|
|
blessure.loc = encaissement.locName;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
/** @override */
|
|
getRollData() {
|
|
const data = super.getRollData();
|
|
return data;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async resetItemUse() {
|
|
await this.unsetFlag('foundryvtt-reve-de-dragon', 'itemUse');
|
|
await this.setFlag('foundryvtt-reve-de-dragon', 'itemUse', {});
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async incDecItemUse(itemId, inc = 1) {
|
|
let itemUse = duplicate(this.getFlag('foundryvtt-reve-de-dragon', 'itemUse') ?? {});
|
|
itemUse[itemId] = (itemUse[itemId] ?? 0) + inc;
|
|
await this.setFlag('foundryvtt-reve-de-dragon', 'itemUse', itemUse);
|
|
console.log("ITEM USE INC", inc, itemUse);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
getItemUse(itemId) {
|
|
let itemUse = this.getFlag('foundryvtt-reve-de-dragon', 'itemUse') ?? {};
|
|
console.log("ITEM USE GET", itemUse);
|
|
return itemUse[itemId] ?? 0;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
/* -- entites -- */
|
|
/* retourne true si on peut continuer, false si on ne peut pas continuer */
|
|
async targetEntiteNonAccordee(target, when = 'avant-encaissement') {
|
|
if (target) {
|
|
return !await this.accorder(target.actor, when);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async accorder(entite, when = 'avant-encaissement') {
|
|
if (when != game.settings.get("foundryvtt-reve-de-dragon", "accorder-entite-cauchemar")
|
|
|| !entite.isEntiteCauchemar()
|
|
|| entite.isEntiteCauchemarAccordee(this)) {
|
|
return true;
|
|
}
|
|
const tplData = Misc.templateData(this);
|
|
let rolled = await RdDResolutionTable.roll(this.getReveActuel(), - Number(tplData.carac.niveau.value));
|
|
const rollData = {
|
|
alias: this.name,
|
|
rolled: rolled,
|
|
entite: entite.name,
|
|
selectedCarac: tplData.carac.reve
|
|
};
|
|
|
|
if (rolled.isSuccess) {
|
|
await entite.setEntiteReveAccordee(this);
|
|
}
|
|
|
|
await RdDResolutionTable.displayRollData(rollData, this, 'chat-resultat-accorder-cauchemar.html');
|
|
if (rolled.isPart) {
|
|
await this.appliquerAjoutExperience(rollData, true);
|
|
}
|
|
return rolled.isSuccess;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
isEntiteCauchemar() {
|
|
return this.data.type == 'entite';
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
isEntiteCauchemarAccordee(attaquant) {
|
|
if (!this.isEntiteCauchemar()) { return true; }
|
|
let resonnance = Misc.templateData(this).sante.resonnance;
|
|
return (resonnance.actors.find(it => it == attaquant._id));
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async setEntiteReveAccordee(attaquant) {
|
|
if (!this.isEntiteCauchemar()) {
|
|
ui.notifications.error("Impossible de s'accorder à " + this.name + ": ce n'est pas une entite de cauchemer/rêve");
|
|
return;
|
|
}
|
|
let resonnance = duplicate(Misc.templateData(this).sante.resonnance);
|
|
if (resonnance.actors.find(it => it == attaquant._id)) {
|
|
// déjà accordé
|
|
return;
|
|
}
|
|
resonnance.actors.push(attaquant._id);
|
|
await this.update({ "data.sante.resonnance": resonnance });
|
|
return;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
getFortune() {
|
|
let monnaies = Monnaie.filtrerMonnaies(this.data.items);
|
|
if (monnaies.length < 4) {
|
|
ui.notifications.error("Problème de monnaies manquantes, impossible de payer correctement!")
|
|
return 0;
|
|
}
|
|
return monnaies.map(m => Misc.templateData(m))
|
|
.map(tpl => tpl.valeur_deniers * Number(tpl.quantite))
|
|
.reduce(Misc.sum(), 0);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async optimizeArgent(fortuneTotale) {
|
|
let monnaies = Monnaie.filtrerMonnaies(this.data.items);
|
|
let parValeur = Misc.classifyFirst(monnaies, it => Misc.templateData(it).valeur_deniers);
|
|
let nouvelleFortune = {
|
|
1000: Math.floor(fortuneTotale / 1000), // or
|
|
100: Math.floor(fortuneTotale / 100) % 10, // argent
|
|
10: Math.floor(fortuneTotale / 10) % 10, // bronze
|
|
1: fortuneTotale % 10 // étain
|
|
}
|
|
let updates = []
|
|
for (const [valeur, nombre] of Object.entries(nouvelleFortune)) {
|
|
updates.push({ _id: parValeur[valeur]._id, 'data.quantite': nombre });
|
|
}
|
|
await this.updateEmbeddedDocuments('Item', updates);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async depenserDeniers(depense, dataObj = undefined, quantite = 1, toActorId) {
|
|
depense = Number(depense);
|
|
let fortune = this.getFortune();
|
|
console.log("depenserDeniers", game.user.character, depense, fortune);
|
|
let msg = "";
|
|
if (depense == 0) {
|
|
if (dataObj) {
|
|
dataObj.payload.data.cout = depense / 100; // Mise à jour du prix en sols , avec le prix acheté
|
|
dataObj.payload.data.quantite = quantite;
|
|
await this.createEmbeddedDocuments('Item', [dataObj.payload]);
|
|
msg += `<br>L'objet <strong>${dataObj.payload.name}</strong> a été ajouté gratuitement à votre inventaire.`;
|
|
}
|
|
}
|
|
else {
|
|
if (fortune >= depense) {
|
|
fortune -= depense;
|
|
const toActor = game.actors.get(toActorId)
|
|
await toActor?.ajouterDeniers(depense, this.id);
|
|
await this.optimizeArgent(fortune);
|
|
msg = `Vous avez payé <strong>${depense} Deniers</strong>${toActor ? " à " + toActor.name : ''}, qui ont été soustraits de votre argent.`;
|
|
RdDAudio.PlayContextAudio("argent"); // Petit son
|
|
|
|
if (dataObj) {
|
|
dataObj.payload.data.cout = depense / 100; // Mise à jour du prix en sols , avec le prix acheté
|
|
dataObj.payload.data.quantite = quantite;
|
|
await this.createEmbeddedDocuments('Item', [dataObj.payload]);
|
|
msg += `<br>Et l'objet <strong>${dataObj.payload.name}</strong> a été ajouté à votre inventaire.`;
|
|
}
|
|
} 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 depenser(depense) {
|
|
depense = Number(depense);
|
|
let fortune = this.getFortune();
|
|
let reste = fortune - depense;
|
|
if (reste >= 0) {
|
|
fortune -= depense;
|
|
await this.optimizeArgent(fortune);
|
|
}
|
|
return reste;
|
|
}
|
|
|
|
async ajouterDeniers(gain, fromActorId = undefined) {
|
|
if (fromActorId && !game.user.isGM) {
|
|
RdDActor.remoteActorCall({ userId: Misc.connectedGMOrUser(), actorId: this.id, method: 'ajouterDeniers', args: [gain, fromActorId] });
|
|
}
|
|
else {
|
|
const fromActor = game.actors.get(fromActorId)
|
|
let fortune = this.getFortune();
|
|
fortune += Number(gain);
|
|
await this.optimizeArgent(fortune);
|
|
|
|
RdDAudio.PlayContextAudio("argent"); // Petit son
|
|
ChatMessage.create({
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(this.name),
|
|
content: `Vous avez reçu <strong>${gain} Deniers</strong> ${fromActor ? " de " + fromActor.name : ''}, qui ont été ajoutés à votre argent.`
|
|
});
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async monnaieIncDec(id, value) {
|
|
let monnaie = this.getMonnaie(id);
|
|
if (monnaie) {
|
|
const quantite = Math.max(0, Misc.templateData(monnaie).quantite + value);
|
|
await this.updateEmbeddedDocuments('Item', [{ _id: monnaie.id, 'data.quantite': quantite }]);
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async achatVente(achat) {
|
|
if (achat.vendeurId == achat.acheteurId) {
|
|
ui.notifications.info("Inutile de se vendre à soi-même");
|
|
return;
|
|
}
|
|
if (!Misc.isElectedUser()) {
|
|
RdDActor.remoteActorCall({
|
|
actorId: achat.vendeurId ?? achat.acheteurId,
|
|
method: 'achatVente', args: [achat]
|
|
});
|
|
return;
|
|
}
|
|
|
|
const acheteur = achat.acheteurId ? game.actors.get(achat.acheteurId) : undefined;
|
|
const vendeur = achat.vendeurId ? game.actors.get(achat.vendeurId) : undefined;
|
|
const messageVente = game.messages.get(achat.chatMessageIdVente);
|
|
const html = await messageVente.getHTML();
|
|
const buttonAcheter = html.find(".button-acheter")[0];
|
|
const vente = DialogItemAchat.prepareVenteData(buttonAcheter, achat.vendeurId, vendeur, acheteur);
|
|
const itemId = vente.item._id;
|
|
|
|
const coutDeniers = Math.floor((achat.prixTotal ?? 0) * 100);
|
|
achat.quantiteTotal = (achat.nombreLots ?? 1) * (vente.tailleLot);
|
|
if (acheteur) {
|
|
let resteAcheteur = await acheteur.depenser(coutDeniers);
|
|
if (resteAcheteur < 0) {
|
|
ui.notifications.warn(`Vous n'avez pas assez d'argent pour payer ${vente.prixTotal} sols !`);
|
|
return;
|
|
}
|
|
}
|
|
const itemVendu = vendeur?.getObjet(itemId);
|
|
if (itemVendu) {
|
|
let itemVenduData = Misc.data(itemVendu);
|
|
if ("quantite" in itemVenduData.data ? itemVenduData.data.quantite < achat.quantiteTotal : achat.nombreLots != 1) {
|
|
await acheteur?.ajouterDeniers(coutDeniers);
|
|
ui.notifications.warn(`Le vendeur n'a plus assez de ${vente.item.name} !`);
|
|
return;
|
|
}
|
|
vendeur.ajouterDeniers(coutDeniers);
|
|
let resteQuantite = (itemVenduData.data.quantite ?? 1) - achat.quantiteTotal;
|
|
if (resteQuantite == 0) {
|
|
vendeur.deleteEmbeddedDocuments("Item", itemId);
|
|
}
|
|
else {
|
|
vendeur.updateEmbeddedDocuments("Item", [{ _id: itemId, 'data.quantite': resteQuantite }]);
|
|
}
|
|
}
|
|
if (acheteur) {
|
|
const achatData = {
|
|
type: vente.item.type,
|
|
img: vente.item.img,
|
|
name: vente.item.name,
|
|
data: vente.item.data
|
|
}
|
|
achatData.data.quantite = achat.quantiteTotal;
|
|
await acheteur.createEmbeddedDocuments("Item", [achatData]);
|
|
}
|
|
if (coutDeniers > 0) {
|
|
RdDAudio.PlayContextAudio("argent");
|
|
}
|
|
|
|
ChatMessage.create({
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(this.name),
|
|
content: await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/chat-achat-item.html', vente)
|
|
});
|
|
|
|
if (!vente.quantiteIllimite) {
|
|
if (vente.quantiteNbLots <= achat.nombreLots) {
|
|
ChatUtility.removeChatMessageId(chatMessageIdVente);
|
|
}
|
|
else {
|
|
vente["properties"] = new RdDItem(vente.item).getProprietes();
|
|
vente.quantiteNbLots -= achat.nombreLots;
|
|
vente.jsondata = JSON.stringify(vente.item);
|
|
messageVente.update({ content: await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/chat-vente-item.html', vente) });
|
|
messageVente.render(true);
|
|
}
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async effectuerTacheAlchimie(recetteId, tacheAlchimie, texteTache) {
|
|
let recetteData = Misc.data(this.getItemOfType(recetteId, 'recettealchimique'));
|
|
const actorData = Misc.data(this);
|
|
if (recetteData) {
|
|
if (tacheAlchimie != "couleur" && tacheAlchimie != "consistance") {
|
|
ui.notifications.warn(`L'étape alchimique ${tacheAlchimie} - ${texteTache} est inconnue`);
|
|
return;
|
|
}
|
|
|
|
const sansCristal = tacheAlchimie == "couleur" && this.data.items.filter(it => it.isCristalAlchimique()).length == 0;
|
|
const caracTache = RdDAlchimie.getCaracTache(tacheAlchimie);
|
|
const alchimieData = Misc.data(this.getCompetence("alchimie"));
|
|
|
|
let rollData = {
|
|
recette: recetteData,
|
|
carac: { [caracTache]: actorData.data.carac[caracTache] },
|
|
selectedCarac: actorData.data.carac[caracTache],
|
|
competence: alchimieData,
|
|
diffLibre: RdDAlchimie.getDifficulte(texteTache),
|
|
diffConditions: sansCristal ? -4 : 0,
|
|
alchimie: {
|
|
tache: Misc.upperFirst(tacheAlchimie),
|
|
texte: texteTache,
|
|
sansCristal: sansCristal
|
|
}
|
|
}
|
|
rollData.competence.data.defaut_carac = caracTache;
|
|
|
|
const dialog = await RdDRoll.create(this, rollData,
|
|
{
|
|
html: 'systems/foundryvtt-reve-de-dragon/templates/dialog-roll-alchimie.html',
|
|
},
|
|
{
|
|
name: 'tache-alchimique',
|
|
label: 'Tache Alchimique',
|
|
callbacks: [
|
|
this.createCallbackExperience(),
|
|
this.createCallbackAppelAuMoral(),
|
|
{ action: r => this._alchimieResult(r, false) }
|
|
]
|
|
}
|
|
);
|
|
dialog.render(true);
|
|
}
|
|
}
|
|
|
|
isCristalAlchimique(it) {
|
|
return it.type == 'objet' && Grammar.toLowerCaseNoAccent(it.name) == 'cristal alchimique' && it.data.quantite > 0;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
_alchimieResult(rollData) {
|
|
RdDResolutionTable.displayRollData(rollData, this, 'chat-resultat-alchimie.html');
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
listeVehicules() {
|
|
const listeVehichules = Misc.templateData(this).subacteurs?.vehicules ?? [];
|
|
return this._buildActorLinksList(listeVehichules, vehicle => RdDActor._vehicleData(vehicle));
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
listeSuivants() {
|
|
return this._buildActorLinksList(Misc.templateData(this).subacteurs?.suivants ?? []);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
listeMontures() {
|
|
return this._buildActorLinksList(Misc.templateData(this).subacteurs?.montures ?? []);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
_buildActorLinksList(links, actorTransformation = it => RdDActor._buildActorData(it)) {
|
|
return links.map(link => game.actors.get(link.id))
|
|
.filter(it => it != null)
|
|
.map(actorTransformation);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
static _vehicleData(vehicle) {
|
|
const vehicleData = Misc.data(vehicle);
|
|
return {
|
|
id: vehicle.id,
|
|
name: vehicleData.name,
|
|
img: vehicleData.img,
|
|
categorie: vehicleData.data.categorie,
|
|
structure: vehicleData.data.structure,
|
|
};
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
static _buildActorData(it) {
|
|
return { id: it.id, name: it.data.name, img: it.data.img };
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async pushSubacteur(actor, dataArray, dataPath, dataName) {
|
|
let alreadyPresent = dataArray.find(attached => attached.id == actor.data._id);
|
|
if (!alreadyPresent) {
|
|
let newArray = duplicate(dataArray);
|
|
newArray.push({ id: actor.data._id });
|
|
await this.update({ [dataPath]: newArray });
|
|
} else {
|
|
ui.notifications.warn(dataName + " est déja attaché à ce Personnage.");
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
addSubacteur(subActorId) {
|
|
let subActor = game.actors.get(subActorId);
|
|
//console.log("Ajout acteur : ", actor, this);
|
|
if (subActor && subActor.owner) {
|
|
const actorData = Misc.data(this);
|
|
if (subActor.data.type == 'vehicule') {
|
|
this.pushSubacteur(subActor, actorData.data.subacteurs.vehicules, 'data.subacteurs.vehicules', 'Ce Véhicule');
|
|
} else if (subActor.data.type == 'creature') {
|
|
this.pushSubacteur(subActor, actorData.data.subacteurs.montures, 'data.subacteurs.montures', 'Cette Monture');
|
|
} else if (subActor.data.type == 'personnage') {
|
|
this.pushSubacteur(subActor, actorData.data.subacteurs.suivants, 'data.subacteurs.suivants', 'Ce Suivant');
|
|
}
|
|
} else {
|
|
ui.notifications.warn("Vous n'avez pas les droits sur l'acteur que vous attachez.")
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async removeSubacteur(actorId) {
|
|
const actorData = Misc.data(this);
|
|
let newVehicules = actorData.data.subacteurs.vehicules.filter(function (obj, index, arr) { return obj.id != actorId });
|
|
let newSuivants = actorData.data.subacteurs.suivants.filter(function (obj, index, arr) { return obj.id != actorId });
|
|
let newMontures = actorData.data.subacteurs.montures.filter(function (obj, index, arr) { return obj.id != actorId });
|
|
await this.update({ 'data.subacteurs.vehicules': newVehicules });
|
|
await this.update({ 'data.subacteurs.suivants': newSuivants });
|
|
await this.update({ 'data.subacteurs.montures': newMontures });
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async buildPotionGuerisonList(pointsGuerison) {
|
|
let pointsGuerisonInitial = pointsGuerison;
|
|
let myData = Misc.templateData(this);
|
|
const blessures = duplicate(myData.blessures);
|
|
let guerisonData = { list: [], pointsConsommes: 0 }
|
|
|
|
console.log(blessures);
|
|
for (let critique of blessures.critiques.liste) {
|
|
if (critique.active && pointsGuerison >= 6) {
|
|
pointsGuerison -= 6;
|
|
critique.active = false;
|
|
guerisonData.list.push("1 Blessure Critique (6 points)");
|
|
}
|
|
}
|
|
for (let grave of blessures.graves.liste) {
|
|
if (grave.active && pointsGuerison >= 4) {
|
|
pointsGuerison -= 4;
|
|
grave.active = false;
|
|
guerisonData.list.push("1 Blessure Grave (4 points)");
|
|
}
|
|
}
|
|
for (let legere of blessures.legeres.liste) {
|
|
if (legere.active && pointsGuerison >= 2) {
|
|
pointsGuerison -= 2;
|
|
legere.active = false;
|
|
guerisonData.list.push("1 Blessure Légère (2 points)");
|
|
}
|
|
}
|
|
await this.update({ "data.blessures": blessures });
|
|
|
|
let pvManquants = myData.sante.vie.max - myData.sante.vie.value;
|
|
let pvSoignees = Math.min(pvManquants, Math.floor(pointsGuerison / 2));
|
|
pointsGuerison -= pvSoignees * 2;
|
|
guerisonData.list.push(pvSoignees + " Points de Vie soignés");
|
|
await this.santeIncDec('vie', +pvSoignees, false);
|
|
guerisonData.pointsConsommes = pointsGuerisonInitial - pointsGuerison;
|
|
|
|
return guerisonData;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async consommerPotionSoin(potionData) {
|
|
potionData.alias = this.name;
|
|
potionData.supprimer = true;
|
|
|
|
if (potionData.data.magique) {
|
|
ChatMessage.create({
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
|
|
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-consommer-potion-soin.html`, potionData)
|
|
});
|
|
// Gestion de la résistance:
|
|
let rolled = await RdDResolutionTable.roll(this.getReveActuel(), -8);
|
|
potionData.reussiteReve = false;
|
|
if (!rolled.isSuccess) {
|
|
await this.reveActuelIncDec(-1);
|
|
potionData.guerisonData = await this.buildPotionGuerisonList(potionData.data.puissance);
|
|
potionData.guerisonMinutes = potionData.guerisonData.pointsConsommes * 5;
|
|
potionData.reussiteReve = true;
|
|
}
|
|
ChatMessage.create({
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
|
|
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-appliquer-potion-soin.html`, potionData)
|
|
});
|
|
} else {
|
|
ChatMessage.create({
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
|
|
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-appliquer-potion-soin.html`, potionData)
|
|
});
|
|
this.bonusRecuperationPotion = potionData.data.herbeBonus;
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async consommerPotionRepos(potionData) {
|
|
potionData.alias = this.name;
|
|
potionData.supprimer = true;
|
|
|
|
if (potionData.data.magique) {
|
|
ChatMessage.create({
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
|
|
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-consommer-potion-repos.html`, potionData)
|
|
});
|
|
// Gestion de la résistance:
|
|
let rolled = await RdDResolutionTable.roll(this.getReveActuel(), -8);
|
|
potionData.reussiteReve = false;
|
|
if (!rolled.isSuccess) {
|
|
await this.reveActuelIncDec(-1);
|
|
let fatigueActuelle = this.getFatigueActuelle();
|
|
potionData.caseFatigueReel = Math.min(fatigueActuelle, potionData.data.puissance);
|
|
potionData.guerisonDureeUnite = (potionData.data.reposalchimique) ? "rounds" : "minutes";
|
|
potionData.guerisonDureeValue = (potionData.data.reposalchimique) ? potionData.caseFatigueReel : potionData.caseFatigueReel * 5;
|
|
potionData.reussiteReve = true;
|
|
potionData.aphasiePermanente = false;
|
|
if (potionData.data.reposalchimique) {
|
|
let chanceAphasie = await RdDDice.rollTotal("1d100");
|
|
if (chanceAphasie <= potionData.data.pr) {
|
|
potionData.aphasiePermanente = true;
|
|
}
|
|
}
|
|
await this.santeIncDec("fatigue", -potionData.caseFatigueReel);
|
|
}
|
|
ChatMessage.create({
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
|
|
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-appliquer-potion-repos.html`, potionData)
|
|
});
|
|
} else {
|
|
ChatMessage.create({
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
|
|
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-appliquer-potion-repos.html`, potionData)
|
|
});
|
|
this.bonusRepos = potionData.data.herbeBonus;
|
|
}
|
|
}
|
|
/* -------------------------------------------- */
|
|
dialogFabriquerPotion(herbe) {
|
|
DialogFabriquerPotion.create(this, herbe, {
|
|
html: 'systems/foundryvtt-reve-de-dragon/templates/dialog-fabriquer-potion-base.html',
|
|
}, []);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async fabriquerPotion(herbeData) {
|
|
let newPotion = {
|
|
name: `Potion de ${herbeData.data.categorie} (${herbeData.name})`, type: 'potion',
|
|
img: "systems/foundryvtt-reve-de-dragon/icons/objets/fiole_verre.webp",
|
|
data: {
|
|
quantite: 1, valeur_deniers: 1, encombrement: 0.01,
|
|
categorie: herbeData.data.categorie,
|
|
herbe: herbeData.name,
|
|
rarete: herbeData.data.rarete,
|
|
herbebrins: herbeData.nbBrins,
|
|
description: ""
|
|
}
|
|
}
|
|
await this.createEmbeddedDocuments('Item', [newPotion], { renderSheet: true });
|
|
|
|
let newQuantite = herbeData.data.quantite - herbeData.nbBrins;
|
|
let messageData = {
|
|
alias: this.name,
|
|
categorie: herbeData.data.categorie,
|
|
herbe: herbeData.name,
|
|
nbBrinsPotion: herbeData.nbBrins,
|
|
nbBrinsReste: newQuantite
|
|
}
|
|
this.diminuerQuantiteObjet(herbeData._id, herbeData.nbBrins);
|
|
|
|
ChatMessage.create({
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
|
|
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-fabriquer-potion-base.html`, messageData)
|
|
});
|
|
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async diminuerQuantiteObjet(id, nb, options = { supprimerSiZero: false }) {
|
|
const item = this.getObjet(id);
|
|
if (item) {
|
|
await item.diminuerQuantite(nb, options);
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async consommerPotionGenerique(potionData) {
|
|
potionData.alias = this.name;
|
|
|
|
ChatMessage.create({
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
|
|
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-consommer-potion-generique.html`, potionData)
|
|
});
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async consommerPotion(potion) {
|
|
const potionData = Misc.data(potion);
|
|
|
|
if (potionData.data.categorie.includes('Soin')) {
|
|
this.consommerPotionSoin(potionData);
|
|
} else if (potionData.data.categorie.includes('Repos')) {
|
|
this.consommerPotionRepos(potionData);
|
|
} else {
|
|
this.consommerPotionGenerique(potionData);
|
|
}
|
|
this.diminuerQuantiteObjet(potion.id, 1, { supprimerSiZero: potionData.supprimer });
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async onUpdateActor(update, options, actorId) {
|
|
const updatedEndurance = update?.data?.sante?.endurance;
|
|
if (updatedEndurance && options.diff) {
|
|
this.forceStatusEffectId('unconscious', updatedEndurance.value == 0);
|
|
}
|
|
}
|
|
/* -------------------------------------------- */
|
|
async onCreateActiveEffect(effect, options) {
|
|
switch (StatusEffects.statusId(effect)) {
|
|
case 'sonne':
|
|
await this.setStateSonne(true);
|
|
return;
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async onDeleteActiveEffect(effect, options) {
|
|
switch (StatusEffects.statusId(effect)) {
|
|
case 'sonne':
|
|
await this.setStateSonne(false);
|
|
return;
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
enleverTousLesEffets() {
|
|
const ids = Array.from(this.effects?.keys() ?? []);
|
|
this.deleteEmbeddedDocuments('ActiveEffect', ids);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
listeEffets(matching = it => true) {
|
|
const all = Array.from(this.effects?.values() ?? []);
|
|
const filtered = all.filter(it => matching(it.data));
|
|
return filtered;
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async setStatusDemiReve(status) {
|
|
const demiReve = StatusEffects.demiReve();
|
|
if (status) {
|
|
await this.addStatusEffect(demiReve)
|
|
} else {
|
|
await this.deleteStatusEffect(demiReve)
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async setStatusSonne(sonne) {
|
|
if (this.isEntiteCauchemar()) {
|
|
return;
|
|
}
|
|
await this.forceStatusEffectId('sonne', sonne);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async forceStatusEffectId(statusId, isSet) {
|
|
if (isSet) {
|
|
await this.addStatusEffectById(statusId);
|
|
}
|
|
else {
|
|
await this.deleteStatusEffectById(statusId);
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async deleteStatusEffectById(id) {
|
|
|
|
const ids = Array.from(this.effects?.values())
|
|
.filter(it => it.data.flags.core?.statusId == id)
|
|
.map(it => it.id);
|
|
console.log("Delete effect IDS1: ", this.effects, ids);
|
|
if (ids.length > 0) {
|
|
await this.deleteEmbeddedDocuments('ActiveEffect', ids);
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async deleteStatusEffect(effect) {
|
|
const ids = Array.from(this.effects?.values())
|
|
.filter(it => StatusEffects.statusId(it.data) == StatusEffects.statusId(effect))
|
|
.map(it => it.id);
|
|
console.log("Delete effect 1: ", this.effects, ids);
|
|
if (ids.length > 0) {
|
|
await this.deleteEmbeddedDocuments('ActiveEffect', ids);
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async addStatusEffectById(id) {
|
|
const statusEffect = CONFIG.statusEffects.find(it => it.id == id);
|
|
await this.addStatusEffect(statusEffect);
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async addStatusEffect(statusEffect) {
|
|
const effet = Misc.data(statusEffect);
|
|
await this.deleteStatusEffectById(effet.id);
|
|
effet.flags = effet.flags ?? { core: {} };
|
|
effet.flags.core.statusId = effet.id;
|
|
let effectArray = await this.createEmbeddedDocuments('ActiveEffect', [effet]);
|
|
//if (effectArray[0]) {
|
|
//await effectArray[0].setFlag('core', 'statusId', effet.id);
|
|
//}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async onPreUpdateItem(item, change, options, id) {
|
|
const itemData = Misc.data(item);
|
|
if (itemData.type == 'competence' && itemData.data.defaut_carac && itemData.data.xp) {
|
|
await this.checkCompetenceXP(itemData.name, itemData.data.xp);
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async onCreateItem(item, options, id) {
|
|
switch (item.type) {
|
|
case 'tete':
|
|
case 'queue':
|
|
case 'ombre':
|
|
case 'souffle':
|
|
await this.onCreateOwnedDraconique(item, options, id);
|
|
break;
|
|
}
|
|
}
|
|
|
|
async onDeleteItem(item, options, id) {
|
|
switch (item.type) {
|
|
case 'tete':
|
|
case 'queue':
|
|
case 'ombre':
|
|
case 'souffle':
|
|
await this.onDeleteOwnedDraconique(item, options, id);
|
|
break;
|
|
case 'casetmr':
|
|
await this.onDeleteOwnedCaseTmr(item, options, id);
|
|
break;
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async onCreateOwnedDraconique(item, options, id) {
|
|
if (Misc.isElectedUser()) {
|
|
let draconique = Draconique.all().find(it => it.match(item));
|
|
if (draconique) {
|
|
draconique.onActorCreateOwned(this, item)
|
|
this.notifyGestionTeteSouffleQueue(item, draconique.manualMessage());
|
|
}
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async onDeleteOwnedDraconique(item, options, id) {
|
|
if (Misc.isElectedUser()) {
|
|
let draconique = Draconique.all().find(it => it.match(item));
|
|
if (draconique) {
|
|
draconique.onActorDeleteOwned(this, item)
|
|
}
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
async onDeleteOwnedCaseTmr(item, options, id) {
|
|
if (Misc.isElectedUser()) {
|
|
let draconique = Draconique.all().find(it => it.isCase(item));
|
|
if (draconique) {
|
|
draconique.onActorDeleteCaseTmr(this, Misc.data(item))
|
|
}
|
|
}
|
|
}
|
|
|
|
/* -------------------------------------------- */
|
|
notifyGestionTeteSouffleQueue(item, manualMessage = true) {
|
|
ChatMessage.create({
|
|
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
|
|
content: `${this.name} a reçu un/une ${item.type}: ${item.name}, qui ${manualMessage ? "n'est pas" : "est"} géré(e) automatiquement. ${manualMessage ? manualMessage : ''}`
|
|
});
|
|
}
|
|
}
|
|
|