Initial import

This commit is contained in:
2024-11-21 23:59:44 +01:00
commit d8ce83bcf2
98 changed files with 120909 additions and 0 deletions

View File

@ -0,0 +1,10 @@
export { default as LethalFantasyCharacterSheet } from "./sheets/character-sheet.mjs"
export { default as LethalFantasyOpponentSheet } from "./sheets/opponent-sheet.mjs"
export { default as LethalFantasyPathSheet } from "./sheets/path-sheet.mjs"
export { default as LethalFantasyTalentSheet } from "./sheets/talent-sheet.mjs"
export { default as LethalFantasyWeaponSheet } from "./sheets/weapon-sheet.mjs"
export { default as LethalFantasyArmorSheet } from "./sheets/armor-sheet.mjs"
export { default as LethalFantasySpellSheet } from "./sheets/spell-sheet.mjs"
export { default as LethalFantasyAttackSheet } from "./sheets/attack-sheet.mjs"
export { default as LethalFantasyFortune } from "./fortune.mjs"
export { default as LethalFantasyManager } from "./manager.mjs"

View File

@ -0,0 +1,156 @@
const { HandlebarsApplicationMixin, ApplicationV2 } = foundry.applications.api
import { SYSTEM } from "../config/system.mjs"
/**
* An application for configuring the permissions which are available to each User role.
* @extends ApplicationV2
* @mixes HandlebarsApplication
* @alias PermissionConfig
*/
export default class LethalFantasyFortune extends HandlebarsApplicationMixin(ApplicationV2) {
/** @inheritDoc */
static DEFAULT_OPTIONS = {
id: "tenebris-application-fortune",
tag: "form",
window: {
contentClasses: ["tenebris-fortune"],
title: "TENEBRIS.Fortune.title",
controls: [],
},
position: {
width: 200,
height: 200,
top: 80,
left: 150,
},
form: {
closeOnSubmit: true,
},
actions: {
fortune: LethalFantasyFortune.#requestFortune,
increaseFortune: LethalFantasyFortune.#increaseFortune,
decreaseFortune: LethalFantasyFortune.#decreaseFortune,
},
}
/** @override */
_getHeaderControls() {
const controls = []
if (game.user.isGM) {
controls.push(
{
action: "increaseFortune",
icon: "fa fa-plus",
label: "Augmenter",
},
{
action: "decreaseFortune",
icon: "fa fa-minus",
label: "Diminuer",
},
)
}
return controls
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-lethal-fantasy/templates/fortune.hbs",
},
}
/* -------------------------------------------- */
/* Rendering */
/* -------------------------------------------- */
/** @override */
async _prepareContext(_options = {}) {
return {
fortune: game.settings.get("tenebris", "fortune"),
userId: game.user.id,
isGM: game.user.isGM,
}
}
/**
* Handles the request for a fortune.
*
* @param {Event} event The event that triggered the request.
* @param {Object} target The target object for the request.
* @private
*/
static #requestFortune(event, target) {
console.debug("request Fortune, event, target")
game.socket.emit(`system.${SYSTEM.id}`, {
action: "fortune",
data: {
userId: game.user.id,
},
})
}
static async #increaseFortune(event, target) {
console.log("increase Fortune", event, target)
const currentValue = game.settings.get("tenebris", "fortune")
const newValue = currentValue + 1
await game.settings.set("tenebris", "fortune", newValue)
}
static async #decreaseFortune(event, target) {
console.log("decrease Fortune", event, target)
const currentValue = game.settings.get("tenebris", "fortune")
if (currentValue > 0) {
const newValue = currentValue - 1
await game.settings.set("tenebris", "fortune", newValue)
}
}
/**
* Handles the fortune spcket event for a given user.
*
* @param {Object} [options] The options object.
* @param {string} [options.userId] The ID of the user.
* @returns {Promise<ChatMessage>} - The created chat message.
*/
static async handleSocketEvent({ userId } = {}) {
console.debug(`handleSocketEvent Fortune from ${userId} !`)
const origin = game.users.get(userId)
const chatData = {
name: origin.name,
actingCharImg: origin.character?.img,
origin: origin,
user: game.user,
isGM: game.user.isGM,
}
const content = await renderTemplate("systems/fvtt-lethal-fantasy/templates/chat-fortune.hbs", chatData)
const messageData = {
style: CONST.CHAT_MESSAGE_STYLES.OTHER,
user: origin,
speaker: { user: origin },
content: content,
flags: { tenebris: { typeMessage: "fortune", accepted: false } },
}
ChatMessage.applyRollMode(messageData, CONST.DICE_ROLL_MODES.PRIVATE)
return ChatMessage.implementation.create(messageData)
}
/**
* Handles the acceptance of a request event in the chat message by the GM
*
* @param {Event} event The event object that triggered the request.
* @param {HTMLElement} html The HTML element associated with the event.
* @param {Object} data Additional data related to the event.
* @returns {Promise<void>} A promise that resolves when the request has been processed.
*/
static async acceptRequest(event, html, data) {
console.debug("acceptRequest Fortune", event, html, data)
const currentValue = game.settings.get("tenebris", "fortune")
if (currentValue > 0) {
const newValue = currentValue - 1
await game.settings.set("tenebris", "fortune", newValue)
}
let message = game.messages.get(data.message._id)
message.update({ "flags.tenebris.accepted": true })
}
}

View File

@ -0,0 +1,142 @@
const { HandlebarsApplicationMixin, ApplicationV2 } = foundry.applications.api
import { SYSTEM } from "../config/system.mjs"
/**
* An application for configuring the permissions which are available to each User role.
* @extends ApplicationV2
* @mixes HandlebarsApplication
* @alias PermissionConfig
*/
export default class LethalFantasyManager extends HandlebarsApplicationMixin(ApplicationV2) {
static DEFAULT_OPTIONS = {
id: "tenebris-application-manager",
tag: "form",
window: {
contentClasses: ["tenebris-manager"],
title: "TENEBRIS.Manager.title",
resizable: true,
},
position: {
width: "auto",
height: "auto",
top: 80,
left: 400,
},
form: {
closeOnSubmit: true,
},
actions: {
resourceAll: LethalFantasyManager.#onResourceAll,
resourceOne: LethalFantasyManager.#onResourceOne,
saveAll: LethalFantasyManager.#onSaveAll,
saveOne: LethalFantasyManager.#onSaveOne,
openSheet: LethalFantasyManager.#onOpenSheet,
},
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-lethal-fantasy/templates/manager.hbs",
},
}
/* -------------------------------------------- */
/* Rendering */
/* -------------------------------------------- */
/** @override */
async _prepareContext(_options = {}) {
return {
players: game.users.filter((u) => u.hasPlayerOwner && u.active),
}
}
static async #onResourceAll(event, target) {
const value = event.target.dataset.resource
LethalFantasyManager.askRollForAll("resource", value)
}
static async #onSaveAll(event, target) {
const value = event.target.dataset.save
LethalFantasyManager.askRollForAll("save", value)
}
static #onResourceOne(event, target) {
const value = event.target.dataset.resource
const recipient = event.target.parentElement.dataset.userId
const name = event.target.parentElement.dataset.characterName
LethalFantasyManager.askRollForOne("resource", value, recipient, name)
}
static async #onSaveOne(event, target) {
const value = event.target.dataset.save
const recipient = event.target.parentElement.dataset.userId
const name = event.target.parentElement.dataset.characterName
LethalFantasyManager.askRollForOne("save", value, recipient, name)
}
static #onOpenSheet(event, target) {
const characterId = event.target.dataset.characterId
game.actors.get(characterId).sheet.render(true)
}
static async askRollForAll(type, value, title = null, avantage = null) {
let label = game.i18n.localize(`TENEBRIS.Manager.${value}`)
let text = game.i18n.format("TENEBRIS.Chat.askRollForAll", { value: label })
if (avantage) {
switch (avantage) {
case "++":
text += ` ${game.i18n.localize("TENEBRIS.Roll.doubleAvantage")}`
break
case "+":
text += ` ${game.i18n.localize("TENEBRIS.Roll.avantage")}`
break
case "-":
text += ` ${game.i18n.localize("TENEBRIS.Roll.desavantage")}`
break
case "--":
text += ` ${game.i18n.localize("TENEBRIS.Roll.doubleDesavantage")}`
break
default:
break
}
}
ChatMessage.create({
user: game.user.id,
content: await renderTemplate(`systems/fvtt-lethal-fantasy/templates/chat-ask-roll.hbs`, {
title: title !== null ? title : "",
text: text,
rollType: type,
value: value,
avantage: avantage,
}),
flags: { tenebris: { typeMessage: "askRoll" } },
})
}
static async askRollForOne(type, value, recipient, name) {
let label = game.i18n.localize(`TENEBRIS.Manager.${value}`)
const text = game.i18n.format("TENEBRIS.Chat.askRollForOne", { value: label, name: name })
game.socket.emit(`system.${SYSTEM.id}`, {
action: "askRoll",
data: {
userId: recipient,
},
})
ChatMessage.create({
user: game.user.id,
content: await renderTemplate(`systems/fvtt-lethal-fantasy/templates/chat-ask-roll.hbs`, {
text: text,
rollType: type,
value: value,
}),
whisper: [recipient],
flags: { tenebris: { typeMessage: "askRoll" } },
})
}
}

View File

@ -0,0 +1,27 @@
import LethalFantasyItemSheet from "./base-item-sheet.mjs"
export default class LethalFantasyArmorSheet extends LethalFantasyItemSheet {
/** @override */
static DEFAULT_OPTIONS = {
classes: ["armor"],
position: {
width: 400,
},
window: {
contentClasses: ["armor-content"],
},
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-lethal-fantasy/templates/armor.hbs",
},
}
/** @override */
async _prepareContext() {
const context = await super._prepareContext()
return context
}
}

View File

@ -0,0 +1,27 @@
import LethalFantasyItemSheet from "./base-item-sheet.mjs"
export default class LethalFantasyAttackSheet extends LethalFantasyItemSheet {
/** @override */
static DEFAULT_OPTIONS = {
classes: ["attack"],
position: {
width: 600,
},
window: {
contentClasses: ["attack-content"],
},
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-lethal-fantasy/templates/attack.hbs",
},
}
/** @override */
async _prepareContext() {
const context = await super._prepareContext()
return context
}
}

View File

