経緯
ゲーム開発のユニットの意思決定周りの実装をしたときにtype周りの理解が浅くて手こずった。
type周りの理解を深めるために実装内容を振り返る。
何がしたかった?
「敵を発見した」等のトリガーから、「敵に近づいて攻撃をする」等の意図(Intent)を生成する処理の実装。
「敵に近づいて攻撃をする」等をIntentTypeとして扱う。
IntentTypeベースで拡張可能にしたかったので、下記の設定をIntentTypeベースに集約
- IntentTypeを生成しうるトリガー一覧
- トリガー、ユニット情報を下に、Intentを生成するかを判別する処理
- 実際にIntentを生成する処理
どう実装したか
ベースのIntentType, Intentのtype定義
// IntentTypeをstringのunionとして定義
type IntentType = "approachingToEnemy" | "attackEnemy";
// IntentTypeごとのPropsを辞書的なtypeとして定義
type IntentTypeProps = {
approachingToEnemy: approachingToEnemyProps["intentTypeProps"];
attackEnemy: attackEnemyProps["intentTypeProps"];
};
// IntentTypeをgeneric typeとして使用し、IntentTypeとPropsを相関させる形でIntentを定義
export type Intent<T extends IntentType = IntentType> = {
type: T;
props: IntentTypeProps[T];
};
IntentTypeごとの設定の定義。
export type IntentTypeConfig<T extends IntentType> = {
// IntentTriggerをoptionalなmapped typesとして使用。
// IntentTypeを生成しうるトリガーだけ設定する
triggers: { [P in IntentTrigger]?: { propsMapper: TriggerPropsToGenerateProps<P, T> } };
generator: IntentTypeGenerator<T>;
};
export type IntentTypeGenerator<T extends IntentType> = {
isGeneratable: (allyUnit: DeployedAttackAllyUnit) => boolean;
generate: (allyUnit: DeployedAttackAllyUnit, props: IntentTypeGenerateProps[T]) => Intent<T>;
};
type IntentTypeGenerateProps = {
approachingToEnemy: approachingToEnemyProps["IntentTypeGenerateProps"];
attackEnemy: {
enemy: Enemy;
};
};
// トリガー周りの定義
export type IntentTrigger = "scannedEnemy";
export type IntentTriggerProps = {
scannedEnemy: { enemies: Enemy[] };
};
export type TriggerPropsToGenerateProps<T extends IntentTrigger, K extends IntentType> = (
triggerProps: IntentTriggerProps[T]
) => IntentTypeGenerateProps[K];
IntentTypeごとの設定
// intentTypes/approachingToEnemy.ts のようにIntentTypeごとにファイルを分ける形
export const approachingToEnemyConfig: IntentTypeConfig<"approachingToEnemy"> = {
triggers: {
scannedEnemy: {
propsMapper: (triggerProps) => ({
enemies: triggerProps.enemies,
}),
},
},
generator: {
isGeneratable: (_) =>
// Implement logic to determine if the intent can be generated
true,
generate: (allyUnit, props) => ({
type: "approachingToEnemy",
props: {
enemy: props.enemies[0],
attackEquipmentTypeId: allyUnit.getAttackEquipmentTypeIds()[0], // TODO: Choose appropriate equipment
},
}),
},
};
// 上記の定義はIntentGenerator上で下記のように使用する
export class IntentGenerator {
private readonly config: { [K in IntentType]: IntentTypeConfig<K> } = {
approachingToEnemy: approachingToEnemyConfig,
attackEnemy: attackEnemyConfig,
};
このような形で、IntentType単位で拡張可能(IntentTypeを追加するときはファイルを追加し、そこに設定を書くだけ)な形で実装できた。
メモ
Typescriptのtype周りのtips
Indexed Access Types
type IntentTypeProps = {
approachingToEnemy: approachingToEnemyProps["intentTypeProps"];
attackEnemy: attackEnemyProps["intentTypeProps"];
};
// []の記法で前にtypeしたものを再利用できる
type foo = IntentTypeProps["approachingToEnemy"];
Mapped Types
type IntentType = "approachingToEnemy" | "attackEnemy";
// 前に定義したunion等のリストをもとに別のtypeを定義
private readonly config: { [K in IntentType]: IntentTypeConfig<K> } = {
approachingToEnemy: approachingToEnemyConfig,
attackEnemy: attackEnemyConfig,
};
Generic type with constraints
// extendsでgeneric typeをIntentTypeに制限
// propsの型をtypeの特定の型と相関させる
export type Intent<T extends IntentType = IntentType> = {
type: T;
props: IntentTypeProps[T];
};
Type narrowingが上手く機能しないケース
おそらくループ内の特定のIntentTypeへの束縛が無くなってしまっていた。
public generate<T extends IntentTrigger>(
trigger: T,
triggerProps: IntentTriggerProps[T],
allyUnit: DeployedAttackAllyUnit
): Intent | null {
const intentTypes = this.getIntentTypesTriggeredBy(trigger);
if (intentTypes.length === 0) {
return null;
}
const intents: Intent[] = [];
for (const intentType of intentTypes) {
const generator = this.config[intentType].generator
if (generator.isGeneratable(allyUnit)) {
const propsMapper = this.config[intentType].triggers[trigger]?.propsMapper;
if (!propsMapper) {
continue;
}
// 第二引数のIntentTypeProps[T] の特定のIntentTypeでのnarrowingが効かず、typeが広がってしまいエラーに
const intent = generator.generate(allyUnit, propsMapper(triggerProps));
intents.push(intent);
}
}
return intents[0] || null; // TODO: Handle multiple intents properly
}
下記のようにpicker関数を使い、ループ内でも特定のIntentTypeに束縛させる形にしたらエラーが解消した。
private pickIntentTypesGenerator<T extends IntentType>(intentType: T): IntentTypeGenerator<T> {
return this.config[intentType].generator;
}
private pickPropsMapper<T extends IntentTrigger, K extends IntentType>(
trigger: T,
intentType: K
): TriggerPropsToGenerateProps<T, K> | null {
const mapper = this.config[intentType].triggers[trigger]?.propsMapper;
return mapper || null;
}