the-game-domain
Version:
Complete domain layer for 'The Game' card game with rich business entities, automatic persistence, action tracking, and advanced game mechanics. Features Game, Player, Card, Deck, Pile entities with repository pattern, turn management, victory/defeat dete
85 lines • 2.69 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Pile = void 0;
const Card_1 = require("./Card");
class Pile {
constructor(_number, _direction, _lastCard, _id) {
this._number = _number;
this._direction = _direction;
this._lastCard = _lastCard;
this._id = _id;
this._validatePileNumber(_number);
this._validateLastCard(_lastCard);
}
get number() {
return this._number;
}
get direction() {
return this._direction;
}
get lastCard() {
return this._lastCard;
}
get id() {
return this._id;
}
_validatePileNumber(number) {
if (number < 1 || number > 4) {
throw new Error('Pile number must be between 1 and 4');
}
}
_validateLastCard(card) {
if (!(card instanceof Card_1.Card)) {
throw new Error('Last card must be a Card instance');
}
}
canAcceptCard(card) {
if (!(card instanceof Card_1.Card)) {
return false;
}
const cardValue = card.value;
const lastCardValue = this._lastCard.value;
if (this._direction === 'asc') {
return cardValue > lastCardValue || (cardValue < lastCardValue && lastCardValue - cardValue === 10);
}
else {
return cardValue < lastCardValue || (cardValue > lastCardValue && cardValue - lastCardValue === 10);
}
}
addCard(card) {
if (!this.canAcceptCard(card)) {
throw new Error(`Card ${card.value} cannot be added to ${this._direction} pile ${this._number}`);
}
this._lastCard = card;
}
equals(other) {
return this._number === other._number &&
this._direction === other._direction &&
this._lastCard.equals(other._lastCard);
}
toString() {
return `Pile(${this._number}, ${this._direction}, ${this._lastCard.value})`;
}
toJSON() {
return {
number: this._number,
direction: this._direction,
lastCard: this._lastCard.toJSON(),
...(this._id && { id: this._id })
};
}
static fromJSON(data) {
const lastCard = Card_1.Card.fromJSON(data.lastCard);
return new Pile(data.number, data.direction, lastCard, data.id);
}
static createInitialPiles() {
return [
new Pile(1, 'asc', new Card_1.Card(1)),
new Pile(2, 'asc', new Card_1.Card(1)),
new Pile(3, 'desc', new Card_1.Card(100)),
new Pile(4, 'desc', new Card_1.Card(100))
];
}
}
exports.Pile = Pile;
//# sourceMappingURL=Pile.js.map