@ -0,0 +1,292 @@
const { HandlebarsApplicationMixin } = foundry.applications.api
export default class LethalFantasyActorSheet extends HandlebarsApplicationMixin(foundry.applications.sheets.ActorSheetV2) {
/**
* Different sheet modes.r
* @enum {number}
*/
static SHEET_MODES = { EDIT: 0, PLAY: 1 }
constructor(options = {}) {
super(options)
this.#dragDrop = this.#createDragDropHandlers()
}
#dragDrop
/** @override */
static DEFAULT_OPTIONS = {
classes: ["tenebris", "actor"],
position: {
width: 1400,
height: "auto",
},
form: {
submitOnChange: true,
},
window: {
resizable: true,
},
dragDrop: [{ dragSelector: '[data-drag="true"], .rollable', dropSelector: null }],
actions: {
editImage: LethalFantasyActorSheet.#onEditImage,
toggleSheet: LethalFantasyActorSheet.#onToggleSheet,
edit: LethalFantasyActorSheet.#onItemEdit,
delete: LethalFantasyActorSheet.#onItemDelete,
createSpell: LethalFantasyActorSheet.#onCreateSpell,
},
}
/**
* The current sheet mode.
* @type {number}
*/
_sheetMode = this.constructor.SHEET_MODES.PLAY
/**
* Is the sheet currently in 'Play' mode?
* @type {boolean}
*/
get isPlayMode() {
return this._sheetMode === this.constructor.SHEET_MODES.PLAY
}
/**
* Is the sheet currently in 'Edit' mode?
* @type {boolean}
*/
get isEditMode() {
return this._sheetMode === this.constructor.SHEET_MODES.EDIT
}
/** @override */
async _prepareContext() {
const context = {
fields: this.document.schema.fields,
systemFields: this.document.system.schema.fields,
actor: this.document,
system: this.document.system,
source: this.document.toObject(),
enrichedDescription: await TextEditor.enrichHTML(this.document.system.description, { async: true }),
isEditMode: this.isEditMode,
isPlayMode: this.isPlayMode,
isEditable: this.isEditable,
}
return context
}
/** @override */
_onRender(context, options) {
this.#dragDrop.forEach((d) => d.bind(this.element))
// Add listeners to rollable elements
const rollables = this.element.querySelectorAll(".rollable")
rollables.forEach((d) => d.addEventListener("click", this._onRoll.bind(this)))
}
// #region Drag-and-Drop Workflow
/**
* Create drag-and-drop workflow handlers for this Application
* @returns {DragDrop[]} An array of DragDrop handlers
* @private
*/
#createDragDropHandlers() {
return this.options.dragDrop.map((d) => {
d.permissions = {
dragstart: this._canDragStart.bind(this),
drop: this._canDragDrop.bind(this),
}
d.callbacks = {
dragstart: this._onDragStart.bind(this),
dragover: this._onDragOver.bind(this),
drop: this._onDrop.bind(this),
}
return new DragDrop(d)
})
}
/**
* Callback actions which occur when a dragged element is dropped on a target.
* @param {DragEvent} event The originating DragEvent
* @protected
*/
async _onDrop(event) {}
/**
* Define whether a user is able to begin a dragstart workflow for a given drag selector
* @param {string} selector The candidate HTML selector for dragging
* @returns {boolean} Can the current user drag this selector?
* @protected
*/
_canDragStart(selector) {
return this.isEditable
}
/**
* Define whether a user is able to conclude a drag-and-drop workflow for a given drop selector
* @param {string} selector The candidate HTML selector for the drop target
* @returns {boolean} Can the current user drop on this selector?
* @protected
*/
_canDragDrop(selector) {
return this.isEditable && this.document.isOwner
}
/**
* Callback actions which occur at the beginning of a drag start workflow.
* @param {DragEvent} event The originating DragEvent
* @protected
*/
_onDragStart(event) {
if ("link" in event.target.dataset) return
const el = event.currentTarget.closest('[data-drag="true"]')
const dragType = el.dataset.dragType
let dragData = {}
let target
switch (dragType) {
case "save":
target = event.currentTarget.querySelector("input")
dragData = {
actorId: this.document.id,
type: "roll",
rollType: target.dataset.rollType,
rollTarget: target.dataset.rollTarget,
value: target.value,
}
break
case "resource":
target = event.currentTarget.querySelector("select")
dragData = {
actorId: this.document.id,
type: "roll",
rollType: target.dataset.rollType,
rollTarget: target.dataset.rollTarget,
value: target.value,
}
break
case "damage":
dragData = {
actorId: this.document.id,
type: "rollDamage",
rollType: el.dataset.dragType,
rollTarget: el.dataset.itemId,
}
break
case "attack":
dragData = {
actorId: this.document.id,
type: "rollAttack",
rollValue: el.dataset.rollValue,
rollTarget: el.dataset.rollTarget,
}
break
default:
// Handle other cases or do nothing
break
}
// Extract the data you need
if (!dragData) return
// Set data transfer
event.dataTransfer.setData("text/plain", JSON.stringify(dragData))
}
/**
* Callback actions which occur when a dragged element is over a drop target.
* @param {DragEvent} event The originating DragEvent
* @protected
*/
_onDragOver(event) {}
async _onDropItem(item) {
let itemData = item.toObject()
await this.document.createEmbeddedDocuments("Item", [itemData], { renderSheet: false })
}
// #endregion
// #region Actions
/**
* Handle toggling between Edit and Play mode.
* @param {Event} event The initiating click event.
* @param {HTMLElement} target The current target of the event listener.
*/
static #onToggleSheet(event, target) {
const modes = this.constructor.SHEET_MODES
this._sheetMode = this.isEditMode ? modes.PLAY : modes.EDIT
this.render()
}
/**
* Handle changing a Document's image.
*
* @this LethalFantasyCharacterSheet
* @param {PointerEvent} event The originating click event
* @param {HTMLElement} target The capturing HTML element which defined a [data-action]
* @returns {Promise}
* @private
*/
static async #onEditImage(event, target) {
const attr = target.dataset.edit
const current = foundry.utils.getProperty(this.document, attr)
const { img } = this.document.constructor.getDefaultArtwork?.(this.document.toObject()) ?? {}
const fp = new FilePicker({
current,
type: "image",
redirectToRoot: img ? [img] : [],
callback: (path) => {
this.document.update({ [attr]: path })
},
top: this.position.top + 40,
left: this.position.left + 10,
})
return fp.browse()
}
/**
* Edit an existing item within the Actor
* Start with the uuid, if it's not found, fallback to the id (as Embedded item in the actor)
* @this LethalFantasyCharacterSheet
* @param {PointerEvent} event The originating click event
* @param {HTMLElement} target the capturing HTML element which defined a [data-action]
*/
static async #onItemEdit(event, target) {
const id = target.getAttribute("data-item-id")
const uuid = target.getAttribute("data-item-uuid")
let item
item = await fromUuid(uuid)
if (!item) item = this.document.items.get(id)
if (!item) return
item.sheet.render(true)
}
/**
* Delete an existing talent within the Actor
* Use the uuid to display the talent sheet
* @param {PointerEvent} event The originating click event
* @param {HTMLElement} target the capturing HTML element which defined a [data-action]
*/
static async #onItemDelete(event, target) {
const itemUuid = target.getAttribute("data-item-uuid")
const talent = await fromUuid(itemUuid)
await talent.deleteDialog()
}
/**
* Handles the creation of a new attack item.
*
* @param {Event} event The event that triggered the creation of the attack.
* @param {Object} target The target object where the attack will be created.
* @private
* @static
*/
static #onCreateSpell(event, target) {
const item = this.document.createEmbeddedDocuments("Item", [{ name: "Nouveau sortilège", type: "spell" }])
}
// #endregion
}

View File

@ -0,0 +1,193 @@
const { HandlebarsApplicationMixin } = foundry.applications.api
export default class LethalFantasyItemSheet extends HandlebarsApplicationMixin(foundry.applications.sheets.ItemSheetV2) {
/**
* Different sheet modes.
* @enum {number}
*/
static SHEET_MODES = { EDIT: 0, PLAY: 1 }
constructor(options = {}) {
super(options)
this.#dragDrop = this.#createDragDropHandlers()
}
#dragDrop
/** @override */
static DEFAULT_OPTIONS = {
classes: ["tenebris", "item"],
position: {
width: 600,
height: "auto",
},
form: {
submitOnChange: true,
},
window: {
resizable: true,
},
dragDrop: [{ dragSelector: "[data-drag]", dropSelector: null }],
actions: {
toggleSheet: LethalFantasyItemSheet.#onToggleSheet,
editImage: LethalFantasyItemSheet.#onEditImage,
},
}
/**
* The current sheet mode.
* @type {number}
*/
_sheetMode = this.constructor.SHEET_MODES.PLAY
/**
* Is the sheet currently in 'Play' mode?
* @type {boolean}
*/
get isPlayMode() {
return this._sheetMode === this.constructor.SHEET_MODES.PLAY
}
/**
* Is the sheet currently in 'Edit' mode?
* @type {boolean}
*/
get isEditMode() {
return this._sheetMode === this.constructor.SHEET_MODES.EDIT
}
/** @override */
async _prepareContext() {
const context = {
fields: this.document.schema.fields,
systemFields: this.document.system.schema.fields,
item: this.document,
system: this.document.system,
source: this.document.toObject(),
enrichedDescription: await TextEditor.enrichHTML(this.document.system.description, { async: true }),
isEditMode: this.isEditMode,
isPlayMode: this.isPlayMode,
isEditable: this.isEditable,
}
return context
}
/** @override */
_onRender(context, options) {
this.#dragDrop.forEach((d) => d.bind(this.element))
}
// #region Drag-and-Drop Workflow
/**
* Create drag-and-drop workflow handlers for this Application
* @returns {DragDrop[]} An array of DragDrop handlers
* @private
*/
#createDragDropHandlers() {
return this.options.dragDrop.map((d) => {
d.permissions = {
dragstart: this._canDragStart.bind(this),
drop: this._canDragDrop.bind(this),
}
d.callbacks = {
dragstart: this._onDragStart.bind(this),
dragover: this._onDragOver.bind(this),
drop: this._onDrop.bind(this),
}
return new DragDrop(d)
})
}
/**
* Define whether a user is able to begin a dragstart workflow for a given drag selector
* @param {string} selector The candidate HTML selector for dragging
* @returns {boolean} Can the current user drag this selector?
* @protected
*/
_canDragStart(selector) {
return this.isEditable
}
/**
* Define whether a user is able to conclude a drag-and-drop workflow for a given drop selector
* @param {string} selector The candidate HTML selector for the drop target
* @returns {boolean} Can the current user drop on this selector?
* @protected
*/
_canDragDrop(selector) {
return this.isEditable && this.document.isOwner
}
/**
* Callback actions which occur at the beginning of a drag start workflow.
* @param {DragEvent} event The originating DragEvent
* @protected
*/
_onDragStart(event) {
const el = event.currentTarget
if ("link" in event.target.dataset) return
// Extract the data you need
let dragData = null
if (!dragData) return
// Set data transfer
event.dataTransfer.setData("text/plain", JSON.stringify(dragData))
}
/**
* Callback actions which occur when a dragged element is over a drop target.
* @param {DragEvent} event The originating DragEvent
* @protected
*/
_onDragOver(event) {}
/**
* Callback actions which occur when a dragged element is dropped on a target.
* @param {DragEvent} event The originating DragEvent
* @protected
*/
async _onDrop(event) {}
// #endregion
// #region Actions
/**
* Handle toggling between Edit and Play mode.
* @param {Event} event The initiating click event.
* @param {HTMLElement} target The current target of the event listener.
*/
static #onToggleSheet(event, target) {
const modes = this.constructor.SHEET_MODES
this._sheetMode = this.isEditMode ? modes.PLAY : modes.EDIT
this.render()
}
/**
* Handle changing a Document's image.
*
* @this LethalFantasyCharacterSheet
* @param {PointerEvent} event The originating click event
* @param {HTMLElement} target The capturing HTML element which defined a [data-action]
* @returns {Promise}
* @private
*/
static async #onEditImage(event, target) {
const attr = target.dataset.edit
const current = foundry.utils.getProperty(this.document, attr)
const { img } = this.document.constructor.getDefaultArtwork?.(this.document.toObject()) ?? {}
const fp = new FilePicker({
current,
type: "image",
redirectToRoot: img ? [img] : [],
callback: (path) => {
this.document.update({ [attr]: path })
},
top: this.position.top + 40,
left: this.position.left + 10,
})
return fp.browse()
}
// #endregion
}

View File

