Skip to content

Commit

Permalink
feat(docs): Add updating info
Browse files Browse the repository at this point in the history
BREAKING CHANGE: See README for breaking change information for v1
  • Loading branch information
derikb committed Dec 27, 2021
1 parent 10ce4c2 commit e6820b6
Show file tree
Hide file tree
Showing 16 changed files with 123 additions and 60 deletions.
79 changes: 62 additions & 17 deletions README.md
Expand Up @@ -30,6 +30,8 @@ Modules for randomization focused on tables used in roleplaying games.

These are models and logic only, there is no ui and only the most limited of view data. No functions are provided for the organization or storage of table data.

**If you were using pre-v1 release see the upgrading notes at the bottom of this file.**

## Code Example

A simple example setting up a very basic unweighted table (with no subtables), then "rolling" on it, and also generating a dice roll and two random names:
Expand Down Expand Up @@ -107,6 +109,29 @@ console.log(result.die); // '1d6'
```

Add the name token to a table roller:

```
import TableRoller from './TableRoller.js';
import RandomNameGenerator from './RandomNameGenerator.js';
import names from '../sample/names.js';
// Instantiate the TableRoller
const tableRoller = new TableRoller({});
// Format name data
const nameTypes = [];
names.forEach((data) => {
nameTypes.push(new RandomNameType(data));
});
// Create a default name generator.
const defaultNameGenerator = new RandomNameGenerator({ namedata: nameTypes });
// Assign it to the name token of the table roller.
// Bind it to the name generator (else it won't work)
tableRoller.registerTokenType('name', defaultNameGenerator.nameTokenCallback.bind(defaultNameGenerator));
```

Other more complicated (and useful) operations are possible. See below.

## Motivation
Expand Down Expand Up @@ -134,13 +159,11 @@ The `sample` directory includes a few example data sources. A simple way to hand

## API Reference

The module exposes a few objects and constructors.

**This is under construction as I refactor.**
The module includes a number of classes and functions. In general files with CamelCasing are exporting a single class, while those with snake_case are exporting one or more functions.

### randomizer

Utility classes for random selection/generation.
Utility classes for random selection/generation. Mostly used internally by the other classes.

#### randomInteger (min, max)

Expand All @@ -155,7 +178,7 @@ Utility classes for random selection/generation.
- @param {Array} _weights_ array of weighted numbers to correspond to the values array
- @return {String|Number|Object} a randomly selected element from the values array

This is mostly used internally. Returns a randomly selected element from the values array, where the randomization is weighted based on the weights array.
Returns a randomly selected element from the values array, where the randomization is weighted based on the weights array.

```
//a classic bell curve reaction table
Expand All @@ -182,7 +205,7 @@ getWeightedRandom(values, weights); // returns a reaction from the value array
- @param {String[]} _data_ Array of strings to select from.
- @returns {String} the randomly selected string

Takes an array of strings and returns one of the element's value randomly.
Takes an array of strings and returns one of the strings randomly.

