fvtt-les-heritiers/modules/heritiers-actor.js
2023-01-20 15:19:04 +01:00

539 lines
17 KiB
JavaScript

/* -------------------------------------------- */
import { HeritiersUtility } from "./heritiers-utility.js";
import { HeritiersRollDialog } from "./heritiers-roll-dialog.js";
/* -------------------------------------------- */
const __degatsBonus = [-2, -2, -1, -1, 0, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 8, 8, 9, 9, 10, 10]
const __vitesseBonus = [-2, -2, -1, -1, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8]
/* -------------------------------------------- */
/**
* Extend the base Actor entity by defining a custom roll data structure which is ideal for the Simple system.
* @extends {Actor}
*/
export class HeritiersActor 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 == 'personnage') {
const skills = await HeritiersUtility.loadCompendium("fvtt-les-heritiers.competences")
data.items = skills.map(i => i.toObject())
}
if (data.type == 'creature') {
const skills = await HeritiersUtility.loadCompendium("fvtt-les-heritiers.skills-creatures")
data.items = skills.map(i => i.toObject())
data.items.push({ name: "Arme naturelle 1", type: 'arme', img: "systems/fvtt-les-heritiers/assets/icons/melee.webp", system: { typearme: "contact", bonusmaniementoff: 0, seuildefense: 0, degats: "0" } })
data.items.push({ name: "Arme naturelle 2", type: 'arme', img: "systems/fvtt-les-heritiers/assets/icons/melee.webp", system: { typearme: "contact", bonusmaniementoff: 0, seuildefense: 0, degats: "0" } })
}
return super.create(data, options);
}
/* -------------------------------------------- */
prepareArme(arme) {
arme = duplicate(arme)
let combat = this.getCombatValues()
if (arme.system.typearme == "contact" || arme.system.typearme == "contactjet") {
let bonusDefense = 0
arme.system.competence = duplicate(this.items.find(item => item.type == "competence" && item.name.toLowerCase() == "mêlée"))
arme.system.attrKey = "pui"
arme.system.totalDegats = arme.system.degats + "+" + combat.bonusDegatsTotal
arme.system.totalOffensif = this.system.attributs.pui.value + arme.system.competence.system.niveau + arme.system.bonusmaniementoff
arme.system.totalDefensif = combat.defenseTotal + arme.system.competence.system.niveau + arme.system.seuildefense + bonusDefense
arme.system.isdefense = true
}
if (arme.system.typearme == "jet" || arme.system.typearme == "tir") {
arme.system.competence = duplicate(this.items.find(item => item.type == "competence" && item.name.toLowerCase() == "armes à distance"))
arme.system.attrKey = "adr"
arme.system.totalOffensif = this.system.attributs.adr.value + arme.system.competence.system.niveau + arme.system.bonusmaniementoff
arme.system.totalDegats = arme.system.degats
if (arme.system.isdefense) {
arme.system.totalDefensif = combat.defenseTotal + arme.system.competence.system.niveau + arme.system.seuildefense
}
}
return arme
}
/* -------------------------------------------- */
getWeapons() {
let armes = []
for (let arme of this.items) {
if (arme.type == "arme") {
armes.push(this.prepareArme(arme))
}
}
return armes
}
/* -------------------------------------------- */
getMonnaies() {
return this.items.filter(it => it.type == "monnaie")
}
/* ----------------------- --------------------- */
addMember(actorId) {
let members = duplicate(this.system.members)
members.push({ id: actorId })
this.update({ 'system.members': members })
}
async removeMember(actorId) {
let members = this.system.members.filter(it => it.id != actorId)
this.update({ 'system.members': members })
}
/* ----------------------- --------------------- */
getEquipments() {
return this.items.filter(item => item.type == "equipement")
}
getAvantages() {
return this.items.filter(item => item.type == "avantage")
}
getDesavantages() {
return this.items.filter(item => item.type == "desavantage")
}
getMonnaies() {
return this.items.filter(item => item.type == "monnaie")
}
getArmors() {
return this.items.filter(item => item.type == "protection")
}
getTalents() {
return this.items.filter(item => item.type == "talent")
}
getContacts() {
return this.items.filter(item => item.type == "contact")
}
getAtouts() {
return this.items.filter(item => item.type == "atoutfeerique")
}
getCapacites() {
return this.items.filter(item => item.type == "capacitenaturelle")
}
/* -------------------------------------------- */
getSkills() {
let comp = []
for (let item of this.items) {
item = duplicate(item)
if (item.type == "competence") {
comp.push(item)
}
}
return HeritiersUtility.sortByName(comp)
}
/* -------------------------------------------- */
organizeUtileSkills() {
let comp = {}
for (let key in game.system.lesheritiers.config.competenceProfil) {
comp[key] = []
}
for (let item of this.items) {
if (item.type == "competence") {
if (item.system.categorie == "utile") {
comp[item.system.profil].push(item)
}
}
}
return comp
}
/* -------------------------------------------- */
organizeFutileSkills() {
let comp = []
for (let item of this.items) {
if (item.type == "competence") {
if (item.system.categorie == "futile") {
comp.push(item)
}
}
}
return HeritiersUtility.sortByName(comp)
}
/* -------------------------------------------- */
getDefenseBase() {
return Math.max(this.system.attributs.tre.value, this.system.attributs.pui.value)
}
/* -------------------------------------------- */
getVitesseBase() {
return 5 + __vitesseBonus[this.system.attributs.adr.value]
}
/* -------------------------------------------- */
getProtection() {
let equipProtection = 0
for (let armor in this.items) {
if (armor.type == "protection" && armor.system.equipped) {
equipProtection += Number(armor.system.protection)
}
}
if (equipProtection < 4) {
return 4 + equipProtection // Cas des boucliers + sans armure
}
return equipProtection // Uniquement la protection des armures + boucliers
}
/* -------------------------------------------- */
getCombatValues() {
let combat = {
}
return combat
}
/* -------------------------------------------- */
prepareBaseData() {
}
/* -------------------------------------------- */
async prepareData() {
super.prepareData();
}
/* -------------------------------------------- */
prepareDerivedData() {
if (this.type == 'personnage') {
}
super.prepareDerivedData()
}
/* -------------------------------------------- */
_preUpdate(changed, options, user) {
super._preUpdate(changed, options, user);
}
/* -------------------------------------------- */
getItemById(id) {
let item = this.items.find(item => item.id == id);
if (item) {
item = duplicate(item)
}
return item;
}
/* -------------------------------------------- */
async equipItem(itemId) {
let item = this.items.find(item => item.id == itemId)
if (item && item.system) {
let update = { _id: item.id, "system.equipped": !item.system.equipped }
await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
}
}
/* -------------------------------------------- */
editItemField(itemId, itemType, itemField, dataType, value) {
let item = this.items.find(item => item.id == itemId)
if (item) {
console.log("Item ", item, itemField, dataType, value)
if (dataType.toLowerCase() == "number") {
value = Number(value)
} else {
value = String(value)
}
let update = { _id: item.id, [`system.${itemField}`]: value };
this.updateEmbeddedDocuments("Item", [update])
}
}
/* -------------------------------------------- */
getPvMalus() {
if (this.system.pv.value > 0) {
if (this.system.pv.value < this.system.pv.max / 2) {
return -1
}
if (this.system.pv.value < 5) {
return -2
}
return 0
}
return "Moribond(e)"
}
/* -------------------------------------------- */
compareName(a, b) {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
}
/* -------------------------------------------- */
getCarac(attrKey) {
return duplicate(this.system.caracteristiques)
}
/* -------------------------------------------- */
getBonusDegats() {
return 0;
}
/* -------------------------------------------- */
async equipGear(equipmentId) {
let item = this.items.find(item => item.id == equipmentId);
if (item && item.system.data) {
let update = { _id: item.id, "system.equipped": !item.system.equipped };
await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
}
}
/* -------------------------------------------- */
getSubActors() {
let subActors = [];
for (let id of this.system.subactors) {
subActors.push(duplicate(game.actors.get(id)));
}
return subActors;
}
/* -------------------------------------------- */
async addSubActor(subActorId) {
let subActors = duplicate(this.system.subactors);
subActors.push(subActorId);
await this.update({ 'system.subactors': subActors });
}
/* -------------------------------------------- */
async delSubActor(subActorId) {
let newArray = [];
for (let id of this.system.subactors) {
if (id != subActorId) {
newArray.push(id);
}
}
await this.update({ 'system.subactors': newArray });
}
/* -------------------------------------------- */
getTotalAdversite() {
return this.system.adversite.bleue + this.system.adversite.rouge + this.system.adversite.noire
}
/* -------------------------------------------- */
async incDecAdversite(adv, incDec = 0) {
let adversite = duplicate(this.system.adversite)
adversite[adv] += Number(incDec)
adversite[adv] = Math.max(adversite[adv], 0)
this.update({ 'system.adversite': adversite })
}
/* -------------------------------------------- */
async incDecQuantity(objetId, incDec = 0) {
let objetQ = this.items.get(objetId)
if (objetQ) {
let newQ = objetQ.system.quantite + incDec
newQ = Math.max(newQ, 0)
const updated = await this.updateEmbeddedDocuments('Item', [{ _id: objetQ.id, 'system.quantite': newQ }]); // pdates one EmbeddedEntity
}
}
/* -------------------------------------------- */
computeRichesse() {
let valueSC = 0
for (let monnaie of this.items) {
if (monnaie.type == "monnaie") {
valueSC += Number(monnaie.system.prixsc) * Number(monnaie.system.quantite)
}
}
return HeritiersUtility.computeMonnaieDetails(valueSC)
}
/* -------------------------------------------- */
computeValeurEquipement() {
let valueSC = 0
for (let equip of this.items) {
if (equip.type == "equipement" || equip.type == "arme" || equip.type == "protection") {
valueSC += Number(equip.system.prixsc) * Number(equip.system.quantite ?? 1)
valueSC += (Number(equip.system.prixca) * Number(equip.system.quantite ?? 1)) * 20
valueSC += (Number(equip.system.prixpo) * Number(equip.system.quantite ?? 1)) * 400
}
}
return HeritiersUtility.computeMonnaieDetails(valueSC)
}
/* -------------------------------------------- */
getCompetence(compId) {
return this.items.get(compId)
}
/* -------------------------------------------- */
async setPredilectionUsed(compId, predIdx) {
let comp = this.items.get(compId)
let pred = duplicate(comp.system.predilections)
pred[predIdx].used = true
await this.updateEmbeddedDocuments('Item', [{ _id: compId, 'system.predilections': pred }])
}
/* -------------------------------------------- */
getInitiativeScore() {
let init = this.getFlag("world", "last-initiative")
return init || -1
}
/* -------------------------------------------- */
getBestDefenseValue() {
let defenseList = this.items.filter(item => (item.type == "arme") && item.system.equipped)
let maxDef = 0
let bestArme
for (let arme of defenseList) {
if (arme.type == "arme") {
arme = this.prepareArme(arme)
}
if (arme.system.totalDefensif > maxDef) {
maxDef = arme.system.totalDefensif
bestArme = duplicate(arme)
}
}
return bestArme
}
/* -------------------------------------------- */
searchRelevantTalents(competence) {
let talents = []
for (let talent of this.items) {
if (talent.type == "talent" && talent.system.isautomated && talent.system.automations.length > 0) {
for (let auto of talent.system.automations) {
if (auto.eventtype === "prepare-roll") {
if (auto.competence.toLowerCase() == competence.name.toLowerCase()) {
talent = duplicate(talent)
talent.system.bonus = auto.bonus
talent.system.baCost = auto.baCost
talents.push(talent)
}
}
}
}
}
return talents
}
/* -------------------------------------------- */
getTricherie() {
return this.system.rang.tricherie.value
}
/* -------------------------------------------- */
getHeritages() {
return this.system.rang.heritage.value
}
/* -------------------------------------------- */
incDecTricherie(value) {
let tricherie = this.system.rang.tricherie
tricherie.value += value
tricherie.value = Math.max(tricherie.value, 0)
tricherie.value = Math.min(tricherie.value, tricherie.max)
this.update({ 'system.rang.tricherie': tricherie })
}
/* -------------------------------------------- */
getCommonRollData(compId = undefined, compName = undefined) {
let rollData = HeritiersUtility.getBasicRollData()
rollData.alias = this.name
rollData.actorImg = this.img
rollData.actorId = this.id
rollData.tokenId = this.token?.id
rollData.img = this.img
rollData.caracList = this.getCarac()
rollData.caracKey = "agi"
rollData.tricherie = this.getTricherie()
rollData.heritage = this.getHeritages()
rollData.useTricherie = false
rollData.useHeritage = false
rollData.pvMalus = this.getPvMalus()
if (compId) {
rollData.competence = duplicate(this.items.get(compId) || {})
rollData.actionImg = rollData.competence?.img
}
if (compName) {
rollData.competence = duplicate(this.items.find(item => item.name.toLowerCase() == compName.toLowerCase()) || {})
rollData.actionImg = rollData.competence?.img
}
return rollData
}
/* -------------------------------------------- */
async rollCarac(key, isInit = false) {
let rollData = this.getCommonRollData()
rollData.mode = "carac"
rollData.carac = this.system.caracteristiques[key]
rollData.caracKey = key
let rollDialog = await HeritiersRollDialog.create(this, rollData)
rollDialog.render(true)
}
/* -------------------------------------------- */
async rollCompetence(compId) {
let rollData = this.getCommonRollData(compId)
rollData.mode = "competence"
console.log("RollDatra", rollData)
let rollDialog = await HeritiersRollDialog.create(this, rollData)
rollDialog.render(true)
}
/* -------------------------------------------- */
async rollArmeOffensif(armeId) {
let arme = this.items.get(armeId)
if (arme.type == "arme") {
arme = this.prepareArme(arme)
}
let rollData = this.getCommonRollData(arme.system.attrKey, arme.system.competence._id)
rollData.arme = arme
HeritiersUtility.updateWithTarget(rollData)
console.log("ARME!", rollData)
let rollDialog = await HeritiersRollDialog.create(this, rollData)
rollDialog.render(true)
}
/* -------------------------------------------- */
async rollArmeDegats(armeId, targetVigueur = undefined) {
let arme = this.items.get(armeId)
if (arme.type == "arme") {
arme = this.prepareArme(arme)
}
console.log("DEGATS", arme)
let roll = new Roll("1d10+" + arme.system.totalDegats).roll({ async: false })
await HeritiersUtility.showDiceSoNice(roll, game.settings.get("core", "rollMode"));
let nbEtatPerdus = 0
if (targetVigueur) {
nbEtatPerdus = Math.floor(roll.total / targetVigueur)
}
let rollData = {
arme: arme,
finalResult: roll.total,
alias: this.name,
actorImg: this.img,
actorId: this.id,
actionImg: arme.img,
targetVigueur: targetVigueur,
nbEtatPerdus: nbEtatPerdus
}
HeritiersUtility.createChatWithRollMode(rollData.alias, {
content: await renderTemplate(`systems/fvtt-les-heritiers/templates/chat-degats-result.html`, rollData)
})
}
}