feat: add timed effect reminders and fuzz fixtures

This commit is contained in:
Dandaedre 2026-09-19 07:00:02 +02:00
parent 3ab7b46d6b
commit 5e749675cc
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
11 changed files with 434 additions and 7 deletions

6
Jenkinsfile vendored
View File

@ -79,15 +79,17 @@ pipeline {
mkdir -p "${BUILD_DIR}"
uv sync --frozen
uv run python tools/build.py
./scripts/build.sh
uv run python -m unittest discover -s tests -v
uv run python tools/build.py --check
RAVENOUS_CHARACTER_JSON="${BUILD_DIR}/example-character.json" node tests/test_character_io.mjs
./scripts/build.sh --check
test -f "${BUILD_DIR}/ravenous.html"
test -f "${BUILD_DIR}/ravenous.css"
test -f "${BUILD_DIR}/translation.json"
test -f "${BUILD_DIR}/sheet.json"
test -f "${BUILD_DIR}/build-info.json"
test -f "${BUILD_DIR}/example-character.json"
echo "Roll20 sheet build complete:"
ls -lh "${BUILD_DIR}"

View File

@ -147,6 +147,20 @@ python tools/export_monsters.py --id 1 --output /tmp/monster-1.json
python tools/export_monsters.py --all --output /tmp/ravenous-monsters
```
Pour produire un personnage d'exemple aléatoire mais reproductible (toutes les
sections répétables, Unicode et caractères sensibles inclus) :
```sh
python tools/generate_character.py --seed 42 --output /tmp/ravenous-example.json
```
Une même graine produit exactement le même JSON, ce qui permet de reproduire un
échec d'import. Sans `--output`, le JSON est écrit sur la sortie standard. La CI
génère et archive également `build/example-character.json`, puis l'importe dans
le simulateur de l'API Mod.
Le script `./scripts/build.sh` génère automatiquement ce même exemple dans son
dossier de sortie, et `./scripts/build.sh --check` vérifie également son contenu.
Le convertisseur reprend les caractéristiques directement compatibles, les
localisations en lignes répétables, les capacités avec dégâts en attaques, et
les autres capacités en pouvoirs. Leurs descriptions et valeurs de dégâts
@ -169,6 +183,22 @@ Ces tests simulent l'API Mod et valident le format avec la base épinglée. Un
essai dans une partie Roll20 reste nécessaire pour confirmer l'affichage et
les limites des GM Notes.
## Rappels d'effets et tours
Les effets temporaires peuvent porter des rappels distincts de début et de fin
de tour. Leur durée structurée peut être manuelle, exprimée en tours, liée au
prochain début/à la prochaine fin de tour, ou réservée à la fin du combat et au
futur décompte par actions. Les boutons **Début du tour** et **Fin du tour**
affichent uniquement les rappels de la phase, décrémentent les durées concernées
et annoncent les effets terminés. Ils ne modifient jamais automatiquement PV,
armure, résistances ou ressources.
La configuration avancée d'un consommable peut être copiée dans les effets
actifs avec **Appliquer comme effet**. Une technique ou un pouvoir peut aussi
être copié avec **Suivre comme effet**, puis recevoir ses rappels structurés sans
tenter d'interpréter automatiquement sa prose. Les anciennes lignes d'effets,
dépourvues de champs structurés, restent actives en durée manuelle.
## Import d'objets fabriqués
`roll20_mod/ravenous_craft_import.js` importe les résultats finalisés d'un

View File

@ -25,6 +25,11 @@ parser, browser, or chat.
- [x] Define the versioned craft JSON interface and add a GM-only Mod importer
for weapons, protections, consumables, and temporary effects. Validate all
destinations, handout input, and invalid payloads locally.
- [x] Add structured start/end-turn reminders to temporary effects, including
turn countdowns, expiration notices, and copying reminder configuration from
consumables. Keep mechanical changes manual.
- [x] Generate a deterministic randomized character JSON fixture covering all
repeating sections and import it through the Mod simulator in Jenkins.
## Next: Roll20 smoke test

View File

@ -12,3 +12,35 @@ fi
uv sync --frozen
uv run python tools/build.py "$@"
output_dir=build
expect_output_dir=0
list_themes=0
check=0
for argument in "$@"; do
if [ "$expect_output_dir" -eq 1 ]; then
output_dir=$argument
expect_output_dir=0
continue
fi
case "$argument" in
--output-dir) expect_output_dir=1 ;;
--output-dir=*) output_dir=${argument#--output-dir=} ;;
--list-themes) list_themes=1 ;;
--check) check=1 ;;
esac
done
[ "$list_themes" -eq 1 ] && exit 0
example="$output_dir/example-character.json"
if [ "$check" -eq 1 ]; then
temporary=$(mktemp)
trap 'rm -f "$temporary"' EXIT HUP INT TERM
uv run python tools/generate_character.py --seed 20260919 --output "$temporary" >/dev/null
if ! cmp -s "$temporary" "$example"; then
echo "$example is missing or differs from the seeded character fixture" >&2
exit 1
fi
else
uv run python tools/generate_character.py --seed 20260919 --output "$example"
fi

View File

@ -112,7 +112,7 @@
.damage-summary button { padding:6px 10px; color:white; border:0; background:var(--blood); }
.callout { padding:9px 12px; color:var(--muted); background:var(--accent); border-left:3px solid var(--gold); font-style:italic; }
.consumable-card { display:block; }
.consumable-kind { display:grid; grid-template-columns:28px minmax(0,1fr); gap:7px; align-items:center; }
.consumable-kind { display:grid; grid-template-columns:28px minmax(0,1fr) auto; gap:7px; align-items:center; }
.consumable-kind select { height:32px; min-height:32px; margin:0; }
.consumable-details { display:grid; grid-template-columns:minmax(0,1fr) 60px 105px; gap:7px; align-items:end; margin:7px 0; }
.consumable-details>input { height:28px; min-height:28px; margin:0; }
@ -123,6 +123,15 @@
.use-effect { flex:0 0 28px; }
.modifier-card { display:flex; flex-wrap:wrap; gap:7px; align-items:end; margin:8px 0; padding:9px; border:1px solid var(--border); border-left:4px solid var(--gold); background:rgba(var(--light-rgb),.74); }
.modifier-card>.grow { flex:1; }
.turn-controls { display:flex; align-items:center; gap:7px; padding:8px; background:var(--accent); }
.turn-controls button,.consumable-kind button[type=action] { padding:6px 9px; color:var(--light); border:0; background:var(--blood); }
.turn-controls span { color:var(--muted); font-style:italic; }
.effect-timing { flex-basis:100%; width:100%; margin-top:5px; }
.effect-timing summary { color:var(--dark-gold); cursor:pointer; font:700 10px "Cinzel",Georgia,serif; }
.effect-timing-grid { display:grid; grid-template-columns:2fr 70px 1fr 2fr 2fr; gap:7px; margin-top:7px; }
.effect-timing-grid label { display:block; min-width:0; }
.effect-timing-grid label:nth-last-child(-n+2) { grid-column:span 2; }
.effect-timing-grid textarea { min-height:52px; }
.class-picker label { display:grid; grid-template-rows:14px 32px; min-width:240px; flex:1; align-items:end; margin:0 !important; padding:0; }
.class-picker select { display:block; height:32px; min-height:32px; margin:0; }
.class-picker button { align-self:end; height:32px; min-height:32px; margin:0; padding:0 12px; color:white; border:0; background:var(--blood); line-height:32px; white-space:nowrap; }
@ -131,6 +140,7 @@
.tech-title,.tech-meta { display:flex; gap:7px; align-items:end; }
.activate-technique { flex:0 0 28px; }
.tech-title>input { flex:1; color:var(--blood); font-weight:bold; }
.tech-title button[type=action],.power-heading button[type=action] { flex:0 0 auto; padding:6px 9px; color:var(--light); border:0; background:var(--blood); }
.tech-title label { width:75px; }
.tech-meta { margin:5px 0; }
.tech-meta label { display:grid; grid-template-rows:14px 28px; flex:0 0 55px; min-width:0; margin:0 !important; padding:0; align-items:end; }

View File

@ -161,18 +161,22 @@
<div class="section-title"><span>✦</span><h2>Potions & nourriture</h2></div>
<fieldset class="repeating_consumables">
<div class="consumable-card">
<div class="consumable-kind"><button class="use-effect" type="roll" name="roll_use" title="Utiliser dans le chat" aria-label="Utiliser dans le chat" value="@{roll_whisper}&{template:ravenous} {{title=@{name}}} {{subtitle=@{kind} · @{character_name}}} {{duration=@{duration}}} {{details=@{description}}}"></button><select name="attr_kind"><option value="Nourriture">Nourriture</option><option value="Potion">Potion</option><option value="Autre">Autre</option></select></div>
<div class="consumable-kind"><button class="use-effect" type="roll" name="roll_use" title="Utiliser dans le chat" aria-label="Utiliser dans le chat" value="@{roll_whisper}&{template:ravenous} {{title=@{name}}} {{subtitle=@{kind} · @{character_name}}} {{duration=@{duration}}} {{details=@{description}}}"></button><select name="attr_kind"><option value="Nourriture">Nourriture</option><option value="Potion">Potion</option><option value="Autre">Autre</option></select><button type="action" name="act_apply_effect">Appliquer comme effet</button></div>
<div class="consumable-details"><input type="text" name="attr_name" placeholder="Nom du consommable"><label>Qté<input type="number" name="attr_quantity" value="1" min="0"></label><label>Durée<input type="text" name="attr_duration" placeholder="3 tours"></label></div>
<textarea name="attr_description" placeholder="Effet, toxicité, recette, notes…"></textarea>
<details class="effect-timing"><summary>Rappels de tour</summary><div class="effect-timing-grid"><label>Durée structurée<select name="attr_duration_type"><option value="manual">Manuelle</option><option value="turns">Tours</option><option value="until_start">Prochain début de tour</option><option value="until_end">Prochaine fin de tour</option><option value="combat">Fin du combat</option><option value="actions">Actions (futur)</option></select></label><label>Restant<input type="number" name="attr_remaining" value="0" min="0"></label><label>Décompte<select name="attr_countdown_phase"><option value="end">Fin du tour</option><option value="start">Début du tour</option></select></label><label>Début du tour<textarea name="attr_start_reminder"></textarea></label><label>Fin du tour<textarea name="attr_end_reminder"></textarea></label><label>À l'application<textarea name="attr_apply_reminder"></textarea></label><label>Au retrait<textarea name="attr_removal_reminder"></textarea></label></div></details>
</div>
</fieldset>
<div class="section-title small"><span>✧</span><h3>Effets temporaires</h3></div>
<div class="turn-controls"><button type="action" name="act_start_turn">Début du tour</button><button type="action" name="act_end_turn">Fin du tour</button><span name="attr_effect_phase_message"></span></div>
<fieldset class="repeating_modifiers">
<div class="modifier-card">
<button class="use-effect" type="roll" name="roll_use" title="Afficher dans le chat" aria-label="Afficher dans le chat" value="@{roll_whisper}&{template:ravenous} {{title=@{name}}} {{subtitle=Effet temporaire · @{character_name}}} {{duration=@{duration}}} {{details=@{description}}}"></button>
<label>Actif<input type="checkbox" name="attr_active" value="1" checked></label>
<input class="grow" type="text" name="attr_name" placeholder="Bénédiction, blessure, terrain…">
<input type="text" name="attr_duration" placeholder="Durée / fin">
<textarea name="attr_description" placeholder="Effet et conditions…"></textarea>
<details class="effect-timing"><summary>Rappels et durée</summary><div class="effect-timing-grid"><label>Durée structurée<select name="attr_duration_type"><option value="manual">Manuelle</option><option value="turns">Tours</option><option value="until_start">Prochain début de tour</option><option value="until_end">Prochaine fin de tour</option><option value="combat">Fin du combat</option><option value="actions">Actions (futur)</option></select></label><label>Restant<input type="number" name="attr_remaining" value="0" min="0"></label><label>Décompte<select name="attr_countdown_phase"><option value="end">Fin du tour</option><option value="start">Début du tour</option></select></label><label>Début du tour<textarea name="attr_start_reminder"></textarea></label><label>Fin du tour<textarea name="attr_end_reminder"></textarea></label><label>À l'application<textarea name="attr_apply_reminder"></textarea></label><label>Au retrait<textarea name="attr_removal_reminder"></textarea></label></div></details>
</div>
</fieldset>
</section>
@ -183,7 +187,7 @@
<fieldset class="repeating_techniques">
<div class="technique-card">
<input type="hidden" name="attr_source_key">
<div class="tech-title"><button class="activate-technique" type="roll" name="roll_activate" title="Activer dans le chat" aria-label="Activer dans le chat" value="@{roll_whisper}&{template:ravenous} {{title=@{name}}} {{subtitle=@{school} · Tier @{tier} · @{type}}} {{cost=Sang @{blood} · Jauge @{gauge} · @{other}}} {{details=@{effect}}}"></button><input type="text" name="attr_name"><label>Acquise<input type="checkbox" name="attr_owned" value="1"></label></div>
<div class="tech-title"><button class="activate-technique" type="roll" name="roll_activate" title="Activer dans le chat" aria-label="Activer dans le chat" value="@{roll_whisper}&{template:ravenous} {{title=@{name}}} {{subtitle=@{school} · Tier @{tier} · @{type}}} {{cost=Sang @{blood} · Jauge @{gauge} · @{other}}} {{details=@{effect}}}"></button><input type="text" name="attr_name"><button type="action" name="act_track_effect">Suivre comme effet</button><label>Acquise<input type="checkbox" name="attr_owned" value="1"></label></div>
<div class="tech-meta"><label class="grow school-field">École<input type="text" name="attr_school"></label><label>Tier<input type="text" name="attr_tier"></label><label>Niv.<input type="text" name="attr_level"></label><label>Sang<input type="text" name="attr_blood"></label><label>Jauge<input type="text" name="attr_gauge"></label><label>Autre<input type="text" name="attr_other"></label><label class="grow">Type<input type="text" name="attr_type"></label></div>
<textarea name="attr_effect" rows="3"></textarea>
</div>
@ -198,7 +202,7 @@
<fieldset class="repeating_powers">
<div class="power-card">
<input type="hidden" name="attr_source_key">
<div class="power-heading"><button class="use-effect" type="roll" name="roll_activate" title="Afficher dans le chat" aria-label="Afficher dans le chat" value="@{roll_whisper}&{template:ravenous} {{title=@{name}}} {{subtitle=@{origin} · Stade @{stage} · @{type}}} {{details=@{description}}}"></button><input type="text" name="attr_name" placeholder="Nom du pouvoir"></div>
<div class="power-heading"><button class="use-effect" type="roll" name="roll_activate" title="Afficher dans le chat" aria-label="Afficher dans le chat" value="@{roll_whisper}&{template:ravenous} {{title=@{name}}} {{subtitle=@{origin} · Stade @{stage} · @{type}}} {{details=@{description}}}"></button><input type="text" name="attr_name" placeholder="Nom du pouvoir"><button type="action" name="act_track_effect">Suivre comme effet</button></div>
<div class="power-meta"><label>Origine<input type="text" name="attr_origin"></label><label>Stade<input type="number" name="attr_stage" value="1" min="0"></label><label>Type<input type="text" name="attr_type" placeholder="named, passive…"></label></div>
<textarea name="attr_description" rows="4" placeholder="Description du pouvoir"></textarea>
</div>
@ -227,6 +231,7 @@
{{#cost}}<div class="sheet-template-row"><b>Coût</b> {{cost}}</div>{{/cost}}
{{#duration}}<div class="sheet-template-row"><b>Durée</b> {{duration}}</div>{{/duration}}
{{#details}}<div class="sheet-template-notes">{{details}}</div>{{/details}}
{{#turnphase}}{{#triggered}}<div class="sheet-template-row"><b>Rappels</b><br>{{triggered}}</div>{{/triggered}}{{#expired}}<div class="sheet-template-row"><b>Effets terminés</b><br>{{expired}}</div>{{/expired}}{{/turnphase}}
</div>
</rolltemplate>
@ -382,6 +387,68 @@ on("clicked:repeating_attacks:take_damage", event => {
});
});
const EFFECT_FIELDS = ["active","name","duration","description","duration_type","remaining","countdown_phase","start_reminder","end_reminder","apply_reminder","removal_reminder"];
const runEffectPhase = phase => getSectionIDs("modifiers", ids => {
const attrs = ["character_name","roll_whisper", ...ids.flatMap(id => EFFECT_FIELDS.map(field => `repeating_modifiers_${id}_${field}`))];
getAttrs(attrs, values => {
const reminders = [];
const expired = [];
const update = {};
ids.forEach(id => {
const prefix = `repeating_modifiers_${id}_`;
if (values[prefix+"active"] === "0") return;
const name = values[prefix+"name"] || "Effet sans nom";
const reminder = values[prefix+(phase === "start" ? "start_reminder" : "end_reminder")];
if (reminder) reminders.push(`${name} — ${reminder}`);
const type = values[prefix+"duration_type"] || "manual";
let ends = type === `until_${phase}`;
if (type === "turns" && (values[prefix+"countdown_phase"] || "end") === phase) {
const remaining = Math.max(0, Math.floor(number(values[prefix+"remaining"])) - 1);
update[prefix+"remaining"] = remaining;
ends = remaining === 0;
}
if (ends) {
update[prefix+"active"] = "0";
const removal = values[prefix+"removal_reminder"];
expired.push(removal ? `${name} — ${removal}` : name);
}
});
if (Object.keys(update).length) setAttrs(update, {silent:true});
if (!reminders.length && !expired.length) {
setAttrs({effect_phase_message:"Aucun rappel pour cette phase."}, {silent:true});
return;
}
setAttrs({effect_phase_message:`${reminders.length} rappel(s), ${expired.length} fin(s).`}, {silent:true});
const label = phase === "start" ? "Début du tour" : "Fin du tour";
const command = `${values.roll_whisper || ""}&{template:ravenous} {{title=${label} · ${templateText(values.character_name)}}} {{turnphase=1}} {{triggered=${templateText(reminders.join(" · "))}}} {{expired=${templateText(expired.join(" · "))}}} {{phase_marker=[[0]]}}`;
startRoll(command, results => finishRoll(results.rollId, {phase_marker:0}));
});
});
on("clicked:start_turn", () => runEffectPhase("start"));
on("clicked:end_turn", () => runEffectPhase("end"));
on("clicked:repeating_consumables:apply_effect", event => {
const source = event.sourceAttribute.replace(/apply_effect$/, "");
const fields = ["name","duration","description","duration_type","remaining","countdown_phase","start_reminder","end_reminder","apply_reminder","removal_reminder"];
getAttrs(fields.map(field => source+field), values => {
const target = `repeating_modifiers_${generateRowID()}_`;
const update = {[target+"active"]:"1"};
fields.forEach(field => update[target+field] = values[source+field] || (field === "duration_type" ? "manual" : field === "countdown_phase" ? "end" : ""));
setAttrs(update);
});
});
const trackTextEffect = (source, descriptionField) => getAttrs([source+"name",source+descriptionField], values => {
const target = `repeating_modifiers_${generateRowID()}_`;
setAttrs({[target+"active"]:"1", [target+"name"]:values[source+"name"] || "Effet",
[target+"description"]:values[source+descriptionField] || "", [target+"duration_type"]:"manual",
[target+"remaining"]:"0", [target+"countdown_phase"]:"end"});
});
on("clicked:repeating_techniques:track_effect", event => trackTextEffect(event.sourceAttribute.replace(/track_effect$/, ""), "effect"));
on("clicked:repeating_powers:track_effect", event => trackTextEffect(event.sourceAttribute.replace(/track_effect$/, ""), "description"));
const recalculate = () => {
const modifiers = ["torque_modifier","speed_modifier","half_speed_modifier","run_speed_modifier","swim_speed_modifier","fly_speed_modifier","hp_modifier","jauge_max_modifier","fatigue_max_modifier","toxicite_max_modifier","satiete_max_modifier","actions_max_modifier"];
getAttrs([...CHARACTERISTICS, ...CHARACTERISTICS.map(k => `${k}_manual`), "stage", ...modifiers], values => {

View File

@ -15,7 +15,9 @@ class BuildTests(unittest.TestCase):
def test_expected_artifacts(self):
expected = {"ravenous.html", "ravenous.css", "translation.json", "sheet.json", "build-info.json"}
self.assertEqual(expected, {path.name for path in (ROOT / "build").iterdir()})
actual = {path.name for path in (ROOT / "build").iterdir()}
self.assertTrue(expected.issubset(actual))
self.assertLessEqual(actual - expected, {"example-character.json"})
def test_source_data_was_imported(self):
info = json.loads((ROOT / "build/build-info.json").read_text())

View File

@ -0,0 +1,46 @@
import json
import subprocess
import tempfile
import unittest
from pathlib import Path
from tools.generate_character import CHARACTERISTICS, FORMAT, VERSION, generate
ROOT = Path(__file__).resolve().parents[1]
class CharacterGeneratorTests(unittest.TestCase):
def test_same_seed_is_reproducible_and_other_seed_varies(self):
self.assertEqual(generate(42), generate(42))
self.assertNotEqual(generate(42), generate(43))
def test_payload_exercises_sheet_sections_and_import_contract(self):
data = generate(1234)
self.assertEqual((data["format"], data["version"]), (FORMAT, VERSION))
self.assertTrue(data["name"])
self.assertTrue(all(isinstance(data[key], str) for key in
("name", "bio", "gmnotes", "controlledby", "inplayerjournals")))
attrs = data["attributes"]
names = [item["name"] for item in attrs]
self.assertEqual(len(names), len(set(names)))
self.assertTrue(all(set(item) == {"name", "current", "max"} and
all(isinstance(value, str) for value in item.values()) for item in attrs))
for characteristic in CHARACTERISTICS:
self.assertIn(characteristic, names)
for section in ("locations", "customskills", "attacks", "protections", "consumables",
"modifiers", "techniques", "powers"):
self.assertTrue(any(name.startswith(f"repeating_{section}_") for name in names), section)
self.assertTrue(data["abilities"][0]["istokenaction"])
def test_cli_writes_valid_utf8_json(self):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory) / "nested" / "example.json"
subprocess.run(["python", str(ROOT / "tools/generate_character.py"),
"--seed", "77", "--output", str(output)], check=True,
cwd=ROOT, capture_output=True, text=True)
self.assertEqual(json.loads(output.read_text(encoding="utf-8")), generate(77))
if __name__ == "__main__":
unittest.main()

View File

@ -117,3 +117,19 @@ test('a converted database monster imports with its body parts and abilities',
assert.ok(attrs.some(obj => obj.get('name') === 'repeating_attacks_dbability5_name'));
assert.ok(attrs.some(obj => obj.get('name') === 'repeating_powers_dbability1_name'));
});
test('a generated fuzz character imports with all representative repeating sections',
{ skip: !process.env.RAVENOUS_CHARACTER_JSON }, () => {
const data = JSON.parse(readFileSync(process.env.RAVENOUS_CHARACTER_JSON, 'utf8'));
const game = session();
game.send(`!ravenous-import ${JSON.stringify(data)}`);
const character = [...game.objects.values()].find(obj => obj.type === 'character');
assert.equal(character.get('name'), data.name);
const attrs = [...game.objects.values()].filter(obj => obj.type === 'attribute' &&
obj.get('characterid') === character.id);
assert.equal(attrs.length, data.attributes.length);
for (const section of ['locations', 'customskills', 'attacks', 'protections', 'consumables',
'modifiers', 'techniques', 'powers']) {
assert.ok(attrs.some(obj => obj.get('name').startsWith(`repeating_${section}_`)), section);
}
});

View File

@ -196,3 +196,108 @@ test('origin stage picker adds its powers once and preserves custom rows', () =>
assert.equal(Object.keys(sheetWorker.attrs).filter(key => key.startsWith('repeating_powers_') && key.endsWith('_source_key')).length,
stagePowers.length + origins.dragon_1.powers.filter(power => power.stage === '2').length);
});
test('start turn shows only active start reminders and leaves manual effects active', () => {
const sheetWorker = worker({
character_name: 'Ariane',
repeating_modifiers_start_active: '1',
repeating_modifiers_start_name: 'Régénération',
repeating_modifiers_start_duration_type: 'manual',
repeating_modifiers_start_start_reminder: 'Récupérez 3 PV.',
repeating_modifiers_start_end_reminder: 'Ne doit pas apparaître.',
repeating_modifiers_inactive_active: '0',
repeating_modifiers_inactive_name: 'Poison terminé',
repeating_modifiers_inactive_start_reminder: 'Ne doit pas apparaître non plus.',
});
sheetWorker.queueRoll('start-turn', {});
sheetWorker.fire('clicked:start_turn');
assert.equal(sheetWorker.rolls.length, 1);
assert.match(sheetWorker.rolls[0].command, /Début du tour/);
assert.match(sheetWorker.rolls[0].command, /Régénération/);
assert.match(sheetWorker.rolls[0].command, /Récupérez 3 PV/);
assert.doesNotMatch(sheetWorker.rolls[0].command, /Ne doit pas apparaître/);
assert.equal(sheetWorker.attrs.repeating_modifiers_start_active, '1');
});
test('an empty turn phase does not produce a chat card', () => {
const sheetWorker = worker({
repeating_modifiers_manual_active: '1',
repeating_modifiers_manual_name: 'Effet sans rappel',
repeating_modifiers_manual_duration_type: 'manual',
});
sheetWorker.fire('clicked:end_turn');
assert.equal(sheetWorker.rolls.length, 0);
assert.equal(sheetWorker.attrs.repeating_modifiers_manual_active, '1');
});
test('end turn decrements matching durations and reports reminders and expiration', () => {
const sheetWorker = worker({
repeating_modifiers_poison_active: '1',
repeating_modifiers_poison_name: 'Poison',
repeating_modifiers_poison_duration_type: 'turns',
repeating_modifiers_poison_remaining: '1',
repeating_modifiers_poison_countdown_phase: 'end',
repeating_modifiers_poison_end_reminder: 'Subissez 2 dégâts.',
repeating_modifiers_poison_removal_reminder: 'Le poison se dissipe.',
repeating_modifiers_aura_active: '1',
repeating_modifiers_aura_name: 'Aura',
repeating_modifiers_aura_duration_type: 'turns',
repeating_modifiers_aura_remaining: '2',
repeating_modifiers_aura_countdown_phase: 'start',
repeating_modifiers_aura_end_reminder: 'L’aura pulse.',
});
sheetWorker.queueRoll('end-turn', {});
sheetWorker.fire('clicked:end_turn');
assert.equal(sheetWorker.attrs.repeating_modifiers_poison_remaining, 0);
assert.equal(sheetWorker.attrs.repeating_modifiers_poison_active, '0');
assert.equal(sheetWorker.attrs.repeating_modifiers_aura_remaining, '2');
assert.equal(sheetWorker.attrs.repeating_modifiers_aura_active, '1');
assert.match(sheetWorker.rolls[0].command, /Fin du tour/);
assert.match(sheetWorker.rolls[0].command, /Subissez 2 dégâts/);
assert.match(sheetWorker.rolls[0].command, /Le poison se dissipe/);
assert.match(sheetWorker.rolls[0].command, /Poison/);
assert.match(sheetWorker.rolls[0].command, /L’aura pulse/);
});
test('applying a consumable copies its reminder configuration into an active effect', () => {
const prefix = 'repeating_consumables_potion_';
const sheetWorker = worker({
[prefix + 'name']: 'Élixir solaire',
[prefix + 'description']: 'Une chaleur bienfaisante.',
[prefix + 'duration']: '3 tours',
[prefix + 'duration_type']: 'turns',
[prefix + 'remaining']: '3',
[prefix + 'countdown_phase']: 'end',
[prefix + 'start_reminder']: 'Gagnez 1 Jauge.',
[prefix + 'end_reminder']: 'La lumière faiblit.',
[prefix + 'removal_reminder']: 'La lumière disparaît.',
});
sheetWorker.fire('clicked:repeating_consumables:apply_effect', {
sourceAttribute: prefix + 'apply_effect',
});
const effect = 'repeating_modifiers_newrow_';
assert.equal(sheetWorker.attrs[effect + 'active'], '1');
assert.equal(sheetWorker.attrs[effect + 'name'], 'Élixir solaire');
assert.equal(sheetWorker.attrs[effect + 'description'], 'Une chaleur bienfaisante.');
assert.equal(sheetWorker.attrs[effect + 'duration'], '3 tours');
assert.equal(sheetWorker.attrs[effect + 'duration_type'], 'turns');
assert.equal(sheetWorker.attrs[effect + 'remaining'], '3');
assert.equal(sheetWorker.attrs[effect + 'countdown_phase'], 'end');
assert.equal(sheetWorker.attrs[effect + 'start_reminder'], 'Gagnez 1 Jauge.');
assert.equal(sheetWorker.attrs[effect + 'end_reminder'], 'La lumière faiblit.');
assert.equal(sheetWorker.attrs[effect + 'removal_reminder'], 'La lumière disparaît.');
});
test('a technique can be copied to a manual effect for reminder configuration', () => {
const source = 'repeating_techniques_tech_';
const sheetWorker = worker({ [source + 'name']: 'Danse ardente',
[source + 'effect']: 'Inflige des dégâts à la fin du tour.' });
sheetWorker.fire('clicked:repeating_techniques:track_effect', {
sourceAttribute: source + 'track_effect',
});
const effect = 'repeating_modifiers_newrow_';
assert.equal(sheetWorker.attrs[effect + 'active'], '1');
assert.equal(sheetWorker.attrs[effect + 'name'], 'Danse ardente');
assert.equal(sheetWorker.attrs[effect + 'description'], 'Inflige des dégâts à la fin du tour.');
assert.equal(sheetWorker.attrs[effect + 'duration_type'], 'manual');
});

112
tools/generate_character.py Normal file
View File

@ -0,0 +1,112 @@
"""Generate a deterministic, randomized Ravenous character import fixture.
The output intentionally includes every repeating section and awkward text
characters. It is useful both as an example for consumers of the exchange
format and as a lightweight fuzz fixture for the Roll20 importer.
"""
import argparse
import json
import random
import string
from pathlib import Path
FORMAT = "ravenous-roll20-character"
VERSION = 1
CHARACTERISTICS = ("force", "agilite", "perception", "intelligence", "volonte",
"psy", "chance", "charisme")
def generate(seed: int) -> dict:
rng = random.Random(seed)
attributes: dict[str, dict[str, str]] = {}
def add(name: str, current: object = "", maximum: object = "") -> None:
attributes[name] = {"name": name, "current": str(current), "max": str(maximum)}
def row_id() -> str:
# Roll20 row IDs are opaque to the importer. A local deterministic ID
# makes diffs and reproducing a failed seed straightforward.
return "fuzz" + "".join(rng.choice(string.ascii_lowercase + string.digits) for _ in range(10))
names = ("Églantine", "Maël", "Ysabeau", "Noé", "Sélène")
name = f"{rng.choice(names)} — essai #{seed}"
add("character_name", name)
add("player_name", "Fixture <MJ> & joueuse")
add("stage", rng.randint(0, 5))
add("skill_die", rng.choice((4, 6, 8, 10, 12, 20, 30, 100)))
for characteristic in CHARACTERISTICS:
add(characteristic, rng.randint(0, 12))
add(characteristic + "_manual", rng.randint(-2, 3))
for resource, maximum in (("jauge", 20), ("fatigue", 12), ("toxicite", 9),
("satiete", 6), ("sang", 15), ("actions", 6)):
top = rng.randint(1, maximum)
add(resource, rng.randint(0, top), top)
add(resource + "_max", top)
for resistance in ("slash", "pierce", "blunt", "fire", "earth", "wood", "magma",
"water", "wind", "ice", "lightning", "abyssal", "celestial",
"alterations", "mental", "fatigue", "sangressence", "void",
"transcendental"):
add("resist_" + resistance, rng.randint(-2, 8))
add("notes", "Fixture reproductible : accents, apostrophe ' et balises <test> & symboles ◆.")
rows = [
("locations", {"name": "Aile gauche", "hp": 3, "hp_max": 7, "protection": 1,
"armor": 2, "armor_max": 4}),
("customskills", {"name": "Cartographie céleste", "characteristic": "intelligence",
"rank": 3, "temp": -1, "total": 2}),
("attacks", {"name": "Lame d'éclipse", "threshold": 6, "temp": 1,
"base_damage": 5, "damage_per_success": 2, "break_damage": 1,
"rmax": 3, "dodge_threshold": 7, "parry_threshold": 5,
"reposition_threshold": 2, "notes": "Feu & glace ; portée <courte>."}),
("protections", {"active": 1, "name": "Manteau renforcé", "protection": 2,
"integrity": 4, "integrity_max": 6, "parry": 1, "dodge": -1,
"effects": "Résiste aux éclats — test."}),
("consumables", {"kind": "Potion", "name": "Élixir \"Aube\"", "quantity": 2,
"duration": "3 tours", "description": "Récupère 1 jauge/tour.",
"duration_type": "turns", "remaining": 3,
"countdown_phase": "end", "start_reminder": "Récupérez 1 Jauge."}),
("modifiers", {"name": "Brûlure persistante", "duration": "2 tours",
"description": "Subit 2 DMG au début du tour.", "active": 1,
"duration_type": "turns", "remaining": 2,
"countdown_phase": "start", "start_reminder": "Subissez 2 DMG.",
"removal_reminder": "La brûlure prend fin."}),
("techniques", {"source_key": "fixture:technique", "name": "Pas du néant",
"owned": 1, "school": "Liminale", "tier": 2, "level": 1,
"blood": 1, "gauge": 2, "other": "—", "type": "Active",
"effect": "Traverse un obstacle <fin>."}),
("powers", {"source_key": "fixture:pouvoir", "name": "Œil d'orage",
"origin": "Fuzz", "stage": 2, "type": "Passif",
"description": "Voit malgré l'obscurité & les illusions."}),
]
for section, fields in rows:
prefix = f"repeating_{section}_{row_id()}_"
for field, value in fields.items():
add(prefix + field, value)
abilities = [{"name": "Fixture : rappel", "action": "/w gm Test <&> réussi",
"istokenaction": True}]
return {"format": FORMAT, "version": VERSION, "name": name,
"controlledby": "", "inplayerjournals": "", "bio": "Personnage généré pour test.",
"gmnotes": f"Généré avec tools/generate_character.py --seed {seed}",
"attributes": list(attributes.values()), "abilities": abilities}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--seed", type=int, default=0,
help="integer seed; identical seeds produce identical JSON (default: 0)")
parser.add_argument("--output", type=Path,
help="write to this file instead of standard output")
args = parser.parse_args()
rendered = json.dumps(generate(args.seed), ensure_ascii=False, indent=2) + "\n"
if args.output:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(rendered, encoding="utf-8")
print(f"seed {args.seed} -> {args.output}")
else:
print(rendered, end="")
if __name__ == "__main__":
main()