@ -0,0 +1,341 @@
import LethalFantasyActorSheet from "./base-actor-sheet.mjs"
import { ROLL_TYPE } from "../../config/system.mjs"
export default class LethalFantasyCharacterSheet extends LethalFantasyActorSheet {
/** @override */
static DEFAULT_OPTIONS = {
classes: ["character"],
position: {
width: 1150,
height: 780,
},
window: {
contentClasses: ["character-content"],
},
actions: {
deleteVoieMajeure: LethalFantasyCharacterSheet.#onDeleteVoieMajeure,
deleteVoieMineure: LethalFantasyCharacterSheet.#onDeleteVoieMineure,
createEquipment: LethalFantasyCharacterSheet.#onCreateEquipment,
},
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-lethal-fantasy/templates/character-main.hbs",
},
tabs: {
template: "templates/generic/tab-navigation.hbs",
},
items: {
template: "systems/fvtt-lethal-fantasy/templates/character-items.hbs",
},
biography: {
template: "systems/fvtt-lethal-fantasy/templates/character-biography.hbs",
},
}
/** @override */
tabGroups = {
sheet: "items",
}
/**
* Prepare an array of form header tabs.
* @returns {Record<string, Partial<ApplicationTab>>}
*/
#getTabs() {
const tabs = {
items: { id: "items", group: "sheet", icon: "fa-solid fa-shapes", label: "TENEBRIS.Character.Label.details" },
biography: { id: "biography", group: "sheet", icon: "fa-solid fa-book", label: "TENEBRIS.Character.Label.biography" },
}
for (const v of Object.values(tabs)) {
v.active = this.tabGroups[v.group] === v.id
v.cssClass = v.active ? "active" : ""
}
return tabs
}
/** @override */
async _prepareContext() {
const context = await super._prepareContext()
context.tabs = this.#getTabs()
context.tooltipsCaracteristiques = {
rob: this._generateTooltip("save", "rob"),
dex: this._generateTooltip("save", "dex"),
int: this._generateTooltip("save", "int"),
per: this._generateTooltip("save", "per"),
vol: this._generateTooltip("save", "vol"),
dmax: this._generateTooltip("other", "dmax"),
}
context.tooltipsRessources = {
san: this._generateTooltip("resource", "san"),
oeil: this._generateTooltip("resource", "oeil"),
verbe: this._generateTooltip("resource", "verbe"),
bourse: this._generateTooltip("resource", "bourse"),
magie: this._generateTooltip("resource", "magie"),
}
context.rollType = {
saveRob: {
action: "roll",
rollType: "save",
rollTarget: "rob",
tooltip: this._generateTooltip("save", "rob"),
},
saveDex: {
action: "roll",
rollType: "save",
rollTarget: "dex",
tooltip: this._generateTooltip("save", "dex"),
},
saveInt: {
action: "roll",
rollType: "save",
rollTarget: "int",
tooltip: this._generateTooltip("save", "int"),
},
savePer: {
action: "roll",
rollType: "save",
rollTarget: "per",
tooltip: this._generateTooltip("save", "per"),
drag: true,
},
saveVol: {
action: "roll",
rollType: "save",
rollTarget: "vol",
tooltip: this._generateTooltip("save", "vol"),
drag: true,
},
resourceSan: {
action: "roll",
rollType: "resource",
rollTarget: "san",
tooltip: this._generateTooltip("resource", "san"),
drag: true,
},
resourceOeil: {
action: "roll",
rollType: "resource",
rollTarget: "oeil",
tooltip: this._generateTooltip("resource", "oeil"),
drag: true,
},
resourceVerbe: {
action: "roll",
rollType: "resource",
rollTarget: "verbe",
tooltip: this._generateTooltip("resource", "verbe"),
drag: true,
},
resourceBourse: {
action: "roll",
rollType: "resource",
rollTarget: "bourse",
tooltip: this._generateTooltip("resource", "bourse"),
drag: true,
},
resourceMagie: {
action: "roll",
rollType: "resource",
rollTarget: "magie",
tooltip: this._generateTooltip("resource", "magie"),
drag: true,
},
}
return context
}
_generateTooltip(type, target) {
if (type === ROLL_TYPE.SAVE) {
const progres = this.document.system.caracteristiques[target].progression.progres
? game.i18n.localize("TENEBRIS.Label.hasProgressed")
: game.i18n.localize("TENEBRIS.Label.noProgress")
return `${game.i18n.localize("TENEBRIS.Label.experience")} : ${this.document.system.caracteristiques[target].progression.experience} <br> ${progres}`
} else if (type === ROLL_TYPE.RESOURCE) {
return `${game.i18n.localize("TENEBRIS.Label.maximum")} : ${this.document.system.ressources[target].max} <br> ${game.i18n.localize("TENEBRIS.Label.experience")} : ${this.document.system.ressources[target].experience}`
} else if (type === "other") {
return `${game.i18n.localize("TENEBRIS.Label.experience")} : ${this.document.system.dmax.experience}`
}
}
/** @override */
async _preparePartContext(partId, context) {
const doc = this.document
switch (partId) {
case "main":
context.enrichedBiens = await TextEditor.enrichHTML(doc.system.biens, { async: true })
break
case "items":
context.tab = context.tabs.items
const talents = await this._prepareTalents()
context.talents = talents
context.talentsAppris = talents.filter((talent) => talent.appris)
context.weapons = doc.itemTypes.weapon
context.armors = doc.itemTypes.armor
context.spells = doc.itemTypes.spell
context.hasSpells = context.spells.length > 0
break
case "biography":
context.tab = context.tabs.biography
context.enrichedDescription = await TextEditor.enrichHTML(doc.system.description, { async: true })
context.enrichedLangues = await TextEditor.enrichHTML(doc.system.langues, { async: true })
context.enrichedNotes = await TextEditor.enrichHTML(doc.system.notes, { async: true })
break
}
return context
}
/**
* Prepares the talents for the character sheet.
*
* @returns {Array} An array of talents with their properties.
*/
async _prepareTalents() {
const talents = await Promise.all(
this.document.itemTypes.talent.map(async (talent) => {
const pathName = await talent.system.getPathName()
return {
id: talent.id,
uuid: talent.uuid,
name: talent.name,
img: talent.img,
path: `Obtenu par ${pathName}`,
description: talent.system.improvedDescription,
progression: talent.system.progression,
niveau: talent.system.niveau,
appris: talent.system.appris,
details: talent.system.details,
}
}),
)
talents.sort((a, b) => b.appris - a.appris || a.name.localeCompare(b.name, game.i18n.lang))
return talents
}
// #region Drag-and-Drop Workflow
/**
* Callback actions which occur when a dragged element is dropped on a target.
* @param {DragEvent} event The originating DragEvent
* @protected
*/
async _onDrop(event) {
if (!this.isEditable || !this.isEditMode) return
const data = TextEditor.getDragEventData(event)
// Handle different data types
switch (data.type) {
case "Item":
const item = await fromUuid(data.uuid)
if (!["path", "weapon", "armor", "spell"].includes(item.type)) return
if (item.type === "path") return this.#onDropPathItem(item)
if (item.type === "weapon") return super._onDropItem(item)
if (item.type === "armor") return this._onDropItem(item)
if (item.type === "spell") return this._onDropItem(item)
}
}
async #onDropPathItem(item) {
await this.document.addPath(item)
}
// #endregion
// #region Actions
/**
* Suppression de la voie majeure
* @param {Event} event The initiating click event.
* @param {HTMLElement} target The current target of the event listener.
*/
static async #onDeleteVoieMajeure(event, target) {
const proceed = await foundry.applications.api.DialogV2.confirm({
content: game.i18n.localize("TENEBRIS.Dialog.suppressionTalents"),
rejectClose: false,
modal: true,
})
if (!proceed) return
const path = this.document.items.get(this.document.system.voies.majeure.id)
if (!path) return
await this.document.deletePath(path, true)
}
/**
* Suppression de la voie mineure
* @param {Event} event The initiating click event.
* @param {HTMLElement} target The current target of the event listener.
*/
static async #onDeleteVoieMineure(event, target) {
const proceed = await foundry.applications.api.DialogV2.confirm({
content: game.i18n.localize("TENEBRIS.Dialog.suppressionTalents"),
rejectClose: false,
modal: true,
})
if (!proceed) return
const path = this.document.items.get(this.document.system.voies.mineure.id)
if (!path) return
await this.document.deletePath(path, false)
}
/**
* Creates a new attack item directly from the sheet and embeds it into the document.
* @param {Event} event The initiating click event.
* @param {HTMLElement} target The current target of the event listener.
*/
static #onCreateEquipment(event, target) {
// Création d'une armure
if (event.shiftKey) {
this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("TENEBRIS.Label.newArmor"), type: "armor" }])
}
// Création d'une arme
else {
this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("TENEBRIS.Label.newWeapon"), type: "weapon" }])
}
}
/**
* Handles the roll action triggered by user interaction.
*
* @param {PointerEvent} event The event object representing the user interaction.
* @param {HTMLElement} target The target element that triggered the roll.
*
* @returns {Promise<void>} A promise that resolves when the roll action is complete.
*
* @throws {Error} Throws an error if the roll type is not recognized.
*
* @description This method checks the current mode (edit or not) and determines the type of roll
* (save, resource, or damage) based on the target element's data attributes. It retrieves the
* corresponding value from the document's system and performs the roll.
*/
async _onRoll(event, target) {
if (this.isEditMode) return
// Jet de sauvegarde
let elt = event.currentTarget.querySelector("input")
// Jet de ressource
if (!elt) elt = event.currentTarget.querySelector("select")
// Jet de dégâts
if (!elt) elt = event.currentTarget
const rollType = elt.dataset.rollType
let rollTarget
switch (rollType) {
case ROLL_TYPE.SAVE:
rollTarget = elt.dataset.rollTarget
break
case ROLL_TYPE.RESOURCE:
rollTarget = elt.dataset.rollTarget
break
case ROLL_TYPE.DAMAGE:
rollTarget = elt.dataset.itemId
break
default:
break
}
await this.document.system.roll(rollType, rollTarget)
}
// #endregion
}

View File

@ -0,0 +1,89 @@
import LethalFantasyActorSheet from "./base-actor-sheet.mjs"
export default class LethalFantasyOpponentSheet extends LethalFantasyActorSheet {
/** @override */
static DEFAULT_OPTIONS = {
classes: ["opponent"],
position: {
width: 800,
height: 700,
},
window: {
contentClasses: ["opponent-content"],
},
actions: {
createAttack: LethalFantasyOpponentSheet.#onCreateAttack,
},
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-lethal-fantasy/templates/opponent.hbs",
},
}
/** @override */
async _prepareContext() {
const context = await super._prepareContext()
context.attacks = context.actor.itemTypes.attack
context.spells = context.actor.itemTypes.spell
context.hasSpells = context.spells.length > 0
return context
}
/**
* Callback actions which occur when a dragged element is dropped on a target.
* @param {DragEvent} event The originating DragEvent
* @protected
*/
async _onDrop(event) {
if (!this.isEditable || !this.isEditMode) return
const data = TextEditor.getDragEventData(event)
// Handle different data types
switch (data.type) {
case "Item":
const item = await fromUuid(data.uuid)
if (item.type === "attack") return this.#onDropAttackItem(item)
if (item.type === "spell") return this._onDropItem(item)
}
}
/**
* Handles the drop event of an attack item.
*
* @param {Object} item The attack item being dropped.
* @returns {Promise<void>} A promise that resolves when the attack item has been added to the document.
* @private
*/
async #onDropAttackItem(item) {
await this.document.addAttack(item)
}
/**
* Handles the creation of a new attack item.
*
* @param {Event} event The event that triggered the creation of the attack.
* @param {Object} target The target object where the attack will be created.
* @private
* @static
*/
static #onCreateAttack(event, target) {
const item = this.document.createEmbeddedDocuments("Item", [{ name: "Nouvelle attaque", type: "attack" }])
}
/**
* Roll a damage roll.
* @param {PointerEvent} event The originating click event
* @param {HTMLElement} target the capturing HTML element which defined a [data-action]
*/
async _onRoll(event, target) {
if (this.isEditMode) return
const elt = event.currentTarget
const rollValue = elt.dataset.rollValue
const rollTarget = elt.dataset.itemName
await this.document.system.roll(rollValue, rollTarget)
}
}

View File

