Initial import

This commit is contained in:
2021-12-02 07:38:59 +01:00
parent af2436a676
commit 522cad2ff8
77 changed files with 4607 additions and 0 deletions

View File

@@ -0,0 +1,193 @@
/**
* Extend the basic ActorSheet with some very simple modifications
* @extends {ActorSheet}
*/
import { PegasusUtility } from "./pegasus-utility.js";
import { PegasusItemSheet } from "./pegasus-item-sheet.js";
/* -------------------------------------------- */
export class PegasusActorSheet extends ActorSheet {
/** @override */
static get defaultOptions() {
return mergeObject(super.defaultOptions, {
classes: ["fvtt-pegasus-rpg", "sheet", "actor"],
template: "systems/fvtt-pegasus-rpg/templates/actor-sheet.html",
width: 640,
height: 720,
tabs: [{ navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "stats" }],
dragDrop: [{ dragSelector: ".item-list .item", dropSelector: null }],
editScore: false
});
}
/* -------------------------------------------- */
async getData() {
const objectData = PegasusUtility.data(this.object);
let actorData = duplicate(PegasusUtility.templateData(this.object));
let formData = {
title: this.title,
id: objectData.id,
type: objectData.type,
img: objectData.img,
name: objectData.name,
editable: this.isEditable,
cssClass: this.isEditable ? "editable" : "locked",
data: actorData,
effects: this.object.effects.map(e => foundry.utils.deepClone(e.data)),
limited: this.object.limited,
specs: this.actor.getSpecs( ),
weapons: this.actor.checkAndPrepareWeapons( duplicate(this.actor.getWeapons()) ),
armors: duplicate(this.actor.getArmors()),
shields: duplicate(this.actor.getShields()),
equipments: duplicate(this.actor.getEquipments()),
perks: duplicate(this.actor.getPerks()),
powers: duplicate(this.actor.getPowers()),
subActors: duplicate(this.actor.getSubActors()),
options: this.options,
owner: this.document.isOwner,
editScore: this.options.editScore,
isGM: game.user.isGM
}
this.formData = formData;
console.log("PC : ", formData, this.object);
return formData;
}
/* -------------------------------------------- */
/** @override */
activateListeners(html) {
super.activateListeners(html);
// Everything below here is only needed if the sheet is editable
if (!this.options.editable) return;
// Update Inventory Item
html.find('.item-edit').click(ev => {
const li = $(ev.currentTarget).parents(".item");
let itemId = li.data("item-id");
const item = this.actor.items.get( itemId );
item.sheet.render(true);
});
// Delete Inventory Item
html.find('.item-delete').click(ev => {
const li = $(ev.currentTarget).parents(".item");
PegasusUtility.confirmDelete(this, li);
});
html.find('.subactor-edit').click(ev => {
const li = $(ev.currentTarget).parents(".item");
let actorId = li.data("actor-id");
let actor = game.actors.get( actorId );
actor.sheet.render(true);
});
html.find('.subactor-delete').click(ev => {
const li = $(ev.currentTarget).parents(".item");
let actorId = li.data("actor-id");
this.actor.delSubActor(actorId);
});
html.find('.equipement-moins').click(event => {
const li = $(event.currentTarget).parents(".item");
this.actor.decrementeQuantite( li.data("item-id") );
} );
html.find('.equipement-plus').click(event => {
const li = $(event.currentTarget).parents(".item");
this.actor.incrementeQuantite( li.data("item-id") );
} );
html.find('.skill-roll').click((event) => {
const li = $(event.currentTarget).parents(".item");
const skillId = li.data("item-id");
this.actor.rollSkill(skillId);
});
html.find('.technique-roll').click((event) => {
const li = $(event.currentTarget).parents(".item");
const techId = li.data("item-id");
this.actor.rollTechnique(techId);
});
html.find('.weapon-roll').click((event) => {
const li = $(event.currentTarget).parents(".item");
const weaponId = li.data("item-id");
this.actor.rollWeapon(weaponId);
});
html.find('.river-flush').click((event) => {
const diceIndex = $(event.currentTarget).data("dice-index");
this.actor.flushDice(diceIndex);
});
html.find('.river-use').click((event) => {
const diceIndex = $(event.currentTarget).data("dice-index");
this.actor.addDice(diceIndex);
});
html.find('.weapon-label a').click((event) => {
const li = $(event.currentTarget).parents(".item");
const armeId = li.data("item-id");
const statId = li.data("stat-id");
this.actor.rollWeapon(armeId, statId);
});
html.find('.weapon-damage').click((event) => {
const li = $(event.currentTarget).parents(".item");
const weapon = this.actor.getOwnedItem(li.data("item-id"));
this.actor.rollDamage(weapon, 'damage');
});
html.find('.weapon-damage-critical').click((event) => {
const li = $(event.currentTarget).parents(".item");
const weapon = this.actor.getOwnedItem(li.data("item-id"));
this.actor.rollDamage(weapon, 'criticaldamage');
});
html.find('.lock-unlock-sheet').click((event) => {
this.options.editScore = !this.options.editScore;
this.render(true);
});
html.find('.item-link a').click((event) => {
const itemId = $(event.currentTarget).data("item-id");
const item = this.actor.getOwnedItem(itemId);
item.sheet.render(true);
});
html.find('.item-equip').click(ev => {
const li = $(ev.currentTarget).parents(".item");
this.actor.equipItem( li.data("item-id") );
this.render(true);
});
}
/* -------------------------------------------- */
/** @override */
setPosition(options = {}) {
const position = super.setPosition(options);
const sheetBody = this.element.find(".sheet-body");
const bodyHeight = position.height - 192;
sheetBody.css("height", bodyHeight);
return position;
}
/* -------------------------------------------- */
async _onDrop(event) {
let data = event.dataTransfer.getData('text/plain');
if (data) {
let dataItem = JSON.parse( data);
let npc = game.actors.get( dataItem.id);
if ( npc ) {
this.actor.addSubActor( dataItem.id);
return;
}
}
super._onDrop(event);
}
/* -------------------------------------------- */
/** @override */
_updateObject(event, formData) {
// Update the Actor
return this.object.update(formData);
}
}

