Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -929,6 +929,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

### Under the hood

- **PLAYERS CHANGE GEAR, on the server.** A table setting (on to start) for systems with their own item types: switched off, the server keeps every column of a player's gear lines as it was saved, and a thing a player adds comes without column values, while their names, counts and where they carry things still change. The GM can always change them. The GAME tab's switch and the sheet's side come next.
- **Who changed a gear line from its item, and when.** When a line named like one of a system's items is given a value of its own in a column (the Cutlass made 2d8), the server now notes who changed it and when: the player from their sheet, or the GM on a player's or an NPC's. It is worked out from what was saved before, never taken from the sheet, kept while the value stays, and dropped when it is put back to the item's. The sheet shows this as UNIQUE next.
- **A stress test for the shops.** 200 items and a 1500-line catalogue, saved, sent to players, bought from with a 100-line cart and sold to with 300 lines at once, each within a time limit; and a 1000-line shelf opened, filtered and sorted in a real browser.
- **Condition rolls asked of the player, or the GM for an NPC, on the server (8a9a2).** A condition's EACH TURN set to be rolled by the player is now asked of them when it fires (and of the GM for an NPC), said in the dice log, and kept until rolled, even across a reload. Rolled, it does what the table's roll would and the log says who rolled it ("rolled by KES", "rolled by the GM"). Only that player or the GM may roll a player's, and only the GM an NPC's; two clicks roll it once. An ask goes when its condition comes off, when a newer turn asks again, or when the fight ends. Where a token is in two fights, the log names the scene. The ROLL buttons on the sheet and the tracker come with 8a9c.
Expand Down
10 changes: 5 additions & 5 deletions README.md

Large diffs are not rendered by default.