@ -0,0 +1,141 @@
import LethalFantasyItemSheet from "./base-item-sheet.mjs"
export default class LethalFantasyPathSheet extends LethalFantasyItemSheet {
/** @override */
static DEFAULT_OPTIONS = {
classes: ["path"],
position: {
width: 1400,
},
window: {
contentClasses: ["path-content"],
},
dragDrop: [{ dragSelector: "[data-drag]", dropSelector: null }],
actions: {
edit: LethalFantasyPathSheet.#onTalentEdit,
delete: LethalFantasyPathSheet.#onTalentDelete,
},
}
/** @override */
static PARTS = {
header: {
template: "systems/fvtt-lethal-fantasy/templates/path-header.hbs",
},
tabs: {
template: "templates/generic/tab-navigation.hbs",
},
main: {
template: "systems/fvtt-lethal-fantasy/templates/path-main.hbs",
},
talents: {
template: "systems/fvtt-lethal-fantasy/templates/path-talents.hbs",
},
}
/** @override */
tabGroups = {
sheet: "main",
}
/**
* Prepare an array of form header tabs.
* @returns {Record<string, Partial<ApplicationTab>>}
*/
#getTabs() {
const tabs = {
main: { id: "main", group: "sheet", icon: "fa-solid fa-user", label: "TENEBRIS.Label.profil" },
talents: { id: "talents", group: "sheet", icon: "fa-solid fa-book", label: "TENEBRIS.Label.talents" },
}
for (const v of Object.values(tabs)) {
v.active = this.tabGroups[v.group] === v.id
v.cssClass = v.active ? "active" : ""
}
return tabs
}
/** @override */
async _prepareContext() {
const context = await super._prepareContext()
context.tabs = this.#getTabs()
return context
}
/** @override */
async _preparePartContext(partId, context) {
const doc = this.document
switch (partId) {
case "main":
context.tab = context.tabs.main
context.enrichedBiens = await TextEditor.enrichHTML(this.document.system.biens, { async: true })
context.enrichedLangues = await TextEditor.enrichHTML(this.document.system.langues, { async: true })
break
case "talents":
context.tab = context.tabs.talents
const talentItems = []
for (const talent of this.item.system.talents) {
const talentItem = await fromUuid(talent)
if (talentItem) talentItems.push(talentItem)
}
context.talents = talentItems
context.talents.sort((a, b) => a.name.localeCompare(b.name, game.i18n.lang))
break
}
return context
}
/**
* Callback actions which occur when a dragged element is dropped on a target.
* Seul un item de type Talent peut être déposé sur une voie.
* @param {DragEvent} event The originating DragEvent
* @protected
*/
async _onDrop(event) {
const data = TextEditor.getDragEventData(event)
switch (data.type) {
case "Item":
if (this.isPlayMode) return
const item = await fromUuid(data.uuid)
if (item.type !== "talent") return
console.debug("dropped item", item)
const talents = this.item.toObject().system.talents
talents.push(item.uuid)
this.item.update({ "system.talents": talents })
}
}
// #region Actions
/**
* Edit an existing talent within the path item
* Use the uuid to display the talent sheet (from world or compendium)
* @param {PointerEvent} event The originating click event
* @param {HTMLElement} target the capturing HTML element which defined a [data-action]
*/
static async #onTalentEdit(event, target) {
const itemUuid = target.getAttribute("data-item-uuid")
const talent = await fromUuid(itemUuid)
talent.sheet.render(true)
}
/**
* Delete an existing talent within the path item
* Use the uuid to remove it form the array of talents
* @param {PointerEvent} event The originating click event
* @param {HTMLElement} target the capturing HTML element which defined a [data-action]
*/
static async #onTalentDelete(event, target) {
const itemUuid = target.getAttribute("data-item-uuid")
const talents = this.item.toObject().system.talents
const index = talents.indexOf(itemUuid)
talents.splice(index, 1)
this.item.update({ "system.talents": talents })
}
// #endregion
}

View File

@ -0,0 +1,21 @@
import LethalFantasyItemSheet from "./base-item-sheet.mjs"
export default class LethalFantasySpellSheet extends LethalFantasyItemSheet {
/** @override */
static DEFAULT_OPTIONS = {
classes: ["spell"],
position: {
width: 450,
},
window: {
contentClasses: ["spell-content"],
},
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-lethal-fantasy/templates/spell.hbs",
},
}
}

View File

@ -0,0 +1,29 @@
import LethalFantasyItemSheet from "./base-item-sheet.mjs"
export default class LethalFantasyTalentSheet extends LethalFantasyItemSheet {
/** @override */
static DEFAULT_OPTIONS = {
classes: ["talent"],
position: {
width: 600,
},
window: {
contentClasses: ["talent-content"],
},
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-lethal-fantasy/templates/talent.hbs",
},
}
/** @override */
async _prepareContext() {
const context = await super._prepareContext()
context.enrichedDescription = await TextEditor.enrichHTML(this.document.system.improvedDescription, { async: true })
context.canProgress = this.document.system.canProgress
return context
}
}

View File

@ -0,0 +1,21 @@
import LethalFantasyItemSheet from "./base-item-sheet.mjs"
export default class LethalFantasyWeaponSheet extends LethalFantasyItemSheet {
/** @override */
static DEFAULT_OPTIONS = {
classes: ["weapon"],
position: {
width: 400,
},
window: {
contentClasses: ["weapon-content"],
},
}
/** @override */
static PARTS = {
main: {
template: "systems/fvtt-lethal-fantasy/templates/weapon.hbs",
},
}
}

5
module/config/armor.mjs Normal file
View File

@ -0,0 +1,5 @@
export const CATEGORY = Object.freeze({
sommaire: { id: "sommaire", label: "LETHALFANTASY.Armor.Category.sommaire" },
legere: { id: "legere", label: "LETHALFANTASY.Armor.Category.legere" },
guerre: { id: "guerre", label: "LETHALFANTASY.Armor.Category.guerre" },
})

View File

@ -0,0 +1,50 @@
export const CHARACTERISTICS = Object.freeze({
rob: {
id: "rob",
label: "LETHALFANTASY.Character.rob.label",
abbreviation: "LETHALFANTASY.Character.rob.short",
},
dex: {
id: "dex",
label: "LETHALFANTASY.Character.dex.label",
abbreviation: "LETHALFANTASY.Character.dex.short",
},
int: {
id: "int",
label: "LETHALFANTASY.Character.int.label",
abbreviation: "LETHALFANTASY.Character.int.short",
},
per: {
id: "per",
label: "LETHALFANTASY.Character.per.label",
abbreviation: "LETHALFANTASY.Character.per.short",
},
vol: {
id: "vol",
label: "LETHALFANTASY.Character.vol.label",
abbreviation: "LETHALFANTASY.Character.vol.short",
},
})
export const RESOURCES = Object.freeze({
san: {
id: "san",
label: "LETHALFANTASY.Character.san.label",
},
oeil: {
id: "oeil",
label: "LETHALFANTASY.Character.oeil.label",
},
verbe: {
id: "verbe",
label: "LETHALFANTASY.Character.verbe.label",
},
bourse: {
id: "bourse",
label: "LETHALFANTASY.Character.bourse.label",
},
magie: {
id: "magie",
label: "LETHALFANTASY.Character.magie.label",
},
})

22
module/config/spell.mjs Normal file
View File

@ -0,0 +1,22 @@
export const RANGE = Object.freeze({
na: {
id: "na",
label: "LETHALFANTASY.Spell.Range.na",
},
contact: {
id: "contact",
label: "LETHALFANTASY.Spell.Range.contact",
},
proche: {
id: "proche",
label: "LETHALFANTASY.Spell.Range.proche",
},
loin: {
id: "loin",
label: "LETHALFANTASY.Spell.Range.loin",
},
distant: {
id: "distant",
label: "LETHALFANTASY.Spell.Range.distant",
},
})

102
module/config/system.mjs Normal file
View File

@ -0,0 +1,102 @@
import * as CHARACTER from "./character.mjs"
import * as WEAPON from "./weapon.mjs"
import * as ARMOR from "./armor.mjs"
import * as SPELL from "./spell.mjs"
export const SYSTEM_ID = "tenebris"
export const DEV_MODE = false
export const RESOURCE_VALUE = Object.freeze({
ZERO: "0",
D4: "d4",
D6: "d6",
D8: "d8",
D10: "d10",
D12: "d12",
})
export const DICE_VALUE = Object.freeze({
D4: "d4",
D6: "d6",
D8: "d8",
D10: "d10",
D12: "d12",
})
export const DICE_VALUES = ["0", "d4", "d6", "d8", "d10", "d12"]
export const ROLL_TYPE = Object.freeze({
SAVE: "save",
RESOURCE: "resource",
DAMAGE: "damage",
ATTACK: "attack",
})
export const MINOR_PATH = Object.freeze({
epee: {
onze: "rob",
neuf: {
main: "per",
plume: "vol",
livre: "int",
},
},
main: {
onze: "dex",
neuf: {
chene: "rob",
plume: "vol",
livre: "int",
},
},
plume: {
onze: "int",
neuf: {
chene: "rob",
main: "per",
epee: "dex",
},
},
chene: {
onze: "per",
neuf: {
plume: "vol",
livre: "int",
epee: "dex",
},
},
livre: {
onze: "vol",
neuf: {
chene: "rob",
main: "per",
epee: "dex",
},
},
})
export const ASCII = `
██████ ████████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████████ ███████ ███ ██ ███████ ██████ ██████ ██ ███████
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ███████ ██ ██ ██ ███████ ██ ██ ██ █████ ██ ██ ██ █████ ██████ ██████ ██ ███████
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██████ ██ ██ ██ ██████ ███████ ██ ██ ██████ ██ ███████ ██ ████ ███████ ██████ ██ ██ ██ ███████ `
/**
* Include all constant definitions within the SYSTEM global export
* @type {Object}
*/
export const SYSTEM = {
id: SYSTEM_ID,
CHARACTERISTICS: CHARACTER.CHARACTERISTICS,
RESOURCES: CHARACTER.RESOURCES,
RESOURCE_VALUE,
WEAPON_CATEGORY: WEAPON.CATEGORY,
WEAPON_DAMAGE: WEAPON.DAMAGE,
ARMOR_CATEGORY: ARMOR.CATEGORY,
SPELL_RANGE: SPELL.RANGE,
ASCII,
MINOR_PATH,
ROLL_TYPE,
DEV_MODE,
}

30
module/config/weapon.mjs Normal file
View File

@ -0,0 +1,30 @@
export const CATEGORY = Object.freeze({
mains: {
id: "mains",
label: "LETHALFANTASY.Weapon.Category.main",
},
improvisee: {
id: "improvisee",
label: "LETHALFANTASY.Weapon.Category.improvisee",
},
courte: {
id: "courte",
label: "LETHALFANTASY.Weapon.Category.courte",
},
longue: {
id: "longue",
label: "LETHALFANTASY.Weapon.Category.longue",
},
lourde: {
id: "lourde",
label: "LETHALFANTASY.Weapon.Category.lourde",
},
})
export const DAMAGE = Object.freeze({
UN: "1",
D4: "d4",
D6: "d6",
D8: "d8",
D10: "d10",
})

View File

@ -0,0 +1,44 @@
/**
* Menu spécifique au système
*/
export function initControlButtons() {
CONFIG.Canvas.layers.tenebris = { layerClass: ControlsLayer, group: "primary" }
Hooks.on("getSceneControlButtons", (btns) => {
let menu = []
menu.push({
name: "fortune",
title: game.i18n.localize("TENEBRIS.Fortune.title"),
icon: "fa-solid fa-clover",
button: true,
onClick: () => {
if (!foundry.applications.instances.has("tenebris-application-fortune")) {
game.system.applicationFortune.render(true)
} else game.system.applicationFortune.close()
},
})
if (game.user.isGM) {
menu.push({
name: "gm-manager",
title: game.i18n.localize("TENEBRIS.Manager.title"),
icon: "fa-solid fa-users",
button: true,
onClick: () => {
if (!foundry.applications.instances.has("tenebris-application-manager")) {
game.system.applicationManager.render(true)
} else game.system.applicationManager.close()
},
})
}
btns.push({
name: "tenebris",
title: "Cthulhu LethalFantasy",
icon: "tenebris",
layer: "tenebris",
tools: menu,
})
})
}

View File

@ -0,0 +1,4 @@
export { default as LethalFantasyActor } from "./actor.mjs"
export { default as LethalFantasyItem } from "./item.mjs"
export { default as LethalFantasyRoll } from "./roll.mjs"
export { default as LethalFantasyChatMessage } from "./chat-message.mjs"

220
module/documents/actor.mjs Normal file
View File

