Skip to content

Composing Multiple Hooks

Combine multiple hooks to create powerful abstractions.

export function withGameState(scene: Phaser.Scene) {
const player = withPlayer(scene);
const inventory = withInventory(scene);
const quests = withQuests(scene);
return {
player,
inventory,
quests
};
}
// Usage
const game = withGameState(this);
game.player.takeDamage(10);
game.inventory.addItem('sword');
game.quests.complete('tutorial');
export function withCombatStats(scene: Phaser.Scene) {
const player = withPlayer(scene);
const equipment = withEquipment(scene);
return {
totalAttack: () => {
const p = player.get();
const eq = equipment.get();
return p.baseAttack + eq.weapon.attack + eq.armor.bonus;
},
totalDefense: () => {
const p = player.get();
const eq = equipment.get();
return p.baseDefense + eq.armor.defense + eq.shield.block;
},
canEquip: (item: Item) => {
const p = player.get();
return p.level >= item.requiredLevel;
}
};
}
export function withGameActions(scene: Phaser.Scene) {
const player = withPlayer(scene);
const enemies = withEnemies(scene);
const ui = withUI(scene);
return {
attack: (enemyId: string) => {
const damage = calculateDamage(player.get(), enemies.getEnemy(enemyId));
enemies.damageEnemy(enemyId, damage);
ui.showDamageNumber(enemyId, damage);
player.gainExp(10);
},
usePotion: () => {
const inventory = withInventory(scene);
if (inventory.hasItem('potion')) {
inventory.removeItem('potion');
player.heal(50);
ui.showHealEffect();
}
}
};
}
export function withGame(scene: Phaser.Scene) {
// Global state (persists across scenes)
const settings = withSettings(scene);
const progress = withGameProgress(scene);
// Local state (scene-specific)
const player = withPlayer(scene);
const level = withLevel(scene);
return {
settings,
progress,
player,
level,
// Coordinated methods
completeLevel: (score: number) => {
progress.unlockLevel(level.get().number + 1);
progress.setHighScore(level.get().number, score);
progress.patch({ currentLevel: level.get().number + 1 });
// Navigate to next level
scene.scene.start('LevelSelectScene');
}
};
}