512
modules/pegasus-actor.js Normal file
View File

@@ -0,0 +1,512 @@
/* -------------------------------------------- */
import { PegasusUtility } from "./pegasus-utility.js";
import { PegasusRollDialog } from "./pegasus-roll-dialog.js";
/* -------------------------------------------- */
const coverBonusTable = { "nocover": 0, "lightcover": 2, "heavycover": 4, "entrenchedcover": 6};
/* -------------------------------------------- */
/* -------------------------------------------- */
/**
* Extend the base Actor entity by defining a custom roll data structure which is ideal for the Simple system.
* @extends {Actor}
*/
export class PegasusActor extends Actor {
/* -------------------------------------------- */
/**
* Override the create() function to provide additional SoS functionality.
*
* This overrided create() function adds initial items
* Namely: Basic skills, money,
*
* @param {Object} data Barebones actor data which this function adds onto.
* @param {Object} options (Unused) Additional options which customize the creation workflow.
*
*/
static async create(data, options) {
// Case of compendium global import
if (data instanceof Array) {
return super.create(data, options);
}
// If the created actor has items (only applicable to duplicated actors) bypass the new actor creation logic
if (data.items) {
let actor = super.create(data, options);
return actor;
}
if ( data.type == 'character') {
const skills = await PegasusUtility.loadCompendium("fvtt-weapons-of-the-gods.skills");
data.items = skills.map(i => i.toObject());
}
if ( data.type == 'npc') {
}
return super.create(data, options);
}
/* -------------------------------------------- */
prepareBaseData() {
}
/* -------------------------------------------- */
async prepareData() {
super.prepareData();
}
/* -------------------------------------------- */
prepareDerivedData() {
if (this.type == 'character') {
let h = 0;
let updates = [];
for (let key in this.data.data.statistics) {
let attr = this.data.data.statistics[key];
}
/*if ( h != this.data.data.secondary.health.max) {
this.data.data.secondary.health.max = h;
updates.push( {'data.secondary.health.max': h} );
}*/
if ( updates.length > 0 ) {
this.update( updates );
}
}
super.prepareDerivedData();
}
/* -------------------------------------------- */
_preUpdate(changed, options, user) {
super._preUpdate(changed, options, user);
}
/* -------------------------------------------- */
getPerks() {
let comp = this.data.items.filter( item => item.type == 'perk');
return comp;
}
/* -------------------------------------------- */
getPowers() {
let comp = this.data.items.filter( item => item.type == 'power');
return comp;
}
/* -------------------------------------------- */
getArmors() {
let comp = this.data.items.filter( item => item.type == 'armor');
return comp;
}
/* -------------------------------------------- */
getShields() {
let comp = this.data.items.filter( item => item.type == 'shield');
return comp;
}
/* -------------------------------------------- */
checkAndPrepareWeapon(item) {
let types=[];
let specs=[];
let stats=[];
item.data.specs = specs;
item.data.stats = stats;
item.data.typeText = types.join('/');
}
/* -------------------------------------------- */
checkAndPrepareWeapons(weapons) {
for ( let item of weapons) {
this.checkAndPrepareWeapon(item);
}
return weapons;
}
/* -------------------------------------------- */
getWeapons() {
let comp = this.data.items.filter( item => item.type == 'weapon' );
return comp;
}
/* -------------------------------------------- */
getSpecs() {
let comp = this.data.items.filter( item => item.type == 'specialisation');
return comp;
}
/* -------------------------------------------- */
async equipItem(itemId ) {
let item = this.data.items.find( item => item.id == itemId );
if (item && item.data.data) {
let update = { _id: item.id, "data.equipped": !item.data.data.equipped };
await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
}
}
/* -------------------------------------------- */
compareName( a, b) {
if ( a.name < b.name ) {
return -1;
}
if ( a.name > b.name ) {
return 1;
}
return 0;
}
/* ------------------------------------------- */
getEquipments() {
return this.data.items.filter( item => item.type == 'shield' || item.type == 'armor' || item.type == "weapon" || item.type == "equipment");
}
/* -------------------------------------------- */
getActiveEffects(matching = it => true) {
let array = Array.from(this.getEmbeddedCollection("ActiveEffect").values());
return Array.from(this.getEmbeddedCollection("ActiveEffect").values()).filter(it => matching(it));
}
/* -------------------------------------------- */
getEffectByLabel(label) {
return this.getActiveEffects().find(it => it.data.label == label);
}
/* -------------------------------------------- */
getEffectById(id) {
return this.getActiveEffects().find(it => it.id == id);
}
/* -------------------------------------------- */
getAttribute( attrKey ) {
return this.data.data.attributes[attrKey];
}
/* -------------------------------------------- */
async equipGear( equipmentId ) {
let item = this.data.items.find( item => item.id == equipmentId );
if (item && item.data.data) {
let update = { _id: item.id, "data.equipped": !item.data.data.equipped };
await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
}
}
/* -------------------------------------------- */
getInitiativeScore( ) {
if ( this.type == 'character') {
// TODO
}
return 0.0;
}
/* -------------------------------------------- */
getArmorModifier( ) {
let armors = this.getArmors();
let modifier = 0;
for (let armor of armors) {
if (armor.data.data.equipped) {
if (armor.data.data.type == 'light') modifier += 5;
if (armor.data.data.type == 'medium') modifier += 10;
if (armor.data.data.type == 'heavy') modifier += 15;
}
}
return modifier;
}
/* -------------------------------------------- */
async applyDamageLoss( damage) {
let chatData = {
user: game.user.id,
alias : this.name,
rollMode: game.settings.get("core", "rollMode"),
whisper: [game.user.id].concat( ChatMessage.getWhisperRecipients('GM') ),
};
//console.log("Apply damage chat", chatData );
if (damage > 0 ) {
let health = duplicate(this.data.data.secondary.health);
health.value -= damage;
if (health.value < 0 ) health.value = 0;
this.update( { "data.secondary.health.value": health.value});
chatData.content = `${this.name} looses ${damage} health. New health value is : ${health.value}` ;
} else {
chatData.content = `No health loss for ${this.name} !`;
}
await ChatMessage.create( chatData );
}
/* -------------------------------------------- */
processNoDefense( attackRollData) {
let defenseRollData = {
mode : "nodefense",
finalScore: 0,
defenderName: this.name,
attackerName: attackRollData.alias,
armorModifier: this.getArmorModifier(),
actorId: this.id,
alias: this.name,
result: 0,
}
this.syncRoll( defenseRollData );
this.processDefenseResult(defenseRollData, attackRollData);
}
/* -------------------------------------------- */
async processApplyDamage(defenseRollData, attackRollData) { // Processed by the defender actor
if ( attackRollData && attackRollData ) {
let result = attackRollData.finalScore;
defenseRollData.damageDices = WotGUtility.getDamageDice( result );
defenseRollData.damageRoll = await this.rollDamage(defenseRollData);
chatData.damages = true;
chatData.damageDices = defenseRollData.damageDices;
WotGUtility.createChatWithRollMode( this.name, {
content: await renderTemplate(`systems/fvtt-weapons-of-the-gods/templates/chat-opposed-damages.html`, chatData)
});
}
}
/* -------------------------------------------- */
async processDefenseResult(defenseRollData, attackRollData) { // Processed by the defenser
if ( defenseRollData && attackRollData) {
let result = attackRollData.finalScore - defenseRollData.finalScore;
defenseRollData.defenderName = this.name,
defenseRollData.attackerName = attackRollData.alias
defenseRollData.result= result
defenseRollData.damages = false
defenseRollData.damageDices = 0;
if ( result > 0 ) {
defenseRollData.damageDices = WotGUtility.getDamageDice( result );
defenseRollData.damageRoll = await this.rollDamage(defenseRollData, attackRollData);
defenseRollData.damages = true;
defenseRollData.finalDamage = defenseRollData.damageRoll.total;
WotGUtility.updateRollData( defenseRollData);
console.log("DAMAGE ROLL OBJECT", defenseRollData);
WotGUtility.createChatWithRollMode( this.name, {
content: await renderTemplate(`systems/fvtt-weapons-of-the-gods/templates/chat-opposed-damage.html`, defenseRollData)
});
} else {
WotGUtility.updateRollData( defenseRollData );
WotGUtility.createChatWithRollMode( this.name, {
content: await renderTemplate(`systems/fvtt-weapons-of-the-gods/templates/chat-opposed-fail.html`, defenseRollData)
});
}
}
}
/* -------------------------------------------- */
async rollDamage( defenseRollData, attackRollData ) {
let weaponDamage = 0;
if (attackRollData.weapon?.data?.damage) {
weaponDamage = Number(attackRollData.weapon.data.damage);
}
let formula = defenseRollData.damageDices+"d10+"+defenseRollData.armorModifier + "+" + weaponDamage;
console.log("ROLL : ", formula);
let myRoll = new Roll(formula).roll( { async: false} );
await WotGUtility.showDiceSoNice(myRoll, game.settings.get("core", "rollMode") );
return myRoll;
}
/* -------------------------------------------- */
getSubActors() {
let subActors = [];
for (let id of this.data.data.subactors) {
subActors.push(duplicate(game.actors.get(id)));
}
return subActors;
}
/* -------------------------------------------- */
async addSubActor( subActorId) {
let subActors = duplicate( this.data.data.subactors);
subActors.push( subActorId);
await this.update( { 'data.subactors': subActors } );
}
/* -------------------------------------------- */
async delSubActor( subActorId) {
let newArray = [];
for (let id of this.data.data.subactors) {
if ( id != subActorId) {
newArray.push( id);
}
}
await this.update( { 'data.subactors': newArray } );
}
/* -------------------------------------------- */
setDefenseMode( rollData ) {
console.log("DEFENSE MODE IS SET FOR", this.name);
this.data.defenseRollData = rollData;
this.data.defenseDefenderId = rollData.defenderId;
this.data.defenseAttackerId = rollData.attackerId;
}
/* -------------------------------------------- */
clearDefenseMode( ) {
this.data.defenseDefenderId = undefined;
this.data.defenseAttackerId = undefined;
this.data.defenseRollData = undefined;
}
/* -------------------------------------------- */
syncRoll( rollData ) {
let linkedRollId = WotGUtility.getDefenseState(this.id);
if ( linkedRollId) {
rollData.linkedRollId = linkedRollId;
}
rollData.rollId = randomID(16);
this.lastRollId = rollData.rollId;
WotGUtility.saveRollData( rollData );
}
/* -------------------------------------------- */
async rollSkill( skillId ) {
let skill = this.data.items.find( item => item.type == 'skill' && item.id == skillId);
if (skill) {
let rollData = {
mode: "skill",
alias: this.name,
actorImg: this.img,
actorId: this.id,
img: skill.img,
rollMode: game.settings.get("core", "rollMode"),
armorModifier: this.getArmorModifier(),
title: `Skill ${skill.name} `,
skill: duplicate(skill),
skillAttr: this.getAttribute( skill.data.data.attribute ),
optionsNegative: WotGUtility.getNegativeModifiers(),
optionsPositive: WotGUtility.getPositiveModifiers(),
negativeModifier: 0,
positiveModifier: 0,
specialtiesBonus: 0,
}
this.syncRoll( rollData);
let rollDialog = await WotGRollDialog.create( this, rollData);
console.log(rollDialog);
rollDialog.render( true );
} else {
ui.notifications.warn("Skill not found !");
}
}
/* -------------------------------------------- */
applyTechniqueCost( techId) {
let tech = duplicate(this.data.items.find( item => item.id == techId));
if (tech ) {
let attr = this.getAttributeFromChiName( tech.data.chicolor);
let chiscore = attr.chiscore - tech.data.chicost;
chiscore = (chiscore < 0) ? 0 : chiscore;
this.update( { [`data.attributes.${attr.key}.chiscore`]: chiscore } );
}
}
/* -------------------------------------------- */
updateWithTarget( rollData) {
let objectDefender
let target = WotGUtility.getTarget();
if ( !target) {
ui.notifications.warn("You are using a Weapon without a Target.");
} else {
let defenderActor = game.actors.get(target.data.actorId);
objectDefender = WotGUtility.data(defenderActor);
objectDefender = mergeObject(objectDefender, target.data.actorData);
rollData.defender = objectDefender;
rollData.attackerId = this.id;
rollData.defenderId = objectDefender._id;
console.log("ROLLDATA DEFENDER !!!", rollData);
}
}
/* -------------------------------------------- */
async rollTechnique( techId ) {
let technique = this.data.items.find( item => item.type == 'technique' && item.id == techId);
if (technique) {
let usedChi = this.getAttributeFromChiName( technique.data.data.chicolor);
if ( usedChi.chiscore < 0 || technique.data.data.chicost > usedChi.chiscore) {
ui.notifications.warn(`Not enough ${usedChi.chi} to use Technique ${technique.name}`);
return;
}
let chi = undefined;
let skill = this.data.items.find( item => item.type == 'skill' && item.name == technique.data.data.skillchi);
if ( !skill) {
chi = this.getAttributeFromChiName( technique.data.data.skillchi);
}
let rollData = {
mode: "technique",
alias: this.name,
armorModifier: this.getArmorModifier(),
actorImg: this.img,
actorId: this.id,
img: technique.img,
rollMode: game.settings.get("core", "rollMode"),
title: `Technique ${technique.name} `,
technique: duplicate(technique),
optionsNegative: WotGUtility.getNegativeModifiers(),
optionsPositive: WotGUtility.getPositiveModifiers(),
negativeModifier: 0,
positiveModifier: 0,
specialtiesBonus: 0
}
if ( skill) {
rollData.skill = duplicate(skill);
rollData.attr = this.getAttribute( skill.data.data.attribute );
} else {
rollData.attr = chi;
}
this.updateWithTarget(rollData);
this.syncRoll( rollData);
let rollDialog = await WotGRollDialog.create( this, rollData);
console.log(rollDialog);
rollDialog.render( true );
} else {
ui.notifications.warn("Technique not found !");
}
}
/* -------------------------------------------- */
async rollWeapon( weaponId ) {
let weapon = this.data.items.find( item => item.id == weaponId);
console.log("WEAPON :", weaponId, weapon );
if ( weapon ) {
weapon = duplicate(weapon);
this.checkAndPrepareWeapon( weapon );
let rollData = {
mode: 'weapon',
actorType: this.type,
alias: this.name,
actorId: this.id,
img: weapon.img,
rollMode: game.settings.get("core", "rollMode"),
armorModifier: this.getArmorModifier(),
title: "Attack : " + weapon.name,
weapon: weapon,
skillKey : 0,
optionsNegative: WotGUtility.getNegativeModifiers(),
optionsPositive: WotGUtility.getPositiveModifiers(),
negativeModifier: 0,
positiveModifier: 0,
specialtiesBonus: 0,
}
this.updateWithTarget(rollData);
this.syncRoll( rollData);
let rollDialog = await WotGRollDialog.create( this, rollData);
console.log("WEAPON ROLL", rollData);
rollDialog.render( true );
} else {
ui.notifications.warn("Weapon not found !", weaponId);
}
}
}