@ -0,0 +1,220 @@
import { ROLL_TYPE } from "../config/system.mjs"
export default class LethalFantasyActor extends Actor {
async _preCreate(data, options, user) {
await super._preCreate(data, options, user)
// Configure prototype token settings
const prototypeToken = {}
if (this.type === "character") {
Object.assign(prototypeToken, {
sight: { enabled: true },
actorLink: true,
disposition: CONST.TOKEN_DISPOSITIONS.FRIENDLY,
})
this.updateSource({ prototypeToken })
}
}
/**
* Adds a path to the character.
* First path added is the major path, second path added is the minor path.
* Create all talents of the path and add them to the character.
* Add the path to the character.
*
* @param {Object} item The item to add as a path.
* @returns {Promise<void>} - A promise that resolves when the path is added.
*/
async addPath(item) {
if (this.type !== "character") return
let itemData = item.toObject()
if (this.system.hasVoieMajeure && this.system.hasVoieMineure) {
ui.notifications.warn(game.i18n.localize("TENEBRIS.Warning.dejaDeuxVoies"))
return
}
// Voie mineure
if (this.system.hasVoieMajeure) {
if (this.system.voies.majeure.nom === item.name) {
ui.notifications.warn(game.i18n.localize("TENEBRIS.Warning.dejaVoieMajeure"))
return
}
// Voie de base
const isBasePath = itemData.system.key !== "" && this.system.voies.majeure.key !== ""
let dropNotification
let neufModifie
let onze
let neuf
if (isBasePath) {
onze = game.system.CONST.MINOR_PATH[itemData.system.key].onze
const labelOnze = game.i18n.localize(`TENEBRIS.Character.FIELDS.caracteristiques.${onze}.valeur.label`)
dropNotification = `La valeur de ${labelOnze} va être modifiée pour 11`
neuf = game.system.CONST.MINOR_PATH[itemData.system.key].neuf[this.system.voies.majeure.key]
if (neuf) {
neufModifie = true
const labelNeuf = game.i18n.localize(`TENEBRIS.Character.FIELDS.caracteristiques.${neuf}.valeur.label`)
dropNotification += `<br> La valeur de ${labelNeuf} va être modifiée pour 9`
}
} else {
dropNotification = "Vous devez modifier manuellement les caractéristiques selon la voie ajoutée"
}
dropNotification += `<br>Vous pouvez renoncer à des biens de la voie majeure pour ceux de la voie mineure`
dropNotification += `<br> Vous pouvez renoncer à des langues de la voie majeure pour celles de la voie mineure`
const proceed = await foundry.applications.api.DialogV2.confirm({
window: { title: game.i18n.localize("TENEBRIS.Dialog.ajoutVoieMineureTitre") },
content: dropNotification,
rejectClose: false,
modal: true,
})
if (!proceed) return
let voie
// Création de la voie
voie = await this.createEmbeddedDocuments("Item", [itemData], { renderSheet: false })
if (isBasePath) {
await this.update({
"system.voies.mineure.nom": item.name,
"system.voies.mineure.id": voie[0].id,
"system.voies.mineure.key": item.system.key,
[`system.caracteristiques.${onze}.valeur`]: 11,
"system.langues": `${this.system.langues} <br>${item.name} : ${item.system.langues}`,
"system.biens": `${this.system.biens} <br>${item.name} : ${item.system.biens}`,
})
if (neufModifie) {
await this.update({
[`system.caracteristiques.${neuf}.valeur`]: 9,
})
}
} else {
await this.update({
"system.voies.mineure.nom": item.name,
"system.voies.mineure.id": voie[0].id,
"system.voies.mineure.key": item.system.key,
"system.langues": `${this.system.langues} <br>${item.name} : ${item.system.langues}`,
"system.biens": `${this.system.biens} <br>${item.name} : ${item.system.biens}`,
})
}
// Création des talents
let newTalents = []
for (const talent of itemData.system.talents) {
const talentItem = await fromUuid(talent)
if (talentItem) {
const newTalent = await this.createEmbeddedDocuments("Item", [talentItem.toObject()])
// Modification de la voie du talent
await newTalent[0].update({ "system.path": voie[0].uuid })
newTalents.push(newTalent[0].uuid)
}
}
// Mise à jour de la voie avec les nouveaux talents
await voie[0].update({ "system.talents": newTalents })
return ui.notifications.info(game.i18n.localize("TENEBRIS.Warning.voieMineureAjoutee"))
}
// Voie majeure
else {
const proceed = await foundry.applications.api.DialogV2.confirm({
window: { title: game.i18n.localize("TENEBRIS.Dialog.ajoutVoieMajeureTitre") },
content: game.i18n.localize("TENEBRIS.Dialog.ajoutVoieMajeure"),
rejectClose: false,
modal: true,
})
if (!proceed) return
// Création de la voie
const voie = await this.createEmbeddedDocuments("Item", [itemData], { renderSheet: false })
// Création des talents
let newTalents = []
for (const talent of itemData.system.talents) {
const talentItem = await fromUuid(talent)
if (talentItem) {
const newTalent = await this.createEmbeddedDocuments("Item", [talentItem.toObject()])
// Modification de la voie du talent
await newTalent[0].update({ "system.path": voie[0].uuid })
newTalents.push(newTalent[0].uuid)
}
}
// Mise à jour de la voie avec les nouveaux talents
await voie[0].update({ "system.talents": newTalents })
await this.update({
"system.voies.majeure.id": voie[0].id,
"system.voies.majeure.nom": item.name,
"system.voies.majeure.key": item.system.key,
"system.caracteristiques.rob": item.system.caracteristiques.rob,
"system.caracteristiques.dex": item.system.caracteristiques.dex,
"system.caracteristiques.int": item.system.caracteristiques.int,
"system.caracteristiques.per": item.system.caracteristiques.per,
"system.caracteristiques.vol": item.system.caracteristiques.vol,
"system.ressources.san": item.system.ressources.san,
"system.ressources.oeil": item.system.ressources.oeil,
"system.ressources.verbe": item.system.ressources.verbe,
"system.ressources.bourse": item.system.ressources.bourse,
"system.ressources.magie": item.system.ressources.magie,
"system.dv": item.system.dv,
"system.dmax.valeur": item.system.dmax,
"system.langues": `${item.name} : ${item.system.langues}`,
"system.biens": `${item.name} : ${item.system.biens}`,
})
return ui.notifications.info(game.i18n.localize("TENEBRIS.Warning.voieMajeureAjoutee"))
}
}
/**
* Deletes a specified path and its associated talents.
*
* @param {Object} path The path object to be deleted.
* @param {boolean} isMajor Indicates if the path is a major path, elswise it is a minor path.
* @returns {Promise<void>} A promise that resolves when the deletion is complete.
* @throws {Error} Throws an error if the type is not "character".
*/
async deletePath(path, isMajor) {
if (this.type !== "character") return
// Delete all talents linked to the path
let toDelete = path.system.talents.map((talent) => foundry.utils.parseUuid(talent).id)
toDelete.push(path.id)
await this.deleteEmbeddedDocuments("Item", toDelete)
// Voie majeure
if (isMajor) {
await this.update({ "system.voies.majeure.nom": "", "system.voies.majeure.id": null, "system.voies.majeure.key": "" })
ui.notifications.info(game.i18n.localize("TENEBRIS.Warning.voieMajeureSupprimee"))
}
// Voie mineure
else {
await this.update({ "system.voies.mineure.nom": "", "system.voies.mineure.id": null, "system.voies.mineure.key": "" })
ui.notifications.info(game.i18n.localize("TENEBRIS.Warning.voieMineureSupprimee"))
}
}
/**
* Adds an attack to the actor if the actor type is "opponent".
*
* @param {Object} attack The attack object to be added.
* @returns {Promise<void>} A promise that resolves when the attack has been added.
*/
async addAttack(attack) {
if (this.type !== "opponent") return
await this.createEmbeddedDocuments("Item", [attack])
}
async rollResource(resource) {
if (this.type !== "character") return
await this.system.roll(ROLL_TYPE.RESOURCE, resource)
}
async rollSave(save, avantage) {
if (this.type !== "character") return
await this.system.roll(ROLL_TYPE.SAVE, save, avantage)
}
}

View File

@ -0,0 +1,21 @@
import LethalFantasyRoll from "./roll.mjs"
export default class LethalFantasyChatMessage extends ChatMessage {
async _renderRollContent(messageData) {
const data = messageData.message
if (this.rolls[0] instanceof LethalFantasyRoll) {
const isPrivate = !this.isContentVisible
// _renderRollHTML va appeler render sur tous les rolls
const rollHTML = await this._renderRollHTML(isPrivate)
if (isPrivate) {
data.flavor = game.i18n.format("CHAT.PrivateRollContent", { user: this.user.name })
messageData.isWhisper = false
messageData.alias = this.user.name
}
data.content = `<section class="dice-rolls">${rollHTML}</section>`
return
}
return super._renderRollContent(messageData)
}
}

View File

@ -0,0 +1 @@
export default class LethalFantasyItem extends Item {}

592
module/documents/roll.mjs Normal file
View File

