fvtt-malefices/modules/malefices-utility.js

567 lines
19 KiB
JavaScript
Raw Normal View History

2023-02-01 14:28:08 +01:00
/* -------------------------------------------- */
import { MaleficesCommands } from "./malefices-commands.js";
/* -------------------------------------------- */
export class MaleficesUtility {
/* -------------------------------------------- */
2023-03-08 20:24:19 +01:00
static async init() {
2023-02-01 14:28:08 +01:00
Hooks.on('renderChatLog', (log, html, data) => MaleficesUtility.chatListeners(html));
this.rollDataStore = {}
this.defenderStore = {}
MaleficesCommands.init();
2023-03-08 20:24:19 +01:00
}
/* -------------------------------------------- */
static async ready() {
2023-02-01 14:28:08 +01:00
Handlebars.registerHelper('count', function (list) {
return list.length;
})
Handlebars.registerHelper('includes', function (array, val) {
return array.includes(val);
})
Handlebars.registerHelper('upper', function (text) {
return text.toUpperCase();
})
Handlebars.registerHelper('lower', function (text) {
return text.toLowerCase()
})
Handlebars.registerHelper('upperFirst', function (text) {
if (typeof text !== 'string') return text
return text.charAt(0).toUpperCase() + text.slice(1)
})
Handlebars.registerHelper('notEmpty', function (list) {
return list.length > 0;
})
Handlebars.registerHelper('mul', function (a, b) {
return parseInt(a) * parseInt(b);
})
Handlebars.registerHelper('add', function (a, b) {
return parseInt(a) + parseInt(b);
})
game.settings.register("world", "character-summary-data", {
name: "character-summary-data",
scope: "world",
config: false,
default: { npcList: [], x: 200, y: 200 },
type: Object
})
const tarots = await MaleficesUtility.loadCompendium("fvtt-malefices.malefices-tarots")
this.tarots = tarots.map(i => i.toObject())
2023-02-01 14:28:08 +01:00
}
/*-------------------------------------------- */
static upperFirst(text) {
if (typeof text !== 'string') return text
return text.charAt(0).toUpperCase() + text.slice(1)
}
/*-------------------------------------------- */
2023-02-03 17:45:15 +01:00
static getTarots() {
return duplicate(this.tarots)
2023-02-01 14:28:08 +01:00
}
2023-02-03 17:45:15 +01:00
static getTarot(tId) {
return this.tarots.find(t => t._id == tId)
2023-02-01 14:28:08 +01:00
}
/* -------------------------------------------- */
static async loadCompendiumData(compendium) {
const pack = game.packs.get(compendium)
return await pack?.getDocuments() ?? []
}
/* -------------------------------------------- */
static async loadCompendium(compendium, filter = item => true) {
let compendiumData = await MaleficesUtility.loadCompendiumData(compendium)
return compendiumData.filter(filter)
}
/* -------------------------------------------- */
2023-02-01 21:30:35 +01:00
static getActorFromRollData(rollData) {
let actor = game.actors.get(rollData.actorId)
if (rollData.tokenId) {
let token = canvas.tokens.placeables.find(t => t.id == rollData.tokenId)
if (token) {
actor = token.actor
}
2023-02-01 14:28:08 +01:00
}
2023-02-01 21:30:35 +01:00
return actor
2023-02-01 14:28:08 +01:00
}
2023-02-07 19:55:33 +01:00
/* -------------------------------------------- */
static drawDeckCard(msgId) {
if (game.user.isGM) {
game.system.malefices.currentTirage.addCard(msgId)
} else {
game.socket.emit( "system.fvtt-malefices", {name: "msg-draw-card", data: {msgId: msgId}})
}
}
2023-02-01 14:28:08 +01:00
/* -------------------------------------------- */
static async chatListeners(html) {
2023-02-01 21:30:35 +01:00
html.on("click", '.roll-destin', event => {
let messageId = MaleficesUtility.findChatMessageId(event.currentTarget)
let message = game.messages.get(messageId)
let rollData = message.getFlag("world", "rolldata")
let actor = this.getActorFromRollData(rollData)
actor.incDecDestin(-1)
rollData.isReroll = true
this.rollMalefices(rollData)
2023-02-01 14:28:08 +01:00
})
2023-02-07 19:55:33 +01:00
html.on("click", '.draw-tarot-card', event => {
let messageId = MaleficesUtility.findChatMessageId(event.currentTarget)
this.drawDeckCard(messageId)
})
2023-02-01 14:28:08 +01:00
}
/* -------------------------------------------- */
static async preloadHandlebarsTemplates() {
const templatePaths = [
'systems/fvtt-malefices/templates/actors/editor-notes-gm.hbs',
'systems/fvtt-malefices/templates/items/partial-item-nav.hbs',
2023-02-01 19:48:35 +01:00
'systems/fvtt-malefices/templates/items/partial-item-description.hbs'
2023-02-01 14:28:08 +01:00
]
return loadTemplates(templatePaths);
}
/* -------------------------------------------- */
static removeChatMessageId(messageId) {
if (messageId) {
game.messages.get(messageId)?.delete();
}
}
static findChatMessageId(current) {
return MaleficesUtility.getChatMessageId(MaleficesUtility.findChatMessage(current));
}
static getChatMessageId(node) {
return node?.attributes.getNamedItem('data-message-id')?.value;
}
static findChatMessage(current) {
return MaleficesUtility.findNodeMatching(current, it => it.classList.contains('chat-message') && it.attributes.getNamedItem('data-message-id'));
}
static findNodeMatching(current, predicate) {
if (current) {
if (predicate(current)) {
return current;
}
return MaleficesUtility.findNodeMatching(current.parentElement, predicate);
}
return undefined;
}
/* -------------------------------------------- */
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 getTarget() {
if (game.user.targets) {
for (let target of game.user.targets) {
return target
}
}
return undefined
}
/* -------------------------------------------- */
static updateRollData(rollData) {
let id = rollData.rollId
let oldRollData = this.rollDataStore[id] || {}
let newRollData = mergeObject(oldRollData, rollData)
this.rollDataStore[id] = newRollData
}
/* -------------------------------------------- */
static async onSocketMesssage(msg) {
console.log("SOCKET MESSAGE", msg.name)
2023-02-07 19:55:33 +01:00
if (msg.name == "msg-draw-card") {
if ( game.user.isGM && game.system.malefices.currentTirage) {
game.system.malefices.currentTirage.addCard(msg.data.msgId)
2023-02-01 14:28:08 +01:00
}
}
}
/* -------------------------------------------- */
static async searchItem(dataItem) {
let item
if (dataItem.pack) {
let id = dataItem.id || dataItem._id
let items = await this.loadCompendium(dataItem.pack, item => item.id == id)
item = items[0] || undefined
} else {
item = game.items.get(dataItem.id)
}
return item
}
/* -------------------------------------------- */
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 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 processSpecialCard(actor, rollData) {
if (rollData.selectedCard.name.toLowerCase().includes("archange")) {
let actorCard = actor.items.find( c => c.type =="tarot" && c.name.toLowerCase().includes("archange"))
if (actorCard) {
MaleficesUtility.createChatMessage(actor.name, "gmroll", {
content: `Conséquence supplémentaire ! <br>L'Archange : ${actor.name} gagne 1 point de Spiritualité.` })
actor.incDecAttr("spiritualite", 1)
}
}
if (rollData.selectedCard.name.toLowerCase().includes("vicaire")) {
let actorCard = actor.items.find( c => c.type =="tarot" && c.name.toLowerCase().includes("vicaire"))
if (actorCard) {
MaleficesUtility.createChatMessage(actor.name, "blindroll", {
content: `Conséquence supplémentaire ! <br>Le Vicaire : ${actor.name} vient de gagner 1 point en Pratique de la Magie Blanche (MPMB, secret).` })
actor.incDecMPMB(1)
}
}
if (rollData.selectedCard.name.toLowerCase().includes("chance")) {
let actorCard = actor.items.find( c => c.type =="tarot" && c.name.toLowerCase().includes("chance"))
if (actorCard) {
MaleficesUtility.createChatMessage(actor.name, "gmroll", {
content: `Conséquence supplémentaire ! <br>La Chance : ${actor.name} a gagné 1 point de Destin.` })
actor.incDecDestin(1)
}
}
if (rollData.selectedCard.name.toLowerCase().includes("mort")) {
let actorCard = actor.items.find( c => c.type =="tarot" && c.name.toLowerCase().includes("mort"))
if (actorCard) {
MaleficesUtility.createChatMessage(actor.name, "gmroll", {
content: `Conséquence supplémentaire ! <br>La Mort : ${actor.name} est pétrifié par la peur.` })
actor.incDecDestin(1)
}
}
if (rollData.selectedCard.name.toLowerCase().includes("diable")) {
let actorCard = actor.items.find( c => c.type =="tarot" && c.name.toLowerCase().includes("diable"))
if (actorCard) {
MaleficesUtility.createChatMessage(actor.name, "gmroll", {
content: `Conséquence supplémentaire ! <br>Le Diable : ${actor.name} gagne 1 point de Rationnalité.` })
actor.incDecAttr("rationnalite", 1)
}
}
if (rollData.selectedCard.name.toLowerCase().includes("lune noire")) {
let actorCard = actor.items.find( c => c.type =="tarot" && c.name.toLowerCase().includes("lune noire"))
if (actorCard) {
MaleficesUtility.createChatMessage(actor.name, "blindroll", {
content: `Conséquence supplémentaire ! <br>La Lune Noire : ${actor.name} vient de gagner 1 point de Fluide (secret).` })
actor.incDecFluide(1)
}
}
if (rollData.selectedCard.name.toLowerCase().includes("grand livre")) {
let actorCard = actor.items.find( c => c.type =="tarot" && c.name.toLowerCase().includes("grand livre"))
if (actorCard) {
MaleficesUtility.createChatMessage(actor.name, "blindroll", {
content: `Conséquence supplémentaire ! <br>La Lune Noire : ${actor.name} vient de gagner 1 point de Fluide (secret).` })
actor.incDecFluide(1)
}
}
if (rollData.selectedCard.name.toLowerCase().includes("sorcier")) {
let actorCard = actor.items.find( c => c.type =="tarot" && c.name.toLowerCase().includes("sorcier"))
if (actorCard) {
MaleficesUtility.createChatMessage(actor.name, "blindroll", {
content: `Conséquence supplémentaire ! <br>Le Vicaire : ${actor.name} vient de gagner 1 point en Pratique de la Magie Noire (MPMN, secret).` })
actor.incDecMPMN(1)
}
}
}
/* -------------------------------------------- */
static computeResults(rollData) {
rollData.isSuccess = false
if (rollData.total <= rollData.target) {
rollData.isSuccess = true
}
if (rollData.total == 1) {
rollData.isSuccess = true
rollData.isCritical = true
}
if (rollData.total == 20) {
rollData.isSuccess = false
rollData.isFumble = true
}
if (rollData.total <= Math.floor(rollData.target / 3)) {
rollData.isPart = true
}
}
/* -------------------------------------------- */
static async tirageConfrontationMalefices(rollData) {
let actor = game.actors.get(rollData.actorId)
rollData.target = rollData.attr.value - rollData.confrontationDegre + rollData.confrontationModif
let deck = this.getTarots()
let index = Math.round(Math.random() * (deck.length-1))
let selectedCard = deck[index]
selectedCard.system.ispositif = (Math.random() > 0.5)
selectedCard.value = (selectedCard.system.ispositif)? selectedCard.system.numericvalueup : selectedCard.system.numericvaluedown
rollData.total = selectedCard.value
rollData.selectedCard = selectedCard
await MaleficesUtility.createChatMessage(actor.name, "gmroll", {
content: await renderTemplate(`systems/fvtt-malefices/templates/chat/display-tarot-card.hbs`, selectedCard)
})
this.computeResults(rollData)
if (rollData.isSuccess) {
rollData.gainAttr = Math.ceil(rollData.confrontationDegre/2) + ((rollData.isCritical ) ? 1 : 0)
actor.incDecAttr(rollData.attr.abbrev, rollData.gainAttr )
} else {
rollData.gainAttr = rollData.confrontationDegre
actor.incDecAttr(rollData.attr.abbrev, -rollData.gainAttr )
}
await MaleficesUtility.createChatMessage(actor.name, "gmroll", {
content: await renderTemplate(`systems/fvtt-malefices/templates/chat/chat-confrontation-result.hbs`, rollData)
})
this.processSpecialCard(actor, rollData)
}
2023-02-01 14:28:08 +01:00
/* -------------------------------------------- */
static async rollMalefices(rollData) {
let actor = game.actors.get(rollData.actorId)
2023-02-01 21:30:35 +01:00
2023-02-01 14:28:08 +01:00
// Build the dice formula
2023-02-01 19:48:35 +01:00
let diceFormula = "1d20"
2023-02-02 23:59:41 +01:00
rollData.target = rollData.attr.value + rollData.bonusMalusPerso + rollData.bonusMalusSituation + rollData.bonusMalusDef + rollData.bonusMalusPortee
2023-02-01 21:30:35 +01:00
if (rollData.attr.abbrev == "physique") {
rollData.target += rollData.phyMalus
}
2023-02-01 14:28:08 +01:00
rollData.diceFormula = diceFormula
// Performs roll
console.log("Roll formula", diceFormula)
2023-02-01 21:30:35 +01:00
let myRoll = new Roll(diceFormula).roll({ async: false })
await this.showDiceSoNice(myRoll, game.settings.get("core", "rollMode"))
2023-05-25 08:04:31 +02:00
rollData.roll = duplicate(myRoll)
rollData.total = myRoll.total
2023-02-01 14:28:08 +01:00
this.computeResults(rollData)
2023-02-01 14:28:08 +01:00
let msg = await this.createChatWithRollMode(rollData.alias, {
content: await renderTemplate(`systems/fvtt-malefices/templates/chat/chat-generic-result.hbs`, rollData)
})
msg.setFlag("world", "rolldata", rollData)
2023-02-01 19:48:35 +01:00
if (rollData.mode == "initiative") {
2023-02-01 21:30:35 +01:00
actor.setFlag("world", "initiative", myRoll.total)
2023-02-01 14:28:08 +01:00
}
console.log("Rolldata result", rollData)
}
/* -------------------------------------------- */
static sortArrayObjectsByName(myArray) {
myArray.sort((a, b) => {
let fa = a.name.toLowerCase();
let fb = b.name.toLowerCase();
if (fa < fb) {
return -1;
}
if (fa > fb) {
return 1;
}
return 0;
})
}
/* -------------------------------------------- */
static getUsers(filter) {
return game.users.filter(filter).map(user => user.id);
}
/* -------------------------------------------- */
static getWhisperRecipients(rollMode, name) {
switch (rollMode) {
case "blindroll": return this.getUsers(user => user.isGM);
case "gmroll": return this.getWhisperRecipientsAndGMs(name);
2023-02-07 19:55:33 +01:00
case "useronly": return this.getWhisperRecipientsOnly(name);
2023-02-01 14:28:08 +01:00
case "selfroll": return [game.user.id];
}
return undefined;
}
/* -------------------------------------------- */
2023-02-07 19:55:33 +01:00
static getWhisperRecipientsOnly(name) {
let recep1 = ChatMessage.getWhisperRecipients(name) || [];
return recep1
}
/* -------------------------------------------- */
2023-02-01 14:28:08 +01:00
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-malefices", { 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;
}
/* -------------------------------------------- */
2023-02-07 19:55:33 +01:00
static async createChatMessage(name, rollMode, chatOptions) {
2023-02-01 14:28:08 +01:00
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;
2023-02-07 19:55:33 +01:00
return await ChatMessage.create(chatOptions);
2023-02-01 14:28:08 +01:00
}
/* -------------------------------------------- */
static getBasicRollData() {
let rollData = {
rollId: randomID(16),
2023-02-01 19:48:35 +01:00
bonusMalusPerso: 0,
bonusMalusSituation: 0,
bonusMalusDef: 0,
2023-02-02 23:59:41 +01:00
bonusMalusPortee: 0,
2023-02-01 14:28:08 +01:00
rollMode: game.settings.get("core", "rollMode")
}
MaleficesUtility.updateWithTarget(rollData)
return rollData
}
/* -------------------------------------------- */
static updateWithTarget(rollData) {
let target = MaleficesUtility.getTarget()
if (target) {
rollData.defenderTokenId = target.id
}
}
/* -------------------------------------------- */
2023-02-07 19:55:33 +01:00
static async createChatWithRollMode(name, chatOptions) {
return await this.createChatMessage(name, game.settings.get("core", "rollMode"), chatOptions)
2023-02-01 14:28:08 +01:00
}
/* -------------------------------------------- */
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);
}
}