refactor: update Regicide commands and improve code style

This commit is contained in:
hyper 2026-04-23 15:28:45 +08:00
parent d932c2f5e2
commit 2014162819
2 changed files with 561 additions and 531 deletions

View File

@ -1,20 +1,15 @@
import { IGameContext } from "@/core/game";
import { RegicideState } from "@/samples/regicide/state";
import {createGameCommandRegistry} from "@/core/game";
import { PlayerType, RegicideCard } from "@/samples/regicide/types";
import { CARD_VALUES, FACE_CARDS } from "@/samples/regicide/constants";
import { isEnemyDefeated } from "@/samples/regicide/utils";
export type RegicideGame = IGameContext<RegicideState>;
export const registry = createGameCommandRegistry<RegicideState>();
/**
*
*/
const playCmd = registry.register({
schema: 'play <player:string> <cardId:string>',
run: async (game: RegicideGame, player: string, cardId: string) => {
async function playCmd(game: RegicideGame, player: string, cardId: string) {
const state = game.value;
const card = state.cards[cardId];
@ -26,12 +21,15 @@ const playCmd = registry.register({
const playerKey = player as PlayerType;
const playerHand = state.playerHands[playerKey];
if (!playerHand || !playerHand.includes(cardId)) {
return {success: false, error: `卡牌 ${cardId} 不在玩家 ${player} 的手牌中`};
return {
success: false,
error: `卡牌 ${cardId} 不在玩家 ${player} 的手牌中`,
};
}
// 检查是否有当前敌人
if (!state.currentEnemy) {
return {success: false, error: '没有活跃的敌人'};
return { success: false, error: "没有活跃的敌人" };
}
// 计算伤害(基础伤害为卡牌面值)
@ -39,24 +37,27 @@ const playCmd = registry.register({
let attackReduction = 0;
// 梅花双倍伤害
if (card.suit === 'clubs') {
if (card.suit === "clubs") {
damage *= 2;
}
// 黑桃降低敌人攻击力
if (card.suit === 'spades') {
if (card.suit === "spades") {
attackReduction = card.value;
}
const enemyHpBefore = state.currentEnemy.hp;
await game.produce(state => {
await game.produceAsync((state) => {
// 对敌人造成伤害
state.currentEnemy!.hp -= damage;
// 记录黑桃的攻击力降低
if (attackReduction > 0) {
state.currentEnemy!.value = Math.max(0, state.currentEnemy!.value - attackReduction);
state.currentEnemy!.value = Math.max(
0,
state.currentEnemy!.value - attackReduction,
);
}
// 从手牌移除卡牌
@ -67,15 +68,17 @@ const playCmd = registry.register({
}
// 将卡牌移到弃牌堆
state.cards[cardId].regionId = 'discardPile';
state.cards[cardId].regionId = "discardPile";
// 红心能力:将弃牌堆洗回酒馆牌堆
if (card.suit === 'hearts') {
const discardIds = state.regions.discardPile.childIds.filter(id => id !== state.currentEnemy!.id);
if (card.suit === "hearts") {
const discardIds = state.regions.discardPile.childIds.filter(
(id) => id !== state.currentEnemy!.id,
);
if (discardIds.length > 0) {
// 将弃牌堆(除当前敌人外)移回酒馆牌堆
for (const discardId of discardIds) {
state.cards[discardId].regionId = 'tavernDeck';
state.cards[discardId].regionId = "tavernDeck";
}
state.regions.tavernDeck.childIds.push(...discardIds);
state.regions.discardPile.childIds = [state.currentEnemy!.id];
@ -83,7 +86,7 @@ const playCmd = registry.register({
}
// 方块能力:从酒馆牌堆抓牌
if (card.suit === 'diamonds') {
if (card.suit === "diamonds") {
const tavernDeckCount = state.regions.tavernDeck.childIds.length;
if (tavernDeckCount > 0) {
const drawCardId = state.regions.tavernDeck.childIds.shift()!;
@ -104,28 +107,30 @@ const playCmd = registry.register({
enemyHpBefore,
enemyHpAfter: game.value.currentEnemy!.hp,
enemyDefeated,
suitAbility: card.suit
}
suitAbility: card.suit,
},
};
}
});
/**
* A配合另一张牌
*/
const playWithACmd = registry.register({
schema: 'play-with-a <player:string> <aceCardId:string> <otherCardId:string>',
run: async (game: RegicideGame, player: string, aceCardId: string, otherCardId: string) => {
async function playWithACmd(
game: RegicideGame,
player: string,
aceCardId: string,
otherCardId: string,
) {
const state = game.value;
const aceCard = state.cards[aceCardId];
const otherCard = state.cards[otherCardId];
if (!aceCard || !otherCard) {
return {success: false, error: '卡牌不存在'};
return { success: false, error: "卡牌不存在" };
}
// 检查是否是A牌
if (aceCard.rank !== 'A') {
if (aceCard.rank !== "A") {
return { success: false, error: `第一张牌必须是A` };
}
@ -134,36 +139,39 @@ const playWithACmd = registry.register({
// 检查两张牌都在手牌中
if (!playerHand.includes(aceCardId) || !playerHand.includes(otherCardId)) {
return {success: false, error: '卡牌不在手牌中'};
return { success: false, error: "卡牌不在手牌中" };
}
if (!state.currentEnemy) {
return {success: false, error: '没有活跃的敌人'};
return { success: false, error: "没有活跃的敌人" };
}
// 计算两张牌的总伤害
let totalDamage = aceCard.value + otherCard.value;
// 如果另一张牌是梅花,双倍伤害
if (otherCard.suit === 'clubs') {
if (otherCard.suit === "clubs") {
totalDamage *= 2;
}
let attackReduction = 0;
if (aceCard.suit === 'spades') {
if (aceCard.suit === "spades") {
attackReduction += aceCard.value;
}
if (otherCard.suit === 'spades') {
if (otherCard.suit === "spades") {
attackReduction += otherCard.value;
}
await game.produce(state => {
await game.produceAsync((state) => {
// 对敌人造成伤害
state.currentEnemy!.hp -= totalDamage;
// 记录黑桃的攻击力降低
if (attackReduction > 0) {
state.currentEnemy!.value = Math.max(0, state.currentEnemy!.value - attackReduction);
state.currentEnemy!.value = Math.max(
0,
state.currentEnemy!.value - attackReduction,
);
}
// 从手牌移除两张牌
@ -174,8 +182,8 @@ const playWithACmd = registry.register({
if (otherIndex !== -1) hand.splice(otherIndex, 1);
// 将卡牌移到弃牌堆
state.cards[aceCardId].regionId = 'discardPile';
state.cards[otherCardId].regionId = 'discardPile';
state.cards[aceCardId].regionId = "discardPile";
state.cards[otherCardId].regionId = "discardPile";
});
const enemyDefeated = isEnemyDefeated(state.currentEnemy);
@ -186,33 +194,31 @@ const playWithACmd = registry.register({
damage: totalDamage,
attackReduction,
enemyHp: state.currentEnemy!.hp,
enemyDefeated
}
enemyDefeated,
},
};
}
});
/**
*
*/
const passCmd = registry.register({
schema: 'pass <player:string>',
run: async (game: RegicideGame, player: string) => {
async function passCmd(game: RegicideGame, player: string) {
// 即使让过,也会受到敌人反击(在回合结束时处理)
return { success: true, result: { message: `${player} 让过` } };
}
});
/**
* - >=
*/
const enemyCounterattackCmd = registry.register({
schema: 'counterattack <player:string> <discardCards:string[]>',
run: async (game: RegicideGame, player: string, discardCards: string[]) => {
async function enemyCounterattackCmd(
game: RegicideGame,
player: string,
discardCards: string[],
) {
const state = game.value;
if (!state.currentEnemy) {
return {success: false, error: '没有活跃的敌人'};
return { success: false, error: "没有活跃的敌人" };
}
const playerKey = player as PlayerType;
@ -240,19 +246,19 @@ const enemyCounterattackCmd = registry.register({
if (totalValue < enemyAttack) {
return {
success: false,
error: `弃牌点数和 (${totalValue}) 小于敌人攻击力 (${enemyAttack}),游戏失败`
error: `弃牌点数和 (${totalValue}) 小于敌人攻击力 (${enemyAttack}),游戏失败`,
};
}
// 执行弃牌
await game.produce(state => {
await game.produceAsync((state) => {
const hand = state.playerHands[playerKey];
for (const cardId of discardCards) {
const index = hand.indexOf(cardId);
if (index !== -1) {
hand.splice(index, 1);
}
state.cards[cardId].regionId = 'discardPile';
state.cards[cardId].regionId = "discardPile";
}
});
@ -261,22 +267,19 @@ const enemyCounterattackCmd = registry.register({
result: {
discardedCards: discardCards,
totalValue,
enemyAttack
}
enemyAttack,
},
};
}
});
/**
*
*/
const checkEnemyDefeatedCmd = registry.register({
schema: 'check-enemy',
run: async (game: RegicideGame) => {
async function checkEnemyDefeatedCmd(game: RegicideGame) {
const state = game.value;
if (!state.currentEnemy) {
return {success: false, error: '没有活跃的敌人'};
return { success: false as const, error: "没有活跃的敌人" };
}
const defeated = state.currentEnemy.hp <= 0;
@ -284,7 +287,7 @@ const checkEnemyDefeatedCmd = registry.register({
if (defeated) {
const defeatedEnemy = { ...state.currentEnemy };
await game.produce(state => {
await game.produceAsync((state) => {
// 将当前敌人移到弃牌堆
state.regions.discardPile.childIds.push(state.currentEnemy!.id);
@ -300,20 +303,20 @@ const checkEnemyDefeatedCmd = registry.register({
// 检查是否胜利(没有更多敌人)
if (!game.value.currentEnemy) {
await game.produce(state => {
state.phase = 'victory';
await game.produceAsync((state) => {
state.phase = "victory";
state.winner = true;
});
}
return {
success: true,
success: true as const,
result: {
defeated: true,
defeatedEnemy,
nextEnemy: game.value.currentEnemy,
enemiesRemaining: game.value.enemyDeck.length
}
enemiesRemaining: game.value.enemyDeck.length,
},
};
}
@ -322,26 +325,23 @@ const checkEnemyDefeatedCmd = registry.register({
result: {
defeated: false,
currentEnemy: { ...state.currentEnemy },
enemiesRemaining: state.enemyDeck.length
}
enemiesRemaining: state.enemyDeck.length,
},
};
}
});
/**
*
*/
const checkCanPlayCmd = registry.register({
schema: 'check-can-play <player:string>',
run: async (game: RegicideGame, player: string) => {
async function checkCanPlayCmd(game: RegicideGame, player: string) {
const state = game.value;
const playerKey = player as PlayerType;
const playerHand = state.playerHands[playerKey];
const canPlay = playerHand.length > 0;
const canPlayWithA = playerHand.some(cardId => {
const canPlayWithA = playerHand.some((cardId) => {
const card = state.cards[cardId];
return card && card.rank === 'A' && playerHand.length > 1;
return card && card.rank === "A" && playerHand.length > 1;
});
return {
@ -349,27 +349,26 @@ const checkCanPlayCmd = registry.register({
result: {
canPlay,
canPlayWithA,
handSize: playerHand.length
}
handSize: playerHand.length,
},
};
}
});
/**
*
*/
const checkTavernDeckCmd = registry.register({
schema: 'check-tavern-deck',
run: async (game: RegicideGame) => {
async function checkTavernDeckCmd(game: RegicideGame) {
const state = game.value;
const isEmpty = state.regions.tavernDeck.childIds.length === 0;
// 如果酒馆牌堆为空且所有玩家手牌也为空,则游戏失败
if (isEmpty) {
const allHandsEmpty = Object.values(state.playerHands).every(hand => hand.length === 0);
const allHandsEmpty = Object.values(state.playerHands).every(
(hand) => hand.length === 0,
);
if (allHandsEmpty) {
await game.produce(state => {
state.phase = 'defeat';
await game.produceAsync((state) => {
state.phase = "defeat";
state.winner = false;
});
}
@ -379,35 +378,32 @@ const checkTavernDeckCmd = registry.register({
success: true,
result: {
isEmpty,
cardsRemaining: state.regions.tavernDeck.childIds.length
}
cardsRemaining: state.regions.tavernDeck.childIds.length,
},
};
}
});
/**
*
*/
const nextTurnCmd = registry.register({
schema: 'next-turn',
run: async (game: RegicideGame) => {
async function nextTurnCmd(game: RegicideGame) {
const state = game.value;
await game.produce(state => {
state.currentPlayerIndex = (state.currentPlayerIndex + 1) % state.playerCount;
await game.produce((state) => {
state.currentPlayerIndex =
(state.currentPlayerIndex + 1) % state.playerCount;
});
const players: PlayerType[] = ['player1', 'player2', 'player3', 'player4'];
const players: PlayerType[] = ["player1", "player2", "player3", "player4"];
const currentPlayer = players[game.value.currentPlayerIndex];
return {
success: true,
result: {
currentPlayer,
currentPlayerIndex: game.value.currentPlayerIndex
}
currentPlayerIndex: game.value.currentPlayerIndex,
},
};
}
});
export {
playCmd as play,

View File

@ -1,8 +1,15 @@
import { IGameContext } from "@/core/game";
import { RegicideState } from "@/samples/regicide/state";
import {buildEnemyDeck, buildTavernDeck, createAllCards, getPlayerHandRegionId} from "@/samples/regicide/utils";
import {
buildEnemyDeck,
buildTavernDeck,
createAllCards,
getPlayerHandRegionId,
} from "@/samples/regicide/utils";
import { INITIAL_HAND_SIZE } from "@/samples/regicide/constants";
import { Enemy, PlayerType, RegicideCard } from "@/samples/regicide/types";
import { checkEnemy, nextTurn, pass, playWithA } from "./commands";
import { enemyCounterattackCmd, playCmd } from ".";
export type RegicideGame = IGameContext<RegicideState>;
@ -12,9 +19,13 @@ export type RegicideGame = IGameContext<RegicideState>;
* @param playerCount 1-4
* @param seed
*/
export async function setupGame(game: RegicideGame, playerCount: number, seed?: number) {
export async function setupGame(
game: RegicideGame,
playerCount: number,
seed?: number,
) {
if (playerCount < 1 || playerCount > 4) {
throw new Error('玩家数量必须为 1-4 人');
throw new Error("玩家数量必须为 1-4 人");
}
if (seed) {
@ -31,7 +42,7 @@ export async function setupGame(game: RegicideGame, playerCount: number, seed?:
const tavernDeck = buildTavernDeck(game._rng);
// 初始化游戏状态
await game.produceAsync(state => {
await game.produceAsync((state) => {
state.cards = allCards;
state.playerCount = playerCount;
state.currentPlayerIndex = 0;
@ -39,15 +50,15 @@ export async function setupGame(game: RegicideGame, playerCount: number, seed?:
// 设置酒馆牌堆区域
for (const card of tavernDeck) {
card.regionId = 'tavernDeck';
card.regionId = "tavernDeck";
state.regions.tavernDeck.childIds.push(card.id);
}
// 设置敌人牌堆区域只存储ID敌人是独立对象
state.regions.enemyDeck.childIds = enemyDeck.map(e => e.id);
state.regions.enemyDeck.childIds = enemyDeck.map((e) => e.id);
// 给每个玩家发牌
const players: PlayerType[] = ['player1', 'player2', 'player3', 'player4'];
const players: PlayerType[] = ["player1", "player2", "player3", "player4"];
for (let i = 0; i < playerCount; i++) {
const player = players[i];
const regionId = getPlayerHandRegionId(player);
@ -78,13 +89,13 @@ export async function start(game: RegicideGame) {
// 检查游戏是否已设置
if (!state.currentEnemy) {
throw new Error('请先调用 setupGame 初始化游戏');
throw new Error("请先调用 setupGame 初始化游戏");
}
const players: PlayerType[] = ['player1', 'player2', 'player3', 'player4'];
const players: PlayerType[] = ["player1", "player2", "player3", "player4"];
// 主游戏循环
while (state.phase === 'playing') {
while (state.phase === "playing") {
const currentPlayerIndex = state.currentPlayerIndex;
const currentPlayer = players[currentPlayerIndex];
@ -92,8 +103,9 @@ export async function start(game: RegicideGame) {
const currentHand = state.playerHands[currentPlayer];
if (currentHand.length === 0) {
// 玩家没有手牌,跳过回合
await game.produceAsync(state => {
state.currentPlayerIndex = (state.currentPlayerIndex + 1) % state.playerCount;
await game.produceAsync((state) => {
state.currentPlayerIndex =
(state.currentPlayerIndex + 1) % state.playerCount;
});
continue;
}
@ -113,31 +125,37 @@ export async function start(game: RegicideGame) {
/**
*
*/
export async function playTurn(game: RegicideGame, player: PlayerType, action: 'play' | 'pass', cardId?: string, secondCardId?: string) {
export async function playTurn(
game: RegicideGame,
player: PlayerType,
action: "play" | "pass",
cardId?: string,
secondCardId?: string,
) {
const state = game.value;
if (state.phase !== 'playing') {
return {success: false, error: '游戏已结束'};
if (state.phase !== "playing") {
return { success: false, error: "游戏已结束" };
}
if (!state.currentEnemy) {
return {success: false, error: '没有活跃的敌人'};
return { success: false, error: "没有活跃的敌人" };
}
let playResult: any;
// 执行玩家动作
if (action === 'play' && cardId) {
if (action === "play" && cardId) {
// 检查是否是A配合另一张牌
const card = state.cards[cardId];
if (card.rank === 'A' && secondCardId) {
playResult = await game.run(`play-with-a ${player} ${cardId} ${secondCardId}`);
if (card.rank === "A" && secondCardId) {
playResult = await playWithA(game, player, cardId, secondCardId);
} else {
playResult = await game.run(`play ${player} ${cardId}`);
playResult = await playCmd(game, player, cardId);
}
} else {
// 让过
playResult = await game.run(`pass ${player}`);
playResult = await pass(game, player);
}
if (!playResult.success) {
@ -145,7 +163,7 @@ export async function playTurn(game: RegicideGame, player: PlayerType, action: '
}
// 检查敌人是否被击败
const checkResult = await game.run<{defeated: boolean; currentEnemy?: any; nextEnemy?: any; defeatedEnemy?: any; enemiesRemaining?: number}>('check-enemy');
const checkResult = await checkEnemy(game);
if (!checkResult.success) {
return checkResult;
}
@ -160,15 +178,19 @@ export async function playTurn(game: RegicideGame, player: PlayerType, action: '
enemyDefeated: false,
needsDiscard: true,
enemyAttack: state.currentEnemy.value,
playerHand: state.playerHands[player]
}
playerHand: state.playerHands[player],
},
};
}
// 敌人被击败,检查是否还有更多敌人
if (state.enemyDeck.length === 0 && state.currentEnemy && state.currentEnemy.hp <= 0) {
await game.produceAsync(state => {
state.phase = 'victory';
if (
state.enemyDeck.length === 0 &&
state.currentEnemy &&
state.currentEnemy.hp <= 0
) {
await game.produceAsync((state) => {
state.phase = "victory";
state.winner = true;
});
return {
@ -176,41 +198,44 @@ export async function playTurn(game: RegicideGame, player: PlayerType, action: '
result: {
playResult: playResult.result,
enemyDefeated: true,
gameWon: true
}
gameWon: true,
},
};
}
// 切换到下一个玩家
await game.run('next-turn');
await nextTurn(game);
return {
success: true,
result: {
playResult: playResult.result,
enemyDefeated: true,
nextEnemy: state.currentEnemy
}
nextEnemy: state.currentEnemy,
},
};
}
/**
*
*/
export async function handleCounterattack(game: RegicideGame, player: PlayerType, discardCardIds: string[]) {
const result = await game.run(`counterattack ${player} ${JSON.stringify(discardCardIds)}`);
export async function handleCounterattack(
game: RegicideGame,
player: PlayerType,
discardCardIds: string[],
) {
const result = await enemyCounterattackCmd(game, player, discardCardIds);
if (!result.success) {
// 弃牌失败(点数和不足),游戏失败
await game.produceAsync(state => {
state.phase = 'defeat';
await game.produceAsync((state) => {
state.phase = "defeat";
state.winner = false;
});
return result;
}
// 弃牌成功,切换到下一个玩家
await game.run('next-turn');
await nextTurn(game);
return result;
}
@ -223,17 +248,26 @@ export function getGameStatus(game: RegicideGame) {
return {
phase: state.phase,
currentPlayer: ['player1', 'player2', 'player3', 'player4'][state.currentPlayerIndex],
currentEnemy: state.currentEnemy ? {
currentPlayer: ["player1", "player2", "player3", "player4"][
state.currentPlayerIndex
],
currentEnemy: state.currentEnemy
? {
...state.currentEnemy,
hpPercent: Math.round((state.currentEnemy.hp / state.currentEnemy.maxHp) * 100)
} : null,
hpPercent: Math.round(
(state.currentEnemy.hp / state.currentEnemy.maxHp) * 100,
),
}
: null,
enemiesRemaining: state.enemyDeck.length,
tavernDeckCount: state.regions.tavernDeck.childIds.length,
discardPileCount: state.regions.discardPile.childIds.length,
playerHands: Object.fromEntries(
Object.entries(state.playerHands).map(([player, hand]) => [player, hand.length])
Object.entries(state.playerHands).map(([player, hand]) => [
player,
hand.length,
]),
),
winner: state.winner
winner: state.winner,
};
}