8 changes: 5 additions & 3 deletions backend/__tests__/system_builder_band_conditions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,14 @@ describe("the GAME tab's switches a system has (8a6b)", () => {
return runtime.render(ID).switches;
};
it('encumbrance counted, a band naming a condition, a condition APPLIED: each its own', async () => {
expect(await switchesOf(LADEN)).toEqual({ encumbrance: true, band_conditions: true, applied_conditions: false, turn_effects: false });
expect(await switchesOf(LADEN)).toEqual({ encumbrance: true, band_conditions: true, applied_conditions: false, turn_effects: false, gear: true });
const plain = { ...LADEN, items: { ...LADEN.items, encumbrance: { column: 'weight', capacity: '10' } } };
expect(await switchesOf(plain)).toEqual({ encumbrance: true, band_conditions: false, applied_conditions: false, turn_effects: false });
expect(await switchesOf(plain)).toEqual({ encumbrance: true, band_conditions: false, applied_conditions: false, turn_effects: false, gear: true });
const { encumbrance, ...noCount } = LADEN.items;
const applied = { ...LADEN, items: noCount, conditions: { ...LADEN.conditions, slowed: { ...LADEN.conditions.slowed, applied: true, modifiers: [{ target: 'might', amount: -1 }] } } };
expect(await switchesOf(applied)).toEqual({ encumbrance: false, band_conditions: false, applied_conditions: true, turn_effects: false });
expect(await switchesOf(applied)).toEqual({ encumbrance: false, band_conditions: false, applied_conditions: true, turn_effects: false, gear: true });
// PLAYERS CHANGE GEAR (G6a): only where the system makes its own item types.
expect((await switchesOf({ ...LADEN, items: { list: [{ id: 'pack', label: 'Pack' }] } })).gear).toBe(false);
// CONDITION TURN EFFECTS (8a9c): where a condition has an EACH TURN; ending at the end of its next turn alone switches nothing.
const burning = { burning: { name: 'Burning', each_turn: [{ when: 'turn_start', does: 'damage', roll: '1' }] } };
expect((await switchesOf({ ...LADEN, items: noCount, conditions: { ...LADEN.conditions, ...burning } })).turn_effects).toBe(true);
Expand Down
79 changes: 78 additions & 1 deletion backend/__tests__/system_builder_unique_lines.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { drain, until } from './helpers/until.js';

process.env.JWT_SECRET = 'test-secret';
const require_ = createRequire(import.meta.url);
const { withChanges, uniqueColumns } = require_('../systemBuilder/uniqueLines');
const { withChanges, uniqueColumns, keepColumns, PLAYERS_GEAR_SETTING } = require_('../systemBuilder/uniqueLines');
const runtime = require_('../systemBuilder/runtime');
const socketsFactory = require_('../sockets/index.js');

Expand Down Expand Up @@ -164,3 +164,80 @@ describe('kept by every write of the inventory', () => {
expect((await linesOf(`id = ${npc}`))[0].changed).toEqual({ weight: { by: 'gm', gm: true, at: expect.any(String) } });
});
});

describe('PLAYERS CHANGE GEAR off (G6a)', () => {
it('a player\'s lines keep their columns as stored, a new one comes without; name, how many, where and the rest as sent', () => {
const stored = [line('Cutlass', { values: { damage: '2d8' } }), line('Rope')];
const sent = [line('Cutlass', { qty: 2, carry: 'readied', values: { damage: '9d9', range: 'far' } }), line('Rope', { values: { weight: 99 } }), line('A stick', { type: 'weapons', values: { damage: '1d4' } })];
expect(keepColumns(stored, sent)).toEqual([line('Cutlass', { qty: 2, carry: 'readied', values: { damage: '2d8' } }), line('Rope'), line('A stick', { type: 'weapons' })]);
// Found by name where lines moved; a JSON string back as one; unreadable as given.
expect(JSON.parse(keepColumns(JSON.stringify(stored), JSON.stringify([line('Rope'), line('Cutlass', { values: {} })])))).toEqual([line('Rope'), line('Cutlass', { values: { damage: '2d8' } })]);
expect(keepColumns(stored, 'nope')).toBe('nope');
expect(PLAYERS_GEAR_SETTING).toBe('players_change_gear');
});
});

describe('PLAYERS CHANGE GEAR at the table (G6a)', () => {
let db;
let id;

beforeEach(async () => {
db = await makeTestDb();
await run(db, "INSERT INTO global_settings (key, value) VALUES ('game_system', 'cities_without_number')");
const app = express();
app.use(express.json({ limit: '2mb' }));
app.use('/api/systems', require_('../routes/systems.js')(db));
app.use('/api/sheets', require_('../routes/sheets.js')(db, { emit: () => {}, to: () => ({ emit: () => {} }) }));
id = (await request(app).post('/api/systems').set(gm).send({ definition: BLADES })).body.id;
await new Promise((resolve) => runtime.load(db, resolve));
await request(app).post(`/api/systems/${id}/publish`).set(gm);
await request(app).put('/api/sheets/system').set(gm).send({ system: id });
await run(db, 'INSERT INTO character_sheets (username, system, data, is_npc) VALUES (?, ?, ?, 0)',
['kes', id, JSON.stringify({ name: 'Kes', inventory: JSON.stringify([line('Cutlass', { values: { damage: '2d8' } })]) })]);
vi.spyOn(console, 'log').mockImplementation(() => {});
});
afterEach(() => vi.restoreAllMocks());

const connectAs = async (userName, { admin = false } = {}) => {
let connect;
socketsFactory({ on: (e, cb) => { if (e === 'connection') connect = cb; }, emit: () => {}, to: () => ({ emit: () => {} }) },
db, { elevatedUsers: new Set(), emitUpdate: vi.fn(), recordAction: vi.fn() });
const handlers = {};
connect({ id: `pg-${Math.random()}`, on: (e, fn) => { handlers[e] = fn; }, emit: () => {}, broadcast: { emit: () => {} }, use: () => {}, join: () => {}, disconnect: () => {} });
handlers.identify(admin ? { userName, isAdmin: true, token: GM } : userName);
await drain(db);
return handlers;
};
const kesLines = async () => JSON.parse(JSON.parse((await get(db, "SELECT data FROM character_sheets WHERE username = 'kes'")).data).inventory || '[]');
const off = () => run(db, 'INSERT INTO global_settings (key, value) VALUES (?, ?)', [PLAYERS_GEAR_SETTING, '0']);
const write = (handlers, rows) => handlers.updateSheetField({ fieldId: 'inventory', value: JSON.stringify(rows) });

it('off: the player\'s DAMAGE stays as it was, their new line comes without columns, the rest of the write lands', async () => {
await off();
const kes = await connectAs('kes');
write(kes, [line('Cutlass', { qty: 2, values: { damage: '9d9' } }), line('A stick', { type: 'weapons', values: { damage: '1d4' } })]);
await until(async () => (await kesLines()).length === 2, { label: 'written' });
const [cutlass, stick] = await kesLines();
expect(cutlass.qty).toBe(2);
expect(cutlass.values).toEqual({ damage: '2d8' });
expect(stick).toEqual(line('A stick', { type: 'weapons' }));
});

it('off: the GM, on their own socket, still changes it', async () => {
await off();
// The GM playing the character, as the GM: an admin socket.
await run(db, "UPDATE character_sheets SET username = 'gm' WHERE username = 'kes'");
const gmSocket = await connectAs('gm', { admin: true });
write(gmSocket, [line('Cutlass', { values: { damage: '3d8' } })]);
await until(async () => JSON.parse(JSON.parse((await get(db, "SELECT data FROM character_sheets WHERE username = 'gm'")).data).inventory)[0].values.damage === '3d8', { label: 'the GM\'s' });
});

it('on, or never set: the player changes it, as before', async () => {
const kes = await connectAs('kes');
write(kes, [line('Cutlass', { values: { damage: '4d8' } })]);
await until(async () => (await kesLines())[0].values.damage === '4d8', { label: 'never set' });
await run(db, 'INSERT INTO global_settings (key, value) VALUES (?, ?)', [PLAYERS_GEAR_SETTING, '1']);
write(kes, [line('Cutlass', { values: { damage: '5d8' } })]);
await until(async () => (await kesLines())[0].values.damage === '5d8', { label: 'on' });
});
});
12 changes: 10 additions & 2 deletions backend/sockets/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const cyberware = require('../sheets/cyberware');
const { ownToken } = require('../sheets/ownToken');
const sheetRolls = require('../sheets/rolls');
const { rollGear, readGearDice } = require('../systemBuilder/gearRolls');
const { withChanges } = require('../systemBuilder/uniqueLines');
const { withChanges, keepColumns, PLAYERS_GEAR_SETTING } = require('../systemBuilder/uniqueLines');
const rollEngine = require('../sheets/rollEngine');
const sheetAttack = require('../sheets/attack');
const cyberEffects = require('../sheets/cyberwareEffects');
Expand Down Expand Up @@ -1406,6 +1406,11 @@ module.exports = (io, db, { elevatedUsers, emitUpdate, recordAction }) => {
return;
}
if (linkSource) return;
// PLAYERS CHANGE GEAR (G6a): a player's inventory, with the switch off, is asked of the table first; the GM always may.
const gearOff = payload.fieldId === 'inventory' && !isAdminSocket(socket)
? (done) => db.get('SELECT value FROM global_settings WHERE key = ?', [PLAYERS_GEAR_SETTING], (e, row) => done(!e && !!row && row.value === '0'))
: (done) => done(false);
gearOff((keepGear) => {
// Through the queue rather than a bare read-then-write: a GM applying damage to
// this same sheet while the player types would otherwise build its new blob from
// data this edit had already replaced, and one of the two changes would vanish
Expand All @@ -1421,8 +1426,10 @@ module.exports = (io, db, { elevatedUsers, emitUpdate, recordAction }) => {
// A rank past where a new character may start (7f1c2): the GM's to give.
if (!isAdminSocket(socket) && pastStart(customSystems.definitionOf(system), data, payload.fieldId, payload.value)) return undefined;
// The inventory: which lines are their item made unique, and by whom and when (G5a), from what was stored.
// With PLAYERS CHANGE GEAR off, a player's lines keep their columns as stored (G6a).
const sent = keepGear && customSystems.definitionOf(system) ? keepColumns(data.inventory, payload.value) : payload.value;
data[payload.fieldId] = payload.fieldId === 'inventory'
? withChanges(customSystems.definitionOf(system), data.inventory, payload.value, { by: info.userName, gm: isAdminSocket(socket) })
? withChanges(customSystems.definitionOf(system), data.inventory, sent, { by: info.userName, gm: isAdminSocket(socket) })
: payload.value;
// If the changed field is a max, clamp the paired current field.
const curField = sheetTemplates.getMaxPairs(system)[payload.fieldId];
Expand Down Expand Up @@ -1491,6 +1498,7 @@ module.exports = (io, db, { elevatedUsers, emitUpdate, recordAction }) => {
}
}
);
});
});
});