20
modules/pegasus-combat.js Normal file
View File

@@ -0,0 +1,20 @@
import { PegasusUtility } from "./pegasus-utility.js";
/* -------------------------------------------- */
export class PegasusCombat extends Combat {
/* -------------------------------------------- */
async rollInitiative(ids, formula = undefined, messageOptions = {} ) {
console.log("Initiative is requested !!!");
ids = typeof ids === "string" ? [ids] : ids;
const currentId = this.combatant._id;
for (let cId = 0; cId < ids.length; cId++) {
const c = this.getCombatant(ids[cId]);
let initBonus = c.actor ? c.actor.getInitiativeScore() : 0;
await this.updateEmbeddedEntity("Combatant", { _id: c._id, initiative: initBonus });
}
return this;
}
}

View File

@@ -0,0 +1,176 @@
import { PegasusUtility } from "./pegasus-utility.js";
/**
* Extend the basic ItemSheet with some very simple modifications
* @extends {ItemSheet}
*/
export class PegasusItemSheet extends ItemSheet {
/** @override */
static get defaultOptions() {
return mergeObject(super.defaultOptions, {
classes: ["fvtt-pegasus-rpg", "sheet", "item"],
template: "systems/fvtt-pegasus-rpg/templates/item-sheet.html",
dragDrop: [{dragSelector: null, dropSelector: null}],
width: 620,
height: 550
//tabs: [{navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "description"}]
});
}
/* -------------------------------------------- */
_getHeaderButtons() {
let buttons = super._getHeaderButtons();
// Add "Post to chat" button
// We previously restricted this to GM and editable items only. If you ever find this comment because it broke something: eh, sorry!
buttons.unshift(
{
class: "post",
icon: "fas fa-comment",
onclick: ev => {}
})
return buttons
}
/* -------------------------------------------- */
/** @override */
setPosition(options={}) {
const position = super.setPosition(options);
const sheetBody = this.element.find(".sheet-body");
const bodyHeight = position.height - 192;
sheetBody.css("height", bodyHeight);
if ( this.item.type.includes('weapon')) {
position.width = 640;
}
return position;
}
/* -------------------------------------------- */
async getData() {
const objectData = PegasusUtility.data(this.object);
let itemData = foundry.utils.deepClone(PegasusUtility.templateData(this.object));
let formData = {
title: this.title,
id: this.id,
type: objectData.type,
img: objectData.img,
name: objectData.name,
editable: this.isEditable,
cssClass: this.isEditable ? "editable" : "locked",
data: itemData,
limited: this.object.limited,
options: this.options,
owner: this.document.isOwner,
isGM: game.user.isGM
}
this.options.editable = !(this.object.data.origin == "embeddedItem");
console.log("ITEM DATA", formData, this);
return formData;
}
/* -------------------------------------------- */
_getHeaderButtons() {
let buttons = super._getHeaderButtons();
buttons.unshift({
class: "post",
icon: "fas fa-comment",
onclick: ev => this.postItem()
});
return buttons
}
/* -------------------------------------------- */
postItem() {
console.log(this.item);
let chatData = duplicate(PegasusUtility.data(this.item));
if (this.actor) {
chatData.actor = { id: this.actor.id };
}
// Don't post any image for the item (which would leave a large gap) if the default image is used
if (chatData.img.includes("/blank.png")) {
chatData.img = null;
}
// JSON object for easy creation
chatData.jsondata = JSON.stringify(
{
compendium: "postedItem",
payload: chatData,
});
renderTemplate('systems/fvtt-pegasus-rpg/templates/post-item.html', chatData).then(html => {
let chatOptions = WotGUtility.chatDataSetup(html);
ChatMessage.create(chatOptions)
});
}
/* -------------------------------------------- */
/** @override */
activateListeners(html) {
super.activateListeners(html);
// Everything below here is only needed if the sheet is editable
if (!this.options.editable) return;
// Update Inventory Item
html.find('.item-edit').click(ev => {
const li = $(ev.currentTarget).parents(".item");
const item = this.object.options.actor.getOwnedItem(li.data("item-id"));
item.sheet.render(true);
});
// Update Inventory Item
html.find('.item-delete').click(ev => {
const li = $(ev.currentTarget).parents(".item");
let itemId = li.data("item-id");
let itemType = li.data("item-type");
let array = duplicate(this.object.data.data[itemType]);
let newArray = array.filter( item => item._id != itemId);
if ( itemType == 'variations') {
this.object.update( {"data.variations": newArray} );
} else if (itemType == "modifications") {
this.object.update( { "data.modifications": newArray} );
} else {
this.object.update( { "data.traits": newArray} );
}
});
html.find('.trait-name').click(ev => {
const li = $(ev.currentTarget).parents(".item");
let itemId = li.data("item-id");
this.manageTrait( itemId);
});
html.find('.variation-name').click(ev => {
const li = $(ev.currentTarget).parents(".item");
let itemId = li.data("item-id");
this.manageVariation( itemId);
});
html.find('.modification-name').click(ev => {
const li = $(ev.currentTarget).parents(".item");
let itemId = li.data("item-id");
this.manageModification( itemId);
});
}
/* -------------------------------------------- */
async _onDrop(event) {
}
/* -------------------------------------------- */
get template() {
let type = this.item.type;
return `systems/fvtt-pegasus-rpg/templates/item-${type}-sheet.html`;
}
/* -------------------------------------------- */
/** @override */
_updateObject(event, formData) {
return this.object.update(formData);
}
}

