Sync effetcts + initiative

This commit is contained in:
2022-01-28 10:05:54 +01:00
parent a203163b12
commit 68d7344e90
17 changed files with 755 additions and 624 deletions

View File

@ -1,18 +1,22 @@
/* -------------------------------------------- */
/* -------------------------------------------- */
import { PegasusCombat } from "./pegasus-combat.js";
import { PegasusCommands } from "./pegasus-commands.js";
import { PegasusActorCreate } from "./pegasus-create-char.js";
/* -------------------------------------------- */
const __level2Dice = [ "d0", "d4", "d6", "d8", "d10", "d12" ];
const __name2DiceValue = { "0": 0, "d0": 0, "d4": 4, "d6": 6, "d8": 8, "d10" : 10, "d12": 12 }
/* -------------------------------------------- */
const __level2Dice = ["d0", "d4", "d6", "d8", "d10", "d12"];
const __name2DiceValue = { "0": 0, "d0": 0, "d4": 4, "d6": 6, "d8": 8, "d10": 10, "d12": 12 }
/* -------------------------------------------- */
export class PegasusUtility {
/* -------------------------------------------- */
export class PegasusUtility {
/* -------------------------------------------- */
static async init() {
Hooks.on('renderChatLog', (log, html, data) => PegasusUtility.chatListeners(html));
Hooks.on("getCombatTrackerEntryContext", (html, options) => {
PegasusUtility.pushInitiativeOptions(html, options);
});
this.rollDataStore = {}
this.defenderStore = {}
this.diceList = [];
@ -29,10 +33,16 @@ export class PegasusUtility {
return text.charAt(0).toUpperCase() + text.slice(1)
});
}
}
/* -------------------------------------------- */
static getSpecs( ) {
static pushInitiativeOptions(html, options) {
console.log('Option pushed....')
options.push( { name: "Apply -10", condition: true, icon: '<i class="fas fa-plus"></i>', callback: target => { PegasusCombat.decInitBy10(target.data('combatant-id'), -10); } } )
}
/* -------------------------------------------- */
static getSpecs() {
return this.specs;
}
@ -57,21 +67,21 @@ export class PegasusUtility {
/* -------------------------------------------- */
static buildDiceLists() {
let maxLevel = game.settings.get("fvtt-pegasus-rpg", "dice-max-level");
let diceList = [ "0" ];
let diceList = ["0"];
let diceValues = [0];
let diceFoundryList = [ "d0" ];
let diceFoundryList = ["d0"];
let diceLevel = 1;
let concat = "";
let concatFoundry = "";
let optionsDiceList = '<option value="0">0</option>';
let optionsLevel = '<option value="0">0</option>';
for(let i=1; i<=maxLevel;i++) {
for (let i = 1; i <= maxLevel; i++) {
let currentDices = concat + __level2Dice[diceLevel];
diceList.push( currentDices );
diceFoundryList.push( concatFoundry + __level2Dice[diceLevel] + "x" );
if ( __level2Dice[diceLevel] == "d12") {
concat = concat + "d12 ";
concatFoundry = concatFoundry + "d12x, ";
diceList.push(currentDices);
diceFoundryList.push(concatFoundry + __level2Dice[diceLevel] + "x");
if (__level2Dice[diceLevel] == "d12") {
concat = concat + "d12 ";
concatFoundry = concatFoundry + "d12x, ";
diceLevel = 1;
} else {
diceLevel++;
@ -86,9 +96,8 @@ export class PegasusUtility {
this.optionsStatusList = '<option value="notapplicable">Not applicable</option><option value="health">Health</option><option value="nrg">NRG</option><option value="delirium">Delirium</option>';
console.log("Defautl dice List", diceList, diceFoundryList);
}
/* -------------------------------------------- */
static getOptionsStatusList() {
return this.optionsStatusList;
@ -104,80 +113,81 @@ export class PegasusUtility {
/* -------------------------------------------- */
static computeAttackDefense(defenseRollId) {
let defenseRollData = this.getRollData(defenseRollId );
let defenseRollData = this.getRollData(defenseRollId);
let attackRollData = this.getRollData(defenseRollData.linkedRollId);
let defender = game.actors.get( defenseRollData.actorId);
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 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 applyNoDefense(actorId, attackRollId) {
let attackRollData = this.getRollData(attackRollId);
let defender = game.actors.get(actorId);
defender.processNoDefense(attackRollData);
}
/* -------------------------------------------- */
static async chatListeners(html) {
html.on("click", '.chat-create-actor', event => {
game.system.pegasus.creator.processChatEvent(event);
} );
game.system.pegasus.creator.processChatEvent(event);
});
html.on("click", '.view-item-from-chat', event => {
game.system.pegasus.creator.openItemView( event)
} );
game.system.pegasus.creator.openItemView(event)
});
}
/* -------------------------------------------- */
/* -------------------------------------------- */
static async preloadHandlebarsTemplates() {
const templatePaths = [
'systems/fvtt-pegasus-rpg/templates/editor-notes-gm.html',
'systems/fvtt-pegasus-rpg/templates/partial-roll-common-dices.html',
'systems/fvtt-pegasus-rpg/templates/partial-roll-select-effects.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-range.html',
'systems/fvtt-pegasus-rpg/templates/partial-options-equipment-types.html'
]
return loadTemplates(templatePaths);
return loadTemplates(templatePaths);
}
/* -------------------------------------------- */
static removeChatMessageId(messageId) {
if (messageId){
game.messages.get(messageId)?.delete();
/* -------------------------------------------- */
static removeChatMessageId(messageId) {
if (messageId) {
game.messages.get(messageId)?.delete();
}
}
static findChatMessageId(current) {
return PegasusUtility.getChatMessageId(PegasusUtility.findChatMessage(current));
}
static getChatMessageId(node) {
return node?.attributes.getNamedItem('data-message-id')?.value;
}
static findChatMessage(current) {
return PegasusUtility.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 PegasusUtility.findNodeMatching(current.parentElement, predicate);
}
static findChatMessageId(current) {
return PegasusUtility.getChatMessageId(PegasusUtility.findChatMessage(current));
}
static getChatMessageId(node) {
return node?.attributes.getNamedItem('data-message-id')?.value;
}
static findChatMessage(current) {
return PegasusUtility.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 PegasusUtility.findNodeMatching(current.parentElement, predicate);
}
return undefined;
}
return undefined;
}
/* -------------------------------------------- */
static templateData(it) {
return PegasusUtility.data(it)?.data ?? {}
@ -190,9 +200,9 @@ export class PegasusUtility {
}
return it;
}
/* -------------------------------------------- */
static getDiceValue( level = 0) {
static getDiceValue(level = 0) {
let diceString = this.diceList[level]
let diceTab = diceString.split(" ")
let diceValue = 0
@ -210,14 +220,14 @@ export class PegasusUtility {
/* -------------------------------------------- */
static getFoundryDiceFromLevel(level = 0) {
level = Number(level)
console.log(this.diceFoundryList);
//console.log(this.diceFoundryList);
return this.diceFoundryList[level];
}
/* -------------------------------------------- */
static createDirectOptionList( min, max) {
static createDirectOptionList(min, max) {
let options = {};
for(let i=min; i<=max; i++) {
for (let i = min; i <= max; i++) {
options[`${i}`] = `${i}`;
}
return options;
@ -241,69 +251,71 @@ export class PegasusUtility {
}
return undefined;
}
/* -------------------------------------------- */
static getDefenseState( actorId) {
static getDefenseState(actorId) {
return this.defenderStore[actorId];
}
/* -------------------------------------------- */
static async updateDefenseState( defenderId, rollId) {
static async updateDefenseState(defenderId, rollId) {
this.defenderStore[defenderId] = rollId;
if ( game.user.character && game.user.character.id == defenderId ) {
let defender = game.actors.get( defenderId);
if (game.user.character && game.user.character.id == defenderId) {
let defender = game.actors.get(defenderId);
let chatData = {
user: game.user.id,
alias : defender.name,
alias: defender.name,
rollMode: game.settings.get("core", "rollMode"),
whisper: [game.user.id].concat( ChatMessage.getWhisperRecipients('GM') ),
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 );
await ChatMessage.create(chatData);
}
}
/* -------------------------------------------- */
static clearDefenseState( defenderId) {
static clearDefenseState(defenderId) {
this.defenderStore[defenderId] = undefined;
}
/* -------------------------------------------- */
static storeDefenseState( rollData ) {
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 );
name: "msg_update_defense_state", data: { defenderId: rollData.defenderId, rollId: rollData.rollId }
});
this.updateDefenseState(rollData.defenderId, rollData.rollId);
}
/* -------------------------------------------- */
static updateRollData( rollData) {
static updateRollData(rollData) {
let id = rollData.rollId;
let oldRollData = this.rollDataStore[id] || {};
let newRollData = mergeObject( oldRollData, rollData);
let newRollData = mergeObject(oldRollData, rollData);
this.rollDataStore[id] = newRollData;
}
/* -------------------------------------------- */
static saveRollData( rollData ) {
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);
name: "msg_update_roll", data: rollData
}); // Notify all other clients of the roll
this.updateRollData(rollData);
}
/* -------------------------------------------- */
static getRollData( id ) {
static getRollData(id) {
return this.rollDataStore[id];
}
/* -------------------------------------------- */
static onSocketMesssage( msg ) {
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_defense_state") {
this.updateDefenseState(msg.data.defenderId, msg.data.rollId);
}
if (msg.name == "msg_update_roll") {
this.updateRollData(msg.data);
}
if (msg.name == "msg_update_roll" ) {
this.updateRollData( msg.data );
}
}
/* -------------------------------------------- */
@ -325,7 +337,7 @@ export class PegasusUtility {
return chatData;
}
/* -------------------------------------------- */
static async loadCompendiumData(compendium) {
const pack = game.packs.get(compendium);
@ -338,7 +350,7 @@ export class PegasusUtility {
//console.log("Compendium", compendiumData);
return compendiumData.filter(filter);
}
/* -------------------------------------------- */
static async showDiceSoNice(roll, rollMode) {
if (game.modules.get("dice-so-nice")?.active) {
@ -366,26 +378,26 @@ export class PegasusUtility {
/* -------------------------------------------- */
static async rollPegasus( rollData ) {
static async rollPegasus(rollData) {
let actor = game.actors.get(rollData.actorId);
let actor = game.actors.get(rollData.actorId);
let dicePool = [ {name:"stat", level: 0, statmod: 0}, {name: "spec", level: 0}, {name:"bonus", level: 0}, {name:"hindrance", level: 0}, {name:"other", level:0} ];
let dicePool = [{ name: "stat", level: 0, statmod: 0 }, { name: "spec", level: 0 }, { name: "bonus", level: 0 }, { name: "hindrance", level: 0 }, { name: "other", level: 0 }];
if (rollData.stat) {
dicePool[0].level += Number(rollData.stat.value);
dicePool[0].statmod = Number(rollData.stat.mod);
}
if ( rollData.statDicesLevel) {
if (rollData.statDicesLevel) {
dicePool[0].level = rollData.statDicesLevel;
}
if (rollData.selectedSpec && rollData.selectedSpec != "0") {
rollData.spec = rollData.specList.find( item => item._id == rollData.selectedSpec);
rollData.spec = rollData.specList.find(item => item._id == rollData.selectedSpec);
rollData.spec.data.dice = PegasusUtility.getDiceFromLevel(rollData.spec.data.level);
}
if (rollData.spec) {
dicePool[1].level += Number(rollData.spec.data.level);
}
if ( rollData.specDicesLevel) {
if (rollData.specDicesLevel) {
dicePool[1].level = rollData.specDicesLevel;
}
if (rollData.bonusDicesLevel) {
@ -400,17 +412,17 @@ export class PegasusUtility {
let diceFormulaTab = [];
for (let diceGroup of dicePool) {
diceFormulaTab.push( this.getFoundryDiceFromLevel( diceGroup.level) )
diceFormulaTab.push(this.getFoundryDiceFromLevel(diceGroup.level))
}
let diceFormula = '{' + diceFormulaTab.join(', ') + '}kh';
console.log(diceFormula);
// Performs roll
let myRoll = rollData.roll;
if ( !myRoll ) { // New rolls only of no rerolls
myRoll = new Roll(diceFormula).roll( { async: false} );
if (!myRoll) { // New rolls only of no rerolls
myRoll = new Roll(diceFormula).roll({ async: false });
console.log("ROLL : ", diceFormula);
await this.showDiceSoNice(myRoll, game.settings.get("core", "rollMode") );
await this.showDiceSoNice(myRoll, game.settings.get("core", "rollMode"));
rollData.roll = myRoll
}
@ -419,43 +431,49 @@ export class PegasusUtility {
console.log("ROLLLL!!!!", rollData);
if (rollData.damages) {
let dmgFormula = this.getFoundryDiceFromLevel( rollData.damages.value )
let dmgRoll = new Roll(dmgFormula).roll( { async: false} );
await this.showDiceSoNice(dmgRoll, game.settings.get("core", "rollMode") );
rollData.dmgResult = dmgRoll.total;
let dmgFormula = this.getFoundryDiceFromLevel(rollData.damages.value)
let dmgRoll = new Roll(dmgFormula).roll({ async: false });
await this.showDiceSoNice(dmgRoll, game.settings.get("core", "rollMode"));
rollData.dmgResult = dmgRoll.total;
}
this.createChatWithRollMode( rollData.alias, {
this.createChatWithRollMode(rollData.alias, {
content: await renderTemplate(`systems/fvtt-pegasus-rpg/templates/chat-generic-result.html`, rollData)
});
if ( rollData.defender ) {
this.storeDefenseState( rollData );
if (rollData.defender) {
this.storeDefenseState(rollData);
}
this.saveRollData( rollData );
// Init stuf
if (rollData.isInit) {
let combat = game.combats.get( rollData.combatId)
combat.updateEmbeddedDocuments("Combatant", [ { _id: rollData.combatantId, initiative: rollData.finalScore } ]);
}
// And save the roll
this.saveRollData(rollData);
}
/* -------------------------------------------- */
static getDamageDice( result ) {
if ( result < 0) return 0;
return Math.floor(result/5) + 1;
static getDamageDice(result) {
if (result < 0) return 0;
return Math.floor(result / 5) + 1;
}
/* ------------------------- ------------------- */
static async updateRoll( rollData) {
static async updateRoll(rollData) {
let diceResults = rollData.diceResults;
let sortedRoll = [];
for (let i=0; i<10; i++) {
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) {
let bestRoll = 0;
for (let i = 0; i < 10; i++) {
if (sortedRoll[i] > bestRoll) {
bestRoll = sortedRoll[i];
index = i;
}
@ -464,30 +482,30 @@ export class PegasusUtility {
rollData.bestScore = bestScore;
rollData.finalScore = bestScore + rollData.negativeModifier + rollData.positiveModifier;
this.saveRollData(rollData );
this.createChatWithRollMode( rollData.alias, {
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 ) {
static async rerollDice(actorId, diceIndex = -1) {
let actor = game.actors.get(actorId);
let rollData = actor.getRollData( );
let rollData = actor.getRollData();
if ( diceIndex == -1 ) {
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") );
} 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 );
this.rollFraggedKingdom(rollData);
}
/* -------------------------------------------- */
@ -520,18 +538,18 @@ export class PegasusUtility {
/* -------------------------------------------- */
static split3Columns(data) {
let array = [ [], [], [] ];
if (data== undefined) return array;
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);
array[col].push(keyword);
col++;
if (col == 3) col = 0;
}
}
return array;
}
@ -557,6 +575,39 @@ export class PegasusUtility {
ChatMessage.create(chatOptions);
}
/* -------------------------------------------- */
static getBasicRollData() {
let rollData = {
rollId: randomID(16),
rollMode: game.settings.get("core", "rollMode"),
bonusDicesLevel: 0,
hindranceDicesLevel: 0,
otherDicesLevel: 0,
statDicesLevel: 0,
specDicesLevel: 0,
effectsList: [],
armorsList: [],
optionsDiceList: PegasusUtility.getOptionsDiceList()
}
PegasusUtility.updateWithTarget(rollData)
return rollData
}
/* -------------------------------------------- */
static updateWithTarget(rollData) {
let objectDefender
let target = PegasusUtility.getTarget();
if (target) {
let defenderActor = game.actors.get(target.data.actorId)
objectDefender = PegasusUtility.data(defenderActor)
objectDefender = mergeObject(objectDefender, target.data.actorData)
rollData.defender = objectDefender
rollData.attackerId = this.id
rollData.defenderId = objectDefender._id
defenderActor.addHindrancesList(rollData.effectsList)
}
}
/* -------------------------------------------- */
static createChatWithRollMode(name, chatOptions) {
this.createChatMessage(name, game.settings.get("core", "rollMode"), chatOptions);
@ -568,26 +619,26 @@ export class PegasusUtility {
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"
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);
}
msgTxt += "</p>";
let d = new Dialog({
title: "Confirm removal",
content: msgTxt,
buttons: buttons,
default: "cancel"
});
d.render(true);
}
}