Expand Down
4 changes: 3 additions & 1 deletion backend/systemBuilder/runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ const { partOn, PARTS } = require('./parts');
const { buildingOn, buildingName, catalogueCurrency, ownBuildings } = require('./buildings');
const { currenciesOf } = require('./currencies');
const { conditionsOf } = require('./conditions');
const { ownTypes } = require('./itemTypes');
const { loadTableConditions, tableConditionsOf } = require('./tableConditions');
const { bankOf } = require('./bank');
const { distanceOf } = require('./core');
Expand Down Expand Up @@ -210,10 +211,11 @@ const renderOf = (id, definition, on = new Set()) => ({
items: itemsRenderedOf(definition),
// Which of the GAME tab's switches this system has anything for (8a6b): SHOW ENCUMBRANCE where it counts encumbrance,
// BAND CONDITIONS where a band (or the word past them) names a condition, APPLY CONDITION MODIFIERS where a condition is APPLIED,
// CONDITION TURN EFFECTS where a condition has an EACH TURN (8a9c).
// CONDITION TURN EFFECTS where a condition has an EACH TURN (8a9c), PLAYERS CHANGE GEAR where it makes its own item types (G6a).
switches: {
encumbrance: encumbranceOf(definition) !== null, band_conditions: namesCondition(definition), applied_conditions: conditionsOf(definition).some((c) => c.applied),
turn_effects: conditionsOf(definition).some((c) => Array.isArray(c.each_turn) && c.each_turn.length > 0),
gear: ownTypes(definition),
},
});

