foundryvtt-reve-de-dragon/module/actor.js

3735 lines
138 KiB
JavaScript
Raw Normal View History

2020-05-22 22:37:02 +02:00
import { RdDUtility } from "./rdd-utility.js";
2020-07-25 10:29:28 +02:00
import { TMRUtility } from "./tmr-utility.js";
2020-12-06 20:11:30 +01:00
import { RdDRollDialogEthylisme } from "./rdd-roll-ethylisme.js";
import { RdDRoll } from "./rdd-roll.js";
2020-07-05 21:45:25 +02:00
import { RdDTMRDialog } from "./rdd-tmr-dialog.js";
import { Misc } from "./misc.js";
2020-12-11 08:29:24 +01:00
import { RdDAstrologieJoueur } from "./rdd-astrologie-joueur.js";
2020-11-12 16:35:51 +01:00
import { RdDResolutionTable } from "./rdd-resolution-table.js";
2020-11-16 04:32:42 +01:00
import { RdDDice } from "./rdd-dice.js";
import { RdDRollTables } from "./rdd-rolltables.js";
import { ChatUtility } from "./chat-utility.js";
2020-12-04 20:52:04 +01:00
import { RdDItemSort } from "./item-sort.js";
2020-12-08 03:04:00 +01:00
import { Grammar } from "./grammar.js";
import { RdDEncaisser } from "./rdd-roll-encaisser.js";
2021-01-26 19:43:37 +01:00
import { RdDCombat } from "./rdd-combat.js";
import { RdDAudio } from "./rdd-audio.js";
2021-01-01 22:25:32 +01:00
import { RdDItemCompetence } from "./item-competence.js";
import { RdDItemArme } from "./item-arme.js";
2021-01-07 20:04:10 +01:00
import { RdDAlchimie } from "./rdd-alchimie.js";
import { StatusEffects } from "./status-effects.js";
import { RdDItemCompetenceCreature } from "./item-competencecreature.js";
2021-01-26 19:43:37 +01:00
import { ReglesOptionelles } from "./regles-optionelles.js";
2021-02-06 23:58:15 +01:00
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";
2021-03-19 22:20:01 +01:00
import { Monnaie } from "./item-monnaie.js";
2021-04-06 23:44:57 +02:00
import { DialogConsommer } from "./dialog-consommer.js";
2021-04-10 21:07:53 +02:00
import { DialogFabriquerPotion } from "./dialog-fabriquer-potion.js";
2020-05-22 22:37:02 +02:00
2020-12-31 00:55:02 +01:00
/* -------------------------------------------- */
2020-12-15 23:54:05 +01:00
/**
* Extend the base Actor entity by defining a custom roll data structure which is ideal for the Simple system.
* @extends {Actor}
*/
2020-05-22 00:48:43 +02:00
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));
2021-03-29 20:11:32 +02:00
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);
}
}
static remoteActorCall(options) {
console.log("remoteActorCall ", options)
options.userId = options.userId ?? Misc.connectedGMOrUser();
game.socket.emit("system.foundryvtt-reve-de-dragon", { msg: "msg_remote_actor_call", data: options });
}
static onRemoteActorCall(data) {
if (game.user.id == data.userId) { // 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
}
2020-05-24 20:19:57 +02:00
/* -------------------------------------------- */
/**
* Override the create() function to provide additional RdD functionality.
*
* This overrided create() function adds initial items
* Namely: Basic skills, money,
2020-05-24 20:19:57 +02:00
*
* @param {Object} actorData Barebones actor data which this function adds onto.
2020-05-24 20:19:57 +02:00
* @param {Object} options (Unused) Additional options which customize the creation workflow.
*
*/
2021-01-09 19:33:19 +01:00
static async create(actorData, options) {
2020-11-18 16:33:12 +01:00
// Case of compendium global import
if (actorData instanceof Array) {
return super.create(actorData, options);
}
2021-03-19 22:20:01 +01:00
const isPersonnage = actorData.type == "personnage";
2020-05-24 20:19:57 +02:00
// If the created actor has items (only applicable to duplicated actors) bypass the new actor creation logic
if (actorData.items) {
let actor = super.create(actorData, options);
2021-03-19 22:20:01 +01:00
if (isPersonnage) {
await actor.checkMonnaiePresence(actorData.items);
}
return actor;
2020-05-24 20:19:57 +02:00
}
2021-01-09 19:33:19 +01:00
const competences = await RdDUtility.loadCompendium(RdDItemCompetence.actorCompendium(actorData.type));
2021-05-01 19:12:55 +02:00
actorData.items = competences.map(i => i.toObject());
2021-03-19 22:20:01 +01:00
if (isPersonnage) {
actorData.items = actorData.items.concat(Monnaie.monnaiesData());
2021-01-09 19:33:19 +01:00
}
return super.create(actorData, options);
2020-09-20 16:36:39 +02:00
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
2020-05-22 00:48:43 +02:00
prepareData() {
super.prepareData();
const actorData = this.data;
2020-05-22 19:28:01 +02:00
// Dynamic computing fields
2020-12-20 21:54:09 +01:00
this.encTotal = 0;
2021-01-29 23:17:18 +01:00
this.prixTotalEquipement = 0;
/*
// Auto-resize token
if (this.isToken) {
let tokenSize = actorData.data.carac.taille.value/10;
this.token.update({height: tokenSize, width: tokenSize } );
}*/
2021-01-09 19:33:19 +01:00
2020-05-22 00:48:43 +02:00
// 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);
}
/* -------------------------------------------- */
2021-03-15 00:05:56 +01:00
setRollWindowsOpened(flag) {
this.rollWindowsOpened = flag;
}
/* -------------------------------------------- */
2021-03-15 00:05:56 +01:00
isRollWindowsOpened() {
return this.rollWindowsOpened;
}
/* -------------------------------------------- */
_prepareCreatureData(actorData) {
this.computeEncombrementTotalEtMalusArmure();
this.computeEtatGeneral();
2020-05-22 00:48:43 +02:00
}
2021-01-10 22:12:07 +01:00
/* -------------------------------------------- */
_prepareVehiculeData(actorData) {
2021-01-10 22:12:07 +01:00
this.computeEncombrementTotalEtMalusArmure();
}
2020-06-03 21:35:18 +02:00
/* -------------------------------------------- */
2020-05-22 00:48:43 +02:00
/**
* Prepare Character type specific data
*/
2021-01-01 21:11:56 +01:00
async _prepareCharacterData(actorData) {
2020-05-24 20:19:57 +02:00
// Initialize empty items
RdDCarac.computeCarac(actorData.data);
this.computeIsHautRevant();
2021-04-20 00:49:01 +02:00
await this.computeEncombrementTotalEtMalusArmure();
2021-01-29 23:17:18 +01:00
this.computePrixTotalEquipement();
2020-06-07 23:16:29 +02:00
this.computeEtatGeneral();
// Sanity check
2021-01-07 11:42:36 +01:00
await this.checkMonnaiePresence(actorData.items);
2020-05-22 00:48:43 +02:00
}
2020-12-31 00:55:02 +01:00
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async checkMonnaiePresence(items) { // Ajout opportuniste si les pièces n'existent pas.
if (!items) return; // Sanity check during import
2021-03-19 22:20:01 +01:00
let manquantes = Monnaie.monnaiesManquantes(items);
if (manquantes.length > 0) {
2021-03-25 03:18:27 +01:00
await this.createEmbeddedDocuments('Item', manquantes, { renderSheet: false });
}
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
isCreature() {
return this.data.type == 'creature' || this.data.type == 'entite';
}
2020-12-18 23:57:28 +01:00
/* -------------------------------------------- */
isPersonnage() {
return this.data.type == 'personnage';
}
/* -------------------------------------------- */
isHautRevant() {
return Misc.templateData(this).attributs.hautrevant.value != ""
}
/* -------------------------------------------- */
getFatigueActuelle() {
if (!this.isPersonnage()) {
return 0;
}
return Misc.toInt(Misc.templateData(this).sante.fatigue?.value);
}
/* -------------------------------------------- */
getFatigueMax() {
if (!this.isPersonnage()) {
return 1;
}
return Misc.toInt(Misc.templateData(this).sante.fatigue?.max);
}
2020-07-14 22:19:29 +02:00
/* -------------------------------------------- */
2020-11-16 04:01:36 +01:00
getReveActuel() {
const templateData = Misc.templateData(this);
return Misc.toInt(templateData.reve?.reve?.value ?? templateData.carac.reve.value);
2020-07-14 22:19:29 +02:00
}
/* -------------------------------------------- */
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);
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
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);
}
2021-01-29 23:17:18 +01:00
getPrixTotalEquipement() {
2021-04-01 21:31:13 +02:00
return Math.floor(Misc.templateData(this).prixTotalEquipement ?? 0);
2021-01-29 23:17:18 +01:00
}
2021-01-09 19:33:19 +01:00
getSurenc() {
return Misc.templateData(this).compteurs.surenc?.value ?? 0;
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
2021-01-31 19:37:21 +01:00
getCompetence(name) {
return RdDItemCompetence.findCompetence(this.data.items, name);
2021-01-09 19:33:19 +01:00
}
/* -------------------------------------------- */
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);
}
getItemOfType(id, type) {
return id ? this.data.items.find(it => it.id == id && Misc.data(it).type == type) : undefined;
}
2021-03-29 18:08:18 +02:00
getMonnaie(id) {
return this.getItemOfType(id, 'monnaie');
}
2021-01-09 19:33:19 +01:00
getTache(id) {
return this.getItemOfType(id, 'tache');
}
2021-01-09 19:33:19 +01:00
getMeditation(id) {
return this.getItemOfType(id, 'meditation');
}
2021-01-27 23:35:45 +01:00
getChant(id) {
return this.getItemOfType(id, 'chant');
2021-01-27 23:35:45 +01:00
}
getDanse(id) {
return this.getItemOfType(id, 'danse');
2021-01-27 23:35:45 +01:00
}
getMusique(id) {
return this.getItemOfType(id, 'musique');
2021-01-27 23:35:45 +01:00
}
getOeuvre(id, type = 'oeuvre') {
return this.getItemOfType(id, type);
}
2021-01-27 23:35:45 +01:00
getJeu(id) {
return this.getItemOfType(id, 'jeu');
2021-01-27 23:35:45 +01:00
}
getRecetteCuisine(id) {
return this.getItemOfType(id, 'recettecuisine');
2021-01-27 23:35:45 +01:00
}
2020-07-14 22:19:29 +02:00
/* -------------------------------------------- */
2021-03-29 18:08:18 +02:00
getDraconicList() {
return this.items.filter(it => Misc.data(it).type == 'competence' && Misc.templateData(it).categorie == 'draconic')
2021-04-24 00:50:20 +02:00
.sort(Misc.descending(it => Misc.templateData(it).niveau));
2021-03-29 18:08:18 +02:00
}
/* -------------------------------------------- */
2020-07-14 22:19:29 +02:00
getBestDraconic() {
2021-04-24 00:50:20 +02:00
const list = this.getDraconicList();
2021-01-09 19:33:19 +01:00
if (list.length == 0) {
2021-04-24 00:50:20 +02:00
return { name: "Aucun", data: { name: "Aucun", data: { niveau: 0 } } };
2021-01-09 19:33:19 +01:00
}
return duplicate(list[0]);
2021-01-09 19:33:19 +01:00
}
2021-02-28 01:50:46 +01:00
getDemiReve() {
return Misc.templateData(this).reve.tmrpos.coord;
2021-02-28 01:50:46 +01:00
}
2021-04-11 18:43:32 +02:00
2021-04-09 15:23:48 +02:00
/* -------------------------------------------- */
async verifierPotionsEnchantees() {
2021-04-12 00:16:23 +02:00
let potionsEnchantees = this.filterItemsData(it => it.type == 'potion' && it.data.isEnchante);
2021-04-11 18:43:32 +02:00
for (let potion of potionsEnchantees) {
if (!potion.prpermanent) {
2021-04-09 15:23:48 +02:00
console.log(potion);
let newPr = (potion.data.pr > 0) ? potion.data.pr - 1 : 0;
2021-04-11 18:43:32 +02:00
let update = { _id: potion._id, 'data.pr': newPr };
2021-04-09 15:23:48 +02:00
const updated = await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
let messageData = {
2021-04-11 18:43:32 +02:00
pr: newPr,
alias: this.name,
potionName: potion.name,
potionImg: potion.img
2021-04-09 15:23:48 +02:00
}
ChatMessage.create({
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-potionenchantee-chateaudormant.html`, messageData)
});
}
}
}
2020-07-26 18:44:03 +02:00
/* -------------------------------------------- */
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'
2021-03-15 00:05:56 +01:00
? sort => (TMRUtility.getTMR(sort.coord).type == 'fleuve' && sort.sort.name == sortReserve.sort.name)
: sort => (sort.coord == sortReserve.coord && sort.sort.name == sortReserve.sort.name)
);
2021-03-15 00:05:56 +01:00
if (index >= 0) {
reserve.list.splice(index, 1);
2021-01-09 19:33:19 +01:00
await this.update({ "data.reve.reserve": reserve });
2020-07-26 18:44:03 +02:00
}
}
2021-01-09 19:33:19 +01:00
2020-12-14 10:38:43 +01:00
/* -------------------------------------------- */
2021-01-31 19:37:21 +01:00
getSurprise(isCombat = undefined) {
let niveauSurprise = Array.from(this.effects?.values() ?? [])
.map(effect => StatusEffects.valeurSurprise(effect.data, isCombat))
2021-03-29 18:08:18 +02:00
.reduce(Misc.sum(), 0);
if (niveauSurprise > 1) {
return 'totale';
}
if (niveauSurprise == 1 || this.getSonne()) {
return 'demi';
}
return '';
}
2020-12-04 20:52:04 +01:00
/* -------------------------------------------- */
async dormirChateauDormant() {
2021-01-09 19:33:19 +01:00
let message = {
whisper: ChatUtility.getWhisperRecipientsAndGMs(this.name),
content: ""
};
2020-12-19 01:14:02 +01:00
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);
2020-12-27 20:23:14 +01:00
await this._recupererBlessures(message, "critique", blessures.critiques.liste.filter(b => b.active), blessures.graves.liste);
2021-01-09 19:33:19 +01:00
await this.update({ "data.blessures": blessures });
await this._recupererVie(message);
2021-01-29 01:03:16 +01:00
await this.jetDeMoral('neutre');
2021-03-20 00:09:29 +01:00
await this._recupereChance();
await this.transformerStress();
await this.retourSeuilDeReve(message);
2021-04-11 18:43:32 +02:00
this.bonusRecuperationPotion = 0; // Reset potion
2021-04-06 23:44:57 +02:00
await this.retourSust(message);
2021-04-09 15:23:48 +02:00
await this.verifierPotionsEnchantees();
2021-03-20 00:09:29 +01:00
message.content = `A la fin Chateau Dormant, ${message.content}<br>Un nouveau jour se lève`;
ChatMessage.create(message);
}
2021-03-20 00:09:29 +01:00
async _recupereChance() {
// On ne récupère un point de chance que si aucun appel à la chance dans la journée
2021-03-30 23:01:09 +02:00
if (this.getChanceActuel() < this.getChance() && !this.getFlag('foundryvtt-reve-de-dragon', 'utilisationChance')) {
await this.chanceActuelleIncDec(1);
}
2021-03-30 23:01:09 +02:00
// Nouveau jour, suppression du flag
await this.unsetFlag('foundryvtt-reve-de-dragon', 'utilisationChance');
}
2020-12-04 20:52:04 +01:00
/* -------------------------------------------- */
async _recupererBlessures(message, type, liste, moindres) {
2021-04-04 23:07:13 +02:00
if (!this.bonusRecuperationPotion) this.bonusRecuperationPotion = 0;
let count = 0;
const definitions = RdDUtility.getDefinitionsBlessures();
2021-01-09 19:33:19 +01:00
let definition = definitions.find(d => d.type == type);
for (let blessure of liste) {
if (blessure.jours >= definition.facteur) {
2021-04-11 18:43:32 +02:00
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)) {
2021-01-09 19:33:19 +01:00
message.content += ` -- une blessure ${type} cicatrise`;
count++;
}
else if (rolled.isETotal) {
2021-01-09 19:33:19 +01:00
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 {
2021-01-09 19:33:19 +01:00
message.content += ` -- une blessure ${type} reste stable`;
}
}
else {
blessure.jours++;
}
}
}
/* -------------------------------------------- */
2021-01-09 19:33:19 +01:00
_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;
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
_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;
2021-01-09 19:33:19 +01:00
if (nbBlessures == 0 && vieManquante > 0) {
let bonusSoins = 0;
2021-01-09 19:33:19 +01:00
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);
2021-01-09 19:33:19 +01:00
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);
}
2021-01-09 19:33:19 +01:00
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() {
2021-01-09 19:33:19 +01:00
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);
}
}
2021-01-09 19:33:19 +01:00
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 (actorData.data.sante.fatigue) {
2021-03-20 00:09:29 +01:00
await this.update({ "data.sante.fatigue.value": 0 });
}
}
2021-01-09 19:33:19 +01:00
ChatMessage.create(message);
}
2020-11-17 16:30:03 +01:00
/* -------------------------------------------- */
2021-04-23 02:47:59 +02:00
async dormir(heures) {
2021-01-09 19:33:19 +01:00
let message = {
whisper: ChatUtility.getWhisperRecipientsAndGMs(this.name),
2021-03-15 00:05:56 +01:00
content: `${this.name}: Vous dormez ${heures == 1 ? 'une' : heures} heure${heures == 1 ? '' : 's'}.`
};
await this.recupereEndurance(message);
2021-01-09 19:33:19 +01:00
for (let i = 0; i < heures; i++) {
2020-12-19 01:14:02 +01:00
await this._recupererEthylisme(message);
await this.recupererFatigue(message);
2021-04-23 02:47:59 +02:00
await this.recuperationReve(message, 1);
if (EffetsDraconiques.isDonDoubleReve(this)) {
2021-04-23 02:47:59 +02:00
await this.recuperationReve(message, 2);
2021-02-03 20:39:52 +01:00
}
2020-11-16 04:32:42 +01:00
}
2021-01-09 19:33:19 +01:00
ChatMessage.create(message);
2020-11-16 04:32:42 +01:00
}
2021-01-11 20:42:10 +01:00
/* -------------------------------------------- */
2020-12-19 01:14:02 +01:00
async _recupererEthylisme(message) {
let ethylisme = duplicate(Misc.templateData(this).compteurs.ethylisme);
ethylisme.nb_doses = 0;
ethylisme.jet_moral = false;
2021-01-09 19:33:19 +01:00
if (ethylisme.value < 1) {
2020-12-19 01:14:02 +01:00
ethylisme.value = Math.min(ethylisme.value + 1, 1);
if (ethylisme.value <= 0) {
2021-02-06 23:53:14 +01:00
message.content += `Vous dégrisez un peu (${RdDUtility.getNomEthylisme(ethylisme.value)}). `;
2020-12-19 01:14:02 +01:00
}
}
await this.update({ "data.compteurs.ethylisme": ethylisme });
2020-12-19 01:14:02 +01:00
}
2020-11-17 16:30:03 +01:00
/* -------------------------------------------- */
async recupereEndurance(message) {
const manquant = this._computeEnduranceMax() - Misc.templateData(this).sante.endurance.value;
if (manquant > 0) {
await this.santeIncDec("endurance", manquant);
2021-02-06 23:53:14 +01:00
message.content += "Vous récuperez " + manquant + " points d'endurance. ";
2020-11-17 13:08:52 +01:00
}
}
2020-11-17 16:30:03 +01:00
/* -------------------------------------------- */
async recupererFatigue(message) {
let fatigue = Misc.templateData(this).sante.fatigue.value;
const fatigueMin = this._computeFatigueMin();
2021-03-20 00:09:29 +01:00
if (fatigue <= fatigueMin) {
2021-02-06 23:53:14 +01:00
message.content += "Vous êtes déjà reposé. ";
2020-11-17 13:08:52 +01:00
return;
}
2021-03-20 00:09:29 +01:00
fatigue = Math.max(fatigueMin, this._calculRecuperationSegment(fatigue));
console.log("recupererFatigue", fatigue)
2021-03-20 00:09:29 +01:00
await this.update({ "data.sante.fatigue.value": fatigue });
if (fatigue == 0) {
2021-02-06 23:53:14 +01:00
message.content += "Vous êtes complêtement reposé. ";
}
}
2020-11-21 08:27:28 +01:00
/* -------------------------------------------- */
2021-01-09 19:33:19 +01:00
_calculRecuperationSegment(actuel) {
const segments = RdDUtility.getSegmentsFatigue(Misc.templateData(this).sante.endurance.max);
2020-11-17 13:08:52 +01:00
let cumul = 0;
let i;
2021-01-09 19:33:19 +01:00
for (i = 0; i < 11; i++) {
2020-11-17 13:08:52 +01:00
cumul += segments[i];
let diff = cumul - actuel;
2021-01-09 19:33:19 +01:00
if (diff >= 0) {
2020-11-17 13:08:52 +01:00
const limit2Segments = Math.floor(segments[i] / 2);
if (diff > limit2Segments && i > 0) {
2021-01-09 19:33:19 +01:00
cumul -= segments[i - 1]; // le segment est à moins de la moitié, il est récupéré
2020-11-16 04:32:42 +01:00
}
2020-11-17 13:08:52 +01:00
cumul -= segments[i];
break;
}
};
return cumul;
2020-11-17 13:08:52 +01:00
}
2020-11-17 16:30:03 +01:00
/* -------------------------------------------- */
2021-04-23 02:47:59 +02:00
async recuperationReve(message, demiHeure) {
const seuil = Misc.templateData(this).reve.seuil.value;
const reveActuel = this.getReveActuel();
if (reveActuel >= seuil) {
2021-04-23 02:47:59 +02:00
if (demiHeure == 1) {
message.content += `Vous avez suffisament rêvé, au delà de votre seuil. `;
}
2020-11-17 13:08:52 +01:00
}
else {
2021-04-29 02:57:56 +02:00
let deRecuperation = new Roll("1dr + 7").evaluate().total;
2020-11-17 13:08:52 +01:00
console.log("recuperationReve", deRecuperation);
2021-01-09 19:33:19 +01:00
if (deRecuperation >= 7) {
2020-11-17 13:08:52 +01:00
// Rêve de Dragon !
2021-02-06 23:53:14 +01:00
message.content += `Vous faites un <strong>Rêve de Dragon</strong> de ${deRecuperation} Points de rêve! `;
await this.combattreReveDeDragon(deRecuperation);
2020-11-16 04:32:42 +01:00
}
2021-01-09 19:33:19 +01:00
else {
2021-02-06 23:53:14 +01:00
message.content += `Vous récupérez ${deRecuperation} Points de rêve. `;
await this.reveActuelIncDec(deRecuperation);
2020-11-17 13:08:52 +01:00
}
}
2020-11-16 04:32:42 +01:00
}
/* -------------------------------------------- */
async retourSeuilDeReve(message) {
const seuil = Misc.templateData(this).reve.seuil.value;
const reveActuel = this.getReveActuel();
if (reveActuel > seuil) {
2021-01-09 19:33:19 +01:00
message.content += `<br>Votre rêve redescend vers son seuil naturel (${seuil}, nouveau rêve actuel ${(reveActuel - 1)})`;
await this.reveActuelIncDec(-1);
}
}
2020-11-16 04:32:42 +01:00
2021-04-06 23:44:57 +02:00
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);
}
2020-11-17 16:30:03 +01:00
/* -------------------------------------------- */
2021-01-09 19:33:19 +01:00
async combattreReveDeDragon(force) {
2021-02-06 23:58:15 +01:00
let rollData = {
actor: this,
competence: duplicate(this.getBestDraconic()),
canClose: false,
rencontre: duplicate(TMRRencontres.getRencontre('rdd')),
tmr: true,
use: { libre: false, conditions: false },
2021-02-06 23:58:15 +01:00
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,
{
2021-02-06 23:58:15 +01:00
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);
}
2021-04-04 22:34:59 +02:00
/* -------------------------------------------- */
2021-02-06 23:58:15 +01:00
async resultCombatReveDeDragon(rollData) {
rollData.queues = [];
if (rollData.rolled.isEchec) {
2021-03-29 18:08:18 +02:00
rollData.queues.push(Misc.data(await this.ajouterQueue()));
2021-02-06 23:58:15 +01:00
}
if (rollData.rolled.isETotal) {
2021-03-29 18:08:18 +02:00
rollData.queues.push(Misc.data(await this.ajouterQueue()));
2021-02-06 23:58:15 +01:00
}
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 = 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)
});
2020-11-16 04:32:42 +01:00
}
/* -------------------------------------------- */
async sortMisEnReserve(rollData, sort) {
let reserve = duplicate(Misc.templateData(this).reve.reserve.list);
2021-03-20 00:09:29 +01:00
reserve.push({ coord: rollData.tmr.coord, sort: sort, draconic: duplicate(rollData.competence) });
await this.update({ "data.reve.reserve.list": reserve });
this.currentTMR.updateTokens();
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async updateCarac(caracName, caracValue) {
2021-01-14 20:51:32 +01:00
if (caracName == "force") {
if (Number(caracValue) > this.getTaille() + 4) {
2021-01-14 20:51:32 +01:00
ui.notifications.warn("Votre FORCE doit être au maximum de TAILLE+4");
return;
}
}
2021-03-30 23:01:09 +02:00
const tplData = Misc.templateData(this);
if (caracName == "reve") {
2021-03-30 23:01:09 +02:00
if (caracValue > Misc.toInt(tplData.reve.seuil.value)) {
this.setPointsDeSeuil(caracValue);
2020-11-16 04:32:42 +01:00
}
}
if (caracName == "chance") {
2021-03-30 23:01:09 +02:00
if (caracValue > Misc.toInt(tplData.compteurs.chance.value)) {
this.setPointsDeChance(caracValue);
}
}
await this.update({ [`data.carac.${caracName}.value`]: caracValue });
2020-05-24 20:19:57 +02:00
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async updateCaracXP(caracName, caracXP) {
if (caracName == 'Taille') {
return;
}
await this.update({ [`data.carac.${caracName}.xp`]: caracXP ?? 0 });
2021-01-09 19:33:19 +01:00
this.checkCaracXP(caracName);
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async updateCreatureCompetence(compName, fieldName, compValue) {
let comp = this.getCompetence(compName);
2021-01-09 19:33:19 +01:00
if (comp) {
2021-03-29 18:08:18 +02:00
const update = { _id: comp.id }
2020-09-20 17:38:21 +02:00
if (fieldName == "niveau")
2020-09-20 19:17:31 +02:00
update['data.niveau'] = compValue;
2020-09-20 17:38:21 +02:00
else if (fieldName == "dommages")
2020-09-20 19:17:31 +02:00
update['data.dommages'] = compValue;
2021-01-09 19:33:19 +01:00
else
2020-09-20 19:17:31 +02:00
update['data.carac_value'] = compValue;
const updated = await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
2020-09-20 17:38:21 +02:00
}
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async updateCompetence(compName, compValue) {
let comp = this.getCompetence(compName);
2021-01-09 19:33:19 +01:00
if (comp) {
2021-01-14 23:59:57 +01:00
let troncList = RdDItemCompetence.isTronc(compName);
let nouveauNiveau = compValue ?? RdDItemCompetence.getNiveauBase(Misc.data(comp).data.categorie);
2021-01-09 19:33:19 +01:00
if (troncList) {
2020-09-05 22:56:33 +02:00
let message = "Vous avez modifié une compétence 'tronc'. Vérifiez que les compétences suivantes évoluent ensemble jusqu'au niveau 0 : ";
2021-01-09 19:33:19 +01:00
for (let troncName of troncList) {
2020-09-05 22:56:33 +02:00
message += "<br>" + troncName;
2020-08-13 22:28:56 +02:00
}
2021-01-09 19:33:19 +01:00
ChatMessage.create({
whisper: ChatMessage.getWhisperRecipients(game.user.name),
content: message
});
2020-08-13 22:28:56 +02:00
}
2021-03-29 18:08:18 +02:00
const update = { _id: comp.id, 'data.niveau': nouveauNiveau };
await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
2020-06-12 22:46:04 +02:00
} else {
console.log("Competence not found", compName);
}
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async updateCompetenceXP(compName, compValue) {
let comp = this.getCompetence(compName);
2021-01-09 19:33:19 +01:00
if (comp) {
compValue = compValue ?? 0;
2021-01-14 15:29:47 +01:00
this.checkCompetenceXP(compName, compValue);
2021-03-29 18:08:18 +02:00
const update = { _id: comp.id, 'data.xp': compValue };
await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
2020-06-01 23:50:10 +02:00
} else {
console.log("Competence not found", compName);
}
RdDUtility.checkThanatosXP(compName);
2020-06-01 23:50:10 +02:00
}
2021-01-03 19:19:02 +01:00
/* -------------------------------------------- */
async updateCompetenceXPSort(compName, compValue) {
let comp = this.getCompetence(compName);
if (comp) {
compValue = compValue ?? 0;
2021-03-29 18:08:18 +02:00
const update = { _id: comp.id, 'data.xp_sort': compValue };
await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
} else {
console.log("Competence not found", compName);
2021-02-03 23:27:55 +01:00
}
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async updateCompetenceArchetype(compName, compValue) {
2021-01-03 19:19:02 +01:00
let comp = this.getCompetence(compName);
2021-01-09 19:33:19 +01:00
if (comp) {
compValue = compValue ?? 0;
2021-03-29 18:08:18 +02:00
const update = { _id: comp.id, 'data.niveau_archetype': compValue };
await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
2021-01-03 19:19:02 +01:00
} else {
console.log("Competence not found", compName);
}
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async updateCompteurValue(fieldName, fieldValue) {
await this.update({ [`data.compteurs.${fieldName}.value`]: fieldValue });
2020-08-29 22:52:41 +02:00
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async updateAttributeValue(fieldName, fieldValue) {
await this.update({ [`data.attributs.${fieldName}.value`]: fieldValue });
2020-12-18 01:10:03 +01:00
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
2021-04-14 21:51:29 +02:00
_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);
2021-04-14 21:51:29 +02:00
if (subObjet?.id == conteneur.id) {
return true; // Loop detected !
2021-01-08 09:58:15 +01:00
}
2021-04-14 21:51:29 +02:00
if (subObjet?.isConteneur()) {
return this._isConteneurContenu(subObjet, conteneur);
2021-01-08 09:58:15 +01:00
}
}
}
return false;
2021-01-08 09:58:15 +01:00
}
/* -------------------------------------------- */
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)));
2021-03-29 18:08:18 +02:00
return encContenus.reduce(Misc.sum(), 0)
+ Number(tplData.encombrement) /* TODO? Number(tplData.quantite) -- on pourrait avoir plusieurs conteneurs...*/
}
2021-01-10 02:28:45 +01:00
/* -------------------------------------------- */
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 });
}
}
}
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async deleteAllConteneur(itemId) {
let list = [];
list.push({ id: itemId, conteneurId: undefined }); // Init list
2021-01-09 19:33:19 +01:00
this.buildSubConteneurObjetList(itemId, list);
await this.deleteEmbeddedDocuments('Item', list.map(it => it.id));
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
/** Supprime un item d'un conteneur, sur la base
2020-11-12 14:43:08 +01:00
* de leurs ID */
2021-04-13 22:42:39 +02:00
async enleverDeConteneur(itemId, conteneur) {
if (conteneur?.isConteneur()) { // Si présent
let data2use = duplicate(Misc.data(conteneur));
//console.log("Suppression du conteneur1", conteneurId, itemId, data2use.data.contenu);
2020-11-28 09:59:30 +01:00
let contenu = data2use.data.contenu;
2020-11-28 10:05:53 +01:00
let index = contenu.indexOf(itemId);
while (index >= 0) { // Force cleanup, itemId is unique
contenu.splice(index, 1);
index = contenu.indexOf(itemId);
}
await this.updateEmbeddedDocuments('Item', [data2use]);
2020-11-12 14:43:08 +01:00
}
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
/** Ajoute un item dans un conteneur, sur la base
2020-11-12 14:43:08 +01:00
* de leurs ID */
2021-04-13 22:42:39 +02:00
async ajouterDansConteneur(itemId, conteneur) {
if (conteneur?.isConteneur()) {
let data2use = duplicate(Misc.data(conteneur));
2021-01-09 19:33:19 +01:00
data2use.data.contenu.push(itemId);
await this.updateEmbeddedDocuments('Item', [data2use]);
2020-11-12 14:43:08 +01:00
}
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
2021-01-08 11:56:10 +01:00
/** Fonction de remise à plat de l'équipement (ie vide les champs 'contenu') */
2021-01-09 19:33:19 +01:00
async nettoyerConteneurs() {
let conteneurs = this.items.filter(it => it.type == 'conteneur');
2021-01-08 11:56:10 +01:00
let conteneurFixedList = [];
for (let conteneur of conteneurs) {
if (Misc.templateData(conteneur).contenu.length > 0) {
2021-01-09 19:33:19 +01:00
conteneurFixedList.push({ _id: conteneur._id, 'data.contenu': [] });
2021-01-08 11:56:10 +01:00
}
}
2021-01-09 19:33:19 +01:00
if (conteneurFixedList.length > 0)
await this.updateEmbeddedDocuments('Item', conteneurFixedList);
2021-01-08 11:56:10 +01:00
}
2021-04-13 21:30:02 +02:00
/* -------------------------------------------- */
async processItemDropEvent(event, objetVersConteneur) {
let dragData = JSON.parse(event.dataTransfer.getData("text/plain"));
2021-04-13 22:42:39 +02:00
console.log("DRAG", this.id, dragData);
let itemId = dragData.id || dragData.data._id;
2021-04-13 21:30:02 +02:00
if (dragData.type == 'Item') {
2021-04-13 22:42:39 +02:00
if (dragData.actorId && dragData.actorId != this.id) {
console.log("Moving objects", dragData);
this.moveItemsBetweenActors(itemId, dragData.actorId);
return false;
}
if (dragData.actorId == this.id) {
// rangement
const destId = $(event.target).parents(".item").attr("data-item-id");
const srcId = objetVersConteneur[itemId];
if (srcId != destId && itemId != destId) { // déplacement de l'objet
const item = this.getObjet(itemId);
const dest = this.getObjet(destId);
const src = this.getObjet(srcId);
if (!dest) {
// on peut toujours vider son sac
await this.enleverDeConteneur(itemId, src);
}
else if (!dest.isConteneur()) {
// regrouper?
await this.regrouperEquipementsSimilaires(item, dest);
}
else if (this.conteneurPeutContenir(dest, item)) {
// déplacer?
await this.enleverDeConteneur(itemId, src);
await this.ajouterDansConteneur(itemId, dest);
2021-04-13 21:30:02 +02:00
}
}
}
this.computeEncombrementTotalEtMalusArmure();
2021-04-13 22:42:39 +02:00
}
2021-04-13 21:30:02 +02:00
if (dragData.type == "Actor") {
2021-04-13 22:42:39 +02:00
this.addSubacteur(itemId);
}
return true;
}
conteneurPeutContenir(dest, item) {
const destData = Misc.data(dest);
if (destData?.type != 'conteneur') {
ui.notifications.warn(`Impossible de déplacer un objet (${item.name}) vers un ${destData.type} qui n'est pas un conteneur (${dest.name}) !`);
return false;
}
2021-04-14 21:51:29 +02:00
if (this._isConteneurContenu(item, dest)) {
2021-04-13 22:42:39 +02:00
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;
2021-04-13 21:30:02 +02:00
}
return true;
2021-04-13 22:42:39 +02:00
2021-04-13 21:30:02 +02:00
}
2021-01-10 02:28:45 +01:00
/* -------------------------------------------- */
async moveItemsBetweenActors(itemId, sourceActorId) {
2021-01-09 09:54:08 +01:00
let itemsList = []
let sourceActor = game.actors.get(sourceActorId);
itemsList.push({ id: itemId, conteneurId: undefined }); // Init list
sourceActor.buildSubConteneurObjetList(itemId, itemsList); // Get itemId list
2021-01-10 11:35:11 +01:00
2021-01-22 10:05:30 +01:00
let itemMap = {};
2021-01-10 11:35:11 +01:00
for (let item of itemsList) {
let srcItem = sourceActor.data.items.find(subItem => subItem._id == item.id);
2021-03-25 03:18:27 +01:00
let newItem = await this.createEmbeddedDocuments('Item', [duplicate(srcItem)]);
2021-01-22 10:05:30 +01:00
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
2021-01-10 11:35:11 +01:00
// gestion conteneur/contenu
if (item.conteneurId) { // l'Objet était dans un conteneur
2021-01-22 10:05:30 +01:00
let newConteneurId = itemMap[item.conteneurId]; // Get conteneur
let newConteneur = this.getObjet(newConteneurId);
2021-01-22 10:05:30 +01:00
let newItemId = itemMap[item.id]; // Get newItem
console.log('New conteneur filling!', newConteneur, newItemId, item);
2021-04-13 21:33:05 +02:00
let contenu = duplicate(Misc.templateData(newConteneur).contenu);
contenu.push(newItemId);
await this.updateEmbeddedDocuments('Item', [{ _id: newConteneurId, 'data.contenu': contenu }]);
2021-01-10 11:35:11 +01:00
}
2021-01-09 09:54:08 +01:00
}
for (let item of itemsList) {
await sourceActor.deleteEmbeddedDocuments('Item', [item.id]);
2021-01-09 09:54:08 +01:00
}
}
2021-04-13 22:42:39 +02:00
async regrouperEquipementsSimilaires(item, dest) {
if (item.isEquipementSimilaire(dest)) {
await dest.quantiteIncDec(Misc.templateData(item).quantite);
await this.deleteEmbeddedDocuments('Item', [item.id]);
}
}
2021-01-10 02:28:45 +01:00
/* -------------------------------------------- */
detectSurEncombrement() {
return Math.max(0, Math.ceil(Number(this.encTotal) - this.getEncombrementMax()));
2021-04-01 21:31:13 +02:00
}
2021-04-01 21:31:13 +02:00
getEncombrementMax() {
return (this.data.type == 'vehicule')
? Misc.templateData(this).capacite_encombrement
: Misc.templateData(this).attributs.encombrement.value;
}
/* -------------------------------------------- */
computeIsHautRevant() {
const tplData = Misc.templateData(this);
tplData.attributs.hautrevant.value = this.listItemsData('tete').find(it => Grammar.toLowerCaseNoAccent(it.name) == 'don de haut-reve')
? "Haut rêvant"
: "";
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async computeEncombrementTotalEtMalusArmure() {
2021-04-01 21:31:13 +02:00
await this.computeMalusArmure();
return this.computeEncombrement();
}
2021-03-20 00:09:29 +01:00
2021-04-01 21:31:13 +02:00
/* -------------------------------------------- */
computeEncombrement() {
2021-04-20 00:49:01 +02:00
this.encTotal = this.filterItemsData(it => it.data.encombrement != undefined)
.map(it => it.data.encTotal)
2021-04-01 21:31:13 +02:00
.reduce(Misc.sum(), 0);
2021-04-20 00:49:01 +02:00
return this.encTotal;
2021-04-01 21:31:13 +02:00
}
2021-03-20 00:09:29 +01:00
2021-04-01 21:31:13 +02:00
/* -------------------------------------------- */
async computeMalusArmure() {
const newMalusArmure = this.filterItemsData(it => it.type == 'armure' && it.data.equipe)
.map(it => it.data.malus ?? 0)
.reduce(Misc.sum(), 0);
2020-12-02 14:00:54 +01:00
// Mise à jour éventuelle du malus armure
if (newMalusArmure && Misc.templateData(this).attributs?.malusarmure?.value != newMalusArmure) {
await this.updateAttributeValue("malusarmure", newMalusArmure);
2020-12-02 14:00:54 +01:00
}
2021-04-01 21:31:13 +02:00
return newMalusArmure;
2020-11-11 11:43:13 +01:00
}
2021-01-29 23:17:18 +01:00
/* -------------------------------------------- */
2021-04-01 21:31:13 +02:00
computePrixTotalEquipement() {
2021-04-20 00:49:01 +02:00
this.prixTotalEquipement = this.filterItemsData(it => it.data.prixTotal)
.map(it => it.data.prixTotal ?? 0)
.reduce(Misc.sum(), 0);
2021-01-29 23:17:18 +01:00
// Mise à jour valeur totale de l'équipement
2021-04-20 00:49:01 +02:00
return this.prixTotalEquipement;
2021-01-29 23:17:18 +01:00
}
2020-11-11 11:43:13 +01:00
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
computeResumeBlessure(blessures = undefined) {
blessures = blessures ?? Misc.templateData(this).blessures;
2021-01-09 19:33:19 +01:00
let nbLegeres = this.countBlessures(blessures.legeres.liste);
let nbGraves = this.countBlessures(blessures.graves.liste);
let nbCritiques = this.countBlessures(blessures.critiques.liste);
2020-12-05 02:22:37 +01:00
let resume = "Blessures:";
if (nbCritiques > 0 || nbGraves > 0 || nbLegeres > 0) {
if (nbLegeres > 0) {
2021-03-20 00:09:29 +01:00
resume += " " + nbLegeres + " légère" + (nbLegeres > 1 ? "s" : "");
2020-12-05 02:22:37 +01:00
}
if (nbGraves > 0) {
if (nbLegeres > 0)
resume += ",";
2021-03-20 00:09:29 +01:00
resume += " " + nbGraves + " grave" + (nbGraves > 1 ? "s" : "");
2020-12-05 02:22:37 +01:00
}
if (nbCritiques > 0) {
if (nbGraves > 0 || nbLegeres > 0)
resume += ",";
resume += " une CRITIQUE !";
}
}
else {
2021-03-20 00:09:29 +01:00
resume = "Aucune blessure";
2020-12-05 02:22:37 +01:00
}
return resume;
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
computeEtatGeneral() {
const actorData = Misc.data(this);
// Pas d'état général pour les entités forçage à 0
2021-01-09 19:33:19 +01:00
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 (actorData.data.sante.fatigue) {
// Creatures n'ont pas de fatigue
state += RdDUtility.currentFatigueMalus(actorData.data.sante.fatigue.value, actorData.data.sante.endurance.max);
2021-01-09 19:33:19 +01:00
}
// 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();
2020-12-08 21:40:41 +01:00
}
2020-05-29 00:43:16 +02:00
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async ajouterRefoulement(value = 1) {
let refoulement = Misc.templateData(this).reve.refoulement.value + value;
let total = new Roll("1d20").evaluate({ async: false }).total;
2021-03-20 00:09:29 +01:00
if (total <= refoulement) {
refoulement = 0;
await this.ajouterSouffle({ chat: true });
2020-07-17 22:04:35 +02:00
}
2021-03-20 00:09:29 +01:00
await this.update({ "data.reve.refoulement.value": refoulement });
return refoulement == 0 ? "souffle" : "none";
2020-07-17 22:04:35 +02:00
}
2020-11-16 04:32:42 +01:00
2020-11-17 16:30:03 +01:00
/* -------------------------------------------- */
2021-01-09 19:33:19 +01:00
async ajouterSouffle(options = { chat: false }) {
2020-12-30 11:50:18 +01:00
let souffle = await RdDRollTables.getSouffle();
2021-03-25 03:18:27 +01:00
await this.createEmbeddedDocuments('Item', [souffle]);
2021-01-09 19:33:19 +01:00
if (options.chat) {
ChatMessage.create({
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
content: this.name + " subit un Souffle de Dragon : " + souffle.name
});
}
return souffle;
2020-11-16 04:32:42 +01:00
}
2020-11-17 16:30:03 +01:00
/* -------------------------------------------- */
2021-01-09 19:33:19 +01:00
async ajouterQueue(options = { chat: false }) {
2020-11-16 04:32:42 +01:00
let queue;
2021-03-29 18:08:18 +02:00
if (Misc.data(this).data.reve.reve.thanatosused) {
2020-11-16 04:32:42 +01:00
queue = await RdDRollTables.getOmbre();
2021-03-20 00:09:29 +01:00
await this.update({ "data.reve.reve.thanatosused": false });
2020-11-16 04:32:42 +01:00
}
else {
queue = await RdDRollTables.getQueue();
}
2021-03-25 03:18:27 +01:00
await this.createEmbeddedDocuments('Item', [queue]);
2021-01-09 19:33:19 +01:00
if (options.chat) {
ChatMessage.create({
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
content: this.name + " subit une Queue de Dragon : " + queue.name
});
}
2021-02-06 23:58:15 +01:00
return queue;
2020-11-16 04:32:42 +01:00
}
2021-01-09 19:33:19 +01:00
2021-04-25 10:08:40 +02:00
/* -------------------------------------------- */
async cacheTMR( ) {
await this.update({ 'data.reve.tmrpos.cache': true });
}
async montreTMR( ) {
await this.update({ 'data.reve.tmrpos.cache': false });
}
2021-04-28 00:48:39 +02:00
isTMRCache( ) {
2021-04-25 10:08:40 +02:00
return this.data.data.reve.tmrpos.cache;
}
2021-04-28 00:48:39 +02:00
/* -------------------------------------------- */
async cacheTMRetMessage() {
await this.reinsertionAleatoire();
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
}
});
}
2021-04-25 10:08:40 +02:00
/* -------------------------------------------- */
async reinsertionAleatoire(raison) {
ChatMessage.create({
content: `${raison} : ré-insertion aléatoire.`,
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name)
});
const innaccessible = this.buildTMRInnaccessible();
2021-03-15 00:05:56 +01:00
let tmr = TMRUtility.getTMRAleatoire(tmr => !innaccessible.includes(tmr.coord));
this.updateCoordTMR(tmr.coord);
2021-04-25 10:08:40 +02:00
this.cacheTMR();
return tmr;
}
2021-04-25 10:08:40 +02:00
/* -------------------------------------------- */
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;
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async deleteTMRRencontreAtPosition() {
2021-03-20 00:09:29 +01:00
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 });
2020-07-21 23:51:24 +02:00
}
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async addTMRRencontre(currentRencontre) {
2021-03-20 00:09:29 +01:00
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 });
2020-07-21 23:51:24 +02:00
}
}
2020-11-17 16:30:03 +01:00
/* -------------------------------------------- */
async deleteTMRRencontre(rencontreKey) {
let list = duplicate(Misc.templateData(this).reve.rencontre.list);
let newList = [];
for (let i = 0; i < list.length; i++) {
2021-03-15 00:05:56 +01:00
if (i != rencontreKey)
newList.push(list[i]);
}
await this.update({ "data.reve.rencontre.list": newList });
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async updateCoordTMR(coord) {
2021-05-02 21:08:50 +02:00
console.log("UPDATE TMR", coord);
2021-02-28 01:50:46 +01:00
await this.update({ "data.reve.tmrpos.coord": coord });
2020-11-17 16:30:03 +01:00
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async reveActuelIncDec(value) {
2021-05-02 21:08:50 +02:00
let mydata = Misc.templateData(this);
let reve = Math.max(mydata.reve.reve.value + value, 0);
await this.update( { "data.reve.reve.value": reve });
2020-07-17 22:04:35 +02:00
}
2021-01-09 19:33:19 +01:00
2020-11-17 16:30:03 +01:00
/* -------------------------------------------- */
2021-01-09 19:33:19 +01:00
async updatePointDeSeuil(value = 1) {
const seuil = Misc.toInt(Misc.templateData(this).reve.seuil.value);
const reve = Misc.toInt(Misc.templateData(this).carac.reve.value);
2020-11-16 03:52:34 +01:00
if (seuil < reve) {
2021-01-09 19:33:19 +01:00
await this.setPointsDeSeuil(Math.min(seuil + value, reve));
2020-11-16 03:52:34 +01:00
}
}
2021-01-09 19:33:19 +01:00
2020-11-17 16:30:03 +01:00
/* -------------------------------------------- */
2021-03-20 00:09:29 +01:00
async setPointsDeSeuil(seuil) {
await this.update({ "data.reve.seuil.value": seuil });
2020-11-16 03:52:34 +01:00
}
/* -------------------------------------------- */
2021-03-20 00:09:29 +01:00
async setPointsDeChance(chance) {
await this.updateCompteurValue("chance", chance);
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
getSonne() {
return !this.isEntiteCauchemar() && (Misc.templateData(this).sante.sonne?.value ?? false);
}
/* -------------------------------------------- */
getSonneRound() {
return !this.isEntiteCauchemar() && (Misc.templateData(this).sante.sonne?.round ?? false);
}
2021-03-15 00:05:56 +01:00
/* -------------------------------------------- */
2021-03-15 00:05:56 +01:00
async verifierSonneRound(round) {
if (this.getSonne()) {
2021-04-03 08:19:19 +02:00
if (round > this.getSonneRound() + 1) {
2021-03-15 00:05:56 +01:00
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 });
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
getSConst() {
if (this.isEntiteCauchemar()) {
return 0;
}
return RdDCarac.calculSConst(Misc.templateData(this).carac.constitution.value);
}
/* -------------------------------------------- */
async testSiSonne(sante, endurance) {
2021-03-20 00:09:29 +01:00
const roll = new Roll("1d20").evaluate();
roll.showDice = true;
RdDDice.show(roll);
let result = {
roll: roll,
sonne: roll.total > endurance || roll.total == 20 // 20 is always a failure
}
if (roll.total == 1) {
2021-03-20 00:09:29 +01:00
await this.ajoutXpConstitution(1); // +1 XP !
2021-03-15 00:05:56 +01:00
ChatMessage.create({ content: `${this.name} a obenu 1 sur son Jet d'Endurance et a gagné 1 point d'Expérience en Constitution. Ce point d'XP a été ajouté automatiquement).` });
2020-05-31 23:06:25 +02:00
}
if (result.sonne) {
await this.setSonne();
sante.sonne.value = true;
}
return result;
2020-05-31 23:06:25 +02:00
}
2021-03-20 00:09:29 +01:00
async ajoutXpConstitution(xp) {
await this.update({ "data.carac.constitution.xp": Misc.toInt(Misc.templateData(this).carac.constitution.xp) + xp });
2021-03-20 00:09:29 +01:00
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
countBlessures(blessuresListe) {
2020-11-25 00:50:20 +01:00
return blessuresListe.filter(b => b.active).length
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
countBlessuresByName(name) {
return this.countBlessures(Misc.templateData(this).blessures[name].liste);
}
2021-01-09 19:33:19 +01:00
2021-01-29 16:58:45 +01:00
/* -------------------------------------------- */
async jetEndurance() {
let myRoll = new Roll("1d20").roll();
myRoll.showDice = true;
await RdDDice.show(myRoll);
const actorData = Misc.data(this);
let msgText = "Jet d'Endurance : " + myRoll.total + " / " + actorData.data.sante.endurance.value + "<br>";
if (myRoll.total == 1 || (myRoll.total != 20 && myRoll.total <= actorData.data.sante.endurance.value)) {
2021-01-29 16:58:45 +01:00
msgText += `${this.name} a réussi son Jet d'Endurance !`;
if (myRoll.total == 1) {
2021-03-20 00:09:29 +01:00
await this.ajoutXpConstitution();
2021-01-29 16:58:45 +01:00
msgText += `et gagne 1 Point d'Experience en Constitution`;
}
} else {
await this.setSonne();
2021-03-20 00:09:29 +01:00
msgText += `${this.name} a échoué son Jet d'Endurance et devient Sonné`;
2021-01-29 16:58:45 +01:00
}
const message = {
content: msgText,
whisper: ChatMessage.getWhisperRecipients(game.user.name)
};
ChatMessage.create(message);
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
2020-12-06 21:39:55 +01:00
async jetVie() {
let myRoll = new Roll("1d20").roll();
myRoll.showDice = true;
await RdDDice.show(myRoll);
const actorData = Misc.data(this);
let msgText = "Jet de Vie : " + myRoll.total + " / " + actorData.data.sante.vie.value + "<br>";
if (myRoll.total <= actorData.data.sante.vie.value) {
2020-12-06 21:39:55 +01:00
msgText += "Jet réussi, pas de perte de point de vie (prochain jet dans 1 round pour 1 critique, SC minutes pour une grave)";
2021-01-09 19:33:19 +01:00
if (myRoll.total == 1) {
2020-12-06 21:39:55 +01:00
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);
2021-01-09 19:33:19 +01:00
if (myRoll.total == 20) {
2020-12-06 21:39:55 +01:00
msgText += "Votre personnage est mort !!!!!";
}
}
const message = {
content: msgText,
whisper: ChatMessage.getWhisperRecipients(game.user.name)
};
2021-01-09 19:33:19 +01:00
ChatMessage.create(message);
2020-12-06 21:39:55 +01:00
}
2020-08-29 22:52:41 +02:00
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async santeIncDec(name, inc, isCritique = false) {
2021-01-09 19:33:19 +01:00
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 && !isCritique) { // perte endurance et endurance devient 0 (sauf critique) -> -1 vie
sante.vie.value--;
2020-05-31 23:06:25 +02:00
}
result.newValue = Math.max(0, result.newValue);
if (inc > 0) { // le max d'endurance s'applique seulement à la récupération
2021-01-10 02:28:45 +01:00
result.newValue = Math.min(result.newValue, this._computeEnduranceMax())
}
const perte = compteur.value - result.newValue;
if (perte > 1) {
// 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;
2020-05-31 23:06:25 +02:00
}
}
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 (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;
2020-06-07 23:16:29 +02:00
}
2020-08-29 22:52:41 +02:00
isDead() {
return !this.isEntiteCauchemar() && Misc.templateData(this).sante.vie.value < -this.getSConst()
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
_computeFatigueMin() {
return Misc.templateData(this).sante.endurance.max - Misc.templateData(this).sante.endurance.value;
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
_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);
2020-11-25 00:50:20 +01:00
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));
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
2021-03-20 00:09:29 +01:00
async manageBlessureFromSheet(gravite, index) {
let listBlessures = duplicate(Misc.templateData(this).blessures);
2021-03-20 00:09:29 +01:00
let blessure = listBlessures[gravite + "s"].liste[index];
2020-07-20 12:02:07 +02:00
blessure.active = !blessure.active;
2021-01-09 19:33:19 +01:00
if (!blessure.active) {
2021-03-20 00:09:29 +01:00
this._supprimerBlessure(blessure);
}
2021-03-20 00:09:29 +01:00
await this.update({ 'data.blessures': listBlessures });
2020-07-20 12:02:07 +02:00
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
2021-03-20 00:09:29 +01:00
async setDataBlessureFromSheet(gravite, index, psoins, pcomplets, jours, loc) {
let listBlessures = duplicate(Misc.templateData(this).blessures);
2021-03-20 00:09:29 +01:00
let blessure = listBlessures[gravite + "s"].liste[index];
blessure.premiers_soins = psoins;
blessure.soins_complets = pcomplets;
blessure.jours = jours;
blessure.loc = loc;
2021-03-20 00:09:29 +01:00
await this.update({ 'data.blessures': listBlessures });
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
2020-12-16 02:54:28 +01:00
async jetDeMoral(situation) {
let jetMoral = new Roll("1d20").roll();
RdDDice.show(jetMoral);
let moralActuel = Misc.toInt(Misc.templateData(this).compteurs.moral.value);
const difficulte = 10 + moralActuel;
2020-12-21 22:13:13 +01:00
const succes = jetMoral.total <= difficulte;
let ajustementMoral = this._calculAjustementMoral(succes, moralActuel, situation);
2021-01-09 19:33:19 +01:00
await this.moralIncDec(ajustementMoral);
ChatMessage.create({
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
2021-01-09 19:33:19 +01:00
content: `Jet de moral ${succes ? "réussi" : "manqué"} en situation ${situation} (${jetMoral.total}/${difficulte}), vous ${ajustementMoral > 0 ? "gagnez du moral" : ajustementMoral < 0 ? "perdez du moral" : "gardez votre moral"}`
});
return ajustementMoral;
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async moralIncDec(ajustementMoral) {
let tplData = Misc.templateData(this);
2020-12-16 02:54:28 +01:00
if (ajustementMoral != 0) {
let moral = Misc.toInt(tplData.compteurs.moral.value) + ajustementMoral
2021-03-20 00:09:29 +01:00
if (moral > 3) { // exaltation
const exaltation = Misc.toInt(tplData.compteurs.exaltation.value) + moral - 3;
await this.updateCompteurValue('exaltation', exaltation);
2020-12-16 02:54:28 +01:00
}
2021-03-20 00:09:29 +01:00
if (moral < -3) { // dissolution
const dissolution = Misc.toInt(tplData.compteurs.dissolution.value) + 3 - moral;
await this.updateCompteurValue('dissolution', dissolution);
2020-12-16 02:54:28 +01:00
}
2021-03-20 00:09:29 +01:00
moral = Math.max(-3, Math.min(moral, 3));
await this.updateCompteurValue('moral', moral);
2020-12-16 02:54:28 +01:00
}
return tplData.compteurs.moral.value;
2020-12-16 02:54:28 +01:00
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
2020-12-21 22:13:13 +01:00
_calculAjustementMoral(succes, moral, situation) {
2020-12-16 02:54:28 +01:00
switch (situation) {
case 'heureux': case 'heureuse': return succes ? 1 : 0;
case 'malheureuse': case 'malheureux': return succes ? 0 : -1;
2020-12-16 02:54:28 +01:00
case 'neutre':
if (succes && moral <= 0) return 1;
if (!succes && moral > 0) return -1;
}
return 0;
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
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;
}
2021-01-09 19:33:19 +01:00
await this.update({ "data.compteurs.ethylisme": ethylisme });
}
2020-12-06 20:11:30 +01:00
/* -------------------------------------------- */
async jetEthylisme(forceAlcool = 0) {
const actorData = Misc.data(this);
2021-01-09 19:33:19 +01:00
let rollData = {
vieValue: actorData.data.sante.vie.value,
forceAlcool: forceAlcool,
etat: this.getEtatGeneral({ ethylisme: true }),
diffNbDoses: -Number(actorData.data.compteurs.ethylisme.nb_doses || 0),
2020-12-06 20:11:30 +01:00
finalLevel: 0,
2021-04-21 19:40:48 +02:00
diffConditions: 0,
ajustementsForce: CONFIG.RDD.difficultesLibres,
2020-12-06 20:11:30 +01:00
}
let html = await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/dialog-roll-ethylisme.html', rollData);
new RdDRollDialogEthylisme(html, rollData, this, r => this.performEthylisme(r)).render(true);
2020-12-06 20:11:30 +01:00
}
2021-01-09 19:33:19 +01:00
2020-12-06 20:11:30 +01:00
/* -------------------------------------------- */
2021-01-09 19:33:19 +01:00
async performEthylisme(rollData) {
const actorData = Misc.data(this);
let ethylisme = duplicate(actorData.data.compteurs.ethylisme);
2021-01-09 19:33:19 +01:00
// Jet d'ethylisme
2021-01-09 19:33:19 +01:00
let rollEthylisme = await RdDResolutionTable.roll(rollData.vieValue, rollData.finalLevel);
let rollDataView = {
forceAlcool: rollData.forceAlcool,
rollEthylismeIsSuccess: rollEthylisme.isSuccess,
rollEthylismeText: RdDResolutionTable.explain(rollEthylisme),
};
2021-01-09 19:33:19 +01:00
if (rollEthylisme.isSuccess) {
ethylisme.nb_doses++;
rollDataView.doses = ethylisme.nb_doses;
2020-12-06 21:11:30 +01:00
} else {
2021-01-09 19:33:19 +01:00
ethylisme.value = Math.max(ethylisme.value - 1, -7);
ethylisme.nb_doses = 0;
rollDataView.doses = ethylisme.nb_doses;
rollDataView.ajustementEthylique = ethylisme.value;
rollDataView.nomEthylisme = RdDUtility.getNomEthylisme(ethylisme.value);
2020-12-06 21:11:30 +01:00
let enduranceLost = new Roll("1d6").roll().total;
rollDataView.enduranceLost = enduranceLost;
await this.santeIncDec("endurance", -enduranceLost, false);
2020-12-06 21:11:30 +01:00
// Qui a bu boira (p 164)
let rollVolonte = await RdDResolutionTable.roll(actorData.data.carac.volonte.value, Math.min(ethylisme.value, 0) + actorData.data.compteurs.moral.value);
rollDataView.rollVolonteIsSuccess = rollVolonte.isSuccess;
rollDataView.rollVolonteText = RdDResolutionTable.explain(rollVolonte);
}
RdDResolutionTable.displayRollData(rollDataView, this, 'chat-resultat-ethylisme.html');
2021-01-09 19:33:19 +01:00
if (rollEthylisme.isEchec) {
await this._jetDeMoralEthylique(ethylisme);
}
await this.update({'data.compteurs.ethylisme': ethylisme});
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async _jetDeMoralEthylique(ethylisme) {
if (ethylisme.value >= -1 && !ethylisme.jet_moral) {
let adjust = await this.jetDeMoral('heureuse');
if (adjust > 0 || ethylisme.value == -1) {
ethylisme.jet_moral = true;
2020-12-19 01:14:02 +01:00
}
if (ethylisme.value == -1 && adjust <= 0) {
// alcool triste
ChatMessage.create({
content: "Décidément, vous avez l'alcool triste, vous perdez finalement un point de moral !",
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name)
2021-01-09 19:33:19 +01:00
});
2021-03-18 00:41:26 +01:00
await this.moralIncDec(-1);
2020-12-19 01:14:02 +01:00
}
}
2020-12-06 20:11:30 +01:00
}
2021-04-06 23:44:57 +02:00
/* -------------------------------------------- */
2021-04-12 00:16:23 +02:00
async actionItem(item) {
if (!item.getActionPrincipale()) return;
2021-04-12 01:03:37 +02:00
switch (Misc.data(item).type) {
case 'nourritureboisson': return await this.actionNourritureboisson(item);
case 'potion': return await this.actionPotion(item);
}
}
async actionNourritureboisson(item) {
2021-04-11 23:01:10 +02:00
const dialog = await DialogConsommer.create(this, item);
2021-04-12 01:03:37 +02:00
dialog.render(true);
}
2021-04-16 00:29:08 +02:00
2021-04-12 01:03:37 +02:00
async actionPotion(item) {
return await this.consommerPotion(item)
2021-04-06 23:44:57 +02:00
}
2021-04-11 23:01:10 +02:00
/* -------------------------------------------- */
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} poour 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 }) {
2021-04-12 00:16:23 +02:00
if (!item.getActionPrincipale()) return;
2021-04-11 23:01:10 +02:00
await this.apprecierCuisine(item);
const sust = Misc.templateData(item).sust;
2021-04-06 23:44:57 +02:00
if (sust > 0) {
2021-04-11 23:01:10 +02:00
await this.updateCompteurValue('sust', Misc.keepDecimals(Misc.templateData(this).compteurs.sust.value + sust * doses, 2));
2021-04-06 23:44:57 +02:00
}
2021-04-11 23:01:10 +02:00
await item.diminuerQuantite(doses, options);
2021-04-06 23:44:57 +02:00
}
2021-04-12 01:03:37 +02:00
2021-04-11 23:01:10 +02:00
/* -------------------------------------------- */
async boire(item, doses, options = { diminuerQuantite: true }) {
2021-04-12 00:16:23 +02:00
if (!item.getActionPrincipale()) return;
2021-04-11 23:01:10 +02:00
const tplData = Misc.templateData(item);
const desaltere = tplData.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(tplData.force);
}
2021-04-06 23:44:57 +02:00
}
2021-04-11 23:01:10 +02:00
await item.diminuerQuantite(doses, options);
2021-04-06 23:44:57 +02:00
}
2021-04-11 23:01:10 +02:00
async saouler(forceAlcool) {
2021-04-06 23:44:57 +02:00
const actorTplData = Misc.templateData(this);
const etatGeneral = this.getEtatGeneral({ ethylisme: true });
const nbDoses = -Number(actorTplData.compteurs.ethylisme.nb_doses || 0);
let rollData = {
vieValue: actorTplData.sante.vie.value,
forceAlcool: forceAlcool,
etat: etatGeneral,
diffNbDoses: nbDoses,
finalLevel: nbDoses + forceAlcool + etatGeneral,
diffConditions: 0,
};
await this.performEthylisme(rollData);
}
2021-04-11 23:01:10 +02:00
async apprecierCuisine(item) {
2021-04-06 23:44:57 +02:00
const cuisine = Misc.data(this.getCompetence('cuisine'));
2021-04-11 23:01:10 +02:00
const itemData = Misc.data(item);
const qualite = itemData.data.qualite;
2021-04-06 23:44:57 +02:00
if (cuisine && qualite > 0 && qualite > cuisine.data.niveau) {
2021-04-11 23:01:10 +02:00
const rolled = await this.rollCaracCompetence('gout', 'cuisine', qualite, { title: itemData.data.boisson ? "apprécie la boisson" : "apprécie le plat" });
2021-04-06 23:44:57 +02:00
if (rolled.isSuccess) {
await this.jetDeMoral('heureux');
}
}
}
2021-04-11 23:01:10 +02:00
async surmonterExotisme(item, choix = {}) {
const itemData = Misc.data(item);
2021-04-16 00:29:08 +02:00
const exotisme = Math.min(itemData.data.exotisme, itemData.data.qualite, 0);
if (exotisme < 0) {
const rolled = await this.rollCaracCompetence('volonte', 'cuisine', exotisme, { title: `surmonte l'exotisme de ${itemData.name}` });
2021-04-06 23:44:57 +02:00
if (rolled.isEchec) {
2021-04-11 23:01:10 +02:00
if (!choix.seForcer) {
2021-04-06 23:44:57 +02:00
return false;
}
2021-04-11 23:01:10 +02:00
await this.jetDeMoral('malheureux');
2021-04-06 23:44:57 +02:00
}
}
return true;
}
async jetGoutCuisine() {
console.info('Jet de Gout/Cuisine');
return true;
}
2020-11-12 16:35:51 +01:00
/* -------------------------------------------- */
2021-01-29 12:08:02 +01:00
async transformerStress() {
const actorData = Misc.data(this);
const stress = Misc.toInt(actorData.data.compteurs.stress.value);
2021-01-09 19:33:19 +01:00
if (stress <= 0) {
2021-01-29 12:08:02 +01:00
return;
}
2021-01-29 12:08:02 +01:00
const stressRoll = await this._stressRoll(this.getReveActuel());
2021-01-29 12:08:02 +01:00
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));
2020-12-19 01:45:03 +01:00
const annule = Math.min(dissolution, exaltation);
dissolution -= annule;
exaltation -= annule;
2021-01-29 12:08:02 +01:00
const perteDissolution = Math.max(0, Math.min(dissolution, conversion));
let stressRollData = {
alias: this.name,
selectedCarac: actorData.data.carac.reve,
2021-01-29 12:08:02 +01:00
rolled: stressRoll,
stress: stress,
perte: Math.min(conversion, stress),
convertis: conversion - perteDissolution,
xp: conversion - perteDissolution + exaltation,
2021-01-29 12:08:02 +01:00
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);
2021-01-29 12:08:02 +01:00
compteurs.stress.value = Math.max(stress - stressRollData.perte - 1, 0);
compteurs.experience.value += stressRollData.xp;
compteurs.dissolution.value = dissolution - perteDissolution;
2020-12-19 01:45:03 +01:00
compteurs.exaltation.value = 0;
await this.update({ "data.compteurs": compteurs });
2020-08-29 22:52:41 +02:00
}
2020-11-14 21:34:34 +01:00
/* -------------------------------------------- */
2021-01-29 12:08:02 +01:00
async _stressRoll(reveActuel) {
let result = await RdDResolutionTable.roll(reveActuel, 0);
2021-01-29 12:08:02 +01:00
if (result.isPart) {
result.second = await RdDResolutionTable.roll(reveActuel, 0);
}
result.factor = this._getFacteurStress(result);
return result;
}
2021-01-29 12:08:02 +01:00
_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;
2020-11-17 16:30:03 +01:00
case "part":
if (stressRoll.second.isSign) {
stressRoll.quality = "Double Particulière";
return 150;
}
return 100;
2020-11-17 16:30:03 +01:00
}
2021-01-29 12:08:02 +01:00
return 0;
2020-11-12 16:35:51 +01:00
}
2020-11-17 11:35:05 +01:00
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
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')
};
}
2021-03-15 00:05:56 +01:00
2021-02-09 23:23:40 +01:00
/* -------------------------------------------- */
createCallbackAppelAuMoral() { /* Si l'appel au moral est utilisé, on l'affiche dans le chat et on diminue éventuellement le moral */
2021-02-09 23:23:40 +01:00
return {
condition: r => r.use.appelAuMoral && game.settings.get("core", "rollMode") != 'selfroll',
action: r => this._appliquerAppelMoral(r)
2021-02-09 23:23:40 +01:00
};
}
2021-03-15 00:05:56 +01:00
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async checkCaracXP(caracName) {
let carac = Misc.templateData(this).carac[caracName];
if (carac && carac.xp > 0) {
let xpNeeded = RdDCarac.getCaracNextXp(carac.value + 1);
2021-01-09 19:33:19 +01:00
if (carac.xp >= xpNeeded) {
carac = duplicate(carac);
carac.value = Number(carac.value) + 1;
2021-01-09 19:33:19 +01:00
let xpData = {
alias: this.name,
carac: caracName,
value: carac.value,
xp: carac.xp
}
ChatUtility.createChatMessage(this.name, "default", {
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-actor-carac-xp.html`, xpData)
});
}
}
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
2021-01-14 15:29:47 +01:00
async checkCompetenceXP(compName, newXP = undefined) {
let compData = Misc.data(this.getCompetence(compName));
if (compData && newXP && newXP == compData.data.xp) { // Si édition, mais sans changement XP
2021-01-14 15:29:47 +01:00
return;
}
newXP = (newXP) ? newXP : compData.data.xp;
if (compData && newXP > 0) {
let xpNeeded = RdDItemCompetence.getCompetenceNextXp(compData.data.niveau + 1);
2021-01-14 15:29:47 +01:00
if (newXP >= xpNeeded) {
let newCompData = duplicate(compData);
newCompData.data.niveau += 1;
newCompData.data.xp = newXP;
2021-01-14 20:51:32 +01:00
2021-01-09 19:33:19 +01:00
let xpData = {
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
}
ChatUtility.createChatMessage(this.name, "default", {
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-actor-competence-xp.html`, xpData)
});
}
}
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async _appliquerAjoutExperience(rollData, display = true) {
if (!this.isPersonnage()) return;
2021-01-09 19:33:19 +01:00
let xpResult = this.appliquerExperience(rollData.rolled, rollData.selectedCarac.label, rollData.competence);
if (display && xpResult.result) {
2020-12-14 10:38:43 +01:00
let xpmsg = "<br>Points d'expérience gagnés ! Carac: " + xpResult.xpCarac + ", Comp: " + xpResult.xpCompetence;
let message = {
whisher: ChatMessage.getWhisperRecipients(["GM", this.name]),
content: "<strong>" + rollData.selectedCarac.label + "</strong>" + xpmsg,
}
2020-12-14 10:38:43 +01:00
ChatMessage.create(message);
}
2021-01-09 19:33:19 +01:00
if (xpResult && xpResult.xpComp > 0 && rollData.competence) {
this.checkCompetenceXP(rollData.competence.name);
}
2021-01-09 19:33:19 +01:00
if (xpResult && xpResult.xpCarac > 0 && rollData.selectedCarac) {
this.checkCaracXP(rollData.selectedCarac.name);
}
2021-03-15 00:05:56 +01:00
}
2021-02-09 23:23:40 +01:00
/* -------------------------------------------- */
async _appliquerAppelMoral(rollData, display = true) {
if (!this.isPersonnage()) return;
2021-03-18 00:41:26 +01:00
if (!rollData.useMoral) return;
if (rollData.rolled.isEchec ||
(rollData.ajustements.diviseurSignificative && (rollData.rolled.roll * rollData.ajustements.diviseurSignificative > rollData.score))) {
2021-03-19 22:20:01 +01:00
rollData.perteMoralEchec = rollData.moral <= -3 ? 'dissolution' : 'perte';
2021-03-18 00:41:26 +01:00
rollData.moral = await this.moralIncDec(-1); /* L'appel au moral a échoué. Le personnage perd un point de moral */
}
}
2021-02-02 07:56:45 +01:00
/* -------------------------------------------- */
filterSortList(sortList, coord) {
let tmr = TMRUtility.getTMR(coord);
2021-02-02 07:56:45 +01:00
let letfilteredList = []
for (let sort of sortList) {
2021-02-02 08:08:41 +01:00
//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);
2021-02-02 07:56:45 +01:00
}
}
return letfilteredList;
}
/* -------------------------------------------- */
2021-04-24 00:50:20 +02:00
computeDraconicAndSortIndex(sortList) {
let draconicList = this.getDraconicList().map(d => duplicate(Misc.data(d)));
for (let sort of sortList) {
2021-04-24 00:50:20 +02:00
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;
}
2021-02-02 07:56:45 +01:00
}
}
2021-04-24 00:50:20 +02:00
return draconicList;
}
2021-05-01 19:12:55 +02:00
/* -------------------------------------------- */
2021-04-24 00:50:20 +02:00
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)];
2021-02-02 07:56:45 +01:00
}
2020-12-08 23:07:41 +01:00
/* -------------------------------------------- */
async rollUnSort(coord) {
let sortList = duplicate(this.getSortList()); // Duplication car les pts de reve sont modifiés dans le sort
2021-01-09 19:33:19 +01:00
if (!sortList || sortList.length == 0) {
2020-12-08 23:07:41 +01:00
ui.notifications.info("Aucun sort disponible!");
return;
}
2021-02-02 07:56:45 +01:00
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;
}
2021-01-09 19:33:19 +01:00
if (this.currentTMR) this.currentTMR.minimize(); // Hide
2021-04-24 00:50:20 +02:00
let draconicList = this.computeDraconicAndSortIndex(sortList);
const actorData = Misc.data(this);
2021-01-09 19:33:19 +01:00
let rollData = {
forceCarac: { 'reve': duplicate(actorData.data.carac.reve) },
selectedCarac: duplicate(actorData.data.carac.reve),
2021-02-02 07:56:45 +01:00
draconicList: draconicList,
2020-12-08 23:07:41 +01:00
sortList: sortList,
competence: draconicList[0],
2020-12-08 23:07:41 +01:00
selectedSort: sortList[0],
2021-02-06 02:29:58 +01:00
tmr: TMRUtility.getTMR(coord),
2021-03-29 18:08:18 +02:00
diffLibre: RdDItemSort.getDifficulte(sortList[0], -7), // Per default at startup
coutreve: Array(30).fill().map((item, index) => 1 + index),
carac: { 'reve': duplicate(actorData.data.carac.reve) }
2020-12-08 23:07:41 +01:00
}
if (this.currentTMR) this.currentTMR.minimize(); // Hide
2020-12-08 23:07:41 +01:00
const dialog = await RdDRoll.create(this, rollData,
{
html: 'systems/foundryvtt-reve-de-dragon/templates/dialog-roll-sort.html',
2021-04-24 00:50:20 +02:00
options: { height: 600 },
2020-12-28 10:17:40 +01:00
close: html => { this.currentTMR.maximize() } // Re-display TMR
},
2020-12-08 23:07:41 +01:00
{
name: 'lancer-un-sort',
label: 'Lancer un sort',
callbacks: [
this.createCallbackExperience(),
2021-04-24 00:50:20 +02:00
{ action: r => this._rollUnSortResult(r) }
2020-12-08 23:07:41 +01:00
]
2021-04-24 00:50:20 +02:00
}
2020-12-08 23:07:41 +01:00
);
dialog.render(true);
}
/* -------------------------------------------- */
2021-01-09 19:33:19 +01:00
isRencontreSpeciale() { // Gestion queue/souffle 'Mauvaise Rencontre en Perpective'
let addMsg = "";
let rencSpecial = this.data.items.find(item => EffetsDraconiques.isMauvaiseRencontre(item));
2021-01-09 19:33:19 +01:00
if (rencSpecial) {
rencSpecial = Misc.data(rencSpecial); // To keep it
2021-02-06 01:34:49 +01:00
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.";
2021-01-09 19:33:19 +01:00
}
ChatMessage.create({
content: "Vous êtes sous le coup d'une Mauvaise Rencontre en Persective." + addMsg,
2021-01-09 19:33:19 +01:00
whisper: ChatMessage.getWhisperRecipients(game.user.name)
});
}
return rencSpecial;
}
2020-12-30 15:31:43 +01:00
/* -------------------------------------------- */
getTMRFatigue() { // Pour l'instant uniquement Inertie Draconique
let countInertieDraconique = EffetsDraconiques.countInertieDraconique(this);
if (countInertieDraconique > 0) {
2021-01-09 19:33:19 +01:00
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.`,
2021-01-09 19:33:19 +01:00
whisper: ChatMessage.getWhisperRecipients(game.user.name)
});
2020-12-30 15:31:43 +01:00
}
2021-02-06 01:34:49 +01:00
return countInertieDraconique + 1;
}
2020-12-30 16:57:47 +01:00
/* -------------------------------------------- */
async checkSoufflePeage(tmr) {
let peage = this.data.items.find(item => EffetsDraconiques.isPeage(item));
if (peage && (tmr.type == 'pont' || tmr.type == 'cite')) {
2021-01-09 19:33:19 +01:00
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).",
2021-01-09 19:33:19 +01:00
whisper: ChatMessage.getWhisperRecipients(game.user.name)
});
}
}
2020-12-17 09:29:09 +01:00
/* -------------------------------------------- */
2021-04-24 00:50:20 +02:00
async _rollUnSortResult(rollData) {
2020-12-08 23:07:41 +01:00
let rolled = rollData.rolled;
2020-12-31 02:20:52 +01:00
let selectedSort = rollData.selectedSort;
2021-04-24 00:50:20 +02:00
rollData.isSortReserve = rollData.mettreEnReserve && !selectedSort.data.isrituel;
2020-12-31 02:20:52 +01:00
rollData.show = {}
rollData.depenseReve = Number(selectedSort.data.ptreve_reel);
2020-12-11 20:37:00 +01:00
let reveActuel = Misc.templateData(this).reve.reve.value;
2020-12-08 23:07:41 +01:00
if (rolled.isSuccess) { // Réussite du sort !
if (rolled.isPart) {
2020-12-31 02:20:52 +01:00
rollData.depenseReve = Math.max(Math.floor(rollData.depenseReve / 2), 1);
2020-12-08 23:07:41 +01:00
}
if (rollData.isSortReserve) {
2020-12-31 02:20:52 +01:00
rollData.depenseReve++;
2020-12-08 23:07:41 +01:00
}
2021-03-15 00:05:56 +01:00
if (rollData.competence.name.includes('Thanatos')) { // Si Thanatos
await this.update({ "data.reve.reve.thanatosused": true });
2021-02-07 20:36:34 +01:00
}
if (reveActuel > rollData.depenseReve) {
2020-12-08 23:07:41 +01:00
// Incrémenter/gére le bonus de case
RdDItemSort.incrementBonusCase(this, selectedSort, rollData.tmr.coord);
2021-01-09 19:33:19 +01:00
2020-12-08 23:07:41 +01:00
if (rollData.isSortReserve) {
2020-12-31 02:20:52 +01:00
await this.sortMisEnReserve(rollData, selectedSort);
2020-12-08 23:07:41 +01:00
}
}
else {
2020-12-31 02:20:52 +01:00
rollData.depenseReve = 0;
rollData.show.reveInsuffisant = true;
2021-01-09 19:33:19 +01:00
mergeObject(rollData.rolled, RdDResolutionTable.getResultat("echec"), { overwrite: true });
2020-12-08 23:07:41 +01:00
}
} else {
if (rolled.isETotal) { // Echec total !
rollData.depenseReve = Math.min(reveActuel, Math.floor(rollData.depenseReve * 1.5))
2020-12-08 23:07:41 +01:00
// TODO: mise en réserve d'un échec total...
} else {
2020-12-31 02:20:52 +01:00
rollData.depenseReve = 0
2020-12-08 23:07:41 +01:00
}
}
reveActuel = Math.max(reveActuel - rollData.depenseReve, 0);
await this.update({ "data.reve.reve.value": reveActuel });
2021-01-09 19:33:19 +01:00
2021-04-24 00:50:20 +02:00
if (rollData.isSortReserve) {
2020-12-08 23:07:41 +01:00
this.currentTMR.maximize(); // Re-display TMR
2021-04-24 00:50:20 +02:00
} else {
this.currentTMR.close(); // Close TMR !
2020-12-08 23:07:41 +01:00
}
// Final chat message
RdDResolutionTable.displayRollData(rollData, this, 'chat-resultat-sort.html');
2020-12-31 02:20:52 +01:00
if (reveActuel == 0) { // 0 points de reve
2020-12-31 02:20:52 +01:00
ChatMessage.create({ content: this.name + " est réduit à 0 Points de Rêve, et tombe endormi !" });
closeTMR = true;
}
2020-12-08 23:07:41 +01:00
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async rollCarac(caracName) {
let rollData = { selectedCarac: this.getCaracByName(caracName) };
const dialog = await RdDRoll.create(this, rollData,
2021-01-09 19:33:19 +01:00
{ html: 'systems/foundryvtt-reve-de-dragon/templates/dialog-roll-carac.html' },
{
2021-01-09 19:33:19 +01:00
name: 'jet-' + caracName,
2020-12-08 03:04:00 +01:00
label: 'Jet ' + Grammar.apostrophe('de', rollData.selectedCarac.label),
callbacks: [
this.createCallbackExperience(),
this.createCallbackAppelAuMoral(),
{ action: r => this._onRollCaracResult(r) }
]
}
);
dialog.render(true);
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async _onRollCaracResult(rollData) {
// Final chat message
RdDResolutionTable.displayRollData(rollData, this, 'chat-resultat-general.html');
}
2021-04-06 23:44:57 +02:00
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,
2021-04-11 23:01:10 +02:00
finalLevel: (Misc.templateData(competence)?.niveau ?? 0) + diff,
diffLibre: diff,
showDice: true,
2021-04-06 23:44:57 +02:00
show: { title: options?.title ?? '' }
};
await RdDResolutionTable.rollData(rollData);
2021-04-20 00:52:25 +02:00
this._appliquerExperienceRollData(rollData);
2021-03-25 03:18:27 +01:00
RdDResolutionTable.displayRollData(rollData, this)
2021-04-06 23:44:57 +02:00
return rollData.rolled;
}
2021-04-20 00:52:25 +02:00
/* -------------------------------------------- */
_appliquerExperienceRollData(rollData) {
const callback = this.createCallbackExperience();
if (callback.condition(rollData)) { callback.action(rollData); }
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async rollCompetence(name) {
let rollData = { competence: Misc.data(this.getCompetence(name)) }
2020-12-08 03:04:00 +01:00
if (rollData.competence.type == 'competencecreature') {
2021-01-19 23:39:35 +01:00
if (rollData.competence.data.iscombat) {
2021-02-14 09:31:52 +01:00
const arme = RdDItemCompetenceCreature.toArme(rollData.competence);
RdDCombat.createUsingTarget(this).attaque(rollData.competence, arme);
2021-01-19 23:39:35 +01:00
return;
}
2020-12-08 03:04:00 +01:00
// Fake competence pour créature
RdDItemCompetenceCreature.setRollDataCreature(rollData);
2020-12-08 03:04:00 +01:00
}
2021-01-01 22:25:32 +01:00
else {
rollData.carac = Misc.templateData(this).carac;
2020-12-08 03:04:00 +01:00
}
console.log("rollCompetence !!!", rollData);
2020-12-08 03:04:00 +01:00
2021-01-09 19:33:19 +01:00
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(),
2021-01-09 19:33:19 +01:00
{ action: r => this._competenceResult(r) }
]
});
dialog.render(true);
}
/* -------------------------------------------- */
async creerTacheDepuisLivre(item) {
const itemData = Misc.data(item);
2021-01-09 19:33:19 +01:00
let tache = {
name: "Lire " + item.name, type: 'tache',
data: {
carac: 'intellect',
competence: 'Ecriture',
difficulte: itemData.data.difficulte,
2021-01-09 19:33:19 +01:00
periodicite: "60 minutes",
fatigue: 2,
points_de_tache: itemData.data.points_de_tache,
2021-01-09 19:33:19 +01:00
points_de_tache_courant: 0,
description: "Lecture du livre " + item.name + " - XP : " + itemData.data.xp + " - Compétences : " + itemData.data.competence
2021-01-09 19:33:19 +01:00
}
}
2021-03-25 03:18:27 +01:00
await this.createEmbeddedDocuments('Item', [tache], { renderSheet: true });
2021-01-09 19:33:19 +01:00
}
/* -------------------------------------------- */
async rollTache(id) {
2021-03-29 18:08:18 +02:00
const actorData = Misc.data(this);
const tacheData = Misc.data(this.getTache(id));
const compData = Misc.data(this.getCompetence(tacheData.data.competence));
2021-03-29 18:08:18 +02:00
compData.data.defaut_carac = tacheData.data.carac; // Patch !
let rollData = {
2021-03-29 18:08:18 +02:00
competence: compData,
tache: tacheData,
diffConditions: tacheData.data.difficulte,
use: { libre: false, conditions: false },
2021-01-09 19:33:19 +01:00
carac: {}
};
2021-03-29 18:08:18 +02:00
rollData.carac[tacheData.data.carac] = duplicate(actorData.data.carac[tacheData.data.carac]); // Single carac
console.log("rollTache !!!", rollData);
2021-01-09 19:33:19 +01:00
const dialog = await RdDRoll.create(this, rollData, { html: 'systems/foundryvtt-reve-de-dragon/templates/dialog-competence.html' }, {
name: 'jet-competence',
2021-03-29 18:08:18 +02:00
label: 'Jet de Tâche ' + tacheData.name,
2021-01-09 19:33:19 +01:00
callbacks: [
this.createCallbackExperience(),
this.createCallbackAppelAuMoral(),
2021-01-09 19:33:19 +01:00
{ condition: r => r.rolled.isETotal, action: r => this._tacheETotal(r) },
{ action: r => this._tacheResult(r) }
]
});
dialog.render(true);
}
/* -------------------------------------------- */
async _tacheResult(rollData) {
// Mise à jour de la tache
rollData.tache.data.points_de_tache_courant += rollData.rolled.ptTache;
this.updateEmbeddedDocuments('Item', [rollData.tache]);
2021-01-09 19:33:19 +01:00
this.santeIncDec("fatigue", rollData.tache.data.fatigue);
RdDResolutionTable.displayRollData(rollData, this, 'chat-resultat-tache.html');
}
/* -------------------------------------------- */
_tacheETotal(rollData) {
rollData.tache.data.difficulte--;
this.updateEmbeddedDocuments('Item', [rollData.tache]);
}
2021-01-27 23:35:45 +01:00
/* -------------------------------------------- */
async _rollArt(artData, selected, oeuvre, callBackResult = r => this._resultArt(r)) {
const actorData = Misc.data(this);
2021-04-21 00:59:10 +02:00
mergeObject(artData,
{
oeuvre: oeuvre,
art: oeuvre.type,
competence: duplicate(Misc.data(this.getCompetence(artData.compName ?? oeuvre.data.competence ?? artData.art))),
2021-04-21 00:59:10 +02:00
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;
2021-03-15 00:05:56 +01:00
if (!artData.forceCarac) {
2021-02-14 18:31:00 +01:00
artData.forceCarac = {};
artData.forceCarac[selected] = duplicate(actorData.data.carac[selected]);
2021-02-14 18:31:00 +01:00
}
2021-01-27 23:35:45 +01:00
console.log("rollArt !!!", artData);
2021-01-27 23:35:45 +01:00
2021-04-21 22:02:17 +02:00
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) }
]
});
2021-01-27 23:35:45 +01:00
dialog.render(true);
}
2021-01-31 21:37:41 +01:00
2021-01-27 23:35:45 +01:00
/* -------------------------------------------- */
2021-01-31 21:37:41 +01:00
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;
console.log("OEUVRE", artData.art, artData)
RdDResolutionTable.displayRollData(artData, this.name, `chat-resultat-${artData.art}.html`);
2021-01-27 23:35:45 +01:00
}
/* -------------------------------------------- */
async rollChant(id) {
const artData = { art: 'chant', verbe: 'Chanter' };
const oeuvre = duplicate(this.getChant(id));
await this._rollArt(artData, "ouie", oeuvre);
}
2021-02-14 18:31:00 +01:00
2021-01-27 23:35:45 +01:00
/* -------------------------------------------- */
2021-01-31 21:37:41 +01:00
async rollDanse(id) {
const actorData = Misc.data(this);
2021-02-14 18:31:00 +01:00
const artData = { art: 'danse', verbe: 'Danser', forceCarac: {} };
const oeuvre = duplicate(this.getItemOfType(id, artData.art));
2021-03-15 00:05:56 +01:00
if (oeuvre.data.agilite) {
artData.forceCarac['agilite'] = duplicate(actorData.data.carac.agilite);
2021-02-14 18:31:00 +01:00
}
2021-03-15 00:05:56 +01:00
if (oeuvre.data.apparence) {
artData.forceCarac['apparence'] = duplicate(actorData.data.carac.apparence);
2021-02-14 18:31:00 +01:00
}
2021-04-21 00:59:10 +02:00
const selectedCarac = this._getCaracDanse(oeuvre);
await this._rollArt(artData, selectedCarac, oeuvre);
2021-01-31 21:37:41 +01:00
}
2021-01-27 23:35:45 +01:00
2021-02-14 18:31:00 +01:00
/* -------------------------------------------- */
2021-03-15 00:05:56 +01:00
_getCaracDanse(oeuvre) {
2021-01-31 21:37:41 +01:00
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;
2021-01-31 21:37:41 +01:00
}
2021-01-27 23:35:45 +01:00
2021-01-31 21:37:41 +01:00
/* -------------------------------------------- */
async rollMusique(id) {
const artData = { art: 'musique', verbe: 'Jouer' };
const oeuvre = Misc.data(this.getItemOfType(id, artData.art));
await this._rollArt(artData, "ouie", oeuvre);
2021-01-27 23:35:45 +01:00
}
2021-01-31 21:37:41 +01:00
2021-01-27 23:35:45 +01:00
/* -------------------------------------------- */
2021-01-31 21:37:41 +01:00
async rollRecetteCuisine(id) {
2021-04-21 22:02:17 +02:00
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));
2021-01-31 21:37:41 +01:00
}
/* -------------------------------------------- */
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;
2021-04-16 00:29:08 +02:00
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),
2021-04-16 00:29:08 +02:00
"qualite": artData.qualiteFinale,
"exotisme": artData.exotismeFinal,
"encombrement": 0.1,
"quantite": Math.max(1, Math.floor(sust)),
2021-04-16 00:29:08 +02:00
"cout": Math.max(artData.qualiteFinale) * 0.01
}
};
2021-04-11 18:43:32 +02:00
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`);
}
2021-01-31 21:37:41 +01:00
/* -------------------------------------------- */
async rollJeu(id) {
2021-04-21 00:59:10 +02:00
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'
2021-01-31 21:37:41 +01:00
const artData = {
art: 'jeu', verbe: 'Jeu',
use: { libre: true, conditions: true, },
2021-04-21 00:59:10 +02:00
competence: duplicate(Misc.data(this.getCompetence('jeu'))),
forceCarac: {}
2021-01-31 21:37:41 +01:00
};
2021-04-21 00:59:10 +02:00
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);
2021-01-31 21:37:41 +01:00
}
2021-01-27 23:35:45 +01:00
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);
2021-01-27 23:35:45 +01:00
}
/* -------------------------------------------- */
2021-01-09 19:33:19 +01:00
async rollMeditation(id) {
let meditation = Misc.data(this.getMeditation(id));
let competence = Misc.data(this.getCompetence(meditation.data.competence));
competence.data.defaut_carac = "intellect"; // Meditation = tjs avec intellect
let meditationData = {
competence: competence,
meditation: meditation,
conditionMeditation: {
isHeure: false,
isVeture: false,
isComportement: false,
isPurification: false,
},
diffConditions: 0,
2021-01-13 03:11:03 +01:00
use: { libre: false, conditions: true, },
2021-01-09 19:33:19 +01:00
carac: {}
};
meditationData.carac["intellect"] = Misc.templateData(this).carac["intellect"];
console.log("rollMeditation !!!", meditationData);
2021-04-21 20:43:03 +02:00
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.isETotal, action: r => this._meditationETotal(r) },
{ action: r => this._meditationResult(r) }
]
});
dialog.render(true);
}
/* -------------------------------------------- */
async _meditationResult(meditationData) {
2021-01-09 19:33:19 +01:00
this.santeIncDec("fatigue", 2);
meditationData.diffLecture = -7;
2021-01-09 19:33:19 +01:00
if (meditationData.rolled.isPart)
meditationData.diffLecture = 0;
2021-01-09 19:33:19 +01:00
else if (meditationData.rolled.isSign)
meditationData.diffLecture = -3;
RdDResolutionTable.displayRollData(meditationData, this.name, 'chat-resultat-meditation.html');
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
_meditationETotal(meditationData) {
meditationData.meditation.data.malus--;
this.updateEmbeddedDocuments('Item', [meditationData.meditation]);
}
2021-01-09 19:33:19 +01:00
2020-12-11 08:29:24 +01:00
/* -------------------------------------------- */
async _competenceResult(rollData) {
RdDResolutionTable.displayRollData(rollData, this, 'chat-resultat-competence.html')
2020-12-08 03:04:00 +01:00
}
2021-02-09 23:23:40 +01:00
async _moralDecrease(rollData) {
RdDResolutionTable.displayRollData(rollData, this, 'chat-resultat-competence.html')
}
2020-12-06 21:11:30 +01:00
/* -------------------------------------------- */
2021-01-09 19:33:19 +01:00
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,
2021-01-09 19:33:19 +01:00
{ 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) },
]
}
2021-01-09 19:33:19 +01:00
);
dialog.render(true);
}
/* -------------------------------------------- */
async _appelChanceResult(rollData, onSuccess = () => { }, onEchec = () => { }) {
await RdDResolutionTable.displayRollData(rollData, this, 'chat-resultat-appelchance.html')
if (rollData.rolled.isSuccess) {
2021-03-30 23:01:09 +02:00
await this.setFlag('foundryvtt-reve-de-dragon', 'utilisationChance', true);
await this.chanceActuelleIncDec(-1);
2021-01-09 19:33:19 +01:00
onSuccess();
}
else {
onEchec();
}
}
2021-01-09 19:33:19 +01:00
2020-12-06 21:11:30 +01:00
/* -------------------------------------------- */
2021-03-30 23:01:09 +02:00
async chanceActuelleIncDec(value) {
const chance = Math.min(this.getChance(), Math.max(this.getChanceActuel() + value, 0));
await this.updateCompteurValue("chance", chance);
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
2021-01-09 19:33:19 +01:00
async appelDestinee(onSuccess = () => { }, onEchec = () => { }) {
let destinee = Misc.templateData(this).compteurs.destinee?.value ?? 0;
if (destinee > 0) {
2021-01-09 19:33:19 +01:00
ChatMessage.create({ content: `<span class="rdd-roll-part">${this.name} a fait appel à la Destinée !</span>` });
destinee--;
2021-03-25 03:18:27 +01:00
await this.updateCompteurValue("destinee", destinee);
onSuccess();
}
else {
onEchec();
}
}
2020-12-06 21:11:30 +01:00
/* -------------------------------------------- */
ajustementAstrologique() {
if (this.isCreature()) {
return 0;
}
const actorData = Misc.data(this);
2020-12-11 03:23:34 +01:00
// selon l'heure de naissance...
return game.system.rdd.calendrier.getAjustementAstrologique(actorData.data.heure, this.name);
}
2020-12-13 23:32:16 +01:00
/* -------------------------------------------- */
2021-01-09 19:33:19 +01:00
checkDesirLancinant() {
let queue = this.filterItemsData(it => it.type == 'queue' || it.type == 'ombre')
.filter(it => Grammar.toLowerCaseNoAccent(it.name).includes('desir lancinant'));
2020-12-14 10:38:43 +01:00
return (queue.length > 0);
}
/* -------------------------------------------- */
2021-01-09 19:33:19 +01:00
async appliquerExperience(rolled, caracName, competence = undefined) {
2021-01-31 19:37:21 +01:00
if (!this.isPersonnage()) return;
2021-01-09 19:33:19 +01:00
if (rolled.isPart && rolled.finalLevel < 0) {
2020-12-14 10:38:43 +01:00
// Cas de désir lancinant, pas d'expérience sur particulière
2021-01-09 19:33:19 +01:00
if (this.checkDesirLancinant()) {
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 { result: false, xpcarac: 0, xpCompetence: 0 };
2020-12-14 10:38:43 +01:00
}
if (caracName == 'derobee') caracName = 'agilite';
2021-04-03 08:31:01 +02:00
if (caracName == 'reve-actuel') caracName = 'reve';
let xp = Math.abs(rolled.finalLevel);
let xpCarac = Math.floor(xp / 2); // impair: arrondi inférieur en carac
let xpComp = 0;
2021-01-09 19:33:19 +01:00
if (competence) {
xpComp = xp - xpCarac;
2021-04-21 00:59:10 +02:00
let update = { _id: competence.id, 'data.xp': Misc.toInt(competence.data.xp) + xpComp };
await this.updateEmbeddedDocuments('Item', [update]);
} else {
xpCarac = Math.max(xpCarac, 1);
2021-01-09 19:33:19 +01:00
}
if (xpCarac > 0) {
let carac = duplicate(Misc.templateData(this).carac);
let selectedCarac = RdDActor._findCaracByName(carac, caracName);
2021-01-09 19:33:19 +01:00
if (!selectedCarac.derivee) {
selectedCarac.xp = Misc.toInt(selectedCarac.xp) + xpCarac;
2021-01-09 19:33:19 +01:00
await this.update({ "data.carac": carac });
} else {
2021-01-09 19:33:19 +01:00
ChatMessage.create({
2021-01-31 19:37:21 +01:00
content: `Vous avez ${xpCarac} à répartir pour la caractéristique dérivée ${caracName}. Vous devez le faire manuellement.`,
2021-01-09 19:33:19 +01:00
whisper: ChatMessage.getWhisperRecipients(game.user.name)
});
}
2020-12-13 23:32:16 +01:00
}
return { result: true, xpCarac: xpCarac, xpCompetence: xpComp }; //XP
2020-12-13 23:32:16 +01:00
}
2021-01-09 19:33:19 +01:00
return { result: false, xpCarac: 0, xpCompetence: 0 }; // Pas d'XP
2020-12-13 23:32:16 +01:00
}
2021-01-09 19:33:19 +01:00
2020-12-13 23:11:58 +01:00
/* -------------------------------------------- */
2021-01-09 19:33:19 +01:00
async ajouteNombreAstral(data) {
2020-12-13 23:32:16 +01:00
// Gestion expérience (si existante)
data.competence = Misc.data(this.getCompetence("astrologie"));
data.selectedCarac = Misc.templateData(this).carac["vue"];
2021-01-09 19:33:19 +01:00
this._appliquerAjoutExperience(data);
2020-12-13 23:32:16 +01:00
2020-12-13 23:11:58 +01:00
// Ajout du nombre astral
2021-01-09 19:33:19 +01:00
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]);
2021-01-09 19:33:19 +01:00
2020-12-13 23:11:58 +01:00
// 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);
2020-12-13 23:11:58 +01:00
// Affichage Dialog
this.astrologieNombresAstraux();
2021-01-09 19:33:19 +01:00
}
2020-12-11 08:29:24 +01:00
/* -------------------------------------------- */
2021-01-09 19:33:19 +01:00
async astrologieNombresAstraux() {
2020-12-11 08:29:24 +01:00
// Afficher l'interface spéciale
2021-01-09 19:33:19 +01:00
const astrologieDialog = await RdDAstrologieJoueur.create(this, {});
2020-12-13 23:11:58 +01:00
astrologieDialog.render(true);
2020-12-11 08:29:24 +01:00
}
2020-12-06 21:11:30 +01:00
/* -------------------------------------------- */
getCaracByName(caracName) {
2021-01-09 19:33:19 +01:00
switch (caracName) {
2020-12-31 03:51:53 +01:00
case 'reve-actuel': case 'Rêve actuel':
return {
2020-12-31 03:51:53 +01:00
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);
2021-01-09 19:33:19 +01:00
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]);
2021-03-25 03:18:27 +01:00
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.`);
}
2021-03-25 03:18:27 +01:00
if (keys.length > 0) {
return carac[keys[0]];
}
// for (const [key, value] of Object.entries(carac)) {
// if (key.includes(name) || Grammar.toLowerCaseNoAccent(value.label).includes('name')) {
// return carac[key];
// }
// }
return undefined; // Per default
}
/* -------------------------------------------- */
getSortList() {
return this.listItemsData("sort");
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
countMonteeLaborieuse() { // Return +1 par queue/ombre/souffle Montée Laborieuse présente
let countMonteeLaborieuse = this.filterItemsData(it => EffetsDraconiques.isMonteeLaborieuse(it)).length;
if (countMonteeLaborieuse > 0) {
2021-01-09 19:33:19 +01:00
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.`,
2021-01-09 19:33:19 +01:00
whisper: ChatMessage.getWhisperRecipients(game.user.name)
});
}
return countMonteeLaborieuse;
}
/* -------------------------------------------- */
refreshTMRView(tmrData) {
console.log("REFRESH !!!!");
if (this.currentTMR) {
2021-04-28 00:48:39 +02:00
this.currentTMR.externalRefresh( tmrData)
}
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async displayTMR(mode = "normal") {
let isRapide = mode == "rapide";
if (mode != "visu") {
let minReveValue = (isRapide && !EffetsDraconiques.isDeplacementAccelere(this) ? 3 : 2) + this.countMonteeLaborieuse();
2021-01-09 19:33:19 +01:00
if (this.getReveActuel() < minReveValue) {
ChatMessage.create({
content: `Vous n'avez les ${minReveValue} Points de Reve nécessaires pour monter dans les Terres Médianes`,
2021-01-09 19:33:19 +01:00
whisper: ChatMessage.getWhisperRecipients(game.user.name)
});
return;
2021-01-09 19:33:19 +01:00
}
2020-09-20 19:17:31 +02:00
}
2021-01-09 19:33:19 +01:00
const actorData = Misc.data(this);
const fatigue = actorData.data.sante.fatigue.value;
const endurance = actorData.data.sante.endurance.max;
let tmrFormData = {
mode: mode,
fatigue: {
malus: RdDUtility.calculMalusFatigue(fatigue, endurance),
html: "<table class='table-fatigue'>" + RdDUtility.makeHTMLfatigueMatrix(fatigue, endurance).html() + "</table>"
},
draconic: this.getDraconicList(),
sort: this.getSortList(),
caracReve: actorData.data.carac.reve.value,
pointsReve: this.getReveActuel(),
isRapide: isRapide
2021-01-09 19:33:19 +01:00
}
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);
}
2020-12-08 03:04:00 +01:00
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
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));
2021-01-09 19:33:19 +01:00
if (arme || armeName || (competence.type == 'competencecreature' && competence.data.iscombat)) {
2021-03-18 23:55:59 +01:00
RdDCombat.createUsingTarget(this)?.attaque(competence, arme);
} else {
2021-01-09 19:33:19 +01:00
this.rollCompetence(competence.name);
}
}
2020-12-17 09:29:09 +01:00
/* -------------------------------------------- */
_getTarget() {
if (game.user.targets && game.user.targets.size == 1) {
for (let target of game.user.targets) {
return target;
}
}
return undefined;
}
2021-01-09 19:33:19 +01:00
2021-02-09 11:17:17 +01:00
/* -------------------------------------------- */
2021-01-14 00:35:55 +01:00
getArmeParade(armeParadeId) {
2021-03-30 21:56:18 +02:00
const item = armeParadeId ? this.getEmbeddedDocument('Item', armeParadeId) : undefined;
2021-01-14 00:35:55 +01:00
return RdDItemArme.getArmeData(item);
}
2021-02-09 11:17:17 +01:00
/* -------------------------------------------- */
verifierForceMin(itemData) {
const actorData = Misc.data(this);
if (itemData.type == 'arme' && itemData.data.force > actorData.data.carac.force.value) {
2021-03-15 00:05:56 +01:00
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})`
2021-03-15 00:05:56 +01:00
});
2021-02-09 11:17:17 +01:00
}
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async equiperObjet(itemID) {
2021-03-30 21:56:18 +02:00
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]);
2020-12-02 14:00:54 +01:00
this.computeEncombrementTotalEtMalusArmure(); // Mise à jour encombrement
2021-01-29 23:17:18 +01:00
this.computePrixTotalEquipement(); // Mis à jour du prix total de l'équipement
if (isEquipe)
this.verifierForceMin(itemData);
2020-06-24 00:22:40 +02:00
}
2020-06-23 23:34:12 +02:00
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
computeArmure(attackerRoll) {
let dmg = (attackerRoll.dmg.dmgArme ?? 0) + (attackerRoll.dmg.dmgActor ?? 0);
let armeData = attackerRoll.arme;
2020-06-23 23:34:12 +02:00
let protection = 0;
2021-03-30 22:27:03 +02:00
const armures = this.items.map(it => Misc.data(it))
.filter(it => it.type == "armure" && it.data.equipe);
for (const itemData of armures) {
protection += new Roll(itemData.data.protection.toString()).roll().total;
2021-01-19 22:50:02 +01:00
if (dmg > 0) {
this._deteriorerArmure(itemData, dmg);
2021-01-19 22:50:02 +01:00
dmg = 0;
2020-06-23 23:34:12 +02:00
}
}
2021-03-30 22:27:03 +02:00
const penetration = Misc.toInt(armeData?.data.penetration ?? 0);
2020-12-18 01:10:03 +01:00
protection = Math.max(protection - penetration, 0);
protection += this.getProtectionNaturelle();
// Gestion des cas particuliers sur la fenêtre d'encaissement
2021-03-15 00:05:56 +01:00
if (attackerRoll.dmg.encaisserSpecial && attackerRoll.dmg.encaisserSpecial == "noarmure") {
protection = 0;
}
2021-03-15 00:05:56 +01:00
if (attackerRoll.dmg.encaisserSpecial && attackerRoll.dmg.encaisserSpecial == "chute" && Number(protection) > 2) {
protection = 2;
}
console.log("Final protect", protection, attackerRoll);
2020-06-23 23:34:12 +02:00
return protection;
2020-06-07 23:16:29 +02:00
}
2020-11-11 04:21:25 +01:00
/* -------------------------------------------- */
2021-01-19 22:50:02 +01:00
_deteriorerArmure(item, dmg) {
2021-01-26 19:43:37 +01:00
if (!ReglesOptionelles.isUsing('deteriorationArmure')) {
2021-01-25 08:48:03 +01:00
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);
2021-01-19 22:50:02 +01:00
if (!res) {
itemData.data.protection = "1d" + itemData.data.protection;
2021-01-19 22:50:02 +01:00
}
else if (res = /(\d+d\d+)(\-\d+)?/.exec(itemData.data.protection)) {
2021-01-19 22:50:02 +01:00
let malus = Misc.toInt(res[2]) - 1;
itemData.data.protection = res[1] + malus;
2021-01-19 22:50:02 +01:00
}
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 });
2021-01-19 22:50:02 +01:00
}
this.updateEmbeddedDocuments('Item', [itemData]);
2021-01-19 22:50:02 +01:00
}
/* -------------------------------------------- */
2021-01-09 19:33:19 +01:00
async encaisser() {
let data = { ajustementsEncaissement: RdDUtility.getAjustementsEncaissement() };
2021-01-09 19:33:19 +01:00
let html = await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/dialog-roll-encaisser.html', data);
new RdDEncaisser(html, this).render(true);
}
2020-11-11 04:21:25 +01:00
/* -------------------------------------------- */
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 = this.jetEncaissement(rollData);
this.ajouterBlessure(encaissement); // Will upate the result table
2021-01-19 23:01:14 +01:00
const perteVie = this.isEntiteCauchemar()
? { newValue: 0 }
2021-01-19 23:01:14 +01:00
: await this.santeIncDec("vie", - encaissement.vie);
const perteEndurance = await this.santeIncDec("endurance", -encaissement.endurance, (encaissement.critiques > 0));
2021-01-10 02:28:45 +01:00
2020-06-07 23:16:29 +02:00
this.computeEtatGeneral();
this.sheet.render(false);
2021-01-10 02:28:45 +01:00
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 ?? {}
});
2021-01-10 02:28:45 +01:00
ChatUtility.createChatWithRollMode(this.name, {
2021-01-10 02:28:45 +01:00
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)
});
}
2020-06-07 23:16:29 +02:00
}
2020-11-07 21:06:37 +01:00
/* -------------------------------------------- */
jetEncaissement(rollData) {
const roll = new Roll("2d10").roll();
roll.showDice = true;
RdDDice.show(roll, game.settings.get("core", "rollMode"));
const armure = 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;
2021-03-15 00:05:56 +01:00
encaissement.dmg.loc = rollData.dmg.loc ?? 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 = RdDUtility._evaluatePerte(encaissement.vie, over20);
encaissement.endurance = RdDUtility._evaluatePerte(encaissement.endurance, over20);
encaissement.penetration = rollData.arme?.data.penetration ?? 0;
return encaissement;
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
ajouterBlessure(encaissement) {
const actorData = Misc.data(this);
if (actorData.type == 'entite') return; // Une entité n'a pas de blessures
2021-01-09 19:33:19 +01:00
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;
}
}
2021-01-09 19:33:19 +01:00
count = encaissement.graves;
while (count > 0) {
let grave = blessures.graves.liste.find(it => !it.active);
if (grave) {
this._setBlessure(grave, encaissement);
count--;
}
2021-01-09 19:33:19 +01:00
else {
encaissement.critiques += count;
encaissement.graves -= count;
encaissement.endurance = -endActuelle;
encaissement.vie = -4;
break;
}
}
2021-01-09 19:33:19 +01:00
2021-01-23 17:50:57 +01:00
count = encaissement.critiques;
2021-01-09 19:33:19 +01:00
while (count > 0) {
let critique = blessures.critiques.liste[0];
2021-01-09 19:33:19 +01:00
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>`
});
2021-01-23 17:50:57 +01:00
encaissement.critiques -= count;
encaissement.mort = true;
break;
}
}
encaissement.endurance = Math.max(encaissement.endurance, -endActuelle);
2021-01-09 19:33:19 +01:00
this.update({ "data.blessures": blessures });
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
_setBlessure(blessure, encaissement) {
blessure.active = true;
blessure.loc = encaissement.locName;
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
2020-05-21 21:48:20 +02:00
/** @override */
getRollData() {
const data = super.getRollData();
return data;
}
2021-01-09 19:33:19 +01:00
2021-02-09 09:18:52 +01:00
/* -------------------------------------------- */
2021-03-15 00:05:56 +01:00
async resetItemUse() {
await this.unsetFlag('foundryvtt-reve-de-dragon', 'itemUse');
2021-03-15 00:05:56 +01:00
await this.setFlag('foundryvtt-reve-de-dragon', 'itemUse', {});
2021-02-09 09:18:52 +01:00
}
2021-02-25 08:48:31 +01:00
/* -------------------------------------------- */
2021-03-15 00:05:56 +01:00
async incDecItemUse(itemId, inc = 1) {
2021-02-25 08:48:31 +01:00
let itemUse = duplicate(this.getFlag('foundryvtt-reve-de-dragon', 'itemUse') ?? {});
itemUse[itemId] = (itemUse[itemId] ?? 0) + inc;
2021-03-15 00:05:56 +01:00
await this.setFlag('foundryvtt-reve-de-dragon', 'itemUse', itemUse);
console.log("ITEM USE INC", inc, itemUse);
2021-02-09 09:18:52 +01:00
}
/* -------------------------------------------- */
2021-03-15 00:05:56 +01:00
getItemUse(itemId) {
let itemUse = this.getFlag('foundryvtt-reve-de-dragon', 'itemUse') ?? {};
2021-02-09 09:18:52 +01:00
console.log("ITEM USE GET", itemUse);
return itemUse[itemId] ?? 0;
2021-02-09 09:18:52 +01:00
}
2021-03-15 00:05:56 +01:00
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
/* -- entites -- */
/* retourne true si on peut continuer, false si on ne peut pas continuer */
2021-01-09 19:33:19 +01:00
async targetEntiteNonAccordee(target, when = 'avant-encaissement') {
if (target) {
return !await this.accorder(target.actor, when);
}
return false;
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async accorder(entite, when = 'avant-encaissement') {
if (when != game.settings.get("foundryvtt-reve-de-dragon", "accorder-entite-cauchemar")
2021-01-09 19:33:19 +01:00
|| !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
};
2021-01-09 19:33:19 +01:00
if (rolled.isSuccess) {
await entite.setEntiteReveAccordee(this);
}
2021-01-09 19:33:19 +01:00
await RdDResolutionTable.displayRollData(rollData, this, 'chat-resultat-accorder-cauchemar.html');
if (rolled.isPart) {
await this._appliquerAjoutExperience(rollData, true);
}
return rolled.isSuccess;
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
isEntiteCauchemar() {
return this.data.type == 'entite';
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
isEntiteCauchemarAccordee(attaquant) {
if (!this.isEntiteCauchemar()) { return true; }
let resonnance = Misc.templateData(this).sante.resonnance;
return (resonnance.actors.find(it => it == attaquant._id));
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
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);
2021-01-09 19:33:19 +01:00
if (resonnance.actors.find(it => it == attaquant._id)) {
// déjà accordé
return;
}
resonnance.actors.push(attaquant._id);
2021-01-09 19:33:19 +01:00
await this.update({ "data.sante.resonnance": resonnance });
return;
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
2021-04-15 00:25:40 +02:00
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);
}
2020-12-31 00:55:02 +01:00
2021-04-15 00:25:40 +02:00
/* -------------------------------------------- */
async optimizeArgent(fortuneTotale) {
let monnaies = Monnaie.filtrerMonnaies(this.data.items);
let parValeur = Misc.classifyFirst(monnaies, it => Misc.templateData(it).valeur_deniers);
2021-04-15 00:25:40 +02:00
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
2020-12-31 00:55:02 +01:00
}
let updates = []
2021-04-15 00:25:40 +02:00
for (const [valeur, nombre] of Object.entries(nouvelleFortune)) {
2021-03-30 22:27:03 +02:00
updates.push({ _id: parValeur[valeur]._id, 'data.quantite': nombre });
2020-12-31 00:55:02 +01:00
}
await this.updateEmbeddedDocuments('Item', updates);
2020-12-31 00:55:02 +01:00
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
2021-04-15 00:25:40 +02:00
async depenserDeniers(depense, dataObj = undefined, quantite = 1, toActorId) {
depense = Number(depense);
let fortune = this.getFortune();
console.log("depenserDeniers", game.user.character, depense, fortune);
2021-01-01 21:11:56 +01:00
let msg = "";
2021-04-15 00:25:40 +02:00
if (depense == 0) {
2021-03-19 22:20:01 +01:00
if (dataObj) {
2021-04-15 00:25:40 +02:00
dataObj.payload.data.cout = depense / 100; // Mise à jour du prix en sols , avec le prix acheté
2021-03-19 22:20:01 +01:00
dataObj.payload.data.quantite = quantite;
await this.createEmbeddedDocuments('Item', [dataObj.payload]);
2021-04-15 00:25:40 +02:00
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)
if (toActor) {
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 !";
2021-03-19 22:20:01 +01:00
}
2021-01-01 21:11:56 +01:00
}
2021-01-09 19:33:19 +01:00
let message = {
whisper: ChatUtility.getWhisperRecipientsAndGMs(this.name),
content: msg
2021-01-01 21:11:56 +01:00
};
2021-01-09 19:33:19 +01:00
ChatMessage.create(message);
2020-12-31 00:55:02 +01:00
}
2021-04-15 00:25:40 +02:00
async ajouterDeniers(gain, fromActorId = undefined) {
if (fromActorId && !game.user.isGM) {
RdDActor.remoteActorCall({ userId: Misc.connectedGMOrUser(), actorId: this.id, method: 'ajouterDeniers', args: [gain, fromActorId] });
2021-04-15 00:25:40 +02:00
}
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 de votre argent.`
});
}
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
async monnaieIncDec(id, value) {
2021-03-29 18:08:18 +02:00
let monnaie = this.getMonnaie(id);
2021-01-09 19:33:19 +01:00
if (monnaie) {
2021-03-29 18:08:18 +02:00
const quantite = Math.max(0, Misc.templateData(monnaie).quantite + value);
await this.updateEmbeddedDocuments('Item', [{ _id: monnaie.id, 'data.quantite': quantite }]);
2020-12-31 00:55:02 +01:00
}
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
2021-04-20 23:16:18 +02:00
async effectuerTacheAlchimie(recetteId, tacheAlchimie, texteTache) {
let recetteData = Misc.data(this.getItemOfType(recetteId, 'recettealchimique'));
const actorData = Misc.data(this);
2021-04-20 23:16:18 +02:00
if (recetteData) {
if (tacheAlchimie != "couleur" && tacheAlchimie != "consistance") {
ui.notifications.warn(`L'étape alchimique ${tacheAlchimie} - ${texteTache} est inconnue`);
return;
2021-01-07 20:04:10 +01:00
}
2021-01-09 19:33:19 +01:00
2021-04-20 23:16:18 +02:00
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;
2021-04-21 00:59:10 +02:00
2021-01-07 20:04:10 +01:00
const dialog = await RdDRoll.create(this, rollData,
2021-01-09 19:33:19 +01:00
{
html: 'systems/foundryvtt-reve-de-dragon/templates/dialog-roll-alchimie.html',
2021-01-07 20:04:10 +01:00
},
{
name: 'tache-alchimique',
label: 'Tache Alchimique',
callbacks: [
this.createCallbackExperience(),
this.createCallbackAppelAuMoral(),
2021-01-07 20:04:10 +01:00
{ action: r => this._alchimieResult(r, false) }
]
}
);
dialog.render(true);
}
}
2021-04-20 23:16:18 +02:00
isCristalAlchimique(it) {
return it.type == 'objet' && Grammar.toLowerCaseNoAccent(it.name) == 'cristal alchimique' && it.data.quantite > 0;
}
2021-01-09 19:33:19 +01:00
/* -------------------------------------------- */
_alchimieResult(rollData) {
2021-01-07 20:04:10 +01:00
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 });
}
2021-04-04 18:37:16 +02:00
/* -------------------------------------------- */
2021-04-11 18:43:32 +02:00
async buildPotionGuerisonList(pointsGuerison) {
2021-04-04 22:34:59 +02:00
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) {
2021-04-11 18:43:32 +02:00
if (critique.active && pointsGuerison >= 6) {
2021-04-04 22:34:59 +02:00
pointsGuerison -= 6;
critique.active = false;
2021-04-11 18:43:32 +02:00
guerisonData.list.push("1 Blessure Critique (6 points)");
2021-04-04 22:34:59 +02:00
}
}
for (let grave of blessures.graves.liste) {
2021-04-11 18:43:32 +02:00
if (grave.active && pointsGuerison >= 4) {
2021-04-04 22:34:59 +02:00
pointsGuerison -= 4;
grave.active = false;
2021-04-11 18:43:32 +02:00
guerisonData.list.push("1 Blessure Grave (4 points)");
2021-04-04 22:34:59 +02:00
}
}
for (let legere of blessures.legeres.liste) {
2021-04-11 18:43:32 +02:00
if (legere.active && pointsGuerison >= 2) {
2021-04-04 22:34:59 +02:00
pointsGuerison -= 2;
legere.active = false;
2021-04-11 18:43:32 +02:00
guerisonData.list.push("1 Blessure Légère (2 points)");
2021-04-04 22:34:59 +02:00
}
}
await this.update({ "data.blessures": blessures });
let pvManquants = myData.sante.vie.max - myData.sante.vie.value;
2021-04-11 18:43:32 +02:00
let pvSoignees = Math.min(pvManquants, Math.floor(pointsGuerison / 2));
pointsGuerison -= pvSoignees * 2;
guerisonData.list.push(pvSoignees + " Points de Vie soignés");
2021-04-04 22:34:59 +02:00
await this.santeIncDec('vie', +pvSoignees, false);
guerisonData.pointsConsommes = pointsGuerisonInitial - pointsGuerison;
return guerisonData;
2021-04-11 18:43:32 +02:00
}
2021-04-04 22:34:59 +02:00
2021-04-09 15:23:48 +02:00
/* -------------------------------------------- */
2021-04-04 22:34:59 +02:00
async consommerPotionSoin(potionData) {
2021-04-04 23:07:13 +02:00
potionData.alias = this.name;
2021-04-12 01:03:37 +02:00
potionData.supprimer = true;
2021-04-04 23:07:13 +02:00
2021-04-12 00:16:23 +02:00
if (potionData.data.isEnchante) {
2021-04-04 22:34:59 +02:00
ChatMessage.create({
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
2021-04-11 18:43:32 +02:00
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-consommer-potion-soin.html`, potionData)
2021-04-04 22:34:59 +02:00
});
// Gestion de la résistance:
2021-04-11 18:43:32 +02:00
let rolled = await RdDResolutionTable.roll(this.getReveActuel(), -8);
2021-04-09 15:23:48 +02:00
potionData.reussiteReve = false;
2021-04-04 22:34:59 +02:00
if (!rolled.isSuccess) {
await this.reveActuelIncDec(-1);
2021-04-12 00:16:23 +02:00
potionData.guerisonData = await this.buildPotionGuerisonList(potionData.data.puissance);
2021-04-11 18:43:32 +02:00
potionData.guerisonMinutes = potionData.guerisonData.pointsConsommes * 5;
2021-04-04 22:47:33 +02:00
potionData.reussiteReve = true;
2021-04-04 22:34:59 +02:00
}
2021-04-09 15:23:48 +02:00
ChatMessage.create({
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
2021-04-11 18:43:32 +02:00
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-appliquer-potion-soin.html`, potionData)
});
2021-04-04 22:34:59 +02:00
} else {
2021-04-04 23:07:13 +02:00
ChatMessage.create({
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
2021-04-11 18:43:32 +02:00
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-appliquer-potion-soin.html`, potionData)
});
2021-04-04 23:07:13 +02:00
this.bonusRecuperationPotion = potionData.data.herbeBonus;
2021-04-04 22:34:59 +02:00
}
}
2021-04-09 15:23:48 +02:00
/* -------------------------------------------- */
async consommerPotionRepos(potionData) {
potionData.alias = this.name;
2021-04-12 01:03:37 +02:00
potionData.supprimer = true;
2021-04-09 15:23:48 +02:00
2021-04-12 00:16:23 +02:00
if (potionData.data.isEnchante) {
2021-04-09 15:23:48 +02:00
ChatMessage.create({
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
2021-04-11 18:43:32 +02:00
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-consommer-potion-repos.html`, potionData)
2021-04-09 15:23:48 +02:00
});
// Gestion de la résistance:
2021-04-11 18:43:32 +02:00
let rolled = await RdDResolutionTable.roll(this.getReveActuel(), -8);
2021-04-09 15:23:48 +02:00
potionData.reussiteReve = false;
if (!rolled.isSuccess) {
await this.reveActuelIncDec(-1);
let fatigueActuelle = this.getFatigueActuelle();
2021-04-12 00:16:23 +02:00
potionData.caseFatigueReel = Math.min(fatigueActuelle, potionData.data.puissance);
2021-04-09 15:23:48 +02:00
potionData.guerisonDureeUnite = (potionData.data.reposalchimique) ? "rounds" : "minutes";
2021-04-11 18:43:32 +02:00
potionData.guerisonDureeValue = (potionData.data.reposalchimique) ? potionData.caseFatigueReel : potionData.caseFatigueReel * 5;
2021-04-09 15:23:48 +02:00
potionData.reussiteReve = true;
potionData.aphasiePermanente = false;
2021-04-11 18:43:32 +02:00
if (potionData.data.reposalchimique) {
let chanceAphasie = new Roll("1d100").evaluate({ async: false }).total;
if (chanceAphasie <= potionData.data.pr) {
2021-04-09 15:23:48 +02:00
potionData.aphasiePermanente = true;
}
}
await this.santeIncDec("fatigue", -potionData.caseFatigueReel);
}
ChatMessage.create({
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
2021-04-11 18:43:32 +02:00
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-appliquer-potion-repos.html`, potionData)
});
2021-04-09 15:23:48 +02:00
} else {
ChatMessage.create({
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
2021-04-11 18:43:32 +02:00
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-appliquer-potion-repos.html`, potionData)
});
2021-04-09 15:23:48 +02:00
this.bonusRepos = potionData.data.herbeBonus;
}
}
2021-04-10 21:07:53 +02:00
/* -------------------------------------------- */
2021-04-11 18:43:32 +02:00
dialogFabriquerPotion(herbe) {
2021-04-10 21:07:53 +02:00
DialogFabriquerPotion.create(this, herbe, {
html: 'systems/foundryvtt-reve-de-dragon/templates/dialog-fabriquer-potion-base.html',
}, []);
}
/* -------------------------------------------- */
async fabriquerPotion(herbeData) {
2021-04-10 21:07:53 +02:00
let newPotion = {
name: `Potion de ${herbeData.data.categorie} (${herbeData.name})`, type: 'potion',
2021-04-10 21:07:53 +02:00
img: "systems/foundryvtt-reve-de-dragon/icons/objets/fiole_verre.webp",
2021-04-11 18:43:32 +02:00
data: {
quantite: 1, valeur_deniers: 1, encombrement: 0.01,
categorie: herbeData.data.categorie,
herbe: herbeData.name,
rarete: herbeData.data.rarete,
herbebrins: herbeData.nbBrins,
2021-04-11 18:43:32 +02:00
description: ""
}
2021-04-10 21:07:53 +02:00
}
2021-04-11 18:43:32 +02:00
await this.createEmbeddedDocuments('Item', [newPotion], { renderSheet: true });
2021-04-10 21:07:53 +02:00
let newQuantite = herbeData.data.quantite - herbeData.nbBrins;
2021-04-10 21:07:53 +02:00
let messageData = {
alias: this.name,
categorie: herbeData.data.categorie,
herbe: herbeData.name,
nbBrinsPotion: herbeData.nbBrins,
2021-04-10 21:07:53 +02:00
nbBrinsReste: newQuantite
}
2021-04-12 01:03:37 +02:00
this.diminuerQuantiteObjet(herbeData._id, herbeData.nbBrins);
2021-04-13 22:42:39 +02:00
2021-04-10 21:07:53 +02:00
ChatMessage.create({
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
2021-04-11 18:43:32 +02:00
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-fabriquer-potion-base.html`, messageData)
2021-04-10 21:07:53 +02:00
});
2021-04-11 18:43:32 +02:00
}
2021-04-09 15:23:48 +02:00
2021-04-12 01:03:37 +02:00
async diminuerQuantiteObjet(id, nb, options = { supprimerSiZero: false }) {
const item = this.getObjet(id);
2021-04-13 22:42:39 +02:00
if (item) {
2021-04-12 01:03:37 +02:00
await item.diminuerQuantite(nb, options);
}
}
2021-04-09 17:30:32 +02:00
/* -------------------------------------------- */
2021-04-11 18:43:32 +02:00
async consommerPotionGenerique(potionData) {
2021-04-09 17:30:32 +02:00
potionData.alias = this.name;
ChatMessage.create({
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
2021-04-11 18:43:32 +02:00
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-consommer-potion-generique.html`, potionData)
2021-04-09 17:30:32 +02:00
});
2021-04-11 18:43:32 +02:00
}
2021-04-09 17:30:32 +02:00
2021-04-04 22:34:59 +02:00
/* -------------------------------------------- */
2021-04-11 18:43:32 +02:00
async consommerPotion(potion) {
2021-04-04 18:37:16 +02:00
const potionData = Misc.data(potion);
2021-04-04 22:34:59 +02:00
2021-04-11 18:43:32 +02:00
if (potionData.data.categorie.includes('Soin')) {
this.consommerPotionSoin(potionData);
} else if (potionData.data.categorie.includes('Repos')) {
2021-04-09 15:23:48 +02:00
this.consommerPotionRepos(potionData);
2021-04-04 22:34:59 +02:00
} else {
2021-04-11 18:43:32 +02:00
this.consommerPotionGenerique(potionData);
2021-04-04 22:34:59 +02:00
}
2021-04-12 01:03:37 +02:00
this.diminuerQuantiteObjet(potion.id, 1, { supprimerSiZero: potionData.supprimer });
2021-04-04 18:37:16 +02:00
}
/* -------------------------------------------- */
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 {
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 {
this.deleteStatusEffectById(statusId);
}
}
/* -------------------------------------------- */
deleteStatusEffectById(id) {
const ids = Array.from(this.effects?.values())
.filter(it => it.data.flags.core?.statusId == id)
.map(it => it.id);
2021-04-11 23:02:53 +02:00
if (ids.length > 0) {
this.deleteEmbeddedDocuments('ActiveEffect', ids);
}
}
/* -------------------------------------------- */
deleteStatusEffect(effect) {
const ids = Array.from(this.effects?.values())
.filter(it => StatusEffects.statusId(it.data) == StatusEffects.statusId(effect))
.map(it => it.id);
this.deleteEmbeddedDocuments('ActiveEffect', ids);
}
/* -------------------------------------------- */
async addStatusEffectById(id) {
const statusEffect = CONFIG.statusEffects.find(it => it.id == id);
await this.addStatusEffect(statusEffect);
}
/* -------------------------------------------- */
async addStatusEffect(statusEffect) {
2021-04-11 23:02:53 +02:00
const effet = Misc.data(statusEffect);
this.deleteStatusEffectById(effet.id);
2021-04-11 23:02:53 +02:00
effet.flags = effet.flags ?? { core: {} };
effet.flags.core.statusId = effet.id;
await this.createEmbeddedDocuments('ActiveEffect', [effet]);
}
2021-01-14 15:29:47 +01:00
/* -------------------------------------------- */
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);
}
}
2021-01-14 15:29:47 +01:00
/* -------------------------------------------- */
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, item)
}
}
}
2021-03-15 00:05:56 +01:00
notifyGestionTeteSouffleQueue(item, manualMessage = true) {
ChatMessage.create({
whisper: ChatUtility.getWhisperRecipientsAndGMs(game.user.name),
2021-03-15 00:05:56 +01:00
content: `${this.name} a reçu un/une ${item.type}: ${item.name}, qui ${manualMessage ? "n'est pas" : "est"} géré automatiquement. ${manualMessage ?? ''}`
});
2021-03-15 00:05:56 +01:00
}
}