28
modules/pegasus-item.js Normal file
View File

@@ -0,0 +1,28 @@
import { PegasusUtility } from "./pegasus-utility.js";
export const defaultItemImg = {
skill: "systems/fvtt-pegasus-rpg/images/icons/icon_skill.webp",
advantage: "systems/fvtt-pegasus-rpg/images/icons/icon_advantage.webp",
disadvantage: "systems/fvtt-pegasus-rpg/images/icons/icon_disadvantage.webp",
technique: "systems/fvtt-pegasus-rpg/images/icons/icon_technique.webp",
armor: "systems/fvtt-pegasus-rpg/images/icons/icon_armor.webp",
art: "systems/fvtt-pegasus-rpg/icons/images/icon_art.webp",
weapon: "systems/fvtt-pegasus-rpg/images/icons/icon_weapon.webp",
equipment: "systems/fvtt-pegasus-rpg/images/icons/icon_equipment.webp",
style: "systems/fvtt-pegasus-rpg/images/icons/icon_style.webp",
}
/**
* Extend the basic ItemSheet with some very simple modifications
* @extends {ItemSheet}
*/
export class PegasusItem extends Item {
constructor(data, context) {
if (!data.img) {
data.img = defaultItemImg[data.type];
}
super(data, context);
}
}

101
modules/pegasus-main.js Normal file
View File