```
const data = [
Expand All @@ -198,6 +221,8 @@ randomString(data); // returns one of the reactions

### dice_roller

Some simple dice like randomization functions.

#### rollDie (string)

* @params {String} string a die roll notation
Expand Down Expand Up @@ -230,10 +255,7 @@ Get a DiceResult object.

### TableRoller

Exported from the TableRoller.js file.

A class used for generating random results from tables.

A class used for generating random results from RandomTable objects. Also handling for tokens in the results.

#### getTableResultSetByKey (tableKey, table)

Expand All @@ -259,7 +281,7 @@ This is one of two primary ways to generate results from the RandomTable objects
- @param {String} _[start='']_ subtable to roll on
- @return {RandomTableResult[]}

Takes a RandomTable object and returns an array of results. If RandomTable.sequence is set, multiple results may be returned. Optionally a specific subtable can be selected to select from. This is basically a wrapper for selectFromTable() that may, depending on the RandomTable's properties, concatenate multiple selectFromTable() results.
Takes a RandomTable object and returns an array of results. If RandomTable.sequence is set, multiple results may be returned. Optionally a specific subtable can be selected to select from.

```
const table_config = {
Expand Down Expand Up @@ -320,6 +342,12 @@ Will throw TableError if key is empty or a RandomTable object is not found.
Register a custom token type for use in tables.

```
/**
* @param {Array} token_parts Parts of token when brackets are removed and it is then split by the colon
* @param {String} full_token Full original token. If the token fails generally just return the full_token back.
* @param {RandomTable|null} current_table The table the currently processed entry/token came from (or null).
* @returns {Any} Always return something that has a toString() method.
*/
const footoken = function (token_parts, full_token, current_table) {
return token_parts[1] + ' with big red eyes';
}
Expand Down Expand Up @@ -349,6 +377,8 @@ In most cases it is not necessary to call this method directly, getTableResult()

Takes a result value, finds, and replaces any tokens in it.

Unlike convertToken this will find multiple tokens in a string and will always return the original entryLabel with tokens replaced by strings (or the original token if an error occurs).


### RandomTable

Expand Down Expand Up @@ -402,14 +432,13 @@ Return entries for a subtable

Get an entry in case we only have the label and need other data from it.

Warning: if your label had tokens you need to base on the original token, not a replaced version.

#### findDependencies

* @returns {Array} array of table keys that the current table calls on (via tokens)

This method returns an array of table keys that the current table refers to in `{{table:SOMETABLE}}` tokens. Can be useful for making sure you have all the tables necessary to return full results from the current table.



This method returns an array of table keys that the current table refers to in `{{table:SOMETABLE}}` tokens. Can be useful for making sure you have all the tables necessary to return full results from the current table. This will also look in the macros property.


### DisplayOptions
Expand Down Expand Up @@ -458,7 +487,7 @@ If it's the default (sub)table.

#### isError

If it's an error result.
If it's an error result, this will be an instance of the TableErrorResult class (which is otherwise identical to the parent class).

### RandomTableResultSet

Expand Down Expand Up @@ -798,9 +827,25 @@ I'm not going to document these now, but the methods are:
- This is a custom toJSON function for classes that handles Maps and converts them to objects.


## Upgrading to v1

There are a number of breaking changes in the v1 release. I think/hope these changes make things a little more consistent and versatile.

Here are at least some of the changes to note:

- More classes added and all existing classes have been moved to their own file/export (they are all in CamelCase).
- Dice functions have been revamped and moved to their own export (dice_roller.js) (The old roll method on the randomizer has been removed.)
- The random name generator is now a class (RandomNameGenerator) and no longer requires the old randomizer class. (This way you could have different name generators and give them different tokens for use in a TableRoller.)
- Name data is now used via the RandomNameType class. See index.js for how that works.
- The old Randomizer class is now TableRoller class. A number of lower level methods have been moved out of that class (to the randomizer.js file).
- The basic format for random table data should not have changed.
- NPCs will now generate their own UUID.
- A number of Error classes have been added, most of the time they will be thrown and caught internally (generator a TableErrorResult), but note there are places where a method may throw something specific (the docblocks should specify this).


## Contributors

I'd be happy to accept feature requests, bug reports, and pull requests via the github repository. There is an eslint config file for style, which can be run on the code via `npm run eslint:src`
I'd be happy to accept feature requests, bug reports, and pull requests via the github repository. There is an eslint config file for style, and tests (via mocha) are in the test directory.

## License

Expand Down
6 changes: 4 additions & 2 deletions docs/tableformat.md
Expand Up @@ -41,7 +41,7 @@ To roll on subtables of the current table use `{{table:this:SUBTABLE_NAME}}`

### Generate a Name

`{{name:NAMETYPE:GENDER:STYLE}}` will insert a name into the table. `nametype` is required and should be one of the name lists keys ('flemish', 'dutch', etc. from RandomNameGenerator::getValidNameTypes) or "random". `gender` is optional and can be male, female, or random. If left blank, only a surname will be generated. `style` is optional and only accepts the value "first", in which case only a first name will be generated.
`{{name:NAMETYPE:GENDER:STYLE}}` will insert a name into the table. `nametype` is required and should be one of the name lists keys ('flemish', 'dutch', etc. from RandomNameGenerator::getValidNameTypes) or "random". `gender` is optional and can be "mixed", "male", "female", or "random". If left blank, it will default to "mixed". `style` is optional and only accepts the value "first", in which case only a first name will be generated.

### Custom token

Expand All @@ -56,6 +56,8 @@ I've tried to build in an escalating scale of complexity. Simple tables can be f

I've tried to build in as much forgiveness as possible into the format.

The RandomTable class will convert any entries on the table/subtables to RandomTableEntry objects on initialization.

### Simple unweighted table

A basic list of options with no extra information.
Expand Down Expand Up @@ -110,7 +112,7 @@ The `subtable` property in a result can have a number of properties that effect
* @property {String} _description_ an elaboration on the label that can be used when outputting/displaying results
* @property {Boolean} _print_ should this result be included in various result outputs (good for use with the subtable property where you only want the result on the subtable to be displayed/output)

Here's an example using these various properties. The default table is rolled on first (it is weighted so in this case humanoids are most common). The result of the default table decides what subtable should be rolled on next. Some of the subtables then have further subtables to be rolled on (so the "human" subtable will often cause a roll on the "actions_human" subtable).
Here's an example using these various properties. The default table is rolled on first (it is weighted, so in this case humanoids are most common). The result of the default table decides what subtable should be rolled on next. Some of the subtables then have further subtables to be rolled on (so the "human" subtable will often cause a roll on the "actions_human" subtable).

```
"tables": {
Expand Down
2 changes: 1 addition & 1 deletion src/NPC.js
@@ -1,5 +1,5 @@
import { defaultToJSON, isObject } from './r_helpers.js';
import { v4 as uuidv4 } from 'uuid/dist/esm-browser';
import uuidv4 from '../node_modules/uuid/dist/esm-browser/v4.js';

/**
* Class for NPCs
Expand Down
8 changes: 4 additions & 4 deletions src/index.js
@@ -1,14 +1,14 @@
import TableRoller from './TableRoller.js';
import RandomTable from './RandomTable.js';
import normalizeData from './table_normalizer.js';
import * as r_helpers from './r_helpers.js';
import RandomTableEntry from './RandomTableEntry.js';
import RandomNameGenerator from './RandomNameGenerator.js';
import names from '../sample/names.js';
import * as npc_generator from './npc_generator.js';
import NPCSchema from './NPCSchema.js';
import NPCSchemaField from './NPCSchemaField.js';
import * as dice_roller from './dice_roller.js';
import RandomNameType from './RandomNameType.js';
import NPC from './NPC.js';

// Instantiate the TableRoller and set it up with the random name generator.
const tableRoller = new TableRoller({});
Expand All @@ -26,12 +26,12 @@ tableRoller.registerTokenType('name', defaultNameGenerator.nameTokenCallback.bin
export default {
tableRoller,
RandomTable,
normalizeData,
RandomTableEntry,
defaultNameGenerator,
RandomNameGenerator,
RandomNameType,
r_helpers,
npc_generator,
NPC,
NPCSchema,
NPCSchemaField,
dice_roller
Expand Down
2 changes: 1 addition & 1 deletion types/src/DisplayOptions.d.ts
@@ -1,7 +1,7 @@
/**
* Display options for subtable results. Used in RandomTable and RandomTableResultSet
*/
export class DisplayOptions {
export default class DisplayOptions {
/**
*
* @property {String} table Subtable name.
Expand Down
3 changes: 2 additions & 1 deletion types/src/NPCSchema.d.ts
@@ -1,7 +1,7 @@
/**
* Schema for creating NPCs.
*/
export class NPCSchema {
export default class NPCSchema {
/**
* @property {String} key Identifying key
* @property {String} name Name of schema.
Expand Down Expand Up @@ -36,3 +36,4 @@ export class NPCSchema {
*/
toJSON(): any;
}
import NPCSchemaField from "./NPCSchemaField.js";
2 changes: 1 addition & 1 deletion types/src/NPCSchemaField.d.ts
@@ -1,7 +1,7 @@
/**
* Specific field in NPC Schema.
*/
export class NPCSchemaField {
export default class NPCSchemaField {
/**
*
* @property {String} key Identifying key
Expand Down
35 changes: 14 additions & 21 deletions types/src/RandomTable.d.ts
Expand Up @@ -2,7 +2,7 @@
* RandomTable: Model for tables used by TableRoller
* @param {Object} config the tables non-default attributes
*/
export class RandomTable {
export default class RandomTable {
/**
* The primary attributes of this table
* @property {String} id id for the table, primary key for database if used
Expand All @@ -16,14 +16,13 @@ export class RandomTable {
* @property {String[]|Object[]} [table] default table. array of strings or objects. removed after initialization.
* @property {Object} [tables] a property for each subtables.
* @property {RandomTableEntries[]} tables[subtablename] Entries for subtables.
* @property {String[]} [macro] for tables that are only used to aggregate result from other tables, this array consists of table keys to be rolled on in order
* @property {String[]} [macro] for tables that are only used to aggregate result from other tables, this array consists of table keys and optionsl subtables to be rolled on in order
* @property {Map[DisplayOptions]} [display_opt] Display options for the subtables.
* @property @deprecated {Object} [print] Backwards compatible. Key => Object data for display options.
* @property {Array} [dependencies] table keys that are needed to get full results from this table
*
* Note the Constructor args are not exactly the same as the properties. Some type changes are made to convert data.
*/
constructor({ id, key, title, author, description, source, tags, sequence, tables, macro, print, dependencies, table, display_opt }: {
constructor({ id, key, title, author, description, source, tags, sequence, tables, macro, dependencies, table, display_opt }: {
id?: number;
key?: any;
title?: string;
Expand All @@ -34,7 +33,6 @@ export class RandomTable {
sequence?: any[];
tables?: {};
macro?: any[];
print?: {};
dependencies?: any;
table?: any;
display_opt?: any[];
Expand Down Expand Up @@ -71,6 +69,13 @@ export class RandomTable {
* @returns {Object} error information
*/
validate(properties: any): any;
/**
* Basic sequence of table rolls.
* Either the start, the default sequence, the default table, or just the first one.
* @param {String} start Subtable name to start with.
* @returns {String[]}
*/
getSequence(start?: string): string[];
/**
* All the subtable names.
* @returns {String[]}
Expand All @@ -82,25 +87,12 @@ export class RandomTable {
* @returns {RandomTableEntry[]}
*/
getSubtableEntries(name?: string): RandomTableEntry[];
/**
* outputs the json data for the table (import/export)
* @param {Boolean} [editmode=false] if false empty properties will be stripped out
* @returns {Object} table attributes
*/
outputObject(editmode?: boolean): any;
/**
* outputs the json data for the table (import/export)
* @param {Boolean} [editmode=false] if false empty properties will be stripped out
* @param {Boolean} [compress=false] if true JSON will not have indentation, etc.
* @returns {String} table properties in JSON
*/
outputCode(editmode?: boolean, compress?: boolean): string;
/**
* Get a random entry from a subtable.
* @param {String} subtableNames
* @param {String} subtableName
* @returns {RandomTableEntry|null}
*/
getRandomEntry(subtableNames: string): RandomTableEntry | null;
getRandomEntry(subtableName: string): RandomTableEntry | null;
/**
* Get an entry in case we only have the label and need other data from it
* @param {String} label The item we are looking for
Expand All @@ -109,7 +101,7 @@ export class RandomTable {
*/
findEntry(label: string, table?: string): RandomTableEntry | null;
/**
* find the dependent tables to get full results for this table
* Find the dependent tables to get full results for this table
* @return {Array} table keys
*/
findDependencies(): any[];
Expand All @@ -119,3 +111,4 @@ export class RandomTable {
*/
toJSON(): any;
}
import RandomTableEntry from "./RandomTableEntry.js";
2 changes: 1 addition & 1 deletion types/src/RandomTableEntry.d.ts
Expand Up @@ -2,7 +2,7 @@
* Class for entries in a random (sub)table.
* This normalizes the various options into a class that makes the other code simpler.
*/
export class RandomTableEntry {
export default class RandomTableEntry {
/**
*
* @property {String} label Basic string label. Only required field. Can include tokens.
Expand Down
2 changes: 1 addition & 1 deletion types/src/RandomTableResult.d.ts
@@ -1,7 +1,7 @@
/**
* Class for results from RandomTable
*/
export class RandomTableResult {
export default class RandomTableResult {
/**
* @property {String} table Title of subtable.
* @property {String} result Randomized result label.
Expand Down

0 comments on commit e6820b6

Please sign in to comment.