Cleanup - preparation Coeur

Simplification de code:
- des Méthodes simples sur une ligne
- utilisation de item.update au lieu de updateEmbeddedDocuments
  quand possibe
- renommage des templates SubActeur
- déplacement de logs quand compétence non trouvée
This commit is contained in:
2023-11-21 16:03:26 +01:00
parent bfb7b9b6bf
commit b5db2a9ef3
27 changed files with 375 additions and 388 deletions

View File

@ -83,29 +83,27 @@ export class RdDActor extends RdDBaseActorSang {
this.system.compteurs.chance.max = this.system.carac.chance.value;
}
$computeIsHautRevant() {
this.system.attributs.hautrevant.value = this.itemTypes['tete'].find(it => Grammar.equalsInsensitive(it.name, 'don de haut-reve'))
? "Haut rêvant"
: "";
}
/* -------------------------------------------- */
canReceive(item) {
return ![TYPES.competencecreature, TYPES.tarot, TYPES.service].includes(item.type)
}
/* -------------------------------------------- */
isPersonnage() { return true }
isHautRevant() { return this.system.attributs.hautrevant.value != "" }
getReveActuel() {
return Misc.toInt(this.system.reve?.reve?.value ?? this.carac.reve.value);
}
getChanceActuel() {
return Misc.toInt(this.system.compteurs.chance?.value ?? 10);
}
/* -------------------------------------------- */
getAgilite() { return Number(this.system.carac.agilite?.value ?? 0) }
getChance() { return Number(this.system.carac.chance?.value ?? 0) }
/* -------------------------------------------- */
getMoralTotal() {
return Number(this.system.compteurs.moral?.value ?? 0);
}
getReveActuel() { return Misc.toInt(this.system.reve?.reve?.value ?? this.carac.reve.value) }
getChanceActuel() { return Misc.toInt(this.system.compteurs.chance?.value ?? 10) }
getMoralTotal() { return Number(this.system.compteurs.moral?.value ?? 0) }
/* -------------------------------------------- */
getEtatGeneral(options = { ethylisme: false }) {
@ -130,41 +128,19 @@ export class RdDActor extends RdDBaseActorSang {
}
/* -------------------------------------------- */
getTache(id) {
return this.findItemLike(id, 'tache');
}
getMeditation(id) {
return this.findItemLike(id, 'meditation');
}
getChant(id) {
return this.findItemLike(id, 'chant');
}
getDanse(id) {
return this.findItemLike(id, 'danse');
}
getMusique(id) {
return this.findItemLike(id, 'musique');
}
getOeuvre(id, type = 'oeuvre') {
return this.findItemLike(id, type);
}
getJeu(id) {
return this.findItemLike(id, 'jeu');
}
getRecetteCuisine(id) {
return this.findItemLike(id, 'recettecuisine');
}
/* -------------------------------------------- */
getDraconicList() {
return this.itemTypes[TYPES.competence].filter(it => it.system.categorie == 'draconic')
}
/* -------------------------------------------- */
getBestDraconic() {
const list = this.getDraconicList()
.sort(Misc.descending(it => it.system.niveau))
return duplicate(list[0])
}
getTache(id) { return this.findItemLike(id, 'tache') }
getMeditation(id) { return this.findItemLike(id, 'meditation') }
getChant(id) { return this.findItemLike(id, 'chant') }
getDanse(id) { return this.findItemLike(id, 'danse') }
getMusique(id) { return this.findItemLike(id, 'musique') }
getOeuvre(id, type = 'oeuvre') { return this.findItemLike(id, type) }
getJeu(id) { return this.findItemLike(id, 'jeu') }
getRecetteCuisine(id) { return this.findItemLike(id, 'recettecuisine') }
/* -------------------------------------------- */
getDemiReve() { return this.system.reve.tmrpos.coord }
getDraconicList() { return this.itemTypes[TYPES.competence].filter(it => it.system.categorie == 'draconic') }
getBestDraconic() { return duplicate(this.getDraconicList().sort(Misc.descending(it => it.system.niveau)).find(it => true)) }
getDraconicOuPossession() {
return [...this.getDraconicList().filter(it => it.system.niveau >= 0),
super.getDraconicOuPossession()]
@ -172,36 +148,33 @@ export class RdDActor extends RdDBaseActorSang {
.find(it => true)
}
getDemiReve() {
return this.system.reve.tmrpos.coord;
/* -------------------------------------------- */
async $perteRevePotionsEnchantees() {
let potions = this.itemTypes[TYPES.potion]
.filter(it => it.system.categorie.toLowerCase().includes('enchant') && !potion.system.prpermanent)
const potionUpdates = Promise.all(potions.map(async potion => {
console.log(potion)
let nouveauReve = (potion.system.pr > 0) ? potion.system.pr - 1 : 0;
const message = await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-potionenchantee-chateaudormant.html`, {
pr: nouveauReve,
alias: this.name,
potionName: potion.name,
potionImg: potion.img
})
ChatMessage.create({
whisper: ChatUtility.getWhisperRecipientsAndGMs(this.name),
content: message
});
return { _id: potion._id, 'system.pr': nouveauReve };
}))
await this.updateEmbeddedDocuments('Item', potionUpdates);
}
/* -------------------------------------------- */
async verifierPotionsEnchantees() {
let potionsEnchantees = this.filterItems(it => it.type == 'potion' && it.system.categorie.toLowerCase().includes('enchant'));
for (let potion of potionsEnchantees) {
if (!potion.system.prpermanent) {
console.log(potion);
let newPr = (potion.system.pr > 0) ? potion.system.pr - 1 : 0;
let update = { _id: potion._id, 'system.pr': newPr };
const updated = await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
let messageData = {
pr: newPr,
alias: this.name,
potionName: potion.name,
potionImg: potion.img
}
ChatMessage.create({
whisper: ChatUtility.getWhisperRecipientsAndGMs(this.name),
content: await renderTemplate(`systems/foundryvtt-reve-de-dragon/templates/chat-potionenchantee-chateaudormant.html`, messageData)
});
}
}
}
/* -------------------------------------------- */
hasArmeeMeleeEquipee() { // Return true si l'acteur possède au moins 1 arme de mêlée équipée
/** --------------------------------------------
* @returns true si l'acteur possède au moins 1 arme de mêlée équipée
*/
hasArmeeMeleeEquipee() {
return this.itemTypes['arme'].find(it => it.system.equipe && it.system.competence != "")
}
@ -229,12 +202,12 @@ export class RdDActor extends RdDBaseActorSang {
}
/* -------------------------------------------- */
async grisReve(nGrisReve) {
async grisReve(nbJours) {
let message = {
whisper: ChatUtility.getWhisperRecipientsAndGMs(this.name),
content: `${nGrisReve} jours de gris rêve sont passés. `
content: `${nbJours} jours de gris rêve sont passés. `
};
for (let i = 0; i < nGrisReve; i++) {
for (let i = 0; i < nbJours; i++) {
await this.dormir(4, { grisReve: true });
await this._recuperationSante(message);
@ -252,7 +225,7 @@ export class RdDActor extends RdDBaseActorSang {
}
async _recuperationSante(message) {
const maladiesPoisons = this._maladiePoisons(message);
const maladiesPoisons = this.getMaladiePoisons();
const isMaladeEmpoisonne = maladiesPoisons.length > 0;
this._messageRecuperationMaladiePoisons(maladiesPoisons, message);
@ -260,9 +233,8 @@ export class RdDActor extends RdDBaseActorSang {
await this._recupererVie(message, isMaladeEmpoisonne);
}
_maladiePoisons(message) {
const actifs = this.items.filter(item => item.type == 'maladie' || (item.type == 'poison' && item.system.active));
return actifs;
getMaladiePoisons() {
return this.items.filter(item => item.type == 'maladie' || (item.type == 'poison' && item.system.active));
}
_messageRecuperationMaladiePoisons(maladiesPoisons, message) {
@ -275,12 +247,9 @@ export class RdDActor extends RdDBaseActorSang {
case 1: message.content += ` d'un mal inconnu`; break;
default: message.content += ` de ${nonIdentifies.length} maux inconnus`; break;
}
if (identifies.length > 0 && nonIdentifies.length > 0) { message.content += ' et' }
if (identifies.length > 0) {
if (nonIdentifies > 0) {
message.content += ' et';
} else {
message.content += ' de ' + identifies.map(it => it.name).reduce(Misc.joining(', '));
}
message.content += ' de ' + identifies.map(it => it.name).reduce(Misc.joining(', '));
}
}
}
@ -300,7 +269,7 @@ export class RdDActor extends RdDBaseActorSang {
await this.retourSeuilDeReve(message);
await this.setBonusPotionSoin(0);
await this.retourSust(message);
await this.verifierPotionsEnchantees();
await this.$perteRevePotionsEnchantees();
if (message.content != "") {
message.content = `A la fin Chateau Dormant, ${message.content}<br>Un nouveau jour se lève`;
ChatMessage.create(message);
@ -794,10 +763,8 @@ export class RdDActor extends RdDBaseActorSang {
const toNiveau = compValue ?? RdDItemCompetence.getNiveauBase(competence.system.categorie, competence.getCategories());
this.notifyCompetencesTronc(competence, toNiveau);
const fromNiveau = competence.system.niveau;
await this.updateEmbeddedDocuments('Item', [{ _id: competence.id, 'system.niveau': toNiveau }]);
await competence.update({ 'system.niveau': toNiveau });
await ExperienceLog.add(this, XP_TOPIC.NIVEAU, fromNiveau, toNiveau, competence.name, true);
} else {
console.log("Competence not found", idOrName);
}
}
@ -821,13 +788,11 @@ export class RdDActor extends RdDBaseActorSang {
if (isNaN(toXp) || typeof (toXp) != 'number') toXp = 0;
const fromXp = competence.system.xp;
this.checkCompetenceXP(idOrName, toXp);
await this.updateEmbeddedDocuments('Item', [{ _id: competence.id, 'system.xp': toXp }]);
await competence.update({ 'system.xp': toXp });
await ExperienceLog.add(this, XP_TOPIC.XP, fromXp, toXp, competence.name, true);
if (toXp > fromXp) {
RdDUtility.checkThanatosXP(idOrName);
}
} else {
console.log("Competence not found", idOrName);
}
}
@ -837,23 +802,19 @@ export class RdDActor extends RdDBaseActorSang {
if (competence) {
if (isNaN(toXpSort) || typeof (toXpSort) != 'number') toXpSort = 0;
const fromXpSort = competence.system.xp_sort;
await this.updateEmbeddedDocuments('Item', [{ _id: competence.id, 'system.xp_sort': toXpSort }]);
await competence.update({ 'system.xp_sort': toXpSort });
await ExperienceLog.add(this, XP_TOPIC.XPSORT, fromXpSort, toXpSort, competence.name, true);
if (toXpSort > fromXpSort) {
RdDUtility.checkThanatosXP(idOrName);
}
} else {
console.log("Competence not found", idOrName);
}
}
/* -------------------------------------------- */
async updateCompetenceArchetype(idOrName, compValue) {
let competence = this.getCompetence(idOrName);
let competence = this.getCompetence(idOrName)
if (competence) {
await this.updateEmbeddedDocuments('Item', [{ _id: competence.id, 'system.niveau_archetype': Math.max(compValue ?? 0, 0) }]);
} else {
console.log("Competence not found", idOrName);
await competence.update({ 'system.niveau_archetype': Math.max(compValue ?? 0, 0) });
}
}
@ -909,12 +870,6 @@ export class RdDActor extends RdDBaseActorSang {
}
/* -------------------------------------------- */
$computeIsHautRevant() {
this.system.attributs.hautrevant.value = this.itemTypes['tete'].find(it => Grammar.equalsInsensitive(it.name, 'don de haut-reve'))
? "Haut rêvant"
: "";
}
malusEthylisme() {
return Math.min(0, (this.system.compteurs.ethylisme?.value ?? 0));
}
@ -1299,7 +1254,7 @@ export class RdDActor extends RdDBaseActorSang {
if (exotisme < 0 || qualite < 0) {
const competence = qualite > 0 ? 'cuisine' : undefined
const difficulte = Math.min(exotisme, qualite)
const rolled = await this.doRollCaracCompetence('volonte', competence, difficulte, { title: `tente de surmonter l'exotisme de ${item.name}` })
const rolled = await this.doRollCaracCompetence('volonte', competence, difficulte, { title: `tente de surmonter l'exotisme de ${item.name}` })
return rolled.isSuccess
}
return true;
@ -2561,7 +2516,7 @@ export class RdDActor extends RdDBaseActorSang {
let item = this.getEmbeddedDocument('Item', itemID);
if (item?.isEquipable()) {
const isEquipe = !item.system.equipe;
await this.updateEmbeddedDocuments('Item', [{ _id: item.id, "system.equipe": isEquipe }]);
await item.update({ "system.equipe": isEquipe });
this.computeEncTotal();
if (isEquipe)
this.verifierForceMin(item);
@ -2677,85 +2632,106 @@ export class RdDActor extends RdDBaseActorSang {
}
/* -------------------------------------------- */
listeVehicules() {
const listeVehichules = this.system.subacteurs?.vehicules ?? [];
return this._buildActorLinksList(listeVehichules, vehicle => RdDActor._vehicleData(vehicle));
static $transformSubActeurSuivant = (suivant, link) => {
return mergeObject(RdDBaseActor.extractActorMin(suivant), {
coeur: link.coeur ?? 0
})
};
listeSuivants(filter = suivant => true) {
return RdDActor.$buildSubActorLinks(
this.system.subacteurs.suivants.filter(filter), RdDActor.$transformSubActeurSuivant
)
}
/* -------------------------------------------- */
listeSuivants() {
return this._buildActorLinksList(this.system.subacteurs?.suivants ?? []);
}
/* -------------------------------------------- */
listeMontures() {
return this._buildActorLinksList(this.system.subacteurs?.montures ?? []);
}
/* -------------------------------------------- */
_buildActorLinksList(links, actorTransformation = it => RdDActor._buildActorData(it)) {
return links.map(link => game.actors.get(link.id))
.filter(it => it != undefined)
.map(actorTransformation);
}
/* -------------------------------------------- */
static _vehicleData(vehicle) {
return {
id: vehicle.id,
name: vehicle.name,
img: vehicle.img,
system: {
categorie: vehicle.system.categorie,
etat: vehicle.system.etat
}
};
}
/* -------------------------------------------- */
static _buildActorData(it) {
return { id: it.id, name: it.name, img: it.img };
}
/* -------------------------------------------- */
async pushSubacteur(actor, dataArray, dataPath, dataName) {
let alreadyPresent = dataArray.find(attached => attached.id == actor._id);
if (!alreadyPresent) {
let newArray = duplicate(dataArray);
newArray.push({ id: actor._id });
await this.update({ [dataPath]: newArray });
} else {
ui.notifications.warn(dataName + " est déja attaché à ce Personnage.");
getSuivant(actorId) {
const suivant = this.system.subacteurs.suivants.find(it => it.id == actorId);
if (suivant) {
return RdDActor.$transformSubActeurSuivant(game.actors.get(actorId), suivant);
}
return undefined
}
/* -------------------------------------------- */
static $transformSubActeurVehicule = (vehicle, link) => {
return mergeObject(RdDBaseActor.extractActorMin(vehicle), {
system: { categorie: vehicle.system.categorie, etat: vehicle.system.etat }
})
};
listeVehicules() {
return RdDActor.$buildSubActorLinks(this.system.subacteurs.vehicules, RdDActor.$transformSubActeurVehicule)
}
/* -------------------------------------------- */
static $transformSubActeurCreature = (actor, link) => RdDBaseActor.extractActorMin(actor.id)
listeMontures() {
return RdDActor.$buildSubActorLinks(this.system.subacteurs.montures, RdDActor.$transformSubActeurCreature);
}
/* -------------------------------------------- */
static $buildSubActorLinks(subActors, actorTransformation = (actor, link) => undefined) {
if (!subActors) {
return []
}
return subActors.map(link => {
const actor = game.actors.get(link.id)
return actor ? actorTransformation(actor, link) : undefined
})
.filter(it => it != undefined)
.sort(Misc.ascending(it => it.name))
}
/* -------------------------------------------- */
addSubActeur(subActor) {
if (subActor?.id == this.id) {
ui.notifications.warn("Vous ne pouvez pas attacher un acteur à lui même")
if (!this.isAddSubActeurAllowed(subActor)) {
return
}
else if (!subActor?.isOwner) {
ui.notifications.warn("Vous n'avez pas les droits sur l'acteur que vous attachez.")
}
else {
if (subActor.type == 'vehicule') {
this.pushSubacteur(subActor, this.system.subacteurs.vehicules, 'system.subacteurs.vehicules', 'Ce Véhicule');
} else if (subActor.type == 'creature') {
this.pushSubacteur(subActor, this.system.subacteurs.montures, 'system.subacteurs.montures', 'Cette Monture');
} else if (subActor.type == 'personnage') {
this.pushSubacteur(subActor, this.system.subacteurs.suivants, 'system.subacteurs.suivants', 'Ce Suivant');
}
const subActorOnlyId = { id: subActor._id };
if (subActor.type == 'vehicule') {
this.pushSubActeur(subActorOnlyId, this.system.subacteurs.vehicules, `system.subacteurs.vehicules`, `Le véhicule ${subActor.name}`)
} else if (subActor.type == 'creature') {
this.pushSubActeur(subActorOnlyId, this.system.subacteurs.montures, 'system.subacteurs.montures', `L'animal ${subActor.name}`)
} else if (subActor.type == 'personnage') {
this.pushSubActeur(subActorOnlyId, this.system.subacteurs.suivants, 'system.subacteurs.suivants', `Le compagnon ${subActor.name}`)
}
}
/* -------------------------------------------- */
async removeSubacteur(actorId) {
let newVehicules = this.system.subacteurs.vehicules.filter(function (obj, index, arr) { return obj.id != actorId });
let newSuivants = this.system.subacteurs.suivants.filter(function (obj, index, arr) { return obj.id != actorId });
let newMontures = this.system.subacteurs.montures.filter(function (obj, index, arr) { return obj.id != actorId });
await this.update({ 'system.subacteurs.vehicules': newVehicules }, { renderSheet: false });
await this.update({ 'system.subacteurs.suivants': newSuivants }, { renderSheet: false });
await this.update({ 'system.subacteurs.montures': newMontures }, { renderSheet: false });
async pushSubActeur(subActor, dataArray, dataPath, dataName) {
let alreadyPresent = dataArray.find(attached => attached.id == subActor.id);
if (!alreadyPresent) {
let newArray = [...dataArray, subActor]
await this.update({ [dataPath]: newArray });
} else {
ui.notifications.warn(dataName + " est déja attaché à " + this.name);
}
}
isAddSubActeurAllowed(subActor) {
if (subActor?.id == undefined) {
ui.notifications.warn("Aucun acteur à ajouter")
return false
}
if (subActor?.id == this.id) {
ui.notifications.warn("Vous ne pouvez pas attacher un acteur à lui même")
return false
}
else if (!subActor?.isOwner) {
ui.notifications.warn("Vous n'avez pas les droits sur l'acteur que vous attachez.")
return false
}
return true
}
async deleteSubActeur(actorId) {
['vehicules', 'suivants', 'montures'].forEach(async type => {
const subList = this.system.subacteurs[type];
if (subList.find(it => it.id == actorId)) {
let newList = subList.filter(it => it.id != actorId)
await this.update({ [`system.subacteurs.${type}`]: newList }, { renderSheet: false });
}
})
}
/* -------------------------------------------- */