Expand Down
53 changes: 41 additions & 12 deletions backend/systemBuilder/uniqueLines.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@
// is still unique, with no one named.
//
// Pure; the sheet writes call it (sockets updateSheetField, the GM's PUT /api/sheets/user/:username and /npcs/:id).
//
// PLAYERS CHANGE GEAR (G6a; decided 2026-11-20, all A: a GAME tab switch, on to start; off, only the GM changes columns,
// players still name, count and move their things; the user: "the GM can still open, view and change things"). Off, a
// player's write keeps every line's column values as stored, and a line they add comes without any: keepColumns.

/** The table's setting (global_settings): '0' switches PLAYERS CHANGE GEAR off. */
const PLAYERS_GEAR_SETTING = 'players_change_gear';

const { typesOf, typeNamed } = require('./itemTypes');

Expand Down Expand Up @@ -46,6 +53,37 @@ const uniqueColumns = (definition, line) => {
return of.type.columns.filter((c) => filled(own[c.id]) && !same(own[c.id], given[c.id])).map((c) => c.id);
};

/**
* The line each of `next` was in `prev`, or null for one that is new: the one in its place where it has the same name, else
* the first unclaimed of its name. Its type needn't match: a line made another type than its item's is no longer the item.
*/
const pairLines = (prev, next) => {
const claimed = new Set();
const fits = (p, line) => isPlainObject(p) && isPlainObject(line) && key(p.name) === key(line.name);
return next.map((line, i) => {
const j = !claimed.has(i) && fits(prev[i], line) ? i : prev.findIndex((p, n) => !claimed.has(n) && fits(p, line));
if (j < 0) return null;
claimed.add(j);
return prev[j];
});
};

/**
* A player's lines with PLAYERS CHANGE GEAR off (G6a): each line's column values as stored for the line it was, none on a
* line that is new; its name, how many, where it is and the rest as sent. In the form given; as given where unreadable.
*/
const keepColumns = (before, after) => {
const next = parse(after);
if (!next) return after;
const was = pairLines(parse(before) || [], next);
const out = next.map((line, i) => {
if (!isPlainObject(line)) return line;
const { values: _typed, ...rest } = line;
return was[i] && isPlainObject(was[i].values) ? { ...rest, values: { ...was[i].values } } : rest;
});
return typeof after === 'string' ? JSON.stringify(out) : out;
};

/**
* The lines `after` as they are to be stored, each with `changed` worked out against `before` (what was stored): `who` is
* { by: username, gm }. In the form given (a JSON string stays one); as given where the system has no definition or the
Expand All @@ -57,21 +95,12 @@ const withChanges = (definition, before, after, who, at = new Date().toISOString
if (!next) return after;
const prev = parse(before) || [];
const stamp = { by: who && typeof who.by === 'string' ? who.by : '', ...(who && who.gm ? { gm: true } : {}), at };
// The line each was before: the one in its place where it has the same name, else the first unclaimed of its name. Its
// type needn't match: a line made another type than its item's is no longer the item, so has no unique columns anyway.
const claimed = new Set();
const fits = (p, line) => isPlainObject(p) && key(p.name) === key(line.name);
const wasOf = (line, i) => {
const j = !claimed.has(i) && fits(prev[i], line) ? i : prev.findIndex((p, n) => !claimed.has(n) && fits(p, line));
if (j < 0) return null;
claimed.add(j);
return prev[j];
};
const wasLines = pairLines(prev, next);
const out = next.map((line, i) => {
if (!isPlainObject(line)) return line;
// What the sheet says was changed is never taken: worked out here alone.
const { changed: _sent, ...rest } = line;
const was = wasOf(rest, i);
const was = wasLines[i];
const kept = was && isPlainObject(was.changed) ? was.changed : {};
const wasOwn = was && isPlainObject(was.values) ? was.values : {};
const changed = {};
Expand All @@ -83,4 +112,4 @@ const withChanges = (definition, before, after, who, at = new Date().toISOString
return typeof after === 'string' ? JSON.stringify(out) : out;
};

module.exports = { withChanges, uniqueColumns, itemOf };
module.exports = { PLAYERS_GEAR_SETTING, withChanges, keepColumns, pairLines, uniqueColumns, itemOf };
Loading