@ -0,0 +1,592 @@
import { ROLL_TYPE } from "../config/system.mjs"
import LethalFantasyUtils from "../utils.mjs"
export default class LethalFantasyRoll extends Roll {
/**
* The HTML template path used to render dice checks of this type
* @type {string}
*/
static CHAT_TEMPLATE = "systems/fvtt-lethal-fantasy/templates/chat-message.hbs"
get type() {
return this.options.type
}
get isSave() {
return this.type === ROLL_TYPE.SAVE
}
get isResource() {
return this.type === ROLL_TYPE.RESOURCE
}
get isDamage() {
return this.type === ROLL_TYPE.DAMAGE
}
get target() {
return this.options.target
}
get value() {
return this.options.value
}
get treshold() {
return this.options.treshold
}
get actorId() {
return this.options.actorId
}
get actorName() {
return this.options.actorName
}
get actorImage() {
return this.options.actorImage
}
get introText() {
return this.options.introText
}
get introTextTooltip() {
return this.options.introTextTooltip
}
get aide() {
return this.options.aide
}
get gene() {
return this.options.gene
}
get modificateur() {
return this.options.modificateur
}
get avantages() {
return this.options.avantages
}
get resultType() {
return this.options.resultType
}
get isFailure() {
return this.resultType === "failure"
}
get hasTarget() {
return this.options.hasTarget
}
get targetName() {
return this.options.targetName
}
get targetArmor() {
return this.options.targetArmor
}
get targetMalus() {
return this.options.targetMalus
}
get realDamage() {
return this.options.realDamage
}
get rollAdvantage() {
return this.options.rollAdvantage
}
/**
* Generates introductory text based on the roll type.
*
* @returns {string} The formatted introductory text for the roll.
*/
_createIntroText() {
let text
switch (this.type) {
case ROLL_TYPE.SAVE:
const saveLabel = game.i18n.localize(`TENEBRIS.Character.FIELDS.caracteristiques.${this.target}.valeur.label`)
text = game.i18n.format("TENEBRIS.Roll.save", { save: saveLabel })
text = text.concat("<br>").concat(`Seuil : ${this.treshold}`)
break
case ROLL_TYPE.RESOURCE:
const resourceLabel = game.i18n.localize(`TENEBRIS.Character.FIELDS.ressources.${this.target}.valeur.label`)
text = game.i18n.format("TENEBRIS.Roll.resource", { resource: resourceLabel })
break
case ROLL_TYPE.DAMAGE:
const damageLabel = this.target
text = game.i18n.format("TENEBRIS.Roll.damage", { item: damageLabel })
break
case ROLL_TYPE.ATTACK:
const attackLabel = this.target
text = game.i18n.format("TENEBRIS.Roll.attack", { item: attackLabel })
break
}
return text
}
/**
* Generates an introductory text tooltip with characteristics and modifiers.
*
* @returns {string} A formatted string containing the value, help, hindrance, and modifier.
*/
_createIntroTextTooltip() {
let tooltip = game.i18n.format("TENEBRIS.Tooltip.saveIntroTextTooltip", { value: this.value, aide: this.aide, gene: this.gene, modificateur: this.modificateur })
if (this.hasTarget) {
tooltip = tooltip.concat(`<br>Cible : ${this.targetName}`)
}
return tooltip
}
/**
* Prompt the user with a dialog to configure and execute a roll.
*
* @param {Object} options Configuration options for the roll.
* @param {string} options.rollType The type of roll being performed (e.g., RESOURCE, DAMAGE, ATTACK, SAVE).
* @param {string} options.rollValue The initial value or formula for the roll.
* @param {string} options.rollTarget The target of the roll.
* @param {"="|"+"|"++"|"-"|"--"} options.rollAdvantage If there is an avantage (+), a disadvantage (-), a double advantage (++), a double disadvantage (--) or a normal roll (=).
* @param {string} options.actorId The ID of the actor performing the roll.
* @param {string} options.actorName The name of the actor performing the roll.
* @param {string} options.actorImage The image of the actor performing the roll.
* @param {boolean} options.hasTarget Whether the roll has a target.
* @param {Object} options.target The target of the roll, if any.
* @param {Object} options.data Additional data for the roll.
*
* @returns {Promise<Object|null>} The roll result or null if the dialog was cancelled.
*/
static async prompt(options = {}) {
let formula = options.rollValue
// Formula for a resource roll
if (options.rollType === ROLL_TYPE.RESOURCE) {
let ressource = game.i18n.localize(`TENEBRIS.Character.FIELDS.ressources.${options.rollTarget}.valeur.label`)
if (formula === "0" || formula === "") {
ui.notifications.warn(game.i18n.format("TENEBRIS.Warning.plusDeRessource", { ressource: ressource }))
return null
}
}
const rollModes = Object.fromEntries(Object.entries(CONFIG.Dice.rollModes).map(([key, value]) => [key, game.i18n.localize(value)]))
const fieldRollMode = new foundry.data.fields.StringField({
choices: rollModes,
blank: false,
default: "public",
})
const choiceAide = foundry.utils.mergeObject({ 0: "0" }, options.rollValue <= 10 ? { 1: "1" } : { 1: "1", 2: "2" })
const choiceGene = {
0: "0",
"-1": "-1",
"-2": "-2",
"-3": "-3",
"-4": "-4",
"-5": "-5",
"-6": "-6",
"-7": "-7",
"-8": "-8",
"-9": "-9",
"-10": "-10",
}
const choiceAvantage = { normal: "Normal", avantage: "Avantage", desavantage: "Désavantage", doubleAvantage: "Double avantage", doubleDesavantage: "Double désavantage" }
const choiceModificateur = {
0: "0",
"-1": "-1",
"-2": "-2",
"-3": "-3",
"-4": "-4",
"-5": "-5",
"-6": "-6",
"-7": "-7",
"-8": "-8",
"-9": "-9",
"-10": "-10",
}
let damageDice
let damageDiceMax
let damageDiceFinal
let damageDiceLowered
// Damage roll : check the roll is not above the maximum damage
if (options.rollType === ROLL_TYPE.DAMAGE) {
damageDice = options.rollValue
damageDiceMax = game.actors.get(options.actorId).system.dmax.valeur
damageDiceFinal = LethalFantasyUtils.maxDamage(damageDice, damageDiceMax)
damageDiceLowered = damageDiceFinal !== damageDice
// Récupération du nom de l'objet si c'est un jet depuis la fiche de l'acteur
// Si c'est via une macro le nom est connu
options.rollTarget = game.actors.get(options.actorId).items.get(options.rollTarget).name
}
if (options.rollType === ROLL_TYPE.ATTACK) {
damageDice = options.rollValue
}
let malus = "0"
let targetMalus = "0"
let targetName
let targetArmor
const displayOpponentMalus = game.settings.get("tenebris", "displayOpponentMalus")
if (options.rollType === ROLL_TYPE.SAVE && options.hasTarget && options.target.document.actor.type === "opponent") {
targetName = options.target.document.actor.name
if (displayOpponentMalus) malus = options.target.document.actor.system.malus.toString()
else targetMalus = options.target.document.actor.system.malus.toString()
}
if (options.rollType === ROLL_TYPE.DAMAGE && options.hasTarget && options.target.document.actor.type === "opponent") {
targetName = options.target.document.actor.name
targetArmor = options.target.document.actor.system.armure.toString()
}
let dialogContext = {
isSave: options.rollType === ROLL_TYPE.SAVE,
isResource: options.rollType === ROLL_TYPE.RESOURCE,
isDamage: options.rollType === ROLL_TYPE.DAMAGE,
isAttack: options.rollType === ROLL_TYPE.ATTACK,
rollModes,
fieldRollMode,
choiceAide,
choiceGene,
choiceAvantage,
choiceModificateur,
damageDice,
damageDiceMax,
damageDiceFinal,
damageDiceLowered,
formula,
hasTarget: options.hasTarget,
malus,
targetName,
targetArmor,
rollAdvantage: this._convertAvantages(options.rollAdvantage),
rangeAdvantage: this._convertRollAdvantageToRange(options.rollAdvantage),
}
const content = await renderTemplate("systems/fvtt-lethal-fantasy/templates/roll-dialog.hbs", dialogContext)
const title = LethalFantasyRoll.createTitle(options.rollType, options.rollTarget)
const label = game.i18n.localize("TENEBRIS.Roll.roll")
const rollContext = await foundry.applications.api.DialogV2.wait({
window: { title: title },
classes: ["tenebris"],
content,
buttons: [
{
label: label,
callback: (event, button, dialog) => {
const output = Array.from(button.form.elements).reduce((obj, input) => {
if (input.name) obj[input.name] = input.value
return obj
}, {})
// Avantages
switch (output.avantages) {
case "1":
output.avantages = "doubleDesavantage"
break
case "2":
output.avantages = "desavantage"
break
case "3":
output.avantages = "normal"
break
case "4":
output.avantages = "avantage"
break
case "5":
output.avantages = "doubleAvantage"
break
}
return output
},
},
],
rejectClose: false, // Click on Close button will not launch an error
render: (event, dialog) => {
const rangeInput = dialog.querySelector('input[name="avantages"]')
if (rangeInput) {
rangeInput.addEventListener("change", (event) => {
event.preventDefault()
event.stopPropagation()
const readOnly = dialog.querySelector('input[name="selectAvantages"]')
readOnly.value = this._convertAvantages(event.target.value)
})
}
},
})
// If the user cancels the dialog, exit
if (rollContext === null) return
let treshold
if (options.rollType === ROLL_TYPE.SAVE) {
const aide = rollContext.aide === "" ? 0 : parseInt(rollContext.aide, 10)
const gene = rollContext.gene === "" ? 0 : parseInt(rollContext.gene, 10)
const modificateur = rollContext.modificateur === "" ? 0 : parseInt(rollContext.modificateur, 10)
if (options.rollType === ROLL_TYPE.SAVE) {
let dice = "1d20"
switch (rollContext.avantages) {
case "avantage":
dice = "2d20kl"
break
case "desavantage":
dice = "2d20kh"
break
case "doubleAvantage":
dice = "3d20kl"
break
case "doubleDesavantage":
dice = "3d20kh"
break
}
formula = `${dice}`
}
treshold = options.rollValue + aide + gene + modificateur
}
// Formula for a damage roll
if (options.rollType === ROLL_TYPE.DAMAGE) {
formula = damageDiceFinal
}
// Formula for an attack roll
if (options.rollType === ROLL_TYPE.ATTACK) {
formula = damageDice
}
const rollData = {
type: options.rollType,
target: options.rollTarget,
value: options.rollValue,
treshold: treshold,
actorId: options.actorId,
actorName: options.actorName,
actorImage: options.actorImage,
rollMode: rollContext.visibility,
hasTarget: options.hasTarget,
targetName,
targetArmor,
targetMalus,
...rollContext,
}
/**
* A hook event that fires before the roll is made.
* @function tenebris.preRoll
* @memberof hookEvents
* @param {Object} options Options for the roll.
* @param {Object} rollData All data related to the roll.
* @returns {boolean} Explicitly return `false` to prevent roll to be made.
*/
if (Hooks.call("tenebris.preRoll", options, rollData) === false) return
const roll = new this(formula, options.data, rollData)
await roll.evaluate()
let resultType
if (options.rollType === ROLL_TYPE.SAVE) {
resultType = roll.total <= treshold ? "success" : "failure"
} else if (options.rollType === ROLL_TYPE.RESOURCE) {
resultType = roll.total === 1 || roll.total === 2 ? "failure" : "success"
}
let realDamage
if (options.rollType === ROLL_TYPE.DAMAGE) {
realDamage = Math.max(0, roll.total - parseInt(targetArmor, 10))
}
roll.options.resultType = resultType
roll.options.treshold = treshold
roll.options.introText = roll._createIntroText()
roll.options.introTextTooltip = roll._createIntroTextTooltip()
roll.options.realDamage = realDamage
/**
* A hook event that fires after the roll has been made.
* @function tenebris.Roll
* @memberof hookEvents
* @param {Object} options Options for the roll.
* @param {Object} rollData All data related to the roll.
@param {LethalFantasyRoll} roll The resulting roll.
* @returns {boolean} Explicitly return `false` to prevent roll to be made.
*/
if (Hooks.call("tenebris.Roll", options, rollData, roll) === false) return
return roll
}
/**
* Creates a title based on the given type.
*
* @param {string} type The type of the roll.
* @param {string} target The target of the roll.
* @returns {string} The generated title.
*/
static createTitle(type, target) {
switch (type) {
case ROLL_TYPE.SAVE:
return `${game.i18n.localize("TENEBRIS.Dialog.titleSave")} : ${game.i18n.localize(`TENEBRIS.Manager.${target}`)}`
case ROLL_TYPE.RESOURCE:
return `${game.i18n.localize("TENEBRIS.Dialog.titleResource")} : ${game.i18n.localize(`TENEBRIS.Manager.${target}`)}`
case ROLL_TYPE.DAMAGE:
return `${game.i18n.localize("TENEBRIS.Dialog.titleDamage")} : ${target}`
case ROLL_TYPE.ATTACK:
return `${game.i18n.localize("TENEBRIS.Dialog.titleAttack")} : ${target}`
default:
return game.i18n.localize("TENEBRIS.Dialog.titleStandard")
}
}
/** @override */
async render(chatOptions = {}) {
let chatData = await this._getChatCardData(chatOptions.isPrivate)
return await renderTemplate(this.constructor.CHAT_TEMPLATE, chatData)
}
/**
* Generates the data required for rendering a roll chat card.
*
* @param {boolean} isPrivate Indicates if the chat card is private.
* @returns {Promise<Object>} A promise that resolves to an object containing the chat card data.
* @property {Array<string>} css - CSS classes for the chat card.
* @property {Object} data - The data associated with the roll.
* @property {number} diceTotal - The total value of the dice rolled.
* @property {boolean} isGM - Indicates if the user is a Game Master.
* @property {string} formula - The formula used for the roll.
* @property {number} total - The total result of the roll.
* @property {boolean} isSave - Indicates if the roll is a saving throw.
* @property {boolean} isResource - Indicates if the roll is related to a resource.
* @property {boolean} isDamage - Indicates if the roll is for damage.
* @property {boolean} isFailure - Indicates if the roll is a failure.
* @property {Array} avantages - Advantages associated with the roll.
* @property {string} actorId - The ID of the actor performing the roll.
* @property {string} actingCharName - The name of the character performing the roll.
* @property {string} actingCharImg - The image of the character performing the roll.
* @property {string} introText - Introductory text for the roll.
* @property {string} introTextTooltip - Tooltip for the introductory text.
* @property {string} resultType - The type of result (e.g., success, failure).
* @property {boolean} hasTarget - Indicates if the roll has a target.
* @property {string} targetName - The name of the target.
* @property {number} targetArmor - The armor value of the target.
* @property {number} realDamage - The real damage dealt.
* @property {boolean} isPrivate - Indicates if the chat card is private.
* @property {string} cssClass - The combined CSS classes as a single string.
* @property {string} tooltip - The tooltip text for the chat card.
*/
async _getChatCardData(isPrivate) {
const cardData = {
css: [SYSTEM.id, "dice-roll"],
data: this.data,
diceTotal: this.dice.reduce((t, d) => t + d.total, 0),
isGM: game.user.isGM,
formula: this.formula,
total: this.total,
isSave: this.isSave,
isResource: this.isResource,
isDamage: this.isDamage,
isFailure: this.isFailure,
avantages: this.avantages,
actorId: this.actorId,
actingCharName: this.actorName,
actingCharImg: this.actorImage,
introText: this.introText,
introTextTooltip: this.introTextTooltip,
resultType: this.resultType,
hasTarget: this.hasTarget,
targetName: this.targetName,
targetArmor: this.targetArmor,
realDamage: this.realDamage,
isPrivate: isPrivate,
}
cardData.cssClass = cardData.css.join(" ")
cardData.tooltip = isPrivate ? "" : await this.getTooltip()
return cardData
}
/**
* Converts the roll result to a chat message.
*
* @param {Object} [messageData={}] Additional data to include in the message.
* @param {Object} options Options for message creation.
* @param {string} options.rollMode The mode of the roll (e.g., public, private).
* @param {boolean} [options.create=true] Whether to create the message.
* @returns {Promise} - A promise that resolves when the message is created.
*/
async toMessage(messageData = {}, { rollMode, create = true } = {}) {
super.toMessage(
{
isSave: this.isSave,
isResource: this.isResource,
isDamage: this.isDamage,
isFailure: this.resultType === "failure",
avantages: this.avantages,
introText: this.introText,
introTextTooltip: this.introTextTooltip,
actingCharName: this.actorName,
actingCharImg: this.actorImage,
hasTarget: this.hasTarget,
targetName: this.targetName,
targetArmor: this.targetArmor,
targetMalus: this.targetMalus,
realDamage: this.realDamage,
...messageData,
},
{ rollMode: rollMode },
)
}
// Used in the avantages select and with the rollAdvantage parameter: convert the selected value to the corresponding string
static _convertAvantages(value) {
switch (value) {
case "1":
return game.i18n.localize("TENEBRIS.Roll.doubleDesavantage")
case "2":
return game.i18n.localize("TENEBRIS.Roll.desavantage")
case "3":
return game.i18n.localize("TENEBRIS.Roll.normal")
case "4":
return game.i18n.localize("TENEBRIS.Roll.avantage")
case "5":
return game.i18n.localize("TENEBRIS.Roll.doubleAvantage")
case "--":
return game.i18n.localize("TENEBRIS.Roll.doubleDesavantage")
case "-":
return game.i18n.localize("TENEBRIS.Roll.desavantage")
case "=":
return game.i18n.localize("TENEBRIS.Roll.normal")
case "+":
return game.i18n.localize("TENEBRIS.Roll.avantage")
case "++":
return game.i18n.localize("TENEBRIS.Roll.doubleAvantage")
}
}
// Used in the rollAdvantage parameter: convert the selected value to the corresponding range value
static _convertRollAdvantageToRange(value) {
switch (value) {
case "--":
return 1
case "-":
return 2
case "=":
return 3
case "+":
return 4
case "++":
return 5
}
}
}