@@ -0,0 +1,101 @@
/**
* Pegasus system
* Author: Uberwald
* Software License: Prop
*/
/* -------------------------------------------- */
/* -------------------------------------------- */
// Import Modules
import { PegasusActor } from "./pegasus-actor.js";
import { PegasusItemSheet } from "./pegasus-item-sheet.js";
import { PegasusActorSheet } from "./pegasus-actor-sheet.js";
import { PegasusNPCSheet } from "./pegasus-npc-sheet.js";
import { PegasusUtility } from "./pegasus-utility.js";
import { PegasusCombat } from "./pegasus-combat.js";
import { PegasusItem } from "./pegasus-item.js";
/* -------------------------------------------- */
/* Foundry VTT Initialization */
/* -------------------------------------------- */
/************************************************************************************/
Hooks.once("init", async function () {
console.log(`Initializing Pegasus RPG`);
/* -------------------------------------------- */
// preload handlebars templates
PegasusUtility.preloadHandlebarsTemplates();
/* -------------------------------------------- */
// Set an initiative formula for the system
CONFIG.Combat.initiative = {
formula: "1d6",
decimals: 1
};
/* -------------------------------------------- */
game.socket.on("system.fvtt-pegasus-rpg", data => {
PegasusUtility.onSocketMesssage(data);
});
/* -------------------------------------------- */
// Define custom Entity classes
CONFIG.Combat.documentClass = PegasusCombat;
CONFIG.Actor.documentClass = PegasusActor;
CONFIG.Item.documentClass = PegasusItem;
CONFIG.WOTG = {
}
/* -------------------------------------------- */
// Register sheet application classes
Actors.unregisterSheet("core", ActorSheet);
Actors.registerSheet("fvtt-pegasus", PegasusActorSheet, { types: ["character"], makeDefault: true });
Actors.registerSheet("fvtt-pegasus", PegasusNPCSheet, { types: ["npc"], makeDefault: false });
Items.unregisterSheet("core", ItemSheet);
Items.registerSheet("fvtt-pegasus", PegasusItemSheet, { makeDefault: true });
PegasusUtility.init();
});
/* -------------------------------------------- */
function welcomeMessage() {
ChatMessage.create({
user: game.user.id,
whisper: [game.user.id],
content: `<div id="welcome-message-pegasus"><span class="rdd-roll-part">Welcome !</div>
` });
}
/* -------------------------------------------- */
/* Foundry VTT Initialization */
/* -------------------------------------------- */
Hooks.once("ready", function () {
PegasusUtility.ready();
// User warning
if (!game.user.isGM && game.user.character == undefined) {
ui.notifications.info("Warning ! No character linked to your user !");
ChatMessage.create({
content: "<b>WARNING</b> The player " + game.user.name + " is not linked to a character !",
user: game.user._id
});
}
welcomeMessage();
});
/* -------------------------------------------- */
/* Foundry VTT Initialization */
/* -------------------------------------------- */
Hooks.on("chatMessage", (html, content, msg) => {
if (content[0] == '/') {
let regExp = /(\S+)/g;
let commands = content.toLowerCase().match(regExp);
console.log(commands);
}
return true;
});

