Started splitting engine tests into individual files and testing action props

This commit is contained in:
Thaum Rystra
2024-02-15 23:16:18 +02:00
parent 60117308f7
commit 5b7d352323
13 changed files with 1190 additions and 807 deletions

View File

@@ -1,6 +1,7 @@
{
"cSpell.words": [
"autorun",
"Crits",
"cyrb",
"EJSON",
"uncomputed"

View File

@@ -5,7 +5,7 @@
accounts-password@2.4.0
random@1.2.1
underscore@1.0.13
underscore@1.6.0
dburles:mongo-collection-instances
accounts-google@1.4.0
email@2.2.5
@@ -22,7 +22,7 @@ standard-minifier-js@2.8.1
shell-server@0.5.0
ecmascript@0.16.8
es5-shim@4.8.0
service-configuration@1.3.2
service-configuration@1.3.3
dynamic-import@0.7.3
ddp-rate-limiter@1.2.1
rate-limit@1.1.1

View File

@@ -1 +1 @@
METEOR@2.14
METEOR@2.15

View File

@@ -1,4 +1,4 @@
accounts-base@2.2.9
accounts-base@2.2.10
accounts-google@1.4.0
accounts-oauth@1.4.3
accounts-password@2.4.0
@@ -9,7 +9,7 @@ akryum:vue-component-dev-client@0.4.7
akryum:vue-component-dev-server@0.1.4
akryum:vue-router2@0.2.3
aldeed:collection2@3.5.0
aldeed:schema-index@3.0.0
aldeed:schema-index@3.1.0
allow-deny@1.1.1
autoupdate@1.8.0
babel-compiler@7.10.5
@@ -55,7 +55,7 @@ littledata:synced-cron@1.5.1
localstorage@1.2.0
logging@1.3.3
mdg:validated-method@1.3.0
meteor@1.11.4
meteor@1.11.5
meteor-base@1.5.1
meteortesting:browser-tests@1.4.2
meteortesting:mocha@2.1.0
@@ -103,7 +103,7 @@ reload@1.3.1
retry@1.1.0
routepolicy@1.1.1
seba:minifiers-autoprefixer@2.0.1
service-configuration@1.3.2
service-configuration@1.3.3
session@1.2.1
sha@1.0.9
shell-server@0.5.0
@@ -120,9 +120,9 @@ templating-tools@1.2.2
tmeasday:check-npm-versions@1.0.2
tracker@1.3.3
typescript@4.9.5
underscore@1.0.13
underscore@1.6.1
url@1.3.2
webapp@1.13.6
webapp@1.13.8
webapp-hashing@1.1.1
zer0th:meteor-vuetify-loader@0.1.41
zodern:fix-async-stubs@1.0.2

View File

@@ -1,4 +1,6 @@
import { getSingleProperty } from '/imports/api/engine/loadCreatures';
import array from '/imports/parser/parseTree/constant';
import constant from '/imports/parser/parseTree/constant';
//set up the collection for creature variables
let CreatureVariables = new Mongo.Collection('creatureVariables');
@@ -34,4 +36,54 @@ export function getFromScope(name, scope) {
return value;
}
export function getNumberFromScope(name, scope) {
const parseNode = getParseNodeFromScope(name, scope);
if (!parseNode || parseNode.valueType !== 'number') {
return undefined;
}
return parseNode.value;
}
export function getParseNodeFromScope(name, scope) {
let value = getFromScope(name, scope);
if (!value) return;
let valueType = getType(value);
// Iterate into object.values
while (valueType === 'object') {
// Prefer the valueNode over the value
if (value.valueNode) {
value = value.valueNode;
} else {
value = value.value;
}
valueType = getType(value);
}
// Return a discovered parse node
if (valueType === 'parseNode') {
return value;
}
// Return a parse node based on the constant type returned
if (valueType === 'string' || valueType === 'number' || valueType === 'boolean') {
return constant.create({ value });
}
// Return a parser array
if (valueType === 'array') {
// If the first value is a parse node, assume all the values are
if (getType(value[0]) === 'parseNode') {
return array.create({
values: value,
});
}
// Create the array from js primitives instead
return array.fromConstantArray(value);
}
}
function getType(val) {
if (!val) return typeof val;
if (Array.isArray(val)) return 'array';
if (val.parseType) return 'parseNode';
return typeof val;
}
export default CreatureVariables;

View File

@@ -0,0 +1,152 @@
import { assert } from 'chai';
import {
allMutations,
createTestCreature,
randomIds,
removeAllCreaturesAndProps,
runActionById
} from '/imports/api/engine/action/functions/actionEngineTest.testFn';
const [
creatureId, targetCreatureId, targetCreature2Id,
emptyActionId, attackActionId, usesActionId, attackMissId,
] = randomIds;
const actionTestCreature = {
_id: creatureId,
props: [
// Empty
{
_id: emptyActionId,
type: 'action',
},
// Attack that hits
{
_id: attackActionId,
type: 'action',
attackRoll: { calculation: '10' },
},
// Attack that misses
{
_id: attackMissId,
type: 'action',
attackRoll: { calculation: '-20' },
},
// Disable crits
{
type: 'attribute',
attributeType: 'stat',
variableName: '~criticalHitTarget',
baseValue: { calculation: '21' },
},
{
type: 'attribute',
attributeType: 'stat',
variableName: '~criticalMissTarget',
baseValue: { calculation: '0' },
},
// Has uses
{
_id: usesActionId,
type: 'action',
uses: { calculation: '3' },
usesUsed: 1,
reset: 'longRest',
},
],
}
const actionTargetCreature = {
_id: targetCreatureId,
props: [
{
type: 'attribute',
attributeType: 'stat',
variableName: 'armor',
baseValue: { calculation: '10' },
}
]
}
const actionTargetCreature2 = {
_id: targetCreature2Id,
props: [
{
type: 'attribute',
attributeType: 'stat',
variableName: 'armor',
baseValue: { calculation: '10' },
}
]
}
describe('Apply Action Properties', function () {
// Increase timeout
this.timeout(8000);
before(async function () {
await removeAllCreaturesAndProps();
await createTestCreature(actionTestCreature);
await createTestCreature(actionTargetCreature);
await createTestCreature(actionTargetCreature2);
});
it('should run empty actions', async function () {
const action = await runActionById(emptyActionId);
assert.exists(action);
assert.deepEqual(allMutations(action), [{
contents: [{ name: 'Action' }],
targetIds: [],
}]);
});
it('should make attack rolls against multiple creatures', async function () {
const action = await runActionById(attackActionId, [
targetCreatureId,
targetCreature2Id,
]);
assert.deepEqual(allMutations(action), [{
contents: [{
name: 'Action'
}],
targetIds: [
targetCreatureId,
targetCreature2Id,
]
}, {
contents: [{
inline: true,
name: 'Hit!',
value: '1d20 [10] + 10\n**20**',
}],
targetIds: [targetCreatureId],
}, {
contents: [{
inline: true,
name: 'Hit!',
value: '1d20 [10] + 10\n**20**',
}],
targetIds: [targetCreature2Id],
}]);
});
it('should make attack rolls that miss', async function () {
const action = await runActionById(attackMissId, [targetCreatureId]);
assert.deepEqual(allMutations(action), [{
contents: [{
name: 'Action'
}],
targetIds: [
targetCreatureId,
]
}, {
contents: [{
inline: true,
name: 'Miss!',
value: '1d20 [10] + 10\n**20**',
}],
targetIds: [targetCreatureId],
}]);
});
});

View File

@@ -1,7 +1,7 @@
import { EngineAction } from '/imports/api/engine/action/EngineActions';
import { PropTask } from '../tasks/Task';
import TaskResult, { LogContent } from '../tasks/TaskResult';
import { getPropertiesOfType } from '/imports/api/engine/loadCreatures';
import { getPropertiesOfType, getVariables } from '/imports/api/engine/loadCreatures';
import applyTask from '/imports/api/engine/action/tasks/applyTask';
import getPropertyTitle from '/imports/api/utility/getPropertyTitle';
import recalculateInlineCalculations from '/imports/api/engine/action/functions/recalculateInlineCalculations';
@@ -11,6 +11,7 @@ import recalculateCalculation from '/imports/api/engine/action/functions/recalcu
import { getEffectiveActionScope } from '/imports/api/engine/action/functions/getEffectiveActionScope';
import numberToSignedString from '/imports/api/utility/numberToSignedString';
import rollDice from '/imports/parser/rollDice';
import { getFromScope, getNumberFromScope } from '/imports/api/creature/creatures/CreatureVariables';
export default async function applyActionProperty(
task: PropTask, action: EngineAction, result: TaskResult, userInput
@@ -19,7 +20,7 @@ export default async function applyActionProperty(
const targetIds = prop.target === 'self' ? [action.creatureId] : task.targetIds;
//Log the name and summary, check that the property has enough resources to fire
const content: LogContent = { name: prop.name };
const content: LogContent = { name: getPropertyTitle(prop) };
if (prop.summary?.text) {
await recalculateInlineCalculations(prop.summary, action);
content.value = prop.summary.value;
@@ -52,10 +53,10 @@ export default async function applyActionProperty(
// Attack if there is an attack roll
if (attack && attack.calculation) {
if (targetIds.length) {
for (const target of targetIds) {
await applyAttackToTarget(action, prop, attack, targetIds, result, userInput);
await applyAfterTriggers(action, prop, [target], userInput);
await applyChildren(action, prop, [target], userInput);
for (const targetId of targetIds) {
await applyAttackToTarget(task, action, attack, targetId, result);
await applyAfterTriggers(action, prop, [targetId], userInput);
await applyChildren(action, prop, [targetId], userInput);
}
} else {
await applyAttackWithoutTarget(action, prop, attack, result, userInput);
@@ -74,7 +75,9 @@ export default async function applyActionProperty(
return await applyAfterChildrenTriggers(action, prop, targetIds, userInput);
}
async function applyAttackToTarget(action, prop, attack, target, taskResult: TaskResult, userInput) {
async function applyAttackToTarget(
task: PropTask, action: EngineAction, attack, targetId, taskResult: TaskResult
) {
taskResult.pushScope = {
'~attackHit': {},
'~attackMiss': {},
@@ -94,12 +97,13 @@ async function applyAttackToTarget(action, prop, attack, target, taskResult: Tas
criticalMiss,
} = await rollAttack(attack, scope, taskResult.pushScope);
if (target.variables.armor) {
const armor = target.variables.armor.value;
const targetScope = getVariables(targetId);
const targetArmor = getNumberFromScope('armor', targetScope)
if (Number.isFinite(targetArmor)) {
let name = criticalHit ? 'Critical Hit!' :
criticalMiss ? 'Critical Miss!' :
result > armor ? 'Hit!' : 'Miss!';
result > targetArmor ? 'Hit!' : 'Miss!';
if (scope['~attackAdvantage']?.value === 1) {
name += ' (Advantage)';
} else if (scope['~attackAdvantage']?.value === -1) {
@@ -110,10 +114,10 @@ async function applyAttackToTarget(action, prop, attack, target, taskResult: Tas
name,
value: `${resultPrefix}\n**${result}**`,
inline: true,
silenced: prop.silent,
...task.prop.silent && { silenced: true },
});
if (criticalMiss || result < armor) {
if (criticalMiss || result < targetArmor) {
scope['~attackMiss'] = { value: true };
} else {
scope['~attackHit'] = { value: true };
@@ -123,18 +127,18 @@ async function applyAttackToTarget(action, prop, attack, target, taskResult: Tas
name: 'Error',
value: 'Target has no `armor`',
inline: true,
silenced: prop.silent,
...task.prop.silent && { silenced: true },
}, {
name: criticalHit ? 'Critical Hit!' : criticalMiss ? 'Critical Miss!' : 'To Hit',
value: `${resultPrefix}\n**${result}**`,
inline: true,
silenced: prop.silent,
...task.prop.silent && { silenced: true },
});
}
if (contents.length) {
taskResult.mutations.push({
contents,
targetIds: [target],
targetIds: [targetId],
});
}
}
@@ -172,7 +176,7 @@ async function applyAttackWithoutTarget(action, prop, attack, taskResult: TaskRe
name,
value: `${resultPrefix}\n**${result}**`,
inline: true,
silenced: prop.silent,
...prop.silent && { silenced: true },
}],
targetIds: [],
});
@@ -211,20 +215,18 @@ async function rollAttack(attack, scope, resultPushScope) {
}
function applyCrits(value, scope, resultPushScope) {
let scopeCrit = scope['~criticalHitTarget']?.value;
if (scopeCrit?.parseType === 'constant') {
scopeCrit = scopeCrit.value;
}
const criticalHitTarget = scopeCrit || 20;
const scopeCritTarget = getNumberFromScope('~criticalHitTarget', scope);
const criticalHitTarget = Number.isFinite(scopeCritTarget) ? scopeCritTarget : 20;
const scopeCritMissTarget = getNumberFromScope('~criticalMissTarget', scope);
const criticalMissTarget = Number.isFinite(scopeCritMissTarget) ? scopeCritMissTarget : 1;
const criticalHit = value >= criticalHitTarget;
let criticalMiss;
const criticalMiss = value <= criticalMissTarget;
if (criticalHit) {
resultPushScope['~criticalHit'] = { value: true };
} else {
criticalMiss = value === 1;
if (criticalMiss) {
resultPushScope['~criticalMiss'] = { value: true };
}
} else if (criticalMiss) {
resultPushScope['~criticalMiss'] = { value: true };
}
return { criticalHit, criticalMiss };
}
@@ -266,7 +268,7 @@ async function resetProperties(action: EngineAction, prop: any, result: TaskResu
name: getPropertyTitle(act),
value: act.usesUsed >= 0 ? `Restored ${act.usesUsed} uses` : `Removed ${-act.usesUsed} uses`,
inline: true,
silenced: prop.silent,
...prop.silent && { silenced: true },
}]
});
}

View File

@@ -0,0 +1,150 @@
import { assert } from 'chai';
import '/imports/api/simpleSchemaConfig.js';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import { propsFromForest } from '/imports/api/properties/tests/propTestBuilder.testFn';
import Creatures from '/imports/api/creature/creatures/Creatures';
import CreatureVariables from '/imports/api/creature/creatures/CreatureVariables';
import computeCreature from '/imports/api/engine/computeCreature';
import { loadCreature } from '/imports/api/engine/loadCreatures';
import EngineActions, { EngineAction } from '/imports/api/engine/action/EngineActions';
import { applyAction } from '/imports/api/engine/action/functions/applyAction';
import { LogContent, Mutation, Removal, Update } from '/imports/api/engine/action/tasks/TaskResult';
/**
* Removes all creatures, properties, and creatureVariable documents from the database
*/
export async function removeAllCreaturesAndProps() {
return Promise.all([
CreatureProperties.removeAsync({}),
Creatures.removeAsync({}),
CreatureVariables.removeAsync({}),
]);
}
/**
* Creates a test creature with all its props computed and loaded into memory
* You may need to set the timeout of a test higher for this function to conclude
* as it is inserting and reading potentially many database documents
*/
export async function createTestCreature(creature: TestCreature) {
const dummySubscription = Tracker.autorun(() => undefined)
await Creatures.insertAsync({
_id: creature._id,
name: creature.name || 'Test Creature',
owner: Random.id(),
dirty: true,
});
const propsInserted = propsFromForest(creature.props, creature._id).map(prop => {
return CreatureProperties.insertAsync(prop);
});
await Promise.all(propsInserted);
loadCreature(creature._id, dummySubscription);
await computeCreature(creature._id,);
}
type TestCreature = {
_id: string;
name?: string;
props: any[];
}
/**
* A list of 100 random Ids
*/
export const randomIds = new Array(100).fill(undefined).map(() => Random.id());
/**
* Creates a new Engine Action and applies the specified creature property
* @param propId The _id of the property, any property that the engine can apply will work
* @param userInputFn A function that simulates user input
* @returns The Engine Action with mutations resulting from running the action
*/
export async function runActionById(propId, targetIds?, userInputFn = () => 0) {
const prop = await CreatureProperties.findOneAsync(propId);
const actionId = await createAction(prop, targetIds);
const action = await EngineActions.findOneAsync(actionId);
if (!action) throw 'Action is expected to exist';
await applyAction(action, userInputFn, { simulate: true });
return action;
}
/**
* Creates and inserts a new Engine Action into the database
* @param prop The property to start applying
* @param targetIds A list of target ids
* @returns Promise< id of the inserted Engine Action >
*/
function createAction(prop: any, targetIds?: string[]) {
const action: EngineAction = {
creatureId: prop.root.id,
rootPropId: prop._id,
results: [],
taskCount: 0,
targetIds,
};
return EngineActions.insertAsync(action);
}
/**
* Get all the mutations in the results of an engineAction
*/
export function allMutations(action: EngineAction) {
const mutations: Mutation[] = [];
action.results.forEach(result => {
result.mutations.forEach(mutation => {
mutations.push(mutation);
});
});
return mutations;
}
/**
* Get all the updates in all mutations in the result of an Engine Action
*/
export function allUpdates(action: EngineAction) {
const updates: Update[] = [];
allMutations(action).forEach(mutation => {
mutation.updates?.forEach(update => {
updates.push(update);
});
});
return updates;
}
/**
* Get all the inserts in all mutations in the result of an Engine Action
*/
export function allInserts(action: EngineAction) {
const inserts: any[] = [];
allMutations(action).forEach(mutation => {
mutation.inserts?.forEach(update => {
inserts.push(update);
});
});
return inserts;
}
/**
* Get all the removals in all mutations in the result of an Engine Action
*/
export function allRemovals(action: EngineAction) {
const removals: Removal[] = [];
allMutations(action).forEach(mutation => {
mutation.removals?.forEach(update => {
removals.push(update);
});
});
return removals
}
/**
* Get all the log content in all mutations in the result of an Engine Action
*/
export function allLogContent(action: EngineAction) {
const contents: LogContent[] = [];
allMutations(action).forEach(mutation => {
mutation.contents?.forEach(logContent => {
contents.push(logContent);
});
});
return contents;
}

View File

@@ -30,7 +30,7 @@ export default async function spendResources(
if (prop.resources?.attributesConsumed?.length) {
for (const att of prop.resources.attributesConsumed) {
const scope = await getEffectiveActionScope(action);
const statToDamage = getFromScope(att.variableName, scope);
const statToDamage = await getFromScope(att.variableName, scope);
await recalculateCalculation(att.quantity, action, 'reduce');
await applyTask(action, {
prop,

View File

@@ -7,6 +7,7 @@ export default function computeVariableAsConstant(computation, node, prop) {
try {
parseNode = parse(string);
} catch (e) {
console.error(e);
return;
}
prop.value = parseNode;

View File

@@ -1,5 +1,5 @@
import accessor from './accessor';
import array from './array';
import array from './array.js';
import call from './call';
import constant from './constant';
import error from './error';
@@ -12,7 +12,7 @@ import roll from './roll';
import rollArray from './rollArray';
import unaryOperator from './unaryOperator';
export default Object.freeze({
export default {
accessor,
array,
call,
@@ -28,4 +28,4 @@ export default Object.freeze({
// What used to be symbols are now just treated as accessors without a path
symbol: accessor,
unaryOperator,
});
};

1539
app/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -20,11 +20,11 @@
"npm": "6.13.x"
},
"dependencies": {
"@babel/runtime": "^7.23.7",
"@babel/runtime": "^7.23.9",
"@chenfengyuan/vue-countdown": "^1.1.5",
"@tozd/vue-observer-utils": "^0.5.0",
"@types/meteor": "^2.9.7",
"aws-sdk": "^2.1528.0",
"@types/meteor": "^2.9.8",
"aws-sdk": "^2.1559.0",
"bcrypt": "^5.1.1",
"chroma-js": "^2.4.2",
"css-box-shadow": "^1.0.0-3",
@@ -36,7 +36,7 @@
"ddp-rate-limiter-mixin": "^1.1.10",
"discord.js": "^12.5.3",
"dompurify": "^2.4.7",
"ignore": "^5.3.0",
"ignore": "^5.3.1",
"ignore-styles": "^5.0.1",
"lodash": "^4.17.20",
"marked": "^4.3.0",
@@ -49,7 +49,7 @@
"pretty-bytes": "^6.1.1",
"qrcode.vue": "^1.7.0",
"request": "^2.88.2",
"sharp": "^0.33.1",
"sharp": "^0.33.2",
"simpl-schema": "^1.13.1",
"source-map-support": "^0.5.21",
"speakingurl": "^14.0.1",
@@ -60,7 +60,7 @@
"vue-reactive-provide": "^0.3.0",
"vue-router": "^3.6.5",
"vuedraggable": "^2.23.2",
"vuetify": "^2.7.1",
"vuetify": "^2.7.2",
"vuetify-upload-button": "^2.0.2",
"vuex": "^3.1.3"
},
@@ -68,9 +68,9 @@
"@types/mocha": "^10.0.6",
"@typescript-eslint/eslint-plugin": "^5.62.0",
"@typescript-eslint/parser": "^5.62.0",
"@vue/compiler-dom": "^3.4.2",
"@vue/runtime-dom": "^3.4.2",
"chai": "^4.3.10",
"@vue/compiler-dom": "^3.4.19",
"@vue/runtime-dom": "^3.4.19",
"chai": "^4.4.1",
"eslint": "^7.32.0",
"eslint-plugin-vue": "^7.20.0",
"eslint-plugin-vuetify": "^1.1.0",