80
module/enrichers.mjs Normal file
View File

@ -0,0 +1,80 @@
/**
* Enricher qui permet de transformer un texte en un lien de lancer de dés
* Pour une syntaxe de type @jet[x]{y}(z) avec x la caractéristique, y le titre et z l'avantage
* x de type rob, dex, int, per, vol pour les caractéristiques
* et de type oeil, verbe, san, bourse, magie pour les ressources
* y est le titre du jet et permet de décrire l'action
* z est l'avantage du jet, avec pour valeurs possibles : --, -, +, ++
*/
export function setupTextEnrichers() {
CONFIG.TextEditor.enrichers = CONFIG.TextEditor.enrichers.concat([
{
// eslint-disable-next-line no-useless-escape
pattern: /\@jet\[(.+?)\]{(.*?)}\((.*?)\)/gm,
enricher: async (match, options) => {
const a = document.createElement("a")
a.classList.add("ask-roll-journal")
const target = match[1]
const title = match[2]
const avantage = match[3]
let type = "resource"
if (["rob", "dex", "int", "per", "vol"].includes(target)) {
type = "save"
}
let rollAvantage = "normal"
if (avantage) {
switch (avantage) {
case "++":
rollAvantage = "++"
break
case "+":
rollAvantage = "+"
break
case "-":
rollAvantage = "-"
break
case "--":
rollAvantage = "--"
break
default:
break
}
}
a.dataset.rollType = type
a.dataset.rollTarget = target
a.dataset.rollTitle = title
a.dataset.rollAvantage = rollAvantage
a.innerHTML = `
<i class="fas fa-dice-d20"></i> ${getLibelle(target)}${rollAvantage !== "normal" ? rollAvantage : ""}
`
return a
},
},
])
}
const mapLibelles = {
rob: "ROB",
dex: "DEX",
int: "INT",
per: "PER",
vol: "VOL",
oeil: "OEIL",
verbe: "VERBE",
san: "SANTE MENTALE",
bourse: "BOURSE",
magie: "MAGIE",
}
/**
* Retourne le libellé associé à la valeur qui sera affiché dans le journal
* @param {string} value
*/
function getLibelle(value) {
if (mapLibelles[value]) {
return mapLibelles[value]
}
return null
}

82
module/macros.mjs Normal file
View File

@ -0,0 +1,82 @@
export class Macros {
/**
* Creates a macro based on the type of data dropped onto the hotbar.
*
* @param {Object} dropData The data object representing the item dropped.
* @param {string} dropData.type The type of the dropped item (e.g., "Actor", "JournalEntry", "roll").
* @param {string} dropData.uuid The UUID of the dropped item.
* @param {string} [dropData.actorId] The ID of the actor (required if type is "roll").
* @param {string} [dropData.rollType] The type of roll (required if type is "roll").
* @param {string} [dropData.rollTarget] The target of the roll (required if type is "roll").
* @param {string} [dropData.value] The value of the roll (required if type is "roll").
* @param {number} slot The hotbar slot where the macro will be created.
*
* @returns {Promise<void>} A promise that resolves when the macro is created.
*/
static createLethalFantasyMacro = async function (dropData, slot) {
switch (dropData.type) {
case "Actor":
const actor = await fromUuid(dropData.uuid)
const actorCommand = `game.actors.get("${actor.id}").sheet.render(true)`
this.createMacro(slot, actor.name, actorCommand, actor.img)
break
case "JournalEntry":
const journal = await fromUuid(dropData.uuid)
const journalCommand = `game.journal.get("${journal.id}").sheet.render(true)`
this.createMacro(slot, journal.name, journalCommand, journal.img ? journal.img : "icons/svg/book.svg")
break
case "roll":
const rollCommand =
dropData.rollType === "save"
? `game.actors.get('${dropData.actorId}').system.roll('${dropData.rollType}', '${dropData.rollTarget}', '=');`
: `game.actors.get('${dropData.actorId}').system.roll('${dropData.rollType}', '${dropData.rollTarget}');`
const rollName = `${game.i18n.localize("TENEBRIS.Label.jet")} ${game.i18n.localize(`TENEBRIS.Manager.${dropData.rollTarget}`)}`
this.createMacro(slot, rollName, rollCommand, "icons/svg/d20-grey.svg")
break
case "rollDamage":
const weapon = game.actors.get(dropData.actorId).items.get(dropData.rollTarget)
const rollDamageCommand = `game.actors.get('${dropData.actorId}').system.roll('${dropData.rollType}', '${dropData.rollTarget}');`
const rollDamageName = `${game.i18n.localize("TENEBRIS.Label.jet")} ${weapon.name}`
this.createMacro(slot, rollDamageName, rollDamageCommand, weapon.img)
break
case "rollAttack":
const rollAttackCommand = `game.actors.get('${dropData.actorId}').system.roll('${dropData.rollValue}', '${dropData.rollTarget}');`
const rollAttackName = `${game.i18n.localize("TENEBRIS.Label.jet")} ${dropData.rollTarget}`
this.createMacro(slot, rollAttackName, rollAttackCommand, "icons/svg/d20-grey.svg")
break
default:
// Handle other cases or do nothing
break
}
}
/**
* Create a macro
* All macros are flaged with a tenebris.macro flag at true
* @param {*} slot
* @param {*} name
* @param {*} command
* @param {*} img
*/
static createMacro = async function (slot, name, command, img) {
let macro = game.macros.contents.find((m) => m.name === name && m.command === command)
if (!macro) {
macro = await Macro.create(
{
name: name,
type: "script",
img: img,
command: command,
flags: { "tenebris.macro": true },
},
{ displaySheet: false },
)
game.user.assignHotbarMacro(macro, slot)
}
}
}

View File

@ -0,0 +1,8 @@
export { default as LethalFantasyCharacter } from "./character.mjs"
export { default as LethalFantasyOpponent } from "./opponent.mjs"
export { default as LethalFantasyPath } from "./path.mjs"
export { default as LethalFantasyTalent } from "./talent.mjs"
export { default as LethalFantasyArmor } from "./armor.mjs"
export { default as LethalFantasyWeapon } from "./weapon.mjs"
export { default as LethalFantasySpell } from "./spell.mjs"
export { default as LethalFantasyAttack } from "./attack.mjs"

34
module/models/armor.mjs Normal file
View File

@ -0,0 +1,34 @@
import { SYSTEM } from "../config/system.mjs"
import { CATEGORY } from "../config/armor.mjs"
export default class LethalFantasyArmor extends foundry.abstract.TypeDataModel {
static defineSchema() {
const fields = foundry.data.fields
const requiredInteger = { required: true, nullable: false, integer: true }
const schema = {}
schema.description = new fields.HTMLField({ required: true, textSearch: true })
schema.categorie = new fields.StringField({ required: true, initial: "sommaire", choices: SYSTEM.ARMOR_CATEGORY })
schema.valeur = new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 })
schema.malus = new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 })
return schema
}
/** @override */
static LOCALIZATION_PREFIXES = ["TENEBRIS.Armor"]
get armorCategory() {
return game.i18n.localize(CATEGORY[this.categorie].label)
}
get details() {
return game.i18n.format("TENEBRIS.Armor.details", {
valeur: this.valeur,
malus: this.malus,
})
}
}

18
module/models/attack.mjs Normal file
View File

@ -0,0 +1,18 @@
export default class LethalFantasy extends foundry.abstract.TypeDataModel {
static defineSchema() {
const fields = foundry.data.fields
const schema = {}
schema.description = new fields.HTMLField({ required: true, textSearch: true })
schema.degats = new fields.StringField({ required: false, nullable: true, blank: true })
return schema
}
/** @override */
static LOCALIZATION_PREFIXES = ["TENEBRIS.Attack"]
get toolTip() {
return this.description || ""
}
}

176
module/models/character.mjs Normal file
View File