View File

@@ -0,0 +1,139 @@
/**
* Extend the basic ActorSheet with some very simple modifications
* @extends {ActorSheet}
*/
import { PegasusUtility } from "./pegasus-utility.js";
import { PegasusItemSheet } from "./pegasus-item-sheet.js";
/* -------------------------------------------- */
export class PegasusNPCSheet extends ActorSheet {
/** @override */
static get defaultOptions() {
return mergeObject(super.defaultOptions, {
classes: ["pegasus-rpg", "sheet", "actor"],
template: "systems/fvtt-pegasus-rpg/templates/npc-sheet.html",
width: 640,
height: 720,
tabs: [{ navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "stats" }],
dragDrop: [{ dragSelector: ".item-list .item", dropSelector: null }],
editScore: false
});
}
/* -------------------------------------------- */
async getData() {
const objectData = PegasusUtility.data(this.object);
this.actor.prepareTraitsAttributes();
let actorData = duplicate(PegasusUtility.templateData(this.object));
let formData = {
title: this.title,
id: objectData.id,
type: objectData.type,
img: objectData.img,
name: objectData.name,
editable: this.isEditable,
cssClass: this.isEditable ? "editable" : "locked",
data: actorData,
effects: this.object.effects.map(e => foundry.utils.deepClone(e.data)),
limited: this.object.limited,
equipments: this.actor.getEquipments(),
defenseBase: this.actor.getDefenseBase(),
bodyArmourBase: this.actor.getBodyArmour(),
headArmourBase: this.actor.getHeadArmour(),
weapons: this.actor.getWeapons(),
traits: this.actor.getTraits(),
optionsBase: FraggedKingdomUtility.createDirectOptionList(0, 20),
options: this.options,
owner: this.document.isOwner,
editScore: this.options.editScore,
isGM: game.user.isGM
}
this.formData = formData;
console.log("NPC : ", formData, this.object);
return formData;
}
/* -------------------------------------------- */
/** @override */
activateListeners(html) {
super.activateListeners(html);
// Everything below here is only needed if the sheet is editable
if (!this.options.editable) return;
// Update Inventory Item
html.find('.item-edit').click(ev => {
const li = $(ev.currentTarget).parents(".item");
let itemId = li.data("item-id");
const item = this.actor.items.get( itemId );
item.sheet.render(true);
});
// Delete Inventory Item
html.find('.item-delete').click(ev => {
const li = $(ev.currentTarget).parents(".item");
FraggedKingdomUtility.confirmDelete(this, li);
});
html.find('.trait-link').click((event) => {
const itemId = $(event.currentTarget).data("item-id");
const item = this.actor.getOwnedItem(itemId);
item.sheet.render(true);
});
html.find('.competence-label a').click((event) => {
const li = $(event.currentTarget).parents(".item");
const competenceId = li.data("item-id");
this.actor.rollSkill(competenceId);
});
html.find('.weapon-label a').click((event) => {
const li = $(event.currentTarget).parents(".item");
const armeId = li.data("item-id");
const statId = li.data("stat-id");
this.actor.rollWeapon(armeId, statId);
});
html.find('.npc-fight-roll').click((event) => {
this.actor.rollNPCFight();
});
html.find('.npc-skill-roll').click((event) => {
this.actor.rollGenericSkill();
});
html.find('.lock-unlock-sheet').click((event) => {
this.options.editScore = !this.options.editScore;
this.render(true);
});
html.find('.item-link a').click((event) => {
const itemId = $(event.currentTarget).data("item-id");
const item = this.actor.getOwnedItem(itemId);
item.sheet.render(true);
});
html.find('.item-equip').click(ev => {
const li = $(ev.currentTarget).parents(".item");
this.actor.equipItem( li.data("item-id") );
this.render(true);
});
}
/* -------------------------------------------- */
/** @override */
setPosition(options = {}) {
const position = super.setPosition(options);
const sheetBody = this.element.find(".sheet-body");
const bodyHeight = position.height - 192;
sheetBody.css("height", bodyHeight);
return position;
}
/* -------------------------------------------- */
/** @override */
_updateObject(event, formData) {
// Update the Actor
return this.object.update(formData);
}
}

