feat: add player backups and craft fixtures
Roll20 Sheet Build Successful The Ravenous Roll20 sheet was generated and validated successfully.
Ravenous/ravenous_roll20/pipeline/head This commit looks good
Details
Roll20 Sheet Build Successful The Ravenous Roll20 sheet was generated and validated successfully.
Ravenous/ravenous_roll20/pipeline/head This commit looks good
Details
This commit is contained in:
parent
cfae6b6700
commit
af91983bc7
|
|
@ -85,8 +85,9 @@ pipeline {
|
|||
uv run python -m unittest discover -s tests -v
|
||||
if command -v node >/dev/null 2>&1; then
|
||||
RAVENOUS_CHARACTER_JSON="${BUILD_DIR}/example-character.json" node tests/test_character_io.mjs
|
||||
node tests/test_craft_import.mjs
|
||||
else
|
||||
echo 'Node is not installed on this agent; skipping the optional Roll20 Mod simulator test.'
|
||||
echo 'Node is not installed on this agent; skipping the optional Roll20 Mod simulator tests.'
|
||||
fi
|
||||
./scripts/build.sh --check
|
||||
|
||||
|
|
@ -96,6 +97,8 @@ pipeline {
|
|||
test -f "${BUILD_DIR}/sheet.json"
|
||||
test -f "${BUILD_DIR}/build-info.json"
|
||||
test -f "${BUILD_DIR}/example-character.json"
|
||||
test -f "${BUILD_DIR}/example-craft-forge.json"
|
||||
test -f "${BUILD_DIR}/example-craft-alchemy.json"
|
||||
|
||||
echo "Roll20 sheet build complete:"
|
||||
ls -lh "${BUILD_DIR}"
|
||||
|
|
|
|||
49
README.md
49
README.md
|
|
@ -53,6 +53,15 @@ Pour afficher les identifiants disponibles :
|
|||
./scripts/build.sh --list-themes
|
||||
```
|
||||
|
||||
Pour produire un bundle dont le thème initial et de secours couvre aussi les
|
||||
contrôles et boîtes d'interface situés hors de la zone recolorée, utilisez
|
||||
`--theme-ui`. Tous les thèmes restent ensuite disponibles dans **Apparence** :
|
||||
|
||||
```sh
|
||||
./scripts/build.sh --theme-ui steel --output-dir build-steel
|
||||
./scripts/build.sh --theme-ui steel --output-dir build-steel --check
|
||||
```
|
||||
|
||||
La limite des tiers d'école vient directement de
|
||||
`ravenous_typst/data/config/build.yaml` : seuls les tiers strictement inférieurs
|
||||
à `build.max_tier_exclusive` sont proposés par la feuille. Les trigrammes affichés
|
||||
|
|
@ -112,11 +121,11 @@ node tests/test_mod_import.mjs
|
|||
|
||||
## Sauvegarde et import de personnages et de créatures
|
||||
|
||||
`roll20_mod/ravenous_character_io.js` est le script Mod destiné aux MJ. Installez-le
|
||||
comme **New Script** dans une partie avec la feuille Ravenous. Il utilise le format
|
||||
JSON versionné `ravenous-roll20-character` et crée toujours un nouveau personnage
|
||||
à l'import. Les attributs (y compris les lignes répétables), les capacités Roll20,
|
||||
la bio, les notes MJ et les droits de consultation/contrôle sont conservés.
|
||||
`roll20_mod/ravenous_character_io.js` est le script Mod d'échange de personnages.
|
||||
Installez-le comme **New Script** dans une partie avec la feuille Ravenous. Il
|
||||
utilise le format JSON versionné `ravenous-roll20-character`. Un MJ peut créer un
|
||||
nouveau personnage ; un joueur peut exporter un personnage qu'il contrôle et le
|
||||
remplacer en place à partir d'un handout auquel il a accès.
|
||||
|
||||
Dans le chat, en tant que MJ :
|
||||
|
||||
|
|
@ -127,8 +136,23 @@ Dans le chat, en tant que MJ :
|
|||
!ravenous-import {"format":"ravenous-roll20-character","version":1,"name":"Ariane","attributes":[]}
|
||||
```
|
||||
|
||||
Pour un joueur, sélectionnez un token lié à son personnage :
|
||||
|
||||
```text
|
||||
!ravenous-export
|
||||
!ravenous-import --replace --handout ID_DU_HANDOUT
|
||||
```
|
||||
|
||||
L'export joueur crée un handout contrôlé par ce joueur et place le JSON dans ses
|
||||
**Notes** visibles. Le remplacement conserve l'objet personnage, son ID, ses
|
||||
tokens liés, son avatar, ses droits et ses notes MJ ; il remplace son nom, sa bio,
|
||||
ses attributs de feuille et ses capacités. Le JSON est entièrement validé avant
|
||||
la suppression des anciennes lignes. Un joueur ne peut cibler qu'un personnage
|
||||
qu'il contrôle ni lire un handout auquel il n'a pas accès. Le MJ peut aussi faire
|
||||
un remplacement avec `--replace`, éventuellement suivi de `--id ID_DU_PERSONNAGE`.
|
||||
|
||||
Sans ID, sélectionnez exactement un token lié au personnage avant la commande.
|
||||
Utilisez `--id` si vous ne disposez pas d'un token lié. L'export crée un handout
|
||||
Utilisez `--id` si vous ne disposez pas d'un token lié. L'export MJ crée un handout
|
||||
réservé au MJ, dont les **GM Notes** contiennent le JSON
|
||||
lisible. Copiez ce JSON dans un fichier pour le stocker hors de Roll20. Pour
|
||||
importer un fichier volumineux, créez un handout, collez le JSON dans ses GM
|
||||
|
|
@ -160,6 +184,19 @@ l'agent ; l'absence de ce runtime n'empêche pas la construction de la feuille.
|
|||
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 build génère aussi deux charges utiles prêtes à importer :
|
||||
`build/example-craft-forge.json` (attaque et protection) et
|
||||
`build/example-craft-alchemy.json` (consommable et effet temporaire). Copiez le
|
||||
contenu d'un fichier dans les GM Notes d'un handout privé, puis sélectionnez un
|
||||
token lié au personnage et lancez :
|
||||
|
||||
```text
|
||||
!ravenous-import-craft --handout ID_DU_HANDOUT
|
||||
```
|
||||
|
||||
Ces exemples couvrent les quatre sections répétables prises en charge par
|
||||
l'importeur et sont régénérés et vérifiés de façon déterministe par la CI.
|
||||
|
||||
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
|
||||
|
|
|
|||
4
TASKS.md
4
TASKS.md
|
|
@ -22,6 +22,8 @@ parser, browser, or chat.
|
|||
- [x] Add a GM-only character JSON export/import Mod script and a monster
|
||||
database converter. Verify round trips, repeating rows, invalid input, and
|
||||
all master-visible monsters locally.
|
||||
- [x] Allow players to export controlled characters and restore them in place
|
||||
without changing character IDs, token links, ownership, or GM-only notes.
|
||||
- [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.
|
||||
|
|
@ -31,6 +33,8 @@ parser, browser, or chat.
|
|||
- [x] Generate, validate, and archive a deterministic randomized character JSON
|
||||
fixture covering all repeating sections in Jenkins. Import it through the Mod
|
||||
simulator when Node is available on the build agent.
|
||||
- [x] Generate and archive deterministic forge and alchemy craft fixtures that
|
||||
exercise all four destinations supported by the Roll20 craft importer.
|
||||
|
||||
## Next: Roll20 smoke test
|
||||
|
||||
|
|
|
|||
|
|
@ -19,10 +19,33 @@ Players cannot import into another player's character or read an unshared
|
|||
handout through the script. A GM can use the same macro with any character and
|
||||
handout.
|
||||
|
||||
## Player character backup and replacement
|
||||
|
||||
Select one token linked to a character the player controls. Export creates a
|
||||
handout controlled by that player, with JSON in its visible Notes.
|
||||
|
||||
**Name:** `Ravenous — Sauvegarder le personnage`
|
||||
|
||||
```text
|
||||
!ravenous-export
|
||||
```
|
||||
|
||||
To restore that JSON into the same Roll20 character while preserving its ID,
|
||||
linked tokens, ownership, avatar, and GM Notes:
|
||||
|
||||
**Name:** `Ravenous — Restaurer le personnage`
|
||||
|
||||
```text
|
||||
!ravenous-import --replace --handout ?{ID du handout personnage}
|
||||
```
|
||||
|
||||
Replacement deletes the destination's existing sheet attributes and abilities.
|
||||
The player must control both the selected character and the source handout.
|
||||
|
||||
## GM character import
|
||||
|
||||
Character import creates a new journal character and remains GM-only. Put the
|
||||
export JSON in a private handout's GM Notes.
|
||||
Character creation remains GM-only. Put the export JSON in a private handout's
|
||||
GM Notes.
|
||||
|
||||
**Name:** `Ravenous — Importer un personnage`
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://books.dandaedre.com/ravenous_sheet/ravenous-craft-v1.schema.json",
|
||||
"$id": "https://books.dandaedre.com/RPG/ravenous_sheet/ravenous-craft-v1.schema.json",
|
||||
"title": "Ravenous Roll20 craft exchange",
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
|
|
|
|||
|
|
@ -1,16 +1,32 @@
|
|||
/* Ravenous character exchange for Roll20 Mod. GM commands:
|
||||
/* Ravenous character exchange for Roll20 Mod. Commands:
|
||||
* !ravenous-export (selected token's character)
|
||||
* !ravenous-export --id CHARACTER_ID
|
||||
* !ravenous-import {"format":"ravenous-roll20-character",...}
|
||||
* !ravenous-import --handout HANDOUT_ID
|
||||
* Exports are stored in a GM-only handout. Each import creates a new character.
|
||||
* !ravenous-import --replace [--id CHARACTER_ID] --handout HANDOUT_ID
|
||||
* Players may export and replace characters they control. New-character import is GM-only.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
var FORMAT = 'ravenous-roll20-character';
|
||||
var VERSION = 1;
|
||||
|
||||
function whisper(message) { sendChat('Ravenous IO', '/w gm ' + message); }
|
||||
function whisper(playerId, message) {
|
||||
if (playerIsGM(playerId)) return sendChat('Ravenous IO', '/w gm ' + message);
|
||||
var player = getObj('player', playerId);
|
||||
var name = String(player && player.get('_displayname') || 'player').replace(/"/g, '');
|
||||
sendChat('Ravenous IO', '/w "' + name + '" ' + message);
|
||||
}
|
||||
function grantsAccess(list, playerId) {
|
||||
return String(list || '').split(',').some(function (id) { return id === 'all' || id === playerId; });
|
||||
}
|
||||
function canControl(character, playerId) {
|
||||
return playerIsGM(playerId) || grantsAccess(character && character.get('controlledby'), playerId);
|
||||
}
|
||||
function canReadHandout(handout, playerId) {
|
||||
return playerIsGM(playerId) || grantsAccess(handout && handout.get('controlledby'), playerId) ||
|
||||
grantsAccess(handout && handout.get('inplayerjournals'), playerId);
|
||||
}
|
||||
function validText(value) { return typeof value === 'string' && value.length <= 200000; }
|
||||
function validPayload(data) {
|
||||
if (!data || Array.isArray(data) || typeof data !== 'object' ||
|
||||
|
|
@ -41,13 +57,25 @@
|
|||
.replace(/ /g, ' ').trim();
|
||||
return JSON.parse(text);
|
||||
}
|
||||
function importCharacter(data) {
|
||||
if (!validPayload(data)) return whisper('Invalid or unsupported Ravenous character JSON.');
|
||||
var character = createObj('character', { name: data.name.trim(),
|
||||
controlledby: data.controlledby || '', inplayerjournals: data.inplayerjournals || '' });
|
||||
if (!character) return whisper('Roll20 could not create the character.');
|
||||
if (data.bio) character.set('bio', data.bio);
|
||||
if (data.gmnotes) character.set('gmnotes', data.gmnotes);
|
||||
function readHandout(handout, isGM, callback) {
|
||||
if (!isGM) return handout.get('notes', callback);
|
||||
handout.get('gmnotes', function (gmnotes) {
|
||||
if (String(gmnotes || '').trim()) return callback(gmnotes);
|
||||
handout.get('notes', callback);
|
||||
});
|
||||
}
|
||||
function populateCharacter(character, data, replace, isGM, playerId) {
|
||||
if (replace) {
|
||||
findObjs({ type: 'attribute', characterid: character.id }).forEach(function (item) { item.remove(); });
|
||||
findObjs({ type: 'ability', characterid: character.id }).forEach(function (item) { item.remove(); });
|
||||
}
|
||||
character.set('name', data.name.trim());
|
||||
character.set('bio', data.bio || '');
|
||||
if (isGM) {
|
||||
character.set('gmnotes', data.gmnotes || '');
|
||||
character.set('controlledby', data.controlledby || '');
|
||||
character.set('inplayerjournals', data.inplayerjournals || '');
|
||||
}
|
||||
data.attributes.forEach(function (item) {
|
||||
createObj('attribute', { characterid: character.id, name: item.name,
|
||||
current: item.current, max: item.max });
|
||||
|
|
@ -56,11 +84,28 @@
|
|||
createObj('ability', { characterid: character.id, name: item.name,
|
||||
action: item.action, istokenaction: item.istokenaction });
|
||||
});
|
||||
whisper('Imported ' + data.attributes.length + ' attributes into character ' + character.id + '.');
|
||||
whisper(playerId, (replace ? 'Replaced ' : 'Imported ') + data.attributes.length +
|
||||
' attributes in character ' + character.id + '.');
|
||||
}
|
||||
function exportCharacter(id) {
|
||||
function importCharacter(data, playerId, targetId) {
|
||||
if (!validPayload(data)) return whisper(playerId, 'Invalid or unsupported Ravenous character JSON.');
|
||||
if (targetId) {
|
||||
var target = getObj('character', targetId);
|
||||
if (!target) return whisper(playerId, 'Character not found.');
|
||||
if (!canControl(target, playerId)) return whisper(playerId, 'Permission denied for that character.');
|
||||
return populateCharacter(target, data, true, playerIsGM(playerId), playerId);
|
||||
}
|
||||
if (!playerIsGM(playerId)) return whisper(playerId, 'Only a GM can create a new character. Use --replace on a character you control.');
|
||||
var character = createObj('character', { name: data.name.trim(),
|
||||
controlledby: data.controlledby || '', inplayerjournals: data.inplayerjournals || '' });
|
||||
if (!character) return whisper(playerId, 'Roll20 could not create the character.');
|
||||
populateCharacter(character, data, false, true, playerId);
|
||||
}
|
||||
function exportCharacter(id, playerId) {
|
||||
var character = getObj('character', id);
|
||||
if (!character) return whisper('Character not found. Use its Roll20 character ID.');
|
||||
if (!character) return whisper(playerId, 'Character not found. Use its Roll20 character ID.');
|
||||
if (!canControl(character, playerId)) return whisper(playerId, 'Permission denied for that character.');
|
||||
var isGM = playerIsGM(playerId);
|
||||
character.get('bio', function (bio) {
|
||||
character.get('gmnotes', function (gmnotes) {
|
||||
var attributes = findObjs({ type: 'attribute', characterid: id }).map(function (item) {
|
||||
|
|
@ -76,53 +121,84 @@
|
|||
var data = { format: FORMAT, version: VERSION, name: character.get('name'),
|
||||
controlledby: character.get('controlledby') || '',
|
||||
inplayerjournals: character.get('inplayerjournals') || '',
|
||||
bio: bio || '', gmnotes: gmnotes || '', attributes: attributes,
|
||||
bio: bio || '', gmnotes: isGM ? gmnotes || '' : '', attributes: attributes,
|
||||
abilities: abilities };
|
||||
var handout = createObj('handout', { name: 'Ravenous export - ' + data.name,
|
||||
inplayerjournals: '', controlledby: '' });
|
||||
if (!handout) return whisper('Roll20 could not create the export handout.');
|
||||
inplayerjournals: isGM ? '' : playerId, controlledby: isGM ? '' : playerId });
|
||||
if (!handout) return whisper(playerId, 'Roll20 could not create the export handout.');
|
||||
var readable = JSON.stringify(data, null, 2).replace(/&/g, '&')
|
||||
.replace(/</g, '<').replace(/>/g, '>');
|
||||
handout.set('gmnotes', '<pre>' + readable + '</pre>');
|
||||
whisper('Exported ' + attributes.length + ' attributes to GM handout ' + handout.id + '.');
|
||||
handout.set(isGM ? 'gmnotes' : 'notes', '<pre>' + readable + '</pre>');
|
||||
whisper(playerId, 'Exported ' + attributes.length + ' attributes to handout ' + handout.id + '.');
|
||||
});
|
||||
});
|
||||
}
|
||||
function selectedCharacterId(message) {
|
||||
var selected = message.selected || [];
|
||||
if (selected.length !== 1 || selected[0]._type !== 'graphic') {
|
||||
whisper('Select one token representing a character, or use !ravenous-export --id CHARACTER_ID.');
|
||||
whisper(message.playerid, 'Select one token representing a character, or use --id CHARACTER_ID.');
|
||||
return '';
|
||||
}
|
||||
var token = getObj('graphic', selected[0]._id);
|
||||
var id = token && token.get('represents');
|
||||
if (!id) whisper('The selected token does not represent a character.');
|
||||
if (!id) whisper(message.playerid, 'The selected token does not represent a character.');
|
||||
return id || '';
|
||||
}
|
||||
function importArguments(input) {
|
||||
var result = { replace: false, id: '', handout: '', json: '' };
|
||||
var rest = input.trim();
|
||||
while (rest.indexOf('--') === 0) {
|
||||
var flag = rest.match(/^--replace(?:\s+|$)/);
|
||||
if (flag) {
|
||||
if (result.replace) return null;
|
||||
result.replace = true;
|
||||
rest = rest.slice(flag[0].length);
|
||||
continue;
|
||||
}
|
||||
var option = rest.match(/^--(id|handout)\s+(\S+)\s*/);
|
||||
if (!option || result[option[1]]) return null;
|
||||
result[option[1]] = option[2];
|
||||
rest = rest.slice(option[0].length);
|
||||
}
|
||||
result.json = rest;
|
||||
if (!!result.handout === !!result.json || (!result.replace && result.id)) return null;
|
||||
return result;
|
||||
}
|
||||
on('chat:message', function (message) {
|
||||
if (message.type !== 'api' || !playerIsGM(message.playerid)) return;
|
||||
if (message.type !== 'api') return;
|
||||
var content = message.content.trim();
|
||||
if (content === '!ravenous-export') {
|
||||
var selectedId = selectedCharacterId(message);
|
||||
if (selectedId) return exportCharacter(selectedId);
|
||||
if (selectedId) return exportCharacter(selectedId, message.playerid);
|
||||
return;
|
||||
}
|
||||
if (content.indexOf('!ravenous-export ') === 0) {
|
||||
var argument = content.slice('!ravenous-export '.length).trim();
|
||||
if (argument.indexOf('--id ') === 0) argument = argument.slice('--id '.length).trim();
|
||||
return exportCharacter(argument);
|
||||
return exportCharacter(argument, message.playerid);
|
||||
}
|
||||
if (content.indexOf('!ravenous-import ') !== 0) return;
|
||||
var input = content.slice('!ravenous-import '.length).trim();
|
||||
if (input.indexOf('--handout ') === 0) {
|
||||
var handout = getObj('handout', input.slice('--handout '.length).trim());
|
||||
if (!handout) return whisper('Handout not found.');
|
||||
return handout.get('gmnotes', function (notes) {
|
||||
try { importCharacter(decodeHandout(notes)); }
|
||||
catch (error) { whisper('Handout does not contain valid Ravenous JSON.'); }
|
||||
var args = importArguments(content.slice('!ravenous-import '.length));
|
||||
if (!args) return whisper(message.playerid, 'Invalid import command.');
|
||||
if (!playerIsGM(message.playerid) && !args.replace)
|
||||
return whisper(message.playerid, 'Only a GM can create a new character. Use --replace.');
|
||||
var targetId = '';
|
||||
if (args.replace) {
|
||||
targetId = args.id || selectedCharacterId(message);
|
||||
if (!targetId) return;
|
||||
if (!canControl(getObj('character', targetId), message.playerid))
|
||||
return whisper(message.playerid, 'Permission denied for that character.');
|
||||
}
|
||||
if (args.handout) {
|
||||
var handout = getObj('handout', args.handout);
|
||||
if (!handout) return whisper(message.playerid, 'Handout not found.');
|
||||
if (!canReadHandout(handout, message.playerid)) return whisper(message.playerid, 'Permission denied for that handout.');
|
||||
return readHandout(handout, playerIsGM(message.playerid), function (notes) {
|
||||
try { importCharacter(decodeHandout(notes), message.playerid, targetId); }
|
||||
catch (error) { whisper(message.playerid, 'Handout does not contain valid Ravenous JSON.'); }
|
||||
});
|
||||
}
|
||||
try { importCharacter(JSON.parse(input)); }
|
||||
catch (error) { whisper('Invalid JSON.'); }
|
||||
try { importCharacter(JSON.parse(args.json), message.playerid, targetId); }
|
||||
catch (error) { whisper(message.playerid, 'Invalid JSON.'); }
|
||||
});
|
||||
}());
|
||||
|
|
|
|||
|
|
@ -33,14 +33,25 @@ done
|
|||
[ "$list_themes" -eq 1 ] && exit 0
|
||||
|
||||
example="$output_dir/example-character.json"
|
||||
craft_forge="$output_dir/example-craft-forge.json"
|
||||
craft_alchemy="$output_dir/example-craft-alchemy.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
|
||||
temporary_dir=$(mktemp -d)
|
||||
trap 'rm -rf "$temporary_dir"' EXIT HUP INT TERM
|
||||
uv run python tools/generate_character.py --seed 20260919 --output "$temporary_dir/example-character.json" >/dev/null
|
||||
uv run python tools/generate_crafts.py --output-dir "$temporary_dir" >/dev/null
|
||||
if ! cmp -s "$temporary_dir/example-character.json" "$example"; then
|
||||
echo "$example is missing or differs from the seeded character fixture" >&2
|
||||
exit 1
|
||||
fi
|
||||
for craft in "$craft_forge" "$craft_alchemy"; do
|
||||
name=${craft##*/}
|
||||
if ! cmp -s "$temporary_dir/$name" "$craft"; then
|
||||
echo "$craft is missing or differs from the generated craft fixture" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
else
|
||||
uv run python tools/generate_character.py --seed 20260919 --output "$example"
|
||||
uv run python tools/generate_crafts.py --output-dir "$output_dir"
|
||||
fi
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import json
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
|
@ -16,7 +17,9 @@ class BuildTests(unittest.TestCase):
|
|||
expected = {"ravenous.html", "ravenous.css", "translation.json", "sheet.json", "build-info.json"}
|
||||
actual = {path.name for path in (ROOT / "build").iterdir()}
|
||||
self.assertTrue(expected.issubset(actual))
|
||||
self.assertLessEqual(actual - expected, {"example-character.json"})
|
||||
self.assertLessEqual(actual - expected, {
|
||||
"example-character.json", "example-craft-forge.json", "example-craft-alchemy.json"
|
||||
})
|
||||
|
||||
def test_source_data_was_imported(self):
|
||||
info = json.loads((ROOT / "build/build-info.json").read_text())
|
||||
|
|
@ -245,6 +248,19 @@ class BuildTests(unittest.TestCase):
|
|||
self.assertNotIn("{{THEME_VARS}}", css)
|
||||
self.assertNotIn("{{THEME_CSS}}", css)
|
||||
|
||||
def test_export_can_choose_initial_ui_theme(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
command = ["python", "tools/build.py", "--theme-ui", "steel", "--output-dir", directory]
|
||||
subprocess.run(command, cwd=ROOT, check=True, capture_output=True)
|
||||
sheet = (Path(directory) / "ravenous.html").read_text()
|
||||
css = (Path(directory) / "ravenous.css").read_text()
|
||||
info = json.loads((Path(directory) / "build-info.json").read_text())
|
||||
self.assertIn('<option value="steel" selected>', sheet)
|
||||
self.assertIn('name="attr_theme_state" value="steel"', sheet)
|
||||
self.assertIn(".ravenous-sheet,.sheet-rolltemplate-ravenous { --ink:#292b32", css)
|
||||
self.assertEqual("steel", info["default_theme"])
|
||||
subprocess.run(command + ["--check"], cwd=ROOT, check=True, capture_output=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ function session() {
|
|||
type,
|
||||
get(key, callback) { const value = data[key] ?? ''; if (callback) callback(value); else return value; },
|
||||
set(key, value) { data[key] = value; },
|
||||
remove() { objects.delete(object.id); },
|
||||
data,
|
||||
};
|
||||
objects.set(object.id, object);
|
||||
|
|
@ -92,6 +93,62 @@ test('inline JSON imports a character, while non-GM and invalid input do not', (
|
|||
assert.match(game.chat.at(-1).content, /Imported 1 attributes/);
|
||||
});
|
||||
|
||||
test('a player can export and replace a controlled character in place', () => {
|
||||
const game = session();
|
||||
game.createObj('player', { _displayname: 'Alice' }).id = 'player';
|
||||
const character = game.createObj('character', { name: 'Avant', bio: 'Ancienne bio',
|
||||
gmnotes: 'Secret MJ', controlledby: 'player', inplayerjournals: 'player' });
|
||||
const token = game.createObj('graphic', { represents: character.id });
|
||||
game.createObj('attribute', { characterid: character.id, name: 'force', current: '2', max: '' });
|
||||
game.createObj('attribute', { characterid: character.id, name: 'obsolete', current: 'oui', max: '' });
|
||||
game.createObj('ability', { characterid: character.id, name: 'Ancienne', action: '/em test', istokenaction: false });
|
||||
|
||||
game.send('!ravenous-export', 'player', [{ _type: 'graphic', _id: token.id }]);
|
||||
const exported = [...game.objects.values()].find(obj => obj.type === 'handout');
|
||||
assert.equal(exported.get('controlledby'), 'player');
|
||||
assert.equal(exported.get('gmnotes'), '');
|
||||
assert.match(exported.get('notes'), /"gmnotes": ""/);
|
||||
|
||||
const replacement = { format: 'ravenous-roll20-character', version: 1, name: 'Après',
|
||||
bio: 'Nouvelle bio', gmnotes: 'Tentative joueur', controlledby: 'intrus', inplayerjournals: 'intrus',
|
||||
attributes: [{ name: 'force', current: '9', max: '' }],
|
||||
abilities: [{ name: 'Nouvelle', action: '/em nouveau', istokenaction: true }] };
|
||||
exported.set('notes', `<pre>${JSON.stringify(replacement)}</pre>`);
|
||||
game.send(`!ravenous-import --replace --handout ${exported.id}`, 'player',
|
||||
[{ _type: 'graphic', _id: token.id }]);
|
||||
|
||||
assert.equal(character.get('name'), 'Après');
|
||||
assert.equal(character.get('bio'), 'Nouvelle bio');
|
||||
assert.equal(character.get('gmnotes'), 'Secret MJ');
|
||||
assert.equal(character.get('controlledby'), 'player');
|
||||
assert.equal(character.get('inplayerjournals'), 'player');
|
||||
assert.equal(token.get('represents'), character.id);
|
||||
const attrs = [...game.objects.values()].filter(obj => obj.type === 'attribute' &&
|
||||
obj.get('characterid') === character.id);
|
||||
assert.deepEqual(attrs.map(obj => [obj.get('name'), obj.get('current')]), [['force', '9']]);
|
||||
const abilities = [...game.objects.values()].filter(obj => obj.type === 'ability' &&
|
||||
obj.get('characterid') === character.id);
|
||||
assert.deepEqual(abilities.map(obj => obj.get('name')), ['Nouvelle']);
|
||||
assert.match(game.chat.at(-1).content, /Replaced 1 attributes/);
|
||||
});
|
||||
|
||||
test('players cannot export or replace characters and handouts they cannot access', () => {
|
||||
const game = session();
|
||||
const player = game.createObj('player', { _displayname: 'Alice' });
|
||||
const other = game.createObj('character', { name: 'Autre', controlledby: 'someone-else' });
|
||||
const token = game.createObj('graphic', { represents: other.id });
|
||||
const payload = { format: 'ravenous-roll20-character', version: 1,
|
||||
name: 'Intrusion', attributes: [] };
|
||||
const privateHandout = game.createObj('handout', { controlledby: 'someone-else',
|
||||
notes: JSON.stringify(payload) });
|
||||
game.send('!ravenous-export', player.id, [{ _type: 'graphic', _id: token.id }]);
|
||||
game.send(`!ravenous-import --replace --handout ${privateHandout.id}`, player.id,
|
||||
[{ _type: 'graphic', _id: token.id }]);
|
||||
assert.equal(other.get('name'), 'Autre');
|
||||
assert.equal([...game.objects.values()].filter(obj => obj.type === 'handout').length, 1);
|
||||
assert.match(game.chat.at(-1).content, /Permission denied/);
|
||||
});
|
||||
|
||||
test('a GM can import JSON pasted into a handout and HTML escaped by Roll20', () => {
|
||||
const game = session();
|
||||
const json = JSON.stringify({ format: 'ravenous-roll20-character', version: 1,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,27 @@
|
|||
import json
|
||||
import unittest
|
||||
|
||||
from tools.generate_crafts import CRAFTS, render
|
||||
|
||||
|
||||
class CraftGeneratorTests(unittest.TestCase):
|
||||
def test_examples_cover_every_import_destination(self):
|
||||
payloads = list(CRAFTS.values())
|
||||
self.assertEqual({"attack", "protection", "consumable", "modifier"}, {
|
||||
item["type"] for payload in payloads for item in payload["items"]
|
||||
})
|
||||
for payload in payloads:
|
||||
self.assertEqual("ravenous-roll20-craft", payload["format"])
|
||||
self.assertEqual(1, payload["version"])
|
||||
self.assertTrue(payload["items"])
|
||||
self.assertTrue(all(item.get("name") for item in payload["items"]))
|
||||
|
||||
def test_render_is_stable_utf8_json(self):
|
||||
for payload in CRAFTS.values():
|
||||
rendered = render(payload)
|
||||
self.assertEqual(payload, json.loads(rendered))
|
||||
self.assertIn("—", rendered)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -4,6 +4,8 @@ import { test } from 'node:test';
|
|||
import vm from 'node:vm';
|
||||
|
||||
const script = readFileSync(new URL('../roll20_mod/ravenous_craft_import.js', import.meta.url), 'utf8');
|
||||
const craftFixtures = ['example-craft-forge.json', 'example-craft-alchemy.json'].map(name =>
|
||||
JSON.parse(readFileSync(new URL(`../build/${name}`, import.meta.url), 'utf8')));
|
||||
|
||||
function session() {
|
||||
const objects = new Map();
|
||||
|
|
@ -59,6 +61,20 @@ test('imports all supported craft item types into a selected character', () => {
|
|||
assert.match(game.chat.at(-1).content, /Imported 4 craft item/);
|
||||
});
|
||||
|
||||
test('generated craft fixtures import into all supported repeating sections', () => {
|
||||
const game = session();
|
||||
const character = game.createObj('character', { name: 'Fixture' });
|
||||
const token = game.createObj('graphic', { represents: character.id });
|
||||
for (const fixture of craftFixtures) {
|
||||
game.send(`!ravenous-import-craft ${JSON.stringify(fixture)}`, 'gm',
|
||||
[{ _type: 'graphic', _id: token.id }]);
|
||||
}
|
||||
const names = attributes(game, character.id).map(attribute => attribute.get('name'));
|
||||
for (const section of ['attacks', 'protections', 'consumables', 'modifiers']) {
|
||||
assert.ok(names.some(name => name.startsWith(`repeating_${section}_`)), section);
|
||||
}
|
||||
});
|
||||
|
||||
test('supports explicit character and HTML-escaped handout JSON', () => {
|
||||
const game = session();
|
||||
const character = game.createObj('character', { name: 'Arangar' });
|
||||
|
|
|
|||
|
|
@ -395,6 +395,7 @@ def skill_target_options(skills: list[dict[str, str]]) -> str:
|
|||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--check", action="store_true", help="fail when build/ differs from generated output")
|
||||
parser.add_argument("--theme-ui", help="initial/fallback UI theme for this export")
|
||||
parser.add_argument("--list-themes", action="store_true", help="list color themes from the book and exit")
|
||||
parser.add_argument("--output-dir", type=Path, default=BUILD, help="directory for generated files (default: build/)")
|
||||
args = parser.parse_args()
|
||||
|
|
@ -404,7 +405,7 @@ def main() -> None:
|
|||
return
|
||||
data = read_character_data()
|
||||
config = read_build_config()
|
||||
default_theme = config["document"]["color_scheme"]
|
||||
default_theme = args.theme_ui or config["document"]["color_scheme"]
|
||||
if default_theme not in palettes:
|
||||
parser.error(f"unknown default theme {default_theme!r}; choose from: {', '.join(palettes)}")
|
||||
output_dir = args.output_dir
|
||||
|
|
|
|||
|
|
@ -0,0 +1,79 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Generate deterministic Ravenous craft payloads for Roll20 import tests."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
CRAFTS = {
|
||||
"example-craft-forge.json": {
|
||||
"format": "ravenous-roll20-craft",
|
||||
"version": 1,
|
||||
"craft": {
|
||||
"name": "Panoplie de la braise",
|
||||
"discipline": "Forge",
|
||||
"element": "Feu",
|
||||
"recipe": "Acier; Affilage; Cendre draconique",
|
||||
"level": 3,
|
||||
"difficulty": 2,
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"type": "attack", "name": "Lame de braise", "dice": 5,
|
||||
"threshold": 6, "temp": 0, "base_damage": 8,
|
||||
"damage_per_success": 2, "break_damage": 1, "rmax": 3,
|
||||
"dodge_threshold": 7, "parry_threshold": 5,
|
||||
"reposition_threshold": 2,
|
||||
"notes": "Test d'import — dégâts de Feu; portée courte.",
|
||||
},
|
||||
{
|
||||
"type": "protection", "name": "Targe de scories",
|
||||
"protection": 3, "integrity": 5, "integrity_max": 5,
|
||||
"parry": 1, "dodge": -1,
|
||||
"effects": "Test d'import — chaude au toucher, à activer manuellement.",
|
||||
},
|
||||
],
|
||||
},
|
||||
"example-craft-alchemy.json": {
|
||||
"format": "ravenous-roll20-craft",
|
||||
"version": 1,
|
||||
"craft": {
|
||||
"name": "Nécessaire de veille",
|
||||
"discipline": "Alchimie",
|
||||
"element": "Céleste",
|
||||
"recipe": "Rosée lunaire; Sel d'argent",
|
||||
"level": 2,
|
||||
"difficulty": 1,
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"type": "consumable", "name": "Élixir de veille",
|
||||
"kind": "Potion", "quantity": 2, "duration": "3 tours",
|
||||
"description": "Test d'import — dissipe la somnolence et éclaire faiblement.",
|
||||
},
|
||||
{
|
||||
"type": "modifier", "name": "Clarté lunaire",
|
||||
"duration": "3 tours",
|
||||
"description": "Test d'import — bonus temporaire à configurer manuellement.",
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def render(payload: dict) -> str:
|
||||
return json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output-dir", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
args.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
for name, payload in CRAFTS.items():
|
||||
(args.output_dir / name).write_text(render(payload), encoding="utf-8")
|
||||
print(f"Generated {len(CRAFTS)} craft fixtures in {args.output_dir}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loading…
Reference in New Issue