@ -0,0 +1,176 @@
import { ROLL_TYPE, SYSTEM } from "../config/system.mjs"
import LethalFantasyRoll from "../documents/roll.mjs"
import LethalFantasyUtils from "../utils.mjs"
export default class LethalFantasyCharacter extends foundry.abstract.TypeDataModel {
static defineSchema() {
const fields = foundry.data.fields
const requiredInteger = { required: true, nullable: false, integer: true }
const schema = {}
schema.description = new fields.HTMLField({ required: true, textSearch: true })
schema.langues = new fields.HTMLField({ required: true, textSearch: true })
schema.notes = new fields.HTMLField({ required: true, textSearch: true })
schema.biens = new fields.HTMLField({ required: true, textSearch: true })
// Caractéristiques
const characteristicField = (label) => {
const schema = {
valeur: new fields.NumberField({ ...requiredInteger, initial: 10, min: 0 }),
progression: new fields.SchemaField({
experience: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 }),
progres: new fields.BooleanField(),
}),
}
return new fields.SchemaField(schema, { label })
}
schema.caracteristiques = new fields.SchemaField(
Object.values(SYSTEM.CHARACTERISTICS).reduce((obj, characteristic) => {
obj[characteristic.id] = characteristicField(characteristic.label)
return obj
}, {}),
)
// Ressources
const resourceField = (label) => {
const schema = {
valeur: new fields.StringField({
required: true,
nullable: false,
initial: SYSTEM.RESOURCE_VALUE.ZERO,
choices: Object.fromEntries(Object.entries(SYSTEM.RESOURCE_VALUE).map(([key, value]) => [value, { label: `${value}` }])),
blank: true,
}),
max: new fields.StringField({
required: true,
nullable: false,
initial: SYSTEM.RESOURCE_VALUE.ZERO,
choices: Object.fromEntries(Object.entries(SYSTEM.RESOURCE_VALUE).map(([key, value]) => [value, { label: `${value}` }])),
blank: true,
}),
experience: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 }),
}
return new fields.SchemaField(schema, { label })
}
schema.ressources = new fields.SchemaField(
Object.values(SYSTEM.RESOURCES).reduce((obj, resource) => {
obj[resource.id] = resourceField(resource.label)
return obj
}, {}),
)
schema.commanditaire = new fields.StringField({})
schema.dv = new fields.StringField({
required: true,
nullable: false,
initial: SYSTEM.RESOURCE_VALUE.ZERO,
choices: Object.fromEntries(Object.entries(SYSTEM.RESOURCE_VALUE).map(([key, value]) => [value, { label: `${value}` }])),
})
schema.pv = new fields.SchemaField({
value: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 }),
max: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 }),
})
schema.dmax = new fields.SchemaField({
valeur: new fields.StringField({
required: true,
nullable: false,
initial: SYSTEM.RESOURCE_VALUE.ZERO,
choices: Object.fromEntries(Object.entries(SYSTEM.RESOURCE_VALUE).map(([key, value]) => [value, { label: `${value}` }])),
}),
experience: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 }),
})
schema.voies = new fields.SchemaField({
majeure: new fields.SchemaField({
id: new fields.DocumentIdField(),
key: new fields.StringField({ required: true }),
nom: new fields.StringField({ required: true }),
}),
mineure: new fields.SchemaField({
id: new fields.DocumentIdField(),
key: new fields.StringField({ required: true }),
nom: new fields.StringField({ required: true }),
}),
})
return schema
}
/** @override */
static LOCALIZATION_PREFIXES = ["TENEBRIS.Character"]
get hasVoieMajeure() {
return !!this.voies.majeure.id
}
get hasVoieMineure() {
return !!this.voies.mineure.id
}
/**
* Rolls a dice for a character.
* @param {("save"|"resource|damage")} rollType The type of the roll.
* @param {number} rollTarget The target value for the roll. Which caracteristic or resource. If the roll is a damage roll, this is the id of the item.
* @param {"="|"+"|"++"|"-"|"--"} rollAdvantage If there is an avantage (+), a disadvantage (-), a double advantage (++), a double disadvantage (--) or a normal roll (=).
* @returns {Promise<null>} - A promise that resolves to null if the roll is cancelled.
*/
async roll(rollType, rollTarget, rollAdvantage = "=") {
let rollValue
let opponentTarget
switch (rollType) {
case ROLL_TYPE.SAVE:
rollValue = this.caracteristiques[rollTarget].valeur
opponentTarget = game.user.targets.first()
break
case ROLL_TYPE.RESOURCE:
rollValue = this.ressources[rollTarget].valeur
break
case ROLL_TYPE.DAMAGE:
rollValue = this.parent.items.get(rollTarget).system.degats
opponentTarget = game.user.targets.first()
break
default:
// Handle other cases or do nothing
break
}
await this._roll(rollType, rollTarget, rollValue, opponentTarget, rollAdvantage)
}
/**
* Rolls a dice for a character.
* @param {("save"|"resource|damage")} rollType The type of the roll.
* @param {number} rollTarget The target value for the roll. Which caracteristic or resource. If the roll is a damage roll, this is the id of the item.
* @param {number} rollValue The value of the roll. If the roll is a damage roll, this is the dice to roll.
* @param {Token} opponentTarget The target of the roll : used for save rolls to get the oppponent's malus.
* @param {"="|"+"|"++"|"-"|"--"} rollAdvantage If there is an avantage (+), a disadvantage (-), a double advantage (++), a double disadvantage (--) or a normal roll (=).
* @returns {Promise<null>} - A promise that resolves to null if the roll is cancelled.
*/
async _roll(rollType, rollTarget, rollValue, opponentTarget = undefined, rollAdvantage = "=") {
const hasTarget = opponentTarget !== undefined
let roll = await LethalFantasyRoll.prompt({
rollType,
rollTarget,
rollValue,
actorId: this.parent.id,
actorName: this.parent.name,
actorImage: this.parent.img,
hasTarget,
target: opponentTarget,
rollAdvantage,
})
if (!roll) return null
// Perte de ressouces
if (rollType === ROLL_TYPE.RESOURCE && roll.resultType === "failure") {
const value = this.ressources[rollTarget].valeur
const newValue = LethalFantasyUtils.findLowerDice(value)
await this.parent.update({ [`system.ressources.${rollTarget}.valeur`]: newValue })
}
await roll.toMessage({}, { rollMode: roll.options.rollMode })
}
}

View File

@ -0,0 +1,49 @@
import LethalFantasyRoll from "../documents/roll.mjs"
import { ROLL_TYPE } from "../config/system.mjs"
export default class LethalFantasyOpponent extends foundry.abstract.TypeDataModel {
static defineSchema() {
const fields = foundry.data.fields
const requiredInteger = { required: true, nullable: false, integer: true }
const schema = {}
schema.dv = new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 })
schema.pv = new fields.SchemaField({
value: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 }),
max: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 }),
})
schema.armure = new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 })
schema.malus = new fields.NumberField({ ...requiredInteger, initial: 0, max: 0 })
schema.actions = new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 })
schema.description = new fields.HTMLField({ required: true, textSearch: true })
// Attaques : embedded items of type Attack
return schema
}
/** @override */
static LOCALIZATION_PREFIXES = ["TENEBRIS.Opponent"]
/**
* Rolls a dice attack for an opponent.
* @param {number} rollValue The dice to roll.
* @param {number} rollTarget The name of the attack
* @returns {Promise<null>} - A promise that resolves to null if the roll is cancelled.
*/
async roll(rollValue, rollTarget) {
let roll = await LethalFantasyRoll.prompt({
rollType: ROLL_TYPE.ATTACK,
rollValue,
rollTarget,
actorId: this.parent.id,
actorName: this.parent.name,
actorImage: this.parent.img,
})
if (!roll) return null
await roll.toMessage({}, { rollMode: roll.options.rollMode })
}
get toolTip() {
return this.description || ""
}
}

83
module/models/path.mjs Normal file
View File

@ -0,0 +1,83 @@
import { SYSTEM } from "../config/system.mjs"
export default class LethalFantasyPath extends foundry.abstract.TypeDataModel {
static defineSchema() {
const fields = foundry.data.fields
const schema = {}
schema.key = new fields.StringField({ required: true, nullable: false, initial: "" })
// Caractéristiques
const characteristicField = (label) => {
const schema = {
valeur: new fields.NumberField({
required: true,
nullable: false,
integer: true,
initial: 10,
min: 0,
}),
}
return new fields.SchemaField(schema, { label })
}
schema.caracteristiques = new fields.SchemaField(
Object.values(SYSTEM.CHARACTERISTICS).reduce((obj, characteristic) => {
obj[characteristic.id] = characteristicField(characteristic.label)
return obj
}, {}),
)
// Ressources
const resourceField = (label) => {
const schema = {
valeur: new fields.StringField({
required: true,
initial: SYSTEM.RESOURCE_VALUE.ZERO,
choices: Object.fromEntries(Object.entries(SYSTEM.RESOURCE_VALUE).map(([key, value]) => [value, { label: `${value}` }])),
}),
}
return new fields.SchemaField(schema, { label })
}
schema.ressources = new fields.SchemaField(
Object.values(SYSTEM.RESOURCES).reduce((obj, resource) => {
obj[resource.id] = resourceField(resource.label)
return obj
}, {}),
)
schema.dv = new fields.StringField({
required: true,
initial: SYSTEM.RESOURCE_VALUE.ZERO,
choices: Object.fromEntries(Object.entries(SYSTEM.RESOURCE_VALUE).map(([key, value]) => [value, { label: `${value}` }])),
})
schema.dmax = new fields.StringField({
required: true,
initial: SYSTEM.RESOURCE_VALUE.ZERO,
choices: Object.fromEntries(Object.entries(SYSTEM.RESOURCE_VALUE).map(([key, value]) => [value, { label: `${value}` }])),
})
schema.description = new fields.HTMLField({ required: true, textSearch: true })
schema.biens = new fields.HTMLField({ required: true, textSearch: true })
schema.langues = new fields.HTMLField({ required: true, textSearch: true })
schema.talents = new fields.ArrayField(new fields.DocumentUUIDField())
return schema
}
/** @override */
static LOCALIZATION_PREFIXES = ["TENEBRIS.Path"]
async getAllTalents() {
const talents = []
this.talents.forEach(async (element) => {
const talent = await fromUuid(element)
if (talent) talents.push(talent)
})
return talents
}
}

27
module/models/spell.mjs Normal file
View File

@ -0,0 +1,27 @@
import { SYSTEM } from "../config/system.mjs"
export default class LethalFantasySpell extends foundry.abstract.TypeDataModel {
static defineSchema() {
const fields = foundry.data.fields
const requiredInteger = { required: true, nullable: false, integer: true }
const schema = {}
schema.description = new fields.HTMLField({
required: false,
blank: true,
initial: "",
textSearch: true,
})
schema.preparation = new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 })
schema.cible = new fields.StringField({ required: true })
schema.portee = new fields.StringField({ required: true, initial: "contact", choices: SYSTEM.SPELL_RANGE })
schema.duree = new fields.StringField({ required: true })
schema.consequenceA = new fields.StringField({ required: true })
schema.consequenceB = new fields.StringField({ required: true })
return schema
}
/** @override */
static LOCALIZATION_PREFIXES = ["TENEBRIS.Spell"]
}

44
module/models/talent.mjs Normal file
View File

@ -0,0 +1,44 @@
export default class LethalFantasyTalent extends foundry.abstract.TypeDataModel {
static defineSchema() {
const fields = foundry.data.fields
const requiredInteger = { required: true, nullable: false, integer: true }
const schema = {}
schema.description = new fields.HTMLField({ required: true, textSearch: true })
schema.appris = new fields.BooleanField()
schema.progression = new fields.BooleanField()
schema.niveau = new fields.NumberField({ ...requiredInteger, initial: 0, min: 0, max: 3 })
schema.path = new fields.DocumentUUIDField()
return schema
}
/** @override */
static LOCALIZATION_PREFIXES = ["TENEBRIS.Talent"]
get canProgress() {
return this.progression
}
get isLearned() {
return this.appris
}
get improvedDescription() {
return this.description.replace(/#niveau\b/g, this.niveau)
}
get details() {
if (this.progression)
return game.i18n.format("TENEBRIS.Talent.details", {
niveau: this.niveau,
})
return ""
}
async getPathName() {
const path = await fromUuid(this.path)
return path ? path.name : ""
}
}

24
module/models/weapon.mjs Normal file
View File

@ -0,0 +1,24 @@
import { SYSTEM } from "../config/system.mjs"
import { CATEGORY } from "../config/weapon.mjs"
export default class LethalFantasyWeapon extends foundry.abstract.TypeDataModel {
static defineSchema() {
const fields = foundry.data.fields
const schema = {}
schema.description = new fields.HTMLField({ required: true, textSearch: true })
schema.categorie = new fields.StringField({ required: true, initial: "mains", choices: SYSTEM.WEAPON_CATEGORY })
schema.degats = new fields.StringField({
required: true,
initial: SYSTEM.WEAPON_DAMAGE.UN,
choices: Object.fromEntries(Object.entries(SYSTEM.WEAPON_DAMAGE).map(([key, value]) => [value, { label: `${value}` }])),
})
return schema
}
/** @override */
static LOCALIZATION_PREFIXES = ["TENEBRIS.Weapon"]
get weaponCategory() {
return game.i18n.localize(CATEGORY[this.categorie].label)
}
}

33
module/socket.mjs Normal file
View File

@ -0,0 +1,33 @@
import LethalFantasyFortune from "./applications/fortune.mjs"
/**
* Handles socket events based on the provided action.
*
* @param {Object} [params={}] The parameters for the socket event.
* @param {string|null} [params.action=null] The action to be performed.
* @param {Object} [params.data={}] The data associated with the action.
* @returns {*} The result of the action handler, if applicable.
*/
export function handleSocketEvent({ action = null, data = {} } = {}) {
console.debug("handleSocketEvent", action, data)
switch (action) {
case "fortune":
return LethalFantasyFortune.handleSocketEvent(data)
case "askRoll":
return _askRoll(data)
}
}
/**
* Handles the socket event to ask for a roll.
*
* @param {Object} [options={}] The options object.
* @param {string} [options.userId] The ID of the user who initiated the roll.
*/
export function _askRoll({ userId } = {}) {
console.debug(`handleSocketEvent _askRoll from ${userId} !`)
const currentUser = game.user._id
if (userId === currentUser) {
foundry.audio.AudioHelper.play({ src: "/systems/fvtt-lethal-fantasy/sounds/drums.wav", volume: 0.8, autoplay: true, loop: false }, false)
}
}

23
module/utils.mjs Normal file
View File

@ -0,0 +1,23 @@
import { DICE_VALUES } from "./config/system.mjs"
export default class LethalFantasyUtils {
// Return the maximum damage limited by the maximum damage of the character
static maxDamage(damage, damageMax) {
const damageIndex = DICE_VALUES.indexOf(damage)
const damageMaxIndex = DICE_VALUES.indexOf(damageMax)
// If damage exceeds damageMax, return damageMax
if (damageIndex > damageMaxIndex) {
return damageMax
}
// Otherwise, return damage (as it is less than or equal to damageMax)
return damage
}
// Used when a ressource is lost to find the next lower dice
static findLowerDice(dice) {
let index = DICE_VALUES.indexOf(dice)
return DICE_VALUES[index - 1]
}
}