View File

@@ -0,0 +1,84 @@
import { PegasusUtility } from "./pegasus-utility.js";
export class PegasusRollDialog extends Dialog {
/* -------------------------------------------- */
static async create(actor, rollData ) {
let html
let options = { classes: ["WotGdialog"], width: 420, height: 320, 'z-index': 99999 };
if ( rollData.mode == "skill") {
html = await renderTemplate('systems/fvtt-pegasus-rpg/templates/roll-dialog-skill.html', rollData);
options.height = 360;
} else if (rollData.mode == "chidamage") {
html = await renderTemplate('systems/fvtt-pegasus-rpg/templates/roll-dialog-damage-chi.html', rollData);
options.height = 380;
} else if (rollData.mode == "technique") {
html = await renderTemplate('systems/fvtt-pegasus-rpg/templates/roll-dialog-technique.html', rollData);
options.height = 380;
} else if (rollData.mode == "weapon") {
html = await renderTemplate('systems/fvtt-pegasus-rpg/templates/roll-dialog-weapon.html', rollData);
options.height = 460;
} else {
html = await renderTemplate('systems/fvtt-pegasus-rpg/templates/roll-dialog-skill.html', rollData);
}
return new PegasusRollDialog(actor, rollData, html, options );
}
/* -------------------------------------------- */
constructor(actor, rollData, html, options, close = undefined) {
let conf = {
title: (rollData.mode == "skill") ? "Skill" : "Roll",
content: html,
buttons: {
roll: {
icon: '<i class="fas fa-check"></i>',
label: "Roll !",
callback: () => { this.roll() }
},
cancel: {
icon: '<i class="fas fa-times"></i>',
label: "Cancel",
callback: () => { this.close() }
} },
default: "roll",
close: close
}
super(conf, options);
this.actor = actor;
this.rollData = rollData;
}
/* -------------------------------------------- */
roll () {
PegasusUtility.rollWotG( this.rollData )
}
/* -------------------------------------------- */
activateListeners(html) {
super.activateListeners(html);
var dialog = this;
function onLoad() {
}
$(function () { onLoad(); });
html.find('#negativeModifier').change((event) => {
this.rollData.negativeModifier = Number(event.currentTarget.value);
});
html.find('#positiveModifier').change((event) => {
this.rollData.positiveModifier = Number(event.currentTarget.value);
});
html.find('#specialtiesBonus').change((event) => {
this.rollData.specialtiesBonus = Number(event.currentTarget.value);
});
html.find('#selectedChi').change((event) => {
this.rollData.selectedChi = Number(event.currentTarget.value);
});
html.find('#bonusMalus').change((event) => {
this.rollData.bonusMalus = Number(event.currentTarget.value);
});
}
}

593
modules/pegasus-utility.js Normal file
View File

@@ -0,0 +1,593 @@
/* -------------------------------------------- */
/* -------------------------------------------- */
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);
}
}