fvtt-pegasus-rpg/modules/pegasus-utility.js

593 lines
20 KiB
JavaScript

/* -------------------------------------------- */
/* -------------------------------------------- */
export class PegasusUtility {
/* -------------------------------------------- */
static async init() {
Hooks.on('renderChatLog', (log, html, data) => PegasusUtility.chatListeners(html));
this.rollDataStore = {}
this.defenderStore = {}
}
/* -------------------------------------------- */
static getSpecs( ) {
return this.specs;
}
/* -------------------------------------------- */
static async ready() {
const specs = await PegasusUtility.loadCompendium("fvtt-pegasus-rpg.specialisations");
this.specs = specs.map(i => i.toObject());
}
/* -------------------------------------------- */
static computeAttackDefense(defenseRollId) {
let defenseRollData = this.getRollData(defenseRollId );
let attackRollData = this.getRollData(defenseRollData.linkedRollId);
let defender = game.actors.get( defenseRollData.actorId);
defender.processDefenseResult(defenseRollData, attackRollData);
}
/* -------------------------------------------- */
static applyDamage( defenseRollId) {
let defenseRollData = this.getRollData(defenseRollId );
let defender = game.actors.get( defenseRollData.actorId);
defender.applyDamageLoss( defenseRollData.finalDamage) ;
}
/* -------------------------------------------- */
static applyNoDefense( actorId, attackRollId ) {
let attackRollData = this.getRollData(attackRollId );
let defender = game.actors.get( actorId );
defender.processNoDefense( attackRollData ) ;
}
/* -------------------------------------------- */
static reduceDamageWithChi( defenseRollId) {
let defenseRollData = this.getRollData(defenseRollId );
let attackRollData = this.getRollData(defenseRollData.linkedRollId);
let defender = game.actors.get( defenseRollData.actorId);
defender.reduceDamageWithChi(defenseRollData, attackRollData);
}
/* -------------------------------------------- */
static async chatListeners(html) {
html.on("click", '.apply-technique-cost', event => {
const rollId = $(event.currentTarget).data("roll-id");
const actorId = $(event.currentTarget).data("actor-id");
const techId = $(event.currentTarget).data("technique-id");
let actor = game.actors.get( actorId);
actor.applyTechniqueCost(techId);
});
html.on("click", '.apply-defense-roll', event => {
const defenseRollId = $(event.currentTarget).data("roll-id");
this.computeAttackDefense(defenseRollId);
});
html.on("click", '.apply-nodefense', event => {
const actorId = $(event.currentTarget).data("actor-id");
const rollId = $(event.currentTarget).data("roll-id");
this.applyNoDefense(actorId, rollId);
});
html.on("click", '.apply-damage', event => {
const rollId = $(event.currentTarget).data("roll-id");
this.applyDamage(rollId);
});
}
/* -------------------------------------------- */
static async preloadHandlebarsTemplates() {
const templatePaths = [
'systems/fvtt-pegasus-rpg/templates/editor-notes-gm.html',
'systems/fvtt-pegasus-rpg/templates/partial-options-statistics.html',
'systems/fvtt-pegasus-rpg/templates/partial-options-level.html',
'systems/fvtt-pegasus-rpg/templates/partial-options-equipment-types.html'
]
return loadTemplates(templatePaths);
}
/* -------------------------------------------- */
static templateData(it) {
return PegasusUtility.data(it)?.data ?? {}
}
/* -------------------------------------------- */
static data(it) {
if (it instanceof Actor || it instanceof Item || it instanceof Combatant) {
return it.data;
}
return it;
}
/* -------------------------------------------- */
static getChiList() {
let chi = [];
chi.push( { name: "Jade" });
chi.push( { name: "Crimson" });
chi.push( { name: "Gold" });
chi.push( { name: "White" });
chi.push( { name: "Silver" });
return chi;
}
/* -------------------------------------------- */
static getskillChiList( ) {
let skillsName = [];
let skills = this.getSkills();
console.log("SKILLS", skills);
for (let skill of skills) {
skillsName.push( { name: skill.name });
}
skillsName = skillsName.concat( this.getChiList() );
return skillsName;
}
/* -------------------------------------------- */
static createDirectOptionList( min, max) {
let options = {};
for(let i=min; i<=max; i++) {
options[`${i}`] = `${i}`;
}
return options;
}
/* -------------------------------------------- */
static buildListOptions(min, max) {
let options = ""
for (let i = min; i <= max; i++) {
options += `<option value="${i}">${i}</option>`
}
return options;
}
/* -------------------------------------------- */
static getNegativeModifiers(min, max) {
let options = ""
options += `<option value="0">0</option>`
options += `<option value="-5">-5</option>`
options += `<option value="-10">-10</option>`
return options;
}
/* -------------------------------------------- */
static getPositiveModifiers(min, max) {
let options = ""
options += `<option value="0">0</option>`
options += `<option value="5">+5</option>`
options += `<option value="10">+10</option>`
options += `<option value="15">+15</option>`
options += `<option value="20">+20</option>`
options += `<option value="30">+30</option>`
options += `<option value="40">+40</option>`
options += `<option value="50">+60</option>`
options += `<option value="60">+50</option>`
options += `<option value="70">+70</option>`
return options;
}
/* -------------------------------------------- */
static getTarget() {
if (game.user.targets && game.user.targets.size == 1) {
for (let target of game.user.targets) {
return target;
}
}
return undefined;
}
/* -------------------------------------------- */
static getDefenseState( actorId) {
return this.defenderStore[actorId];
}
/* -------------------------------------------- */
static async updateDefenseState( defenderId, rollId) {
this.defenderStore[defenderId] = rollId;
if ( game.user.character && game.user.character.id == defenderId ) {
let defender = game.actors.get( defenderId);
let chatData = {
user: game.user.id,
alias : defender.name,
rollMode: game.settings.get("core", "rollMode"),
whisper: [game.user.id].concat( ChatMessage.getWhisperRecipients('GM') ),
content: `<div>${defender.name} is under attack. He must roll a skill/weapon/technique to defend himself or suffer damages (button below).
<button class="chat-card-button apply-nodefense" data-actor-id="${defenderId}" data-roll-id="${rollId}" >No defense</button></div`
};
//console.log("Apply damage chat", chatData );
await ChatMessage.create( chatData );
}
}
/* -------------------------------------------- */
static clearDefenseState( defenderId) {
this.defenderStore[defenderId] = undefined;
}
/* -------------------------------------------- */
static storeDefenseState( rollData ) {
game.socket.emit("system.fvtt-weapons-of-the-gods", {
name: "msg_update_defense_state", data: { defenderId: rollData.defenderId, rollId: rollData.rollId } } );
this.updateDefenseState(rollData.defenderId, rollData.rollId );
}
/* -------------------------------------------- */
static updateRollData( rollData) {
let id = rollData.rollId;
let oldRollData = this.rollDataStore[id] || {};
let newRollData = mergeObject( oldRollData, rollData);
this.rollDataStore[id] = newRollData;
}
/* -------------------------------------------- */
static saveRollData( rollData ) {
game.socket.emit("system.pegasus-rpg", {
name: "msg_update_roll", data: rollData } ); // Notify all other clients of the roll
this.updateRollData( rollData);
}
/* -------------------------------------------- */
static getRollData( id ) {
return this.rollDataStore[id];
}
/* -------------------------------------------- */
static onSocketMesssage( msg ) {
//console.log("SOCKET MESSAGE", msg.name, game.user.character.id, msg.data.defenderId);
if (msg.name == "msg_update_defense_state" ) {
this.updateDefenseState( msg.data.defenderId, msg.data.rollId );
}
if (msg.name == "msg_update_roll" ) {
this.updateRollData( msg.data );
}
}
/* -------------------------------------------- */
static chatDataSetup(content, modeOverride, isRoll = false, forceWhisper) {
let chatData = {
user: game.user.id,
rollMode: modeOverride || game.settings.get("core", "rollMode"),
content: content
};
if (["gmroll", "blindroll"].includes(chatData.rollMode)) chatData["whisper"] = ChatMessage.getWhisperRecipients("GM").map(u => u.id);
if (chatData.rollMode === "blindroll") chatData["blind"] = true;
else if (chatData.rollMode === "selfroll") chatData["whisper"] = [game.user];
if (forceWhisper) { // Final force !
chatData["speaker"] = ChatMessage.getSpeaker();
chatData["whisper"] = ChatMessage.getWhisperRecipients(forceWhisper);
}
return chatData;
}
/* -------------------------------------------- */
static async loadCompendiumData(compendium) {
const pack = game.packs.get(compendium);
return await pack?.getDocuments() ?? [];
}
/* -------------------------------------------- */
static async loadCompendium(compendium, filter = item => true) {
let compendiumData = await this.loadCompendiumData(compendium);
//console.log("Compendium", compendiumData);
return compendiumData.filter(filter);
}
/* -------------------------------------------- */
static async showDiceSoNice(roll, rollMode) {
if (game.modules.get("dice-so-nice")?.active) {
if (game.dice3d) {
let whisper = null;
let blind = false;
rollMode = rollMode ?? game.settings.get("core", "rollMode");
switch (rollMode) {
case "blindroll": //GM only
blind = true;
case "gmroll": //GM + rolling player
whisper = this.getUsers(user => user.isGM);
break;
case "roll": //everybody
whisper = this.getUsers(user => user.active);
break;
case "selfroll":
whisper = [game.user.id];
break;
}
await game.dice3d.showForRoll(roll, game.user, true, whisper, blind);
}
}
}
/* -------------------------------------------- */
static async rollWotG( rollData ) {
if (rollData.mode == "chidamage" ) {
let defender = game.actors.get( rollData.actorId);
defender.rollChiDamage(rollData);
return;
}
let nbDice = 0;
if ( rollData.mode == 'skill' || rollData.mode == 'technique') {
nbDice = rollData.skill?.data.level || 0;
}
if ( rollData.mode == 'weapon' ) {
rollData.skill = rollData.weapon.data.skills[rollData.skillKey];
rollData.skillAttr = rollData.weapon.data.skills[rollData.skillKey].data.attr;
nbDice = rollData.skill?.data.level || 0;
}
if ( rollData.mode == 'technique') {
// Compute number of dice
if (rollData.attr ) {
rollData.skillAttr = rollData.attr;
}
if (rollData.chi ) {
rollData.skillAttr = rollData.chi;
nbDice = rollData.skillAttr.value || 0;
}
}
if ( rollData.skill && rollData.skillAttr.value >= rollData.skill.data.level) {
nbDice++;
}
if ( nbDice == 0) nbDice = 1;
nbDice += rollData.specialtiesBonus;
// Build dice formula
let diceTab = [];
for(let i=0; i<nbDice; i++) {
diceTab[i] = "1d10";
}
let formula = "{"+ diceTab.join(',') + '}';
// Performs roll
let myRoll = rollData.roll;
if ( !myRoll ) { // New rolls only of no rerolls
myRoll = new Roll(formula).roll( { async: false} );
console.log("ROLL : ", formula);
await this.showDiceSoNice(myRoll, game.settings.get("core", "rollMode") );
rollData.roll = myRoll
}
// Build the list of dices per number of occurence
let sortedRoll = [];
let bestScore = 0;
let diceResults = [];
for (let i=0; i<10; i++) {
sortedRoll[i] = 0;
}
for (let i=0; i<nbDice; i++) {
let dice1 = duplicate(myRoll.dice[i]);
if (dice1.results[0].result == 10) dice1.results[0].result = 0;
dice1.results[0].diceIndex = i;
diceResults.push( dice1.results[0] );
let nbFound = 1;
for (let j=0; j<nbDice; j++) {
if (j!=i) {
let dice2 = myRoll.dice[j];
if (dice2.results[0].result == 10) dice2.results[0].result = 0;
if (dice1.results[0].result == dice2.results[0].result) {
nbFound++;
}
}
}
let score = (nbFound * 10) + dice1.results[0].result;
if (score > bestScore) bestScore = score;
sortedRoll[dice1.results[0].result] = nbFound;
}
// Final score and keep data
rollData.nbDice = nbDice;
rollData.bestScore = bestScore;
rollData.diceResults = diceResults;
rollData.finalScore = bestScore + rollData.negativeModifier + rollData.positiveModifier;
console.log("ROLLLL!!!!", rollData);
let actor = game.actors.get(rollData.actorId);
this.createChatWithRollMode( rollData.alias, {
content: await renderTemplate(`systems/fvtt-weapons-of-the-gods/templates/chat-generic-result.html`, rollData)
});
if ( rollData.defender ) {
this.storeDefenseState( rollData );
}
this.saveRollData( rollData );
}
/* -------------------------------------------- */
static getDamageDice( result ) {
if ( result < 0) return 0;
return Math.floor(result/5) + 1;
}
/* -------------------------------------------- */
static removeDice( rollData, diceIndex) {
let diceResults = rollData.diceResults;
diceResults.splice( diceIndex, 1);
rollData.diceResults = diceResults;
rollData.nbDice = diceResults.length;
this.updateRoll(rollData);
}
/* -------------------------------------------- */
static addDice(rollId, diceValue) {
let rollData = this.getRollData( rollId );
let diceResults = rollData.diceResults;
let newResult = duplicate(diceResults[0]);
newResult.result = diceValue;
diceResults.push( newResult);
rollData.diceResults = diceResults;
rollData.nbDice = diceResults.length;
this.updateRoll(rollData);
}
/* ------------------------- ------------------- */
static async updateRoll( rollData) {
let diceResults = rollData.diceResults;
let sortedRoll = [];
for (let i=0; i<10; i++) {
sortedRoll[i] = 0;
}
for (let dice of diceResults) {
sortedRoll[dice.result]++;
}
let index = 0;
let bestRoll = 0;
for (let i=0; i<10; i++) {
if ( sortedRoll[i] > bestRoll) {
bestRoll = sortedRoll[i];
index = i;
}
}
let bestScore = (bestRoll * 10) + index;
rollData.bestScore = bestScore;
rollData.finalScore = bestScore + rollData.negativeModifier + rollData.positiveModifier;
this.saveRollData(rollData );
this.createChatWithRollMode( rollData.alias, {
content: await renderTemplate(`systems/fvtt-weapons-of-the-gods/templates/chat-generic-result.html`, rollData)
});
}
/* ------------------------- ------------------- */
static async rerollDice( actorId, diceIndex = -1 ) {
let actor = game.actors.get(actorId);
let rollData = actor.getRollData( );
if ( diceIndex == -1 ) {
rollData.hasWillpower = actor.decrementWillpower();
rollData.roll = undefined;
} else {
let myRoll = new Roll("1d6").roll( { async: false} );
await this.showDiceSoNice(myRoll, game.settings.get("core", "rollMode") );
console.log("Result: ", myRoll);
rollData.roll.dice[0].results[diceIndex].result = myRoll.total; // Patch
rollData.nbStrongHitUsed++;
}
this.rollFraggedKingdom( rollData );
}
/* -------------------------------------------- */
static getUsers(filter) {
return game.users.filter(filter).map(user => user.data._id);
}
/* -------------------------------------------- */
static getWhisperRecipients(rollMode, name) {
switch (rollMode) {
case "blindroll": return this.getUsers(user => user.isGM);
case "gmroll": return this.getWhisperRecipientsAndGMs(name);
case "selfroll": return [game.user.id];
}
return undefined;
}
/* -------------------------------------------- */
static getWhisperRecipientsAndGMs(name) {
let recep1 = ChatMessage.getWhisperRecipients(name) || [];
return recep1.concat(ChatMessage.getWhisperRecipients('GM'));
}
/* -------------------------------------------- */
static blindMessageToGM(chatOptions) {
let chatGM = duplicate(chatOptions);
chatGM.whisper = this.getUsers(user => user.isGM);
chatGM.content = "Blinde message of " + game.user.name + "<br>" + chatOptions.content;
console.log("blindMessageToGM", chatGM);
game.socket.emit("system.fvtt-weapons-of-the-gods", { msg: "msg_gm_chat_message", data: chatGM });
}
/* -------------------------------------------- */
static split3Columns(data) {
let array = [ [], [], [] ];
if (data== undefined) return array;
let col = 0;
for (let key in data) {
let keyword = data[key];
keyword.key = key; // Self-reference
array[col].push( keyword);
col++;
if (col == 3) col = 0;
}
return array;
}
/* -------------------------------------------- */
static createChatMessage(name, rollMode, chatOptions) {
switch (rollMode) {
case "blindroll": // GM only
if (!game.user.isGM) {
this.blindMessageToGM(chatOptions);
chatOptions.whisper = [game.user.id];
chatOptions.content = "Message only to the GM";
}
else {
chatOptions.whisper = this.getUsers(user => user.isGM);
}
break;
default:
chatOptions.whisper = this.getWhisperRecipients(rollMode, name);
break;
}
chatOptions.alias = chatOptions.alias || name;
ChatMessage.create(chatOptions);
}
/* -------------------------------------------- */
static createChatWithRollMode(name, chatOptions) {
this.createChatMessage(name, game.settings.get("core", "rollMode"), chatOptions);
}
/* -------------------------------------------- */
static buildDifficultyOptions( ) {
let options = ""
options += `<option value="0">None</option>`
options += `<option value="8">Easy</option>`
options += `<option value="12">Moderate</option>`
options += `<option value="16">Difficult</option>`
options += `<option value="18">Very Difficult</option>`
return options;
}
/* -------------------------------------------- */
static async confirmDelete(actorSheet, li) {
let itemId = li.data("item-id");
let msgTxt = "<p>Are you sure to remove this Item ?";
let buttons = {
delete: {
icon: '<i class="fas fa-check"></i>',
label: "Yes, remove it",
callback: () => {
actorSheet.actor.deleteEmbeddedDocuments( "Item", [itemId] );
li.slideUp(200, () => actorSheet.render(false));
}
},
cancel: {
icon: '<i class="fas fa-times"></i>',
label: "Cancel"
}
}
msgTxt += "</p>";
let d = new Dialog({
title: "Confirm removal",
content: msgTxt,
buttons: buttons,
default: "cancel"
});
d.render(true);
}
}