65 lines
1.8 KiB
TypeScript
65 lines
1.8 KiB
TypeScript
import {createModel, Signal, signal} from '@preact/signals-core';
|
|
import {createEntityCollection} from "../utils/entity";
|
|
import {Part} from "./part";
|
|
import {Region} from "./region";
|
|
import {RuleRegistry, RuleContext, dispatchCommand as dispatchRuleCommand} from "./rule";
|
|
|
|
export type Context = {
|
|
type: string;
|
|
}
|
|
|
|
export const GameContext = createModel((root: Context) => {
|
|
const parts = createEntityCollection<Part>();
|
|
const regions = createEntityCollection<Region>();
|
|
const rules = signal<RuleRegistry>(new Map());
|
|
const ruleContexts = signal<RuleContext<unknown>[]>([]);
|
|
const contexts = signal<Signal<Context>[]>([]);
|
|
contexts.value = [signal(root)];
|
|
|
|
function pushContext(context: Context) {
|
|
const ctxSignal = signal(context);
|
|
contexts.value = [...contexts.value, ctxSignal];
|
|
return context;
|
|
}
|
|
|
|
function popContext() {
|
|
if (contexts.value.length > 1) {
|
|
contexts.value = contexts.value.slice(0, -1);
|
|
}
|
|
}
|
|
|
|
function latestContext<T extends Context>(type: T['type']): Signal<T> | undefined {
|
|
for(let i = contexts.value.length - 1; i >= 0; i--){
|
|
if(contexts.value[i].value.type === type){
|
|
return contexts.value[i] as Signal<T>;
|
|
}
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
function dispatchCommand(input: string) {
|
|
return dispatchRuleCommand({
|
|
rules: rules.value,
|
|
ruleContexts: ruleContexts.value,
|
|
contexts,
|
|
}, input);
|
|
}
|
|
|
|
return {
|
|
parts,
|
|
regions,
|
|
rules,
|
|
ruleContexts,
|
|
contexts,
|
|
pushContext,
|
|
popContext,
|
|
latestContext,
|
|
dispatchCommand,
|
|
}
|
|
})
|
|
|
|
/** 创建游戏上下文实例 */
|
|
export function createGameContext(root: Context = { type: 'game' }) {
|
|
return new GameContext(root);
|
|
}
|