Best JavaScript code snippet using appium-xcuitest-driver
app.js
Source:app.js
1var express = require('express');2var fs = require("fs");3var bodyParser = require('body-parser');4var cors = require('cors');5class CardDefinition {6 constructor(cardState) {7 this.reactions = [];8 if (!(cardState instanceof EmptyCardArgs)) {9 this.cardState = cardState;10 this.setReactions();11 }12 }13 static registerCardGenerator(id, generator) {14 CardDefinition.CARD_DEFINITIONS[id] = generator;15 }16 static create(id, state) {17 return CardDefinition.CARD_DEFINITIONS[id](state);18 }19 static createFromDTO(dto) {20 var state = new CardState(dto.uuid, dto.zoneId, dto.ownerUUID);21 return CardDefinition.CARD_DEFINITIONS[dto.definitionId](state);22 }23 canPlay(gameDTO) {24 var result = false;25 if (gameDTO.state.phase == Phase.ACTION) {26 if (this.hasType(CardType.ACTION)) {27 result = true;28 }29 }30 else if (gameDTO.state.phase == Phase.BUY) {31 if (this.hasType(CardType.TREASURE)) {32 result = true;33 }34 }35 return result;36 }37 getReactions() {38 return this.reactions;39 }40 addOnPlay(effectLogic) {41 var _this = this;42 var onPlay = new Reaction(EventStatus.RESOLVED, (event, gameDTO) => {43 if ((event.getId() == EventIds.CARD_PLAYED) && (event.args[CardPlayedEvent.CARD_UUID] == _this.cardState.uuid)) {44 return true;45 }46 return false;47 }, effectLogic);48 this.reactions.push(onPlay);49 }50 configureGenerator() {51 var _this = this;52 CardDefinition.registerCardGenerator(this.getCardId(), (state) => {53 var instance = new _this.constructor(state);54 return instance;55 });56 }57 hasType(cardType) {58 var result = false;59 this.getCardTypes().forEach((value) => {60 if (value == cardType) {61 result = true;62 }63 });64 return result;65 }66}67CardDefinition.CARD_DEFINITIONS = {};68class EmptyCardArgs {69}70function RegisterCard(cardType) {71 new cardType(new EmptyCardArgs()).configureGenerator();72}73var CardIds;74(function (CardIds) {75 CardIds[CardIds["COPPER"] = 0] = "COPPER";76 CardIds[CardIds["WORKSHOP"] = 1] = "WORKSHOP";77 CardIds[CardIds["WITCH"] = 2] = "WITCH";78 CardIds[CardIds["MOAT"] = 3] = "MOAT";79 CardIds[CardIds["CELLAR"] = 4] = "CELLAR";80 CardIds[CardIds["LIBRARY"] = 5] = "LIBRARY";81 CardIds[CardIds["GOLD"] = 6] = "GOLD";82 CardIds[CardIds["SILVER"] = 7] = "SILVER";83 CardIds[CardIds["CURSE"] = 8] = "CURSE";84 CardIds[CardIds["ARTISAN"] = 9] = "ARTISAN";85 CardIds[CardIds["BANDIT"] = 10] = "BANDIT";86 CardIds[CardIds["BUREAUCRAT"] = 11] = "BUREAUCRAT";87 CardIds[CardIds["CHAPEL"] = 12] = "CHAPEL";88 CardIds[CardIds["COUNCIL_ROOM"] = 13] = "COUNCIL_ROOM";89 CardIds[CardIds["DUCHY"] = 14] = "DUCHY";90 CardIds[CardIds["ESTATE"] = 15] = "ESTATE";91 CardIds[CardIds["FESTIVAL"] = 16] = "FESTIVAL";92 CardIds[CardIds["GARDENS"] = 17] = "GARDENS";93 CardIds[CardIds["HARBINGER"] = 18] = "HARBINGER";94 CardIds[CardIds["LABORATORY"] = 19] = "LABORATORY";95 CardIds[CardIds["MARKET"] = 20] = "MARKET";96 CardIds[CardIds["MERCHANT"] = 21] = "MERCHANT";97 CardIds[CardIds["MILITIA"] = 22] = "MILITIA";98 CardIds[CardIds["MINE"] = 23] = "MINE";99 CardIds[CardIds["MONEYLENDER"] = 24] = "MONEYLENDER";100 CardIds[CardIds["POACHER"] = 25] = "POACHER";101 CardIds[CardIds["PROVINCE"] = 26] = "PROVINCE";102 CardIds[CardIds["REMODEL"] = 27] = "REMODEL";103 CardIds[CardIds["SENTRY"] = 28] = "SENTRY";104 CardIds[CardIds["SMITHY"] = 29] = "SMITHY";105 CardIds[CardIds["THRONE_ROOM"] = 30] = "THRONE_ROOM";106 CardIds[CardIds["VASSAL"] = 31] = "VASSAL";107 CardIds[CardIds["VILLAGE"] = 32] = "VILLAGE";108})(CardIds || (CardIds = {}));109class CardState {110 constructor(uuid, zoneId, ownerUUID) {111 this.uuid = uuid;112 this.zoneId = zoneId;113 this.ownerUUID = ownerUUID;114 }115}116var CardType;117(function (CardType) {118 CardType[CardType["TREASURE"] = 0] = "TREASURE";119 CardType[CardType["ACTION"] = 1] = "ACTION";120 CardType[CardType["VICTORY"] = 2] = "VICTORY";121 CardType[CardType["ATTACK"] = 3] = "ATTACK";122 CardType[CardType["REACTION"] = 4] = "REACTION";123 CardType[CardType["CURSE"] = 5] = "CURSE";124})(CardType || (CardType = {}));125class ArtisanCardDefinition extends CardDefinition {126 setReactions() {127 var __this = this;128 this.addOnPlay((event, gameDTO) => {129 var gainOptions = [];130 GameDTOAccess.getAvailableCardTypesInSupply(gameDTO).forEach((value) => {131 var topCardUUID = GameDTOAccess.getNextCardInSupplyPile(gameDTO, value);132 if (GameDTOAccess.getCardDefinition(gameDTO, topCardUUID).getCost() <= 5) {133 gainOptions.push(topCardUUID);134 }135 });136 var _ = new LogicalUtils();137 var logicalBuffer = new LogicalBuffer();138 logicalBuffer.addSteps(new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.CARD, _.Value(gainOptions), _.Exactly(_.Value(1)), GainCardEvent.CHOSEN_CARD, "Choose a card to gain."), new EventGeneratorStep(EventIds.GAIN_CARD, new GainCardEventArgs(_.Value(__this.cardState.ownerUUID), _.Reference(GainCardEvent.CHOSEN_CARD))), new LoadHandInfoStep(LoadHandInfoStepOptions.ALL, _.Value(__this.cardState.ownerUUID), "player_hand"), new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.CARD, _.Reference("player_hand"), _.Exactly(_.Value(1)), "card_to_place_on_deck", "Choose a card to place on deck."), new EventGeneratorStep(EventIds.SET_CARD_ONTO_DECK, new SetCardOntoDeckEventArgs(_.Value(__this.cardState.ownerUUID), _.Reference("card_to_place_on_deck"))));139 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);140 });141 }142 getCost() {143 return 6;144 }145 getVictoryPoints() {146 return 0;147 }148 getCardId() {149 return CardIds.ARTISAN;150 }151 getCardTypes() {152 return [CardType.ACTION];153 }154}155RegisterCard(ArtisanCardDefinition);156class BanditCardDefinition extends CardDefinition {157 setReactions() {158 var __this = this;159 this.addOnPlay((event, gameDTO) => {160 var goldCardUUID = GameDTOAccess.getNextCardInSupplyPile(gameDTO, CardIds.GOLD);161 var _ = new LogicalUtils();162 var logicalBuffer = new LogicalBuffer();163 logicalBuffer.addSteps(new EventGeneratorStep(EventIds.GAIN_CARD, new GainCardEventArgs(_.Value(this.cardState.ownerUUID), _.Value(goldCardUUID))));164 GameDTOAccess.getPlayers(gameDTO).forEach((value) => {165 if (value.uuid != __this.cardState.ownerUUID) {166 if (!GameDTOAccess.isPlayerUnaffectedByCard(gameDTO, value.uuid, __this.cardState.uuid)) {167 logicalBuffer.addSteps(new LoadDeckInfoStep(LoadDeckInfoStepOptions.DECK_SIZE, _.Value(value.uuid), "bandit_deckSize"), new RelationalStep(_.Reference("bandit_deckSize"), RelationalOptions.EQUALS, _.Value(0), [168 new EventGeneratorStep(EventIds.RESHUFFLE_DECK, new ReshuffleDeckEventArgs(_.Value(value.uuid)))169 ]), new LoadDeckInfoStep(LoadDeckInfoStepOptions.TOP_CARD, _.Value(value.uuid), "bandit_topCard"), new ArrayStep(ArrayStepOptions.ADD, _.Reference("bandit_topCard"), "bandit_cards_revealed"), new EventGeneratorStep(EventIds.REVEAL_CARD, new RevealCardEventArgs(_.Reference("bandit_topCard"))), new LoadDeckInfoStep(LoadDeckInfoStepOptions.DECK_SIZE, _.Value(value.uuid), "bandit_deckSize"), new RelationalStep(_.Reference("bandit_deckSize"), RelationalOptions.EQUALS, _.Value(0), [170 new EventGeneratorStep(EventIds.RESHUFFLE_DECK, new ReshuffleDeckEventArgs(_.Value(value.uuid)))171 ]), new LoadDeckInfoStep(LoadDeckInfoStepOptions.TOP_CARD, _.Value(value.uuid), "bandit_topCard"), new EventGeneratorStep(EventIds.REVEAL_CARD, new RevealCardEventArgs(_.Reference("bandit_topCard"))), new ArrayStep(ArrayStepOptions.ADD, _.Reference("bandit_topCard"), "bandit_cards_revealed"), new ForEachStep(_.Reference("bandit_cards_revealed"), "each_card_revealed", [172 new LoadCardInfoStep(LoadCardInfoStepOptions.TYPES, _.Reference("each_card_revealed"), "each_card_types"),173 new ContainsStep(_.Value(CardType.TREASURE), _.Reference("each_card_types"), [174 new LoadCardInfoStep(LoadCardInfoStepOptions.CARD_ID, _.Reference("each_card_revealed"), "each_card_id"),175 new RelationalStep(_.Reference("each_card_id"), RelationalOptions.NOT_EQ, _.Value(CardIds.COPPER), [176 new ArrayStep(ArrayStepOptions.ADD, _.Reference("each_card_revealed"), "non_copper_treasures"),177 ])178 ])179 ]), new CountStep(_.Reference("non_copper_treasures"), "non_copper_treasures_count"), new ConditionalStep(_.Reference("non_copper_treasures_count"), {180 0: [181 new ForEachStep(_.Reference("bandit_cards_revealed"), "each_card_revealed", [182 new EventGeneratorStep(EventIds.DISCARD_CARD, new DiscardCardsEventArgs(_.Reference("each_card_revealed")))183 ])184 ],185 1: [186 new EventGeneratorStep(EventIds.TRASH_CARD, new TrashCardsEventArgs(_.Reference("non_copper_treasures"))),187 new QueryStep(_.Reference("non_copper_treasures"), QueryStepOptions.NOT_IN, _.Reference("bandit_cards_revealed"), "not_trashed"),188 new EventGeneratorStep(EventIds.DISCARD_CARD, new DiscardCardsEventArgs(_.Reference("not_trashed")))189 ],190 2: [191 new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.CARD, _.Reference("non_copper_treasures"), _.Exactly(_.Value(1)), "chosen_card_trash", "Choose a card to trash."),192 new EventGeneratorStep(EventIds.TRASH_CARD, new TrashCardsEventArgs(_.Reference("chosen_card_trash"))),193 new QueryStep(_.Reference("non_copper_treasures"), QueryStepOptions.NOT_IN, _.Reference("bandit_cards_revealed"), "not_trashed"),194 new EventGeneratorStep(EventIds.DISCARD_CARD, new DiscardCardsEventArgs(_.Reference("not_trashed")))195 ]196 }));197 }198 }199 });200 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);201 });202 }203 getCost() {204 return 5;205 }206 getVictoryPoints() {207 return 0;208 }209 getCardId() {210 return CardIds.BANDIT;211 }212 getCardTypes() {213 return [CardType.ACTION, CardType.ATTACK];214 }215}216RegisterCard(BanditCardDefinition);217/*new ForEachStep(_EffectBufferReference("top_card"), "top_card_value", [218 new LoadCardInfoStep(LoadCardInfoStepOptions.TYPES, "top_card_value", "card_types"),219 new LoadCardInfoStep(LoadCardInfoStepOptions.CARD_ID, "top_card_value", "card_id"),220 new ContainsStep("card_types", {221 "TREASURE": [222 new RelationalStep("card_id", RelationalOptions.NOT_EQUALS, CardIds.COPPER, [223 new StoreValueStep("card_id", "non_copper_treasures")224 ])225 ]226 })227]),228new QueryStep(_EffectBufferReference("non_copper_treasures"), QueryStepOptions.COUNT, "non_copper_treasures_count"),229new RelationalStep("non_copper_treasures_count", RelationalOptions.EQUALS, 1 + "", [230 new EventGeneratorStep(EventIds.TRASH, new EventGeneratorArgs())231]),232new RelationalStep("non_copper_treasures_count", RelationalOptions.EQUALS, 2 + "", [233 new PlayerChoiceStep(PlayerChoiceType.CARD, _EffectBufferReference("non_copper_treasures"), _Exactly(1), "chosen_card_trash"),234 new EventGeneratorStep(EventIds.TRASH, new EventGeneratorArgs()),235 new QueryStep(_EffectBufferReference("top_card"), QueryStepOptions.NOT_IN, _EffectBufferReference("chosen_card_trash"), "not_trashed"),236 new EventGeneratorStep(EventIds.DISCARD, new EventGeneratorArgs()),237])*/ 238class BureaucratCardDefinition extends CardDefinition {239 setReactions() {240 var __this = this;241 this.addOnPlay((event, gameDTO) => {242 var silverCardUUID = GameDTOAccess.getNextCardInSupplyPile(gameDTO, CardIds.SILVER);243 var _ = new LogicalUtils();244 var logicalBuffer = new LogicalBuffer();245 logicalBuffer.addSteps(new EventGeneratorStep(EventIds.GAIN_CARD, new GainCardEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(silverCardUUID))));246 GameDTOAccess.getPlayers(gameDTO).forEach((value) => {247 if (value.uuid != __this.cardState.ownerUUID) {248 if (!GameDTOAccess.isPlayerUnaffectedByCard(gameDTO, value.uuid, __this.cardState.uuid)) {249 var victoriesInHand = GameDTOAccess.getVictoriesInHand(gameDTO, value.uuid);250 if (victoriesInHand.length > 0) {251 logicalBuffer.addSteps(new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.CARD, _.Value(GameDTOAccess.getVictoriesInHand(gameDTO, value.uuid)), _.Exactly(_.Value(1), "Choose card to place on deck."), "chosen_card"), new EventGeneratorStep(EventIds.REVEAL_CARD, new RevealCardEventArgs(_.Reference("chosen_card"))), new EventGeneratorStep(EventIds.PLACE_IN_DECK, new PlaceInDeckEventArgs(_.Reference("chosen_card"), _.Value(PlaceInDeckEventOptions.TOP))));252 }253 }254 }255 });256 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);257 });258 }259 getCost() {260 return 4;261 }262 getVictoryPoints() {263 return 0;264 }265 getCardId() {266 return CardIds.BUREAUCRAT;267 }268 getCardTypes() {269 return [CardType.ACTION, CardType.ATTACK];270 }271}272RegisterCard(BureaucratCardDefinition);273class CellarCardDefinition extends CardDefinition {274 setReactions() {275 var __this = this;276 this.addOnPlay((event, gameDTO) => {277 var _ = new LogicalUtils();278 var logicalBuffer = new LogicalBuffer();279 logicalBuffer.addSteps(new EventGeneratorStep(EventIds.ADD_ACTION, new AddMoneyEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(1))));280 var cardsInHand = GameDTOAccess.getCardsInZone(gameDTO, __this.cardState.ownerUUID, Zones.HAND);281 logicalBuffer.addSteps(new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.CARD, _.Value(cardsInHand), _.UpTo(_.Value(cardsInHand.length)), "cards_chosen", "Choose card(s) to discard."), new ForEachStep(_.Reference("cards_chosen"), "each_card_chosen", [282 new EventGeneratorStep(EventIds.DISCARD_CARD, new DiscardCardsEventArgs(_.Reference("each_card_chosen")))283 ]), new CountStep(_.Reference("cards_chosen"), "cards_discarded_count"), new DrawCardsStep(__this.cardState.ownerUUID, _.Reference("cards_discarded_count")));284 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);285 });286 }287 getCost() {288 return 2;289 }290 getVictoryPoints() {291 return 0;292 }293 getCardId() {294 return CardIds.CELLAR;295 }296 getCardTypes() {297 return [CardType.ACTION];298 }299}300RegisterCard(CellarCardDefinition);301class ChapelCardDefinition extends CardDefinition {302 setReactions() {303 var __this = this;304 this.addOnPlay((event, gameDTO) => {305 var cardsInHand = GameDTOAccess.getCardsInZone(gameDTO, __this.cardState.ownerUUID, Zones.HAND);306 var _ = new LogicalUtils();307 var logicalBuffer = new LogicalBuffer();308 logicalBuffer.addSteps(new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.CARD, _.Value(cardsInHand), _.UpTo(_.Value(cardsInHand.length)), "cards_chosen", "Choose card(s) to trash."), new ForEachStep(_.Reference("cards_chosen"), "each_card", [309 new EventGeneratorStep(EventIds.TRASH_CARD, new TrashCardsEventArgs(_.Reference("each_card")))310 ]));311 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);312 });313 }314 getCost() {315 return 2;316 }317 getVictoryPoints() {318 return 0;319 }320 getCardId() {321 return CardIds.CHAPEL;322 }323 getCardTypes() {324 return [CardType.ACTION];325 }326}327RegisterCard(ChapelCardDefinition);328class CopperCardDefinition extends CardDefinition {329 setReactions() {330 var __this = this;331 this.addOnPlay((event, gameDTO) => {332 var _ = new LogicalUtils();333 var logicalBuffer = new LogicalBuffer();334 logicalBuffer.addSteps(new EventGeneratorStep(EventIds.ADD_MONEY, new AddMoneyEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(1))));335 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);336 });337 }338 getCost() {339 return 0;340 }341 getVictoryPoints() {342 return 0;343 }344 getCardId() {345 return CardIds.COPPER;346 }347 getCardTypes() {348 return [CardType.TREASURE];349 }350}351RegisterCard(CopperCardDefinition);352class CouncilRoomCardDefinition extends CardDefinition {353 setReactions() {354 var __this = this;355 this.addOnPlay((event, gameDTO) => {356 var _ = new LogicalUtils();357 var logicalBuffer = new LogicalBuffer();358 logicalBuffer.addSteps(new DrawCardsStep(__this.cardState.ownerUUID, _.Value(4)), new EventGeneratorStep(EventIds.ADD_BUYS, new AddBuysEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(1))));359 GameDTOAccess.getPlayers(gameDTO).forEach((value) => {360 if (value.uuid != __this.cardState.ownerUUID) {361 logicalBuffer.addStep(new DrawCardsStep(value.uuid, _.Value(1)));362 }363 });364 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);365 });366 }367 getCost() {368 return 5;369 }370 getVictoryPoints() {371 return 0;372 }373 getCardId() {374 return CardIds.COUNCIL_ROOM;375 }376 getCardTypes() {377 return [CardType.ACTION];378 }379}380RegisterCard(CouncilRoomCardDefinition);381class CurseCardDefinition extends CardDefinition {382 setReactions() {383 }384 getCost() {385 return 0;386 }387 getVictoryPoints() {388 return -1;389 }390 getCardId() {391 return CardIds.CURSE;392 }393 getCardTypes() {394 return [CardType.CURSE];395 }396}397RegisterCard(CurseCardDefinition);398class DuchyCardDefinition extends CardDefinition {399 setReactions() {400 }401 getCost() {402 return 5;403 }404 getVictoryPoints(gameDTO) {405 return 3;406 }407 getCardId() {408 return CardIds.DUCHY;409 }410 getCardTypes() {411 return [CardType.VICTORY];412 }413}414RegisterCard(DuchyCardDefinition);415class EstateCardDefinition extends CardDefinition {416 setReactions() {417 }418 getCost() {419 return 2;420 }421 getVictoryPoints(gameDTO) {422 return 1;423 }424 getCardId() {425 return CardIds.ESTATE;426 }427 getCardTypes() {428 return [CardType.VICTORY];429 }430}431RegisterCard(EstateCardDefinition);432class FestivalCardDefinition extends CardDefinition {433 setReactions() {434 var __this = this;435 this.addOnPlay((event, gameDTO) => {436 var _ = new LogicalUtils();437 var logicalBuffer = new LogicalBuffer();438 logicalBuffer.addSteps(new EventGeneratorStep(EventIds.ADD_ACTION, new AddActionEventArgs(_.Value(this.cardState.ownerUUID), _.Value(2))), new EventGeneratorStep(EventIds.ADD_MONEY, new AddMoneyEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(1))), new EventGeneratorStep(EventIds.ADD_BUYS, new AddBuysEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(1))));439 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);440 });441 }442 getCost() {443 return 5;444 }445 getVictoryPoints(gameDTO) {446 return 0;447 }448 getCardId() {449 return CardIds.FESTIVAL;450 }451 getCardTypes() {452 return [CardType.ACTION];453 }454}455RegisterCard(FestivalCardDefinition);456class GardensCardDefinition extends CardDefinition {457 setReactions() {458 }459 getCost() {460 return 4;461 }462 getVictoryPoints(gameDTO) {463 return Math.floor(GameDTOAccess.getAllCardsOwnedBy(gameDTO, this.cardState.ownerUUID).length / 10);464 }465 getCardId() {466 return CardIds.GARDENS;467 }468 getCardTypes() {469 return [CardType.VICTORY];470 }471}472RegisterCard(GardensCardDefinition);473class GoldCardDefinition extends CardDefinition {474 setReactions() {475 var __this = this;476 this.addOnPlay((event, gameDTO) => {477 var _ = new LogicalUtils();478 var logicalBuffer = new LogicalBuffer();479 logicalBuffer.addSteps(new EventGeneratorStep(EventIds.ADD_MONEY, new AddMoneyEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(3))));480 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);481 });482 }483 getCost() {484 return 6;485 }486 getVictoryPoints(gameDTO) {487 return 0;488 }489 getCardId() {490 return CardIds.GOLD;491 }492 getCardTypes() {493 return [CardType.TREASURE];494 }495}496RegisterCard(GoldCardDefinition);497class HarbingerCardDefinition extends CardDefinition {498 setReactions() {499 var __this = this;500 this.addOnPlay((event, gameDTO) => {501 var _ = new LogicalUtils();502 var logicalBuffer = new LogicalBuffer();503 logicalBuffer.addSteps(new DrawCardsStep(__this.cardState.ownerUUID, _.Value(1)), new EventGeneratorStep(EventIds.ADD_ACTION, new AddActionEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(1))));504 var discardPileCards = GameDTOAccess.getCardsInZone(gameDTO, __this.cardState.ownerUUID, Zones.DISCARD_PILE);505 if (discardPileCards.length > 0) {506 logicalBuffer.addSteps(new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.CARD, _.Value(discardPileCards), _.Exactly(_.Value(1)), GainCardEvent.CHOSEN_CARD, "Choose a card to place on the deck."), new EventGeneratorStep(EventIds.PLACE_IN_DECK, new PlaceInDeckEventArgs(_.Reference(GainCardEvent.CHOSEN_CARD), _.Value(PlaceInDeckEventOptions.TOP))));507 }508 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);509 });510 }511 getCost() {512 return 3;513 }514 getVictoryPoints(gameDTO) {515 return 0;516 }517 getCardId() {518 return CardIds.HARBINGER;519 }520 getCardTypes() {521 return [CardType.ACTION];522 }523}524RegisterCard(HarbingerCardDefinition);525class LaboratoryCardDefinition extends CardDefinition {526 setReactions() {527 var __this = this;528 this.addOnPlay((event, gameDTO) => {529 var _ = new LogicalUtils();530 var logicalBuffer = new LogicalBuffer();531 logicalBuffer.addSteps(new DrawCardsStep(__this.cardState.ownerUUID, _.Value(2)), new EventGeneratorStep(EventIds.ADD_ACTION, new AddActionEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(1))));532 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);533 });534 }535 getCost() {536 return 5;537 }538 getVictoryPoints(gameDTO) {539 return 0;540 }541 getCardId() {542 return CardIds.LABORATORY;543 }544 getCardTypes() {545 return [CardType.ACTION];546 }547}548RegisterCard(LaboratoryCardDefinition);549class LibraryCardDefinition extends CardDefinition {550 setReactions() {551 var __this = this;552 this.addOnPlay((event, gameDTO) => {553 var _ = new LogicalUtils();554 var logicalBuffer = new LogicalBuffer();555 var loadHandSize = new LoadHandInfoStep(LoadHandInfoStepOptions.SIZE, _.Value(__this.cardState.ownerUUID), "hand_size");556 var fullStep = new RelationalStep(_.Reference("hand_size"), RelationalOptions.LESS_THAN, _.Value(7), [557 new LoadDeckInfoStep(LoadDeckInfoStepOptions.DECK_SIZE, _.Value(__this.cardState.ownerUUID), "deckSize"),558 new RelationalStep(_.Reference("deckSize"), RelationalOptions.EQUALS, _.Value(0), [559 new EventGeneratorStep(EventIds.RESHUFFLE_DECK, new ReshuffleDeckEventArgs(_.Value(__this.cardState.ownerUUID)))560 ]),561 new LoadDeckInfoStep(LoadDeckInfoStepOptions.TOP_CARD, _.Value(__this.cardState.ownerUUID), "top_card"),562 new DrawCardsStep(__this.cardState.ownerUUID, _.Value(1)),563 new LoadCardInfoStep(LoadCardInfoStepOptions.TYPES, _.Reference("top_card"), "card_types"),564 new ContainsStep(_.Value(CardType.ACTION), _.Reference("card_types"), [565 new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.STRING, _.Value(["Yes", "No"]), _.Exactly(_.Value(1)), "discardAction", "Discard this card?"),566 new ConditionalStep(_.Reference("discardAction"), {567 "Yes": [568 new EventGeneratorStep(EventIds.DISCARD_CARD, new DiscardCardsEventArgs(_.Reference("top_card")))569 ],570 })571 ]),572 ,573 new RelationalStep(_.Reference("hand_size"), RelationalOptions.LESS_THAN, _.Value(7), [574 new JumpToStep(_.Value(loadHandSize.uuid))575 ])576 ]);577 logicalBuffer.addSteps(loadHandSize, fullStep);578 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);579 });580 }581 getCost() {582 return 5;583 }584 getVictoryPoints(gameDTO) {585 return 0;586 }587 getCardId() {588 return CardIds.LIBRARY;589 }590 getCardTypes() {591 return [CardType.ACTION];592 }593}594RegisterCard(LibraryCardDefinition);595class MarketCardDefinition extends CardDefinition {596 setReactions() {597 var __this = this;598 this.addOnPlay((event, gameDTO) => {599 var _ = new LogicalUtils();600 var logicalBuffer = new LogicalBuffer();601 logicalBuffer.addSteps(new DrawCardsStep(__this.cardState.ownerUUID, _.Value(1)), new EventGeneratorStep(EventIds.ADD_MONEY, new AddMoneyEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(1))), new EventGeneratorStep(EventIds.ADD_BUYS, new AddBuysEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(1))), new EventGeneratorStep(EventIds.ADD_ACTION, new AddActionEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(1))));602 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);603 });604 }605 getCost() {606 return 5;607 }608 getVictoryPoints(gameDTO) {609 return 0;610 }611 getCardId() {612 return CardIds.MARKET;613 }614 getCardTypes() {615 return [CardType.ACTION];616 }617}618RegisterCard(MarketCardDefinition);619class MerchantCardDefinition extends CardDefinition {620 setReactions() {621 var __this = this;622 this.addOnPlay((event, gameDTO) => {623 var _ = new LogicalUtils();624 var logicalBuffer = new LogicalBuffer();625 logicalBuffer.addSteps(new DrawCardsStep(__this.cardState.ownerUUID, _.Value(1)), new EventGeneratorStep(EventIds.ADD_ACTION, new AddMoneyEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(1))));626 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);627 });628 this.reactions.push(new Reaction(EventStatus.RESOLVED, (event, gameDTO) => {629 if (__this.cardState.zoneId == Zones.IN_PLAY) {630 var silversInPlay = GameDTOAccess.getCardsInZone(gameDTO, __this.cardState.ownerUUID, Zones.IN_PLAY).filter((value) => {631 return GameDTOAccess.getCardDefinition(gameDTO, value).getCardId() == CardIds.SILVER;632 });633 if (event.getId() == EventIds.CARD_PLAYED &&634 event.args[CardPlayedEvent.CARD_UUID] != __this.cardState.uuid &&635 GameDTOAccess.getCardDefinition(gameDTO, event.args[CardPlayedEvent.CARD_UUID]).getCardId() == CardIds.SILVER &&636 silversInPlay.length == 1) {637 return true;638 }639 }640 return false;641 }, (event, gameDTO) => {642 var lu = new LoggingUtils(gameDTO);643 Log.send(lu.fname(__this.cardState.ownerUUID) + " recieved +1 money from MERCHANT");644 var _ = new LogicalUtils();645 var logicalBuffer = new LogicalBuffer();646 logicalBuffer.addSteps(new EventGeneratorStep(EventIds.ADD_MONEY, new AddMoneyEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(1))));647 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);648 }));649 }650 getCost() {651 return 3;652 }653 getVictoryPoints(gameDTO) {654 return 0;655 }656 getCardId() {657 return CardIds.MERCHANT;658 }659 getCardTypes() {660 return [CardType.ACTION];661 }662}663RegisterCard(MerchantCardDefinition);664class MilitiaCardDefinition extends CardDefinition {665 setReactions() {666 var __this = this;667 this.addOnPlay((event, gameDTO) => {668 var _ = new LogicalUtils();669 var logicalBuffer = new LogicalBuffer();670 logicalBuffer.addSteps(new EventGeneratorStep(EventIds.ADD_MONEY, new AddMoneyEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(2))));671 GameDTOAccess.getPlayers(gameDTO).forEach((value) => {672 if (value.uuid != __this.cardState.ownerUUID) {673 if (!GameDTOAccess.isPlayerUnaffectedByCard(gameDTO, value.uuid, __this.cardState.uuid)) {674 var cardsInHand = GameDTOAccess.getCardsInZone(gameDTO, value.uuid, Zones.HAND);675 if (cardsInHand.length > 3) {676 logicalBuffer.addSteps(new PlayerChoiceStep(_.Value(value.uuid), PlayerChoiceType.CARD, _.Value(cardsInHand), _.Exactly(_.Value(cardsInHand.length - 3)), "chosen_cards", "Choose cards to discard"), new ForEachStep(_.Reference("chosen_cards"), "each_card_chosen", [677 new EventGeneratorStep(EventIds.DISCARD_CARD, new DiscardCardsEventArgs(_.Reference("each_card_chosen")))678 ]));679 }680 }681 }682 });683 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);684 });685 }686 getCost() {687 return 4;688 }689 getVictoryPoints(gameDTO) {690 return 0;691 }692 getCardId() {693 return CardIds.MILITIA;694 }695 getCardTypes() {696 return [CardType.ACTION];697 }698}699RegisterCard(MilitiaCardDefinition);700class MineCardDefinition extends CardDefinition {701 setReactions() {702 var __this = this;703 this.addOnPlay((event, gameDTO) => {704 var _ = new LogicalUtils();705 var logicalBuffer = new LogicalBuffer();706 var trashOptions = GameDTOAccess.getCardsInZone(gameDTO, __this.cardState.ownerUUID, Zones.HAND).filter((value) => {707 return Util.contains(GameDTOAccess.getCardDefinition(gameDTO, value).getCardTypes(), CardType.TREASURE);708 });709 if (trashOptions.length > 0) {710 var conditionMap = {};711 trashOptions.forEach((value) => {712 var options = [];713 var trashedValue = GameDTOAccess.getCardDefinition(gameDTO, value).getCost();714 GameDTOAccess.getAvailableCardTypesInSupply(gameDTO).forEach((eachCardTypeInSupply) => {715 var eachCard = GameDTOAccess.getNextCardInSupplyPile(gameDTO, eachCardTypeInSupply);716 var definition = GameDTOAccess.getCardDefinition(gameDTO, eachCard);717 if (Util.contains(definition.getCardTypes(), CardType.TREASURE) && definition.getCost() <= (trashedValue + 3)) {718 options.push(definition.cardState.uuid);719 }720 });721 conditionMap[value] = [];722 conditionMap[value].push(new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.CARD, _.Value(options), _.Exactly(_.Value(1)), "gained_card", "Choose a treasure to gain."));723 conditionMap[value].push(new EventGeneratorStep(EventIds.GAIN_CARD, new GainCardEventArgs(_.Value(__this.cardState.ownerUUID), _.Reference("gained_card"), _.Value(Zones.HAND))));724 });725 logicalBuffer.addSteps(new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.CARD, _.Value(trashOptions), _.UpTo(_.Value(1)), "trashed_card", "Choose a treasure to trash."), new CountStep(_.Reference("trashed_card"), "chosen_trashed_card_count"), new RelationalStep(_.Reference("chosen_trashed_card_count"), RelationalOptions.GREATER_THAN, _.Value(0), [726 new EventGeneratorStep(EventIds.TRASH_CARD, new TrashCardsEventArgs(_.Reference("trashed_card"))),727 new ConditionalStep(_.Reference("trashed_card"), conditionMap)728 ]));729 }730 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);731 });732 }733 getCost() {734 return 5;735 }736 getVictoryPoints(gameDTO) {737 return 0;738 }739 getCardId() {740 return CardIds.MINE;741 }742 getCardTypes() {743 return [CardType.ACTION];744 }745}746RegisterCard(MineCardDefinition);747class MoatCardDefinition extends CardDefinition {748 setReactions() {749 var __this = this;750 this.addOnPlay((event, gameDTO) => {751 var _ = new LogicalUtils();752 var logicalBuffer = new LogicalBuffer();753 logicalBuffer.addSteps(new DrawCardsStep(__this.cardState.ownerUUID, _.Value(2)));754 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);755 });756 this.reactions.push(new Reaction(EventStatus.DECLARED, (event, gameDTO) => {757 if (event.getId() == EventIds.CARD_PLAYED &&758 event.eventSourceUUID != __this.cardState.ownerUUID &&759 GameDTOAccess.getCardDefinition(gameDTO, event.args[CardPlayedEvent.CARD_UUID]).hasType(CardType.ATTACK)) {760 return true;761 }762 return false;763 }, (event, gameDTO) => {764 var _ = new LogicalUtils();765 var logicalBuffer = new LogicalBuffer();766 logicalBuffer.addStep(new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.STRING, _.Value(["Yes", "No"]), _.Exactly(_.Value(1)), "revealMoatDecision", "Reveal MOAT?"));767 logicalBuffer.addStep(new ConditionalStep(_.Reference("revealMoatDecision"), {768 "Yes": [769 new EventGeneratorStep(EventIds.REVEAL_CARD, new RevealCardEventArgs(_.Value(__this.cardState.uuid))),770 new EventGeneratorStep(EventIds.SET_UNAFFECTED, new SetUnaffectedEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(event.args[CardPlayedEvent.CARD_UUID]), _.Value(SetUnaffectedEventAction.SET)))771 ]772 }));773 }));774 this.reactions.push(new Reaction(EventStatus.RESOLVED, (event, gameDTO) => {775 if (event.getId() == EventIds.CARD_PLAYED && event.eventSourceUUID != GameDTOAccess.getOwner(gameDTO, __this.cardState.uuid) && GameDTOAccess.getCardDefinition(gameDTO, event.args[CardPlayedEvent.CARD_UUID]).hasType(CardType.ATTACK)) {776 return true;777 }778 return false;779 }, (event, gameDTO) => {780 var _ = new LogicalUtils();781 var logicalBuffer = new LogicalBuffer();782 logicalBuffer.addStep(new EventGeneratorStep(EventIds.SET_UNAFFECTED, new SetUnaffectedEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(event.args[CardPlayedEvent.CARD_UUID]), _.Value(SetUnaffectedEventAction.REMOVE))));783 }));784 }785 getCost() {786 return 2;787 }788 getVictoryPoints(gameDTO) {789 return 0;790 }791 getCardId() {792 return CardIds.MOAT;793 }794 getCardTypes() {795 return [CardType.ACTION, CardType.REACTION];796 }797}798RegisterCard(MoatCardDefinition);799class MoneylenderCardDefinition extends CardDefinition {800 setReactions() {801 var __this = this;802 this.addOnPlay((event, gameDTO) => {803 var coppers = GameDTOAccess.getCardsInZone(gameDTO, __this.cardState.ownerUUID, Zones.HAND).filter((eachCardInHand) => {804 return GameDTOAccess.getCardDefinition(gameDTO, eachCardInHand).getCardId() == CardIds.COPPER;805 });806 var _ = new LogicalUtils();807 var logicalBuffer = new LogicalBuffer();808 if (coppers.length > 0) {809 logicalBuffer.addSteps(new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.CARD, _.Value(["Yes", "No"]), _.Exactly(_.Value(1)), "trash_copper_decision", "Choose a COPPER to trash."), new ConditionalStep(_.Reference("trash_copper_decision"), {810 "Yes": [811 new EventGeneratorStep(EventIds.TRASH_CARD, new TrashCardsEventArgs(_.Value(coppers[0]))),812 new EventGeneratorStep(EventIds.ADD_MONEY, new AddMoneyEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(3)))813 ]814 }));815 }816 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);817 });818 }819 getCost() {820 return 4;821 }822 getVictoryPoints(gameDTO) {823 return 0;824 }825 getCardId() {826 return CardIds.MONEYLENDER;827 }828 getCardTypes() {829 return [CardType.ACTION];830 }831}832RegisterCard(MoneylenderCardDefinition);833class PoacherCardDefinition extends CardDefinition {834 setReactions() {835 var __this = this;836 this.addOnPlay((event, gameDTO) => {837 var _ = new LogicalUtils();838 var logicalBuffer = new LogicalBuffer();839 var emptyPilesCount = GameDTOAccess.countEmptySupplyPiles(gameDTO);840 if (emptyPilesCount > 0) {841 logicalBuffer.addSteps(new DrawCardsStep(__this.cardState.ownerUUID, _.Value(1)), new EventGeneratorStep(EventIds.ADD_MONEY, new AddMoneyEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(1))), new EventGeneratorStep(EventIds.ADD_ACTION, new AddActionEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(1))), new LoadHandInfoStep(LoadHandInfoStepOptions.SIZE, _.Value(__this.cardState.ownerUUID), "hand_size"), new MathStep([_.Value(emptyPilesCount), _.Reference("hand_size")], MathStepOptions.MIN, "numberToDiscard"), new LoadHandInfoStep(LoadHandInfoStepOptions.ALL, _.Value(__this.cardState.ownerUUID), "full_hand"), new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.CARD, _.Reference("full_hand"), _.Exactly(_.Reference("numberToDiscard")), "chosen_discard", "Choose card(s) to discard."), new ForEachStep(_.Reference("chosen_discard"), "each_card_chosen", [842 new EventGeneratorStep(EventIds.DISCARD_CARD, new DiscardCardsEventArgs(_.Reference("each_card_chosen")))843 ]));844 }845 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);846 });847 }848 getCost() {849 return 4;850 }851 getVictoryPoints(gameDTO) {852 return 0;853 }854 getCardId() {855 return CardIds.POACHER;856 }857 getCardTypes() {858 return [CardType.ACTION];859 }860}861RegisterCard(PoacherCardDefinition);862class ProvidenceCardDefinition extends CardDefinition {863 setReactions() {864 }865 getCost() {866 return 8;867 }868 getVictoryPoints(gameDTO) {869 return 6;870 }871 getCardId() {872 return CardIds.PROVINCE;873 }874 getCardTypes() {875 return [CardType.VICTORY];876 }877}878RegisterCard(ProvidenceCardDefinition);879class RemodelCardDefinition extends CardDefinition {880 setReactions() {881 var __this = this;882 this.addOnPlay((event, gameDTO) => {883 var _ = new LogicalUtils();884 var trashOptions = GameDTOAccess.getCardsInZone(gameDTO, __this.cardState.ownerUUID, Zones.HAND);885 var conditionMap = {};886 trashOptions.forEach((value) => {887 var options = [];888 var trashedValue = GameDTOAccess.getCardDefinition(gameDTO, value).getCost();889 GameDTOAccess.getAvailableCardTypesInSupply(gameDTO).forEach((eachCardTypeInSupply) => {890 var eachCard = GameDTOAccess.getNextCardInSupplyPile(gameDTO, eachCardTypeInSupply);891 var definition = GameDTOAccess.getCardDefinition(gameDTO, eachCard);892 if (definition.getCost() <= (trashedValue + 2)) {893 options.push(definition.cardState.uuid);894 }895 });896 conditionMap[value] = [];897 conditionMap[value].push(new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.CARD, _.Value(options), _.Exactly(_.Value(1)), "gained_card", "Choose a card to gain."));898 conditionMap[value].push(new EventGeneratorStep(EventIds.GAIN_CARD, new GainCardEventArgs(_.Value(__this.cardState.ownerUUID), _.Reference("gained_card"))));899 });900 var logicalBuffer = new LogicalBuffer();901 logicalBuffer.addSteps(new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.CARD, _.Value(trashOptions), _.Exactly(_.Value(1)), "trashed_card", "Choose a card to trash."), new EventGeneratorStep(EventIds.TRASH_CARD, new TrashCardsEventArgs(_.Reference("trashed_card"))), new ConditionalStep(_.Reference("trashed_card"), conditionMap));902 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);903 });904 }905 getCost() {906 return 4;907 }908 getVictoryPoints(gameDTO) {909 return 0;910 }911 getCardId() {912 return CardIds.REMODEL;913 }914 getCardTypes() {915 return [CardType.ACTION];916 }917}918RegisterCard(RemodelCardDefinition);919///<reference path="../CardDefinition.ts" />920class SentryCardDefinition extends CardDefinition {921 setReactions() {922 var __this = this;923 this.addOnPlay((event, gameDTO) => {924 var _ = new LogicalUtils();925 var logicalBuffer = new LogicalBuffer();926 logicalBuffer.addSteps(new DrawCardsStep(__this.cardState.ownerUUID, _.Value(1)), new EventGeneratorStep(EventIds.ADD_ACTION, new AddMoneyEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(1))));927 logicalBuffer.addSteps(new LoadDeckInfoStep(LoadDeckInfoStepOptions.DECK_SIZE, _.Value(__this.cardState.ownerUUID), "deck_size"), new RelationalStep(_.Reference("deck_size"), RelationalOptions.EQUALS, _.Value(0), [928 new EventGeneratorStep(EventIds.RESHUFFLE_DECK, new ReshuffleDeckEventArgs(_.Value(__this.cardState.ownerUUID)))929 ]), new LoadDeckInfoStep(LoadDeckInfoStepOptions.TOP_CARD, _.Value(__this.cardState.ownerUUID), "top_card"), new EventGeneratorStep(EventIds.REVEAL_CARD, new RevealCardEventArgs(_.Reference("top_card"))), new LoadDeckInfoStep(LoadDeckInfoStepOptions.DECK_SIZE, _.Value(__this.cardState.ownerUUID), "deck_size"), new RelationalStep(_.Reference("deck_size"), RelationalOptions.EQUALS, _.Value(0), [930 new EventGeneratorStep(EventIds.RESHUFFLE_DECK, new ReshuffleDeckEventArgs(_.Value(__this.cardState.ownerUUID)))931 ]), new LoadDeckInfoStep(new LoadDeckStepCardAtIndexFromTopOption(1), _.Value(__this.cardState.ownerUUID), "top_card_2"), new EventGeneratorStep(EventIds.REVEAL_CARD, new RevealCardEventArgs(_.Reference("top_card_2"))), new ArrayStep(ArrayStepOptions.ADD, _.Reference("top_card"), "cards_revealed"), new ArrayStep(ArrayStepOptions.ADD, _.Reference("top_card_2"), "cards_revealed"), new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.CARD, _.Reference("cards_revealed"), _.UpTo(_.Value(2)), "chosen_cards_trash", "Choose card(s) to trash."), new QueryStep(_.Reference("chosen_cards_trash"), QueryStepOptions.NOT_IN, _.Reference("cards_revealed"), "chosen_cards_not_trashed"), new CountStep(_.Reference("chosen_cards_not_trashed"), "num_chosen_cards_not_trashed"), new RelationalStep(_.Reference("num_chosen_cards_not_trashed"), RelationalOptions.GREATER_THAN, _.Value(0), [932 new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.CARD, _.Reference("chosen_cards_not_trashed"), _.UpTo(_.Reference("num_chosen_cards_not_trashed")), "chosen_cards_discard", "Choose card(s) to discard."),933 new QueryStep(_.Reference("chosen_cards_discard"), QueryStepOptions.NOT_IN, _.Reference("chosen_cards_not_trashed"), "chosen_cards_not_discarded"),934 new CountStep(_.Reference("chosen_cards_not_discarded"), "num_chosen_cards_not_discarded"),935 new RelationalStep(_.Reference("num_chosen_cards_not_discarded"), RelationalOptions.EQUALS, _.Value(1), [936 new EventGeneratorStep(EventIds.PLACE_IN_DECK, new PlaceInDeckEventArgs(_.Reference("chosen_cards_not_discarded"), _.Value(PlaceInDeckEventOptions.TOP)))937 ]),938 new RelationalStep(_.Reference("num_chosen_cards_not_discarded"), RelationalOptions.EQUALS, _.Value(2), [939 new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.CARD, _.Reference("chosen_cards_not_discarded"), _.Exactly(_.Value(1)), "card_to_put_back_first", "Choose first card to put on deck."),940 new QueryStep(_.Reference("card_to_put_back_first"), QueryStepOptions.NOT_IN, _.Reference("chosen_cards_not_discarded"), "card_to_put_back_second"),941 new EventGeneratorStep(EventIds.PLACE_IN_DECK, new PlaceInDeckEventArgs(_.Reference("card_to_put_back_second"), _.Value(PlaceInDeckEventOptions.TOP))),942 new EventGeneratorStep(EventIds.PLACE_IN_DECK, new PlaceInDeckEventArgs(_.Reference("card_to_put_back_first"), _.Value(PlaceInDeckEventOptions.TOP)))943 ]),944 new ForEachStep(_.Reference("chosen_cards_discard"), "each_card_chosen", [945 new EventGeneratorStep(EventIds.DISCARD_CARD, new DiscardCardsEventArgs(_.Reference("each_card_chosen")))946 ])947 ]), new ForEachStep(_.Reference("chosen_cards_trash"), "each_card_chosen", [948 new EventGeneratorStep(EventIds.TRASH_CARD, new TrashCardsEventArgs(_.Reference("each_card_chosen")))949 ]));950 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);951 });952 }953 getCost() {954 return 5;955 }956 getVictoryPoints(gameDTO) {957 return 0;958 }959 getCardId() {960 return CardIds.SENTRY;961 }962 getCardTypes() {963 return [CardType.ACTION];964 }965}966RegisterCard(SentryCardDefinition);967class SilverCardDefinition extends CardDefinition {968 setReactions() {969 var __this = this;970 this.addOnPlay((event, gameDTO) => {971 var _ = new LogicalUtils();972 var logicalBuffer = new LogicalBuffer();973 logicalBuffer.addSteps(new EventGeneratorStep(EventIds.ADD_MONEY, new AddMoneyEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(2))));974 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);975 });976 }977 getCost() {978 return 2;979 }980 getVictoryPoints(gameDTO) {981 return 0;982 }983 getCardId() {984 return CardIds.SILVER;985 }986 getCardTypes() {987 return [CardType.TREASURE];988 }989}990RegisterCard(SilverCardDefinition);991class SmithyCardDefinition extends CardDefinition {992 setReactions() {993 var __this = this;994 this.addOnPlay((event, gameDTO) => {995 var _ = new LogicalUtils();996 var logicalBuffer = new LogicalBuffer();997 logicalBuffer.addSteps(new DrawCardsStep(__this.cardState.ownerUUID, _.Value(3)));998 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);999 });1000 }1001 getCost() {1002 return 4;1003 }1004 getVictoryPoints(gameDTO) {1005 return 0;1006 }1007 getCardId() {1008 return CardIds.SMITHY;1009 }1010 getCardTypes() {1011 return [CardType.ACTION];1012 }1013}1014RegisterCard(SmithyCardDefinition);1015class ThroneRoomCardDefinition extends CardDefinition {1016 setReactions() {1017 var __this = this;1018 this.addOnPlay((event, gameDTO) => {1019 var actionsInHand = GameDTOAccess.getCardsInZone(gameDTO, __this.cardState.ownerUUID, Zones.HAND).filter((value) => {1020 return Util.contains(GameDTOAccess.getCardDefinition(gameDTO, value).getCardTypes(), CardType.ACTION);1021 });1022 var _ = new LogicalUtils();1023 var logicalBuffer = new LogicalBuffer();1024 if (actionsInHand.length > 0) {1025 logicalBuffer.addStep(new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.CARD, _.Value(actionsInHand), _.Exactly(_.Value(1)), "chosen_card", "Choose a card to play twice."));1026 for (var i = 0; i < 2; i++) {1027 logicalBuffer.addStep(new EventGeneratorStep(EventIds.CARD_PLAYED, new CardPlayedEventArgs(_.Reference("chosen_card"))));1028 }1029 }1030 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);1031 });1032 }1033 getCost() {1034 return 4;1035 }1036 getVictoryPoints(gameDTO) {1037 return 0;1038 }1039 getCardId() {1040 return CardIds.THRONE_ROOM;1041 }1042 getCardTypes() {1043 return [CardType.ACTION];1044 }1045}1046RegisterCard(ThroneRoomCardDefinition);1047class VassalCardDefinition extends CardDefinition {1048 setReactions() {1049 var __this = this;1050 this.addOnPlay((event, gameDTO) => {1051 var _ = new LogicalUtils();1052 var _ = new LogicalUtils();1053 var logicalBuffer = new LogicalBuffer();1054 logicalBuffer.addSteps();1055 var cardsOnDeck = GameDTOAccess.getCardsOnDeck(gameDTO, __this.cardState.ownerUUID, 1);1056 var _ = new LogicalUtils();1057 var logicalBuffer = new LogicalBuffer();1058 logicalBuffer.addSteps(new EventGeneratorStep(EventIds.ADD_MONEY, new AddMoneyEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(2))), new LoadDeckInfoStep(LoadDeckInfoStepOptions.DECK_SIZE, _.Value(__this.cardState.ownerUUID), "deck_size"), new RelationalStep(_.Reference("deck_size"), RelationalOptions.EQUALS, _.Value(0), [1059 new EventGeneratorStep(EventIds.RESHUFFLE_DECK, new ReshuffleDeckEventArgs(_.Value(__this.cardState.ownerUUID)))1060 ]), new LoadDeckInfoStep(LoadDeckInfoStepOptions.DECK_SIZE, _.Value(__this.cardState.ownerUUID), "deck_size"), new RelationalStep(_.Reference("deck_size"), RelationalOptions.GREATER_THAN, _.Value(0), [1061 new LoadDeckInfoStep(LoadDeckInfoStepOptions.TOP_CARD, _.Value(__this.cardState.ownerUUID), "top_card"),1062 new EventGeneratorStep(EventIds.REVEAL_CARD, new RevealCardEventArgs(_.Reference("top_card"))),1063 new LoadCardInfoStep(LoadCardInfoStepOptions.TYPES, _.Reference("top_card"), "card_revealed_types"),1064 new ContainsStep(_.Value(CardType.ACTION), _.Reference("card_revealed_types"), [1065 new EventGeneratorStep(EventIds.CARD_PLAYED, new CardPlayedEventArgs(_.Reference("top_card")))1066 ]),1067 new ContainsStep(_.Value(CardType.ACTION), _.Reference("card_revealed_types"), [1068 new EventGeneratorStep(EventIds.DISCARD_CARD, new DiscardCardsEventArgs(_.Reference("top_card")))1069 ], ContainsStep.DOES_NOT_CONTAIN)1070 ]));1071 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);1072 });1073 }1074 getCost() {1075 return 3;1076 }1077 getVictoryPoints(gameDTO) {1078 return 0;1079 }1080 getCardId() {1081 return CardIds.VASSAL;1082 }1083 getCardTypes() {1084 return [CardType.ACTION];1085 }1086}1087RegisterCard(VassalCardDefinition);1088class VillageCardDefinition extends CardDefinition {1089 setReactions() {1090 var __this = this;1091 this.addOnPlay((event, gameDTO) => {1092 var _ = new LogicalUtils();1093 var logicalBuffer = new LogicalBuffer();1094 logicalBuffer.addSteps(new DrawCardsStep(__this.cardState.ownerUUID, _.Value(1)), new EventGeneratorStep(EventIds.ADD_ACTION, new AddActionEventArgs(_.Value(__this.cardState.ownerUUID), _.Value(2))));1095 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);1096 });1097 }1098 getCost() {1099 return 3;1100 }1101 getVictoryPoints(gameDTO) {1102 return 0;1103 }1104 getCardId() {1105 return CardIds.VILLAGE;1106 }1107 getCardTypes() {1108 return [CardType.ACTION];1109 }1110}1111RegisterCard(VillageCardDefinition);1112class WitchCardDefinition extends CardDefinition {1113 setReactions() {1114 var __this = this;1115 this.addOnPlay((event, gameDTO) => {1116 var _ = new LogicalUtils();1117 var logicalBuffer = new LogicalBuffer();1118 logicalBuffer.addSteps(new DrawCardsStep(__this.cardState.ownerUUID, _.Value(2)));1119 GameDTOAccess.getPlayers(gameDTO).forEach((value) => {1120 if (value.uuid != __this.cardState.ownerUUID) {1121 if (!GameDTOAccess.isPlayerUnaffectedByCard(gameDTO, value.uuid, __this.cardState.uuid)) {1122 var nextCurse = GameDTOAccess.getNextCardInSupplyPile(gameDTO, CardIds.CURSE);1123 if (nextCurse != null) {1124 logicalBuffer.addSteps(new EventGeneratorStep(EventIds.GAIN_CARD, new GainCardEventArgs(_.Value(value.uuid), _.Value(nextCurse))));1125 }1126 }1127 }1128 });1129 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);1130 });1131 }1132 getCost() {1133 return 5;1134 }1135 getVictoryPoints(gameDTO) {1136 return 0;1137 }1138 getCardId() {1139 return CardIds.WITCH;1140 }1141 getCardTypes() {1142 return [CardType.ACTION, CardType.ATTACK];1143 }1144}1145RegisterCard(WitchCardDefinition);1146class WorkshopCardDefinition extends CardDefinition {1147 setReactions() {1148 var __this = this;1149 this.addOnPlay((event, gameDTO) => {1150 var _ = new LogicalUtils();1151 var cardChoices = [];1152 GameDTOAccess.getAvailableCardTypesInSupply(gameDTO).forEach((eachCardType) => {1153 var cardInPile = GameDTOAccess.getNextCardInSupplyPile(gameDTO, eachCardType);1154 var definition = GameDTOAccess.getCardDefinition(gameDTO, cardInPile);1155 if (definition.getCost() <= 4) {1156 cardChoices.push(cardInPile);1157 }1158 });1159 var logicalBuffer = new LogicalBuffer();1160 logicalBuffer.addSteps(new PlayerChoiceStep(_.Value(__this.cardState.ownerUUID), PlayerChoiceType.CARD, _.Value(cardChoices), _.Exactly(_.Value(1)), GainCardEvent.CHOSEN_CARD, "Choose a card to gain."), new EventGeneratorStep(EventIds.GAIN_CARD, new GainCardEventArgs(_.Value(__this.cardState.ownerUUID), _.Reference(GainCardEvent.CHOSEN_CARD))));1161 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicalBuffer);1162 });1163 }1164 getCost() {1165 return 4;1166 }1167 getVictoryPoints(gameDTO) {1168 return 0;1169 }1170 getCardId() {1171 return CardIds.WORKSHOP;1172 }1173 getCardTypes() {1174 return [CardType.ACTION];1175 }1176}1177RegisterCard(WorkshopCardDefinition);1178class AIPlayer {1179 constructor(gameDTO, playerUUIDMappedTo) {1180 var __this = this;1181 this.gameDTO = gameDTO;1182 this.uuid = UUID();1183 this.playerUUIDMappedTo = playerUUIDMappedTo;1184 var lu = new LoggingUtils(gameDTO);1185 TurnNotify.subscribe((turnPlayer) => {1186 if (turnPlayer == this.playerUUIDMappedTo) {1187 if (GlobalAIConfig.AUTORUN) {1188 this.doTurn(gameDTO);1189 }1190 else {1191 Log.send(this.uuid + ": Press A to advance " + lu.fname(this.playerUUIDMappedTo) + "'s turn.");1192 var thisCallbackTwo = (event) => {1193 if (event.key == "a") {1194 window.removeEventListener('keydown', thisCallbackTwo);1195 this.doTurn(gameDTO);1196 }1197 };1198 window.addEventListener('keydown', thisCallbackTwo);1199 }1200 }1201 });1202 PlayerChoiceNotify.subscribe((playerUUID, options, prepositionType, prepositionValue) => {1203 if (__this.playerUUIDMappedTo == playerUUID) {1204 GameDTOAccess.setPlayerChoice(gameDTO, this.makePlayerChoice(options, prepositionType, prepositionValue));1205 }1206 });1207 }1208 doTurn(gameDTO) {1209 var __this = this;1210 var lu = new LoggingUtils(gameDTO);1211 Log.send(lu.fname(this.playerUUIDMappedTo) + " is thinking...");1212 setTimeout(function () {1213 var moves = new PossibleMovesGenerator().generate(__this.playerUUIDMappedTo, gameDTO);1214 if (moves.length > 0) {1215 if (GlobalAIConfig.AUTORUN) {1216 Util.shuffle(moves);1217 moves[0].execute(gameDTO);1218 GameDTOAccess.setState(gameDTO, GameState.RESOLVING_EVENT_STACK);1219 DriverNotify.ping();1220 }1221 else {1222 MessagingCenter.notify("move_display", { moves: moves, gameDto: gameDTO });1223 }1224 }1225 }, 500);1226 }1227 makePlayerChoice(options, prepositionType, prepositionValue) {1228 var numberToPick = null;1229 if (prepositionType == PlayerChoicePrepositionValues.EXACTLY) {1230 numberToPick = prepositionValue;1231 }1232 else {1233 numberToPick = Util.randomInRange(0, prepositionValue);1234 }1235 var choices = [];1236 var shuffledOptions = Util.shuffle(options);1237 for (var i = 0; i < numberToPick; i++) {1238 choices.push(shuffledOptions[i]);1239 }1240 return choices;1241 }1242}1243class ChosenMoveReceiver {1244 receive(move, gameDTO) {1245 this.process(move, gameDTO);1246 }1247 validate() {1248 }1249 process(move, gameDTO) {1250 move.execute(gameDTO);1251 GameDTOAccess.setState(gameDTO, GameState.RESOLVING_EVENT_STACK);1252 }1253}1254class GlobalAIConfig {1255}1256GlobalAIConfig.AUTORUN = false;1257class PossibleMovesGenerator {1258 generate(playerUUID, gameDTO) {1259 var result = [];1260 if (playerUUID == gameDTO.state.turnPlayer) {1261 if (gameDTO.state.state == GameState.WAITING_FOR_PLAYER_CHOICE) {1262 var _ = new LogicalUtils();1263 var stack = GameDTOAccess.getLogicalStack(gameDTO);1264 var topBuffer = stack.buffers[stack.buffers.length - 1];1265 var currentStep = GameDTOAccess.traverseLogicalStep(gameDTO, topBuffer, topBuffer.getCurrentStep());1266 if (currentStep instanceof PlayerChoiceStep) {1267 var optionsResolved = _.ResolveVariable(currentStep.options, topBuffer);1268 var maxChoicesNum;1269 var minChoicesNum;1270 if (currentStep.preposition.type == PlayerChoicePrepositionValues.EXACTLY) {1271 maxChoicesNum = _.ResolveVariable(currentStep.preposition.value, topBuffer);1272 minChoicesNum = _.ResolveVariable(currentStep.preposition.value, topBuffer);1273 }1274 else {1275 minChoicesNum = 0;1276 maxChoicesNum = _.ResolveVariable(currentStep.preposition.value, topBuffer);1277 }1278 result.push(currentStep.choiceType, new ChoiceMove([], optionsResolved, minChoicesNum, maxChoicesNum, currentStep.displayText));1279 }1280 }1281 else if (gameDTO.state.state == GameState.TURN_WAITING) {1282 var playerDTO = GameDTOAccess.getPlayerFromUUID(gameDTO, playerUUID);1283 GameDTOAccess.getCardsInZone(gameDTO, playerUUID, Zones.HAND).forEach((eachCardInHand) => {1284 var definition = GameDTOAccess.getCardDefinition(gameDTO, eachCardInHand);1285 if (definition.canPlay(gameDTO)) {1286 result.push(new PlayMove(eachCardInHand));1287 }1288 });1289 if (gameDTO.state.phase == Phase.BUY && playerDTO.turn.buys > 0) {1290 GameDTOAccess.getAvailableCardTypesInSupply(gameDTO).forEach((eachType) => {1291 if (eachType != CardIds.COPPER) {1292 var topCard = GameDTOAccess.getNextCardInSupplyPile(gameDTO, eachType);1293 var definition = GameDTOAccess.getCardDefinition(gameDTO, topCard);1294 var cost = definition.getCost();1295 if (playerDTO.turn.money >= cost) {1296 result.push(new BuyMove(playerDTO.uuid, topCard));1297 }1298 }1299 });1300 }1301 result.push(new AdvancePhaseMove());1302 }1303 }1304 return result;1305 }1306}1307var MoveType;1308(function (MoveType) {1309 MoveType[MoveType["PLAY"] = 0] = "PLAY";1310 MoveType[MoveType["BUY"] = 1] = "BUY";1311 MoveType[MoveType["ADVANCE_PHASE"] = 2] = "ADVANCE_PHASE";1312 MoveType[MoveType["CHOICE"] = 3] = "CHOICE";1313})(MoveType || (MoveType = {}));1314///<reference path="MoveType.ts" />1315class Move {1316 static fromJson(json) {1317 var moveType = json["moveType"];1318 var newInstance = Move.create(moveType);1319 for (var key in json) {1320 newInstance[key] = json[key];1321 }1322 return newInstance;1323 }1324 static toJsonObject(moveObject, gameDTO) {1325 var instance = {};1326 for (var key in moveObject) {1327 instance[key] = moveObject[key];1328 }1329 instance["moveType"] = moveObject.getMoveType();1330 return instance;1331 }1332 static registerMoveGenerator(id, generator) {1333 Move.MOVE_GENERATORS[id] = generator;1334 }1335 static create(moveType) {1336 return Move.MOVE_GENERATORS[moveType]();1337 }1338 configureGenerator() {1339 var _this = this;1340 Move.registerMoveGenerator(this.getMoveType(), () => {1341 var instance = new _this.constructor();1342 return instance;1343 });1344 }1345}1346Move.MOVE_GENERATORS = {};1347function RegisterMove(moveType) {1348 new moveType().configureGenerator();1349}1350///<reference path="Move.ts" />1351class AdvancePhaseMove extends Move {1352 execute(gameDTO) {1353 var playEvent = GameEvent.create(EventIds.ADVANCE_PHASE, {});1354 GameDTOAccess.pushEventToStack(gameDTO, playEvent);1355 GameDTOAccess.setState(gameDTO, GameState.RESOLVING_EVENT_STACK);1356 }1357 getMoveType() {1358 return MoveType.ADVANCE_PHASE;1359 }1360}1361RegisterMove(AdvancePhaseMove);1362///<reference path="Move.ts" />1363class BuyMove extends Move {1364 constructor(playerToGain, cardToBuy) {1365 super();1366 this.cardToBuy = cardToBuy;1367 this.playerToGain = playerToGain;1368 }1369 execute(gameDTO) {1370 var _ = new LogicalUtils();1371 var args = {};1372 args[GainCardEvent.CHOSEN_CARD] = this.cardToBuy;1373 args[GainCardEvent.RECIPIENT] = this.playerToGain;1374 var playEvent = GameEvent.create(EventIds.GAIN_CARD, args);1375 GameDTOAccess.pushEventToStack(gameDTO, playEvent);1376 var buyArgs = {};1377 buyArgs[AddBuysEvent.AMOUNT] = -1;1378 buyArgs[AddBuysEvent.PLAYER_UUID] = this.playerToGain;1379 var buyEvent = GameEvent.create(EventIds.ADD_BUYS, buyArgs);1380 GameDTOAccess.pushEventToStack(gameDTO, buyEvent);1381 GameDTOAccess.setState(gameDTO, GameState.RESOLVING_EVENT_STACK);1382 }1383 getMoveType() {1384 return MoveType.BUY;1385 }1386 toString(gameDTO) {1387 var lu = new LoggingUtils(gameDTO);1388 return "Buy " + lu.fname(this.cardToBuy);1389 }1390}1391RegisterMove(BuyMove);1392///<reference path="Move.ts" />1393class ChoiceMove extends Move {1394 constructor(choiceType, choices, options, minChoicesNum, maxChoicesNum, choiceString) {1395 super();1396 this.choiceType = choiceType;1397 this.choices = choices;1398 this.options = options;1399 this.minChoicesNum = minChoicesNum;1400 this.maxChoicesNum = maxChoicesNum;1401 this.choiceString = choiceString;1402 }1403 execute(gameDTO) {1404 var stack = GameDTOAccess.getLogicalStack(gameDTO);1405 var topBuffer = stack.buffers[stack.buffers.length - 1];1406 var currentStep = GameDTOAccess.traverseLogicalStep(gameDTO, topBuffer, topBuffer.getCurrentStep());1407 if (currentStep instanceof PlayerChoiceStep) {1408 currentStep.fulfill(this.choices, topBuffer, gameDTO);1409 GameDTOAccess.setState(gameDTO, GameState.RESOLVING_LOGICAL_STACK);1410 }1411 }1412 getMoveType() {1413 return MoveType.CHOICE;1414 }1415}1416RegisterMove(ChoiceMove);1417class PlayMove extends Move {1418 constructor(cardToPlay) {1419 super();1420 this.cardToPlay = cardToPlay;1421 }1422 execute(gameDTO) {1423 var _ = new LogicalUtils();1424 var args = {};1425 args[CardPlayedEvent.CARD_UUID] = this.cardToPlay;1426 var playEvent = GameEvent.create(EventIds.CARD_PLAYED, args);1427 GameDTOAccess.pushEventToStack(gameDTO, playEvent);1428 GameDTOAccess.setState(gameDTO, GameState.RESOLVING_EVENT_STACK);1429 }1430 getMoveType() {1431 return MoveType.PLAY;1432 }1433 toString(gameDTO) {1434 var lu = new LoggingUtils(gameDTO);1435 return "Play " + lu.fname(this.cardToPlay);1436 }1437}1438RegisterMove(PlayMove);1439var Phase;1440(function (Phase) {1441 Phase[Phase["ACTION"] = 0] = "ACTION";1442 Phase[Phase["BUY"] = 1] = "BUY";1443 Phase[Phase["CLEAN_UP"] = 2] = "CLEAN_UP";1444})(Phase || (Phase = {}));1445var Zones;1446(function (Zones) {1447 Zones[Zones["SUPPLY"] = 0] = "SUPPLY";1448 Zones[Zones["DECK"] = 1] = "DECK";1449 Zones[Zones["HAND"] = 2] = "HAND";1450 Zones[Zones["IN_PLAY"] = 3] = "IN_PLAY";1451 Zones[Zones["DISCARD_PILE"] = 4] = "DISCARD_PILE";1452 Zones[Zones["TRASH"] = 5] = "TRASH";1453 Zones[Zones["REVEALED"] = 6] = "REVEALED";1454})(Zones || (Zones = {}));1455class DTO {1456}1457///<reference path="./DTO.ts" />1458class GameDTO extends DTO {1459 constructor() {1460 super(...arguments);1461 this.players = [];1462 this.cards = [];1463 this.engine = new GameDTO_Engine();1464 this.state = new GameDTO_State();1465 }1466}1467class GameDTO_Engine extends DTO {1468 constructor() {1469 super(...arguments);1470 this.logicalStack = [];1471 this.reactionStack = [];1472 this.eventStack = [];1473 }1474}1475class GameDTO_Player extends DTO {1476 constructor() {1477 super(...arguments);1478 this.turn = new GameDTO_Player_Turn();1479 }1480}1481class GameDTO_Player_Turn extends DTO {1482 constructor() {1483 super(...arguments);1484 this.money = 0;1485 this.actions = 0;1486 this.buys = 0;1487 }1488}1489class GameDTO_Card extends DTO {1490}1491class GameDTO_LogicalBuffer extends DTO {1492 constructor() {1493 super(...arguments);1494 this.storedData = {};1495 }1496}1497class GameDTO_LogicalBuffer_Step extends DTO {1498}1499class GameDTO_LogicalBufferVariable extends DTO {1500}1501class GameDTO_EventEntry extends DTO {1502}1503class GameDTO_State extends DTO {1504 constructor() {1505 super(...arguments);1506 this.state = GameState.NOT_STARTED;1507 this.phase = Phase.ACTION;1508 this.unaffectedPlayers = [];1509 }1510}1511class GameDTO_ReactionBuffer extends DTO {1512 constructor() {1513 super(...arguments);1514 this.potentialReactions = [];1515 }1516}1517class GameDTOAccess {1518 static setPlayerChoice(gameDTO, chosenOptions) {1519 var stack = GameDTOAccess.getLogicalStack(gameDTO);1520 var topBuffer = stack.buffers[stack.buffers.length - 1];1521 var currentStep = GameDTOAccess.traverseLogicalStep(gameDTO, topBuffer, topBuffer.getCurrentStep());1522 if (currentStep instanceof PlayerChoiceStep) {1523 currentStep.fulfill(chosenOptions, topBuffer, gameDTO);1524 }1525 }1526 static traverseLogicalStep(gameDTO, currentBuffer, currentStep) {1527 if (!currentStep.hasSubsteps()) {1528 return currentStep;1529 }1530 else {1531 return GameDTOAccess.traverseLogicalStep(gameDTO, currentBuffer, currentStep.getCurrentSubstep(currentBuffer, gameDTO));1532 }1533 }1534 static changeTurns(gameDTO) {1535 var nextPlayer = null;1536 gameDTO.players.forEach((value) => {1537 if (value.uuid != gameDTO.state.turnPlayer) {1538 nextPlayer = value;1539 }1540 });1541 gameDTO.state.turnPlayer = nextPlayer.uuid;1542 nextPlayer.turn.buys = 1;1543 nextPlayer.turn.actions = 1;1544 var lu = new LoggingUtils(gameDTO);1545 Log.send("It is now " + lu.fname(gameDTO.state.turnPlayer) + "'s turn.");1546 }1547 static removeTopReactionBuffer(gameDTO) {1548 gameDTO.engine.reactionStack.splice(gameDTO.engine.reactionStack.indexOf(gameDTO.engine.reactionStack[gameDTO.engine.reactionStack.length - 1]), 1);1549 }1550 static removeLogicalBuffer(gameDTO, bufferToRemove) {1551 var dtoIdx = null;1552 gameDTO.engine.logicalStack.forEach((buffer, index) => {1553 if (buffer.uuid == bufferToRemove.uuid) {1554 dtoIdx = index;1555 }1556 });1557 gameDTO.engine.logicalStack.splice(dtoIdx, 1);1558 }1559 static removeEvent(gameDTO, eventToRemove) {1560 var dtoIdx = null;1561 gameDTO.engine.eventStack.forEach((event, index) => {1562 if (event.eventUUID == eventToRemove.uuid) {1563 dtoIdx = index;1564 }1565 });1566 gameDTO.engine.eventStack.splice(dtoIdx, 1);1567 }1568 static updateEvent(gameDTO, updatingEvent) {1569 //Log.send("EventStack before: " + JSON.stringify(gameDTO.engine.eventStack));1570 var indexToUpdate = -1;1571 gameDTO.engine.eventStack.forEach((event, index) => {1572 if (event.eventUUID == updatingEvent.uuid) {1573 indexToUpdate = index;1574 }1575 });1576 if (indexToUpdate > -1) {1577 gameDTO.engine.eventStack[indexToUpdate] = updatingEvent.convertToDTO();1578 }1579 //Log.send("EventStack after: " + JSON.stringify(gameDTO.engine.eventStack));1580 }1581 static pushNewReactionBuffer(gameDTO, newReactionBuffer) {1582 var dto = newReactionBuffer.convertToDTO();1583 gameDTO.engine.reactionStack.push(dto);1584 }1585 static getReactionStack(gameDTO) {1586 var stack = new ReactionStack();1587 stack.buffers = [];1588 gameDTO.engine.reactionStack.forEach((value) => {1589 var eventStatus = GameDTOAccess.getEvent(gameDTO, value.eventUUIDReactingTo).status;1590 stack.buffers.push(new ReactionBuffer(value.eventUUIDReactingTo, eventStatus, value.potentialReactions));1591 });1592 return stack;1593 }1594 static getEventStack(gameDTO) {1595 var stack = new EventStack();1596 stack.events = [];1597 gameDTO.engine.eventStack.forEach((value) => {1598 stack.events.push(GameEvent.createFromDTO(value));1599 });1600 return stack;1601 }1602 static getLogicalStack(gameDTO) {1603 var stack = new LogicalStack();1604 stack.buffers = [];1605 gameDTO.engine.logicalStack.forEach((value) => {1606 stack.buffers.push(LogicalBuffer.createFromDTO(value, gameDTO));1607 });1608 return stack;1609 }1610 static getEvent(gameDTO, eventUUID) {1611 var result = null;1612 gameDTO.engine.eventStack.forEach((event) => {1613 if (event.eventUUID == eventUUID) {1614 result = GameEvent.createWithStatus(event.eventId, event.status, event.args);1615 }1616 });1617 return result;1618 }1619 static getTopEvent(gameDTO) {1620 var topDTO = gameDTO.engine.eventStack[gameDTO.engine.eventStack.length];1621 return GameEvent.createWithStatus(topDTO.eventId, topDTO.status, topDTO.args);1622 }1623 static updateLogicalBuffer(gameDTO, logicalBuffer) {1624 var dto = logicalBuffer.convertToDTO(gameDTO);1625 var indexToUpdate = 0;1626 gameDTO.engine.logicalStack.forEach((value, index) => {1627 if (value.uuid == logicalBuffer.uuid) {1628 indexToUpdate = index;1629 }1630 });1631 gameDTO.engine.logicalStack[indexToUpdate] = dto;1632 }1633 static getTopLogicalBuffer(gameDTO) {1634 return LogicalBuffer.createFromDTO(gameDTO.engine.logicalStack[gameDTO.engine.logicalStack.length - 1], gameDTO);1635 }1636 static isEventStackCleared(gameDTO) {1637 return gameDTO.engine.eventStack.length <= 0;1638 }1639 static isLogicalStackCleared(gameDTO) {1640 return gameDTO.engine.logicalStack.length <= 0;1641 }1642 static isReactionStackCleared(gameDTO) {1643 return gameDTO.engine.reactionStack.length <= 0;1644 }1645 static rebalanceZone(gameDTO, playerUUID, zoneId) {1646 if (zoneId != Zones.SUPPLY) {1647 var zoneCards = GameDTOAccess.getCardDTOsInZone(gameDTO, playerUUID, zoneId);1648 zoneCards.forEach((value, index) => {1649 value.zoneIndex = index;1650 });1651 }1652 }1653 static isGameOver(gameDTO) {1654 return false;1655 }1656 static getObjectForUUID(gameDTO, uuid) {1657 var result = null;1658 gameDTO.cards.forEach((eachCard) => {1659 if (eachCard.uuid == uuid) {1660 result = eachCard;1661 }1662 });1663 if (result == null) {1664 gameDTO.players.forEach((eachPlayer) => {1665 if (eachPlayer.uuid == uuid) {1666 result = eachPlayer;1667 }1668 });1669 }1670 return result;1671 }1672 static setState(gameDTO, state) {1673 gameDTO.state.state = state;1674 //Log.send("Game state is now " + GameState[state]);1675 }1676 static setTurn(gameDTO, turnPlayerUUID) {1677 var lu = new LoggingUtils(gameDTO);1678 gameDTO.state.turnPlayer = turnPlayerUUID;1679 GameDTOAccess.setState(gameDTO, GameState.TURN_WAITING);1680 // Log.send("It is now " + lu.fname(turnPlayerUUID) + "'s turn.");1681 // TurnNotify.send(turnPlayerUUID);1682 }1683 static removePlayerUnaffectedByEffect(gameDTO, recipient, cardProtectedFrom) {1684 var indexToRemove = null;1685 gameDTO.state.unaffectedPlayers.forEach((value, index) => {1686 if (value["playerUUID"] && value["cardProtectedFrom"]) {1687 indexToRemove = index;1688 }1689 });1690 gameDTO.state.unaffectedPlayers.splice(indexToRemove, 1);1691 }1692 static setPlayerUnaffectedByEffect(gameDTO, recipient, cardProtectedFrom) {1693 var unaffectedEntry = {};1694 unaffectedEntry["playerUUID"] = recipient;1695 unaffectedEntry["cardProtectedFrom"] = cardProtectedFrom;1696 gameDTO.state.unaffectedPlayers.push(unaffectedEntry);1697 }1698 static shuffleDeck(gameDTO, recipient) {1699 var deck = GameDTOAccess.getCardDTOsInZone(gameDTO, recipient, Zones.DECK);1700 var indexes = new Array(deck.length);1701 for (var i = 0; i < indexes.length; i++) {1702 indexes[i] = i;1703 }1704 Util.shuffle(indexes);1705 indexes.forEach((value, index) => {1706 deck[index].zoneIndex = value;1707 });1708 gameDTO.cards.sort(function (a, b) {1709 return a.zoneIndex - b.zoneIndex;1710 });1711 }1712 static getCardDTOsInZone(gameDTO, recipient, zone) {1713 var result = [];1714 gameDTO.cards.forEach((value) => {1715 if (value.ownerUUID == recipient && value.zoneId == zone) {1716 result.push(value);1717 }1718 });1719 return result;1720 }1721 static setDeckIndex(gameDTO, cardUUID, newIndex) {1722 var owner = GameDTOAccess.getOwner(gameDTO, cardUUID);1723 var deck = GameDTOAccess.getCardDTOsInZone(gameDTO, owner, Zones.DECK);1724 deck.forEach((value) => {1725 if (value.zoneIndex >= newIndex) {1726 value.zoneIndex = value.zoneIndex + 1;1727 }1728 });1729 var dto = GameDTOAccess.getCardDTO(gameDTO, cardUUID);1730 dto.zoneIndex = newIndex;1731 }1732 static getAllCardsOwnedBy(gameDTO, ownerUUID) {1733 var result = [];1734 gameDTO.cards.forEach((value) => {1735 if (value.ownerUUID == ownerUUID) {1736 result.push(value.uuid);1737 }1738 });1739 return result;1740 }1741 static countEmptySupplyPiles(gameDTO) {1742 var cardTypes = [];1743 gameDTO.cards.forEach((value) => {1744 if (value.zoneId == Zones.SUPPLY) {1745 var type = value.definitionId;1746 if (cardTypes.indexOf(type) == -1) {1747 cardTypes.push(type);1748 }1749 }1750 });1751 return 17 - cardTypes.length;1752 }1753 static getCardsInZone(gameDTO, ownerUUID, zone) {1754 var result = [];1755 gameDTO.cards.forEach((value) => {1756 if (value.ownerUUID == ownerUUID && value.zoneId == zone) {1757 result.push(value.uuid);1758 }1759 });1760 return result;1761 }1762 static pushEventsToStack(gameDTO, arg1) {1763 throw new Error("Method not implemented.");1764 }1765 static getVictoriesInHand(gameDTO, uuid) {1766 var results = [];1767 var cardsInHand = GameDTOAccess.getCardsInZone(gameDTO, uuid, Zones.HAND);1768 cardsInHand.forEach((value) => {1769 var definition = GameDTOAccess.getCardDefinition(gameDTO, value);1770 if (Util.contains(definition.getCardTypes(), CardType.VICTORY)) {1771 results.push(value);1772 }1773 });1774 return results;1775 }1776 static isPlayerUnaffectedByCard(gameDTO, playerUUID, cardUUID) {1777 var result = false;1778 gameDTO.state.unaffectedPlayers.forEach((value, index) => {1779 if (value["playerUUID"] && value["cardProtectedFrom"]) {1780 result = true;1781 }1782 });1783 return result;1784 }1785 static getNextCardInSupplyPile(gameDTO, cardId) {1786 var result = null;1787 var maxIndex = 0;1788 gameDTO.cards.forEach((value) => {1789 if (value.zoneId == Zones.SUPPLY && value.definitionId == cardId) {1790 if (maxIndex <= value.zoneIndex) {1791 maxIndex = value.zoneIndex;1792 result = value.uuid;1793 }1794 }1795 });1796 return result;1797 }1798 static getCardsInPile(gameDTO, cardId) {1799 var result = [];1800 gameDTO.cards.forEach((value) => {1801 if (value.definitionId == cardId && value.zoneId == Zones.SUPPLY) {1802 result.push(value.uuid);1803 }1804 });1805 return result;1806 }1807 static getCardsOnDeck(gameDTO, ownerUUID, numberToGet) {1808 GameDTOAccess.rebalanceZone(gameDTO, ownerUUID, Zones.DECK);1809 var deck = GameDTOAccess.getCardDTOsInZone(gameDTO, ownerUUID, Zones.DECK);1810 var result = [];1811 var indexesToGet = [];1812 for (var i = 0; i < numberToGet; i++) {1813 indexesToGet.push(deck.length - (i + 1));1814 }1815 deck.forEach((value) => {1816 if (Util.contains(indexesToGet, value.zoneIndex)) {1817 result.push(value.uuid);1818 }1819 });1820 return result;1821 }1822 static getCardDefinition(gameDTO, cardUUID) {1823 var dto = GameDTOAccess.getCardDTO(gameDTO, cardUUID);1824 var state = new CardState(dto.uuid, dto.zoneId, dto.ownerUUID);1825 var definition = CardDefinition.create(dto.definitionId, state);1826 return definition;1827 }1828 static getCardDTO(gameDTO, uuid) {1829 var result = null;1830 gameDTO.cards.forEach((value) => {1831 if (value.uuid == uuid) {1832 result = value;1833 }1834 });1835 return result;1836 }1837 static getOwner(gameDTO, uuid) {1838 var dto = GameDTOAccess.getCardDTO(gameDTO, uuid);1839 return dto.ownerUUID;1840 }1841 static getOwnerDTO(gameDTO, uuid) {1842 var dto = GameDTOAccess.getCardDTO(gameDTO, uuid);1843 var result = null;1844 gameDTO.players.forEach((eachPlayer) => {1845 if (eachPlayer.uuid == dto.ownerUUID) {1846 result = eachPlayer;1847 }1848 });1849 return result;1850 }1851 static getPlayers(gameDTO) {1852 return gameDTO.players;1853 }1854 static getTopCardOfDeck(gameDTO, recipient) {1855 return GameDTOAccess.getCardsOnDeck(gameDTO, recipient, 1)[0];1856 }1857 static setOwner(gameDTO, chosenCard, recipient) {1858 var dto = GameDTOAccess.getCardDTO(gameDTO, chosenCard);1859 dto.ownerUUID = recipient;1860 }1861 static pushNewLogicalBuffer(gameDTO, buffer) {1862 var logicalBuffer = buffer.convertToDTO(gameDTO);1863 gameDTO.engine.logicalStack.push(logicalBuffer);1864 GameDTOAccess.setState(gameDTO, GameState.RESOLVING_LOGICAL_STACK);1865 ReactionStack.currentOutput.createdLogicalOutput = true;1866 }1867 static setZone(gameDTO, cardUUID, zoneId) {1868 var cardDTO = GameDTOAccess.getCardFromUUID(gameDTO, cardUUID);1869 var oldZone = cardDTO.zoneId;1870 cardDTO.zoneId = zoneId;1871 GameDTOAccess.rebalanceZone(gameDTO, cardUUID, zoneId);1872 GameDTOAccess.rebalanceZone(gameDTO, cardUUID, oldZone);1873 }1874 static pushEventToStack(gameDTO, event) {1875 var dto = event.convertToDTO();1876 dto.eventUUID = UUID();1877 gameDTO.engine.eventStack.push(dto);1878 }1879 static getCardFromUUID(game, cardUuid) {1880 return game.cards.filter((value) => {1881 return value.uuid == cardUuid;1882 })[0];1883 }1884 static getPlayerFromUUID(game, playerUUID) {1885 return game.players.filter((value) => {1886 return value.uuid == playerUUID;1887 })[0];1888 }1889 static getPlayerUUIDs_asStringArray(game) {1890 return game.players.map((value) => {1891 return value.uuid + "";1892 });1893 }1894 static getAvailableCardTypesInSupply(gameDTO) {1895 var result = [];1896 gameDTO.cards.forEach((value) => {1897 if (value.zoneId == Zones.SUPPLY) {1898 if (result.indexOf(value.definitionId) == -1) {1899 result.push(value.definitionId);1900 }1901 }1902 });1903 return result;1904 }1905}1906class GameDTOTransform {1907 static createFromJSON(json) {1908 var jsonObj = JSON.parse(json);1909 var gameDTO = new GameDTO();1910 var players = [];1911 jsonObj["players"].forEach((eachPlayer) => {1912 var player = GameDTOTransform.obj2Instance(eachPlayer, GameDTO_Player);1913 var turn = GameDTOTransform.obj2Instance(eachPlayer["turn"], GameDTO_Player_Turn);1914 player.turn = turn;1915 players.push(player);1916 });1917 var cards = [];1918 jsonObj["cards"].forEach((eachCard) => {1919 cards.push(GameDTOTransform.obj2Instance(eachCard, GameDTO_Card));1920 });1921 var engine = new GameDTO_Engine();1922 var logicalStack = [];1923 jsonObj["engine"]["logicalStack"].forEach((eachLogicalBuffer) => {1924 var buffer = GameDTOTransform.obj2Instance(eachLogicalBuffer, GameDTO_LogicalBuffer);1925 var steps = [];1926 eachLogicalBuffer["steps"].forEach((eachStep) => {1927 steps.push(GameDTOTransform.obj2Instance(eachStep, GameDTO_LogicalBuffer_Step));1928 });1929 buffer.steps = steps;1930 logicalStack.push(buffer);1931 });1932 var reactionStack = [];1933 jsonObj["engine"]["reactionStack"].forEach((eachReactionBuffer) => {1934 var buffer = GameDTOTransform.obj2Instance(eachReactionBuffer, GameDTO_ReactionBuffer);1935 var potentialReactions = [];1936 eachReactionBuffer["potentialReactions"].forEach((eachPotentialReaction) => {1937 potentialReactions.push(GameDTOTransform.obj2Instance(eachPotentialReaction, ReactionKey));1938 });1939 buffer.potentialReactions = potentialReactions;1940 reactionStack.push(buffer);1941 });1942 var eventStack = [];1943 jsonObj["engine"]["eventStack"].forEach((eachEventEntry) => {1944 eventStack.push(GameDTOTransform.obj2Instance(eachEventEntry, GameDTO_EventEntry));1945 });1946 engine.eventStack = eventStack;1947 engine.reactionStack = reactionStack;1948 engine.logicalStack = logicalStack;1949 var state = GameDTOTransform.obj2Instance(jsonObj["state"], GameDTO_State);1950 gameDTO.players = players;1951 gameDTO.cards = cards;1952 gameDTO.engine = engine;1953 gameDTO.state = state;1954 return gameDTO;1955 }1956 static obj2Instance(object, type) {1957 var instance = new type();1958 for (var key in object) {1959 instance[key] = object[key];1960 }1961 return instance;1962 }1963}1964class EngineSource {1965}1966var EngineSourceType;1967(function (EngineSourceType) {1968 EngineSourceType[EngineSourceType["LOGICAL"] = 0] = "LOGICAL";1969 EngineSourceType[EngineSourceType["REACTION"] = 1] = "REACTION";1970 EngineSourceType[EngineSourceType["EVENT"] = 2] = "EVENT";1971 EngineSourceType[EngineSourceType["USER"] = 3] = "USER";1972})(EngineSourceType || (EngineSourceType = {}));1973class GameDriver {1974 constructor(gameDTO) {1975 this.waiting = false;1976 if (gameDTO != null) {1977 this.gameDTO = gameDTO;1978 }1979 else {1980 this.gameDTO = new GameDTO();1981 }1982 var __this = this;1983 DriverNotify.subscribe((message) => {1984 __this.process();1985 });1986 }1987 process() {1988 var shouldContinue = true;1989 while (shouldContinue) {1990 shouldContinue = this.step();1991 }1992 }1993 step() {1994 var continueStep = false;1995 var gameState = this.gameDTO.state.state;1996 var gameDTO = this.gameDTO;1997 ;1998 if (gameState == GameState.START) {1999 GamePopulator.populate(gameDTO);2000 GamePopulator.setFirstTurn(gameDTO);2001 }2002 if (GameDTOAccess.isGameOver(gameDTO)) {2003 GameDTOAccess.setState(gameDTO, GameState.END);2004 }2005 else if (GameDTOAccess.isLogicalStackCleared(gameDTO) &&2006 GameDTOAccess.isEventStackCleared(gameDTO) &&2007 GameDTOAccess.isReactionStackCleared(gameDTO)) {2008 GameDTOAccess.setState(gameDTO, GameState.TURN_WAITING);2009 }2010 if (gameState == GameState.RESOLVING_LOGICAL_STACK) {2011 if (!GameDTOAccess.isLogicalStackCleared(gameDTO)) {2012 var logicalStack = GameDTOAccess.getLogicalStack(gameDTO);2013 var output = logicalStack.processAndAdvance(gameDTO);2014 if (output.eventsGenerated) {2015 GameDTOAccess.setState(gameDTO, GameState.RESOLVING_EVENT_STACK);2016 }2017 else if (output.isCurrentBufferComplete) {2018 GameDTOAccess.setState(gameDTO, GameState.RESOLVING_REACTION_STACK);2019 }2020 }2021 else {2022 GameDTOAccess.setState(gameDTO, GameState.RESOLVING_REACTION_STACK);2023 }2024 continueStep = true;2025 }2026 else if (gameState == GameState.RESOLVING_EVENT_STACK) {2027 if (!GameDTOAccess.isEventStackCleared(gameDTO)) {2028 var eventStack = GameDTOAccess.getEventStack(gameDTO);2029 var eventStackOutput = eventStack.processAndAdvance(gameDTO);2030 if (eventStackOutput.reactionsGenerated) {2031 GameDTOAccess.setState(gameDTO, GameState.RESOLVING_REACTION_STACK);2032 }2033 else if (eventStackOutput.isCurrentBufferComplete) {2034 GameDTOAccess.setState(gameDTO, GameState.RESOLVING_LOGICAL_STACK);2035 }2036 }2037 else {2038 GameDTOAccess.setState(gameDTO, GameState.RESOLVING_LOGICAL_STACK);2039 }2040 continueStep = true;2041 }2042 else if (gameState == GameState.RESOLVING_REACTION_STACK) {2043 if (!GameDTOAccess.isReactionStackCleared(gameDTO)) {2044 var reactionStack = GameDTOAccess.getReactionStack(gameDTO);2045 var reactionStackOutput = reactionStack.processAndAdvance(gameDTO);2046 if (reactionStackOutput.createdLogicalOutput) {2047 GameDTOAccess.setState(gameDTO, GameState.RESOLVING_LOGICAL_STACK);2048 }2049 else if (reactionStackOutput.currentBufferFinished) {2050 GameDTOAccess.setState(gameDTO, GameState.RESOLVING_EVENT_STACK);2051 }2052 }2053 else {2054 GameDTOAccess.setState(gameDTO, GameState.RESOLVING_EVENT_STACK);2055 }2056 continueStep = true;2057 }2058 if (gameState == GameState.TURN_WAITING || gameState == GameState.WAITING_FOR_PLAYER_CHOICE) {2059 continueStep = false;2060 }2061 return continueStep;2062 }2063}2064var GameState;2065(function (GameState) {2066 GameState[GameState["NOT_STARTED"] = 0] = "NOT_STARTED";2067 GameState[GameState["START"] = 1] = "START";2068 GameState[GameState["TURN_WAITING"] = 2] = "TURN_WAITING";2069 GameState[GameState["RESOLVING_LOGICAL_STACK"] = 3] = "RESOLVING_LOGICAL_STACK";2070 GameState[GameState["RESOLVING_REACTION_STACK"] = 4] = "RESOLVING_REACTION_STACK";2071 GameState[GameState["RESOLVING_EVENT_STACK"] = 5] = "RESOLVING_EVENT_STACK";2072 GameState[GameState["WAITING_FOR_PLAYER_CHOICE"] = 6] = "WAITING_FOR_PLAYER_CHOICE";2073 GameState[GameState["END"] = 7] = "END";2074})(GameState || (GameState = {}));2075class GamePopulator {2076 static populate(gameDTO) {2077 GamePopulator.populateCards(gameDTO);2078 // GamePopulator.populateUsers(gameDTO);2079 GamePopulator.openingDecks(gameDTO);2080 GamePopulator.openingDraws(gameDTO);2081 }2082 static setFirstTurn(gameDTO) {2083 Util.shuffle(gameDTO.players);2084 GameDTOAccess.setTurn(gameDTO, gameDTO.players[0].uuid);2085 }2086 static populateCards(gameDTO) {2087 var chosenKingdomCards = Util.shuffle(GamePopulator.kingdomCards).slice(0, 10);2088 chosenKingdomCards.forEach((value) => {2089 for (var i = 0; i < 10; i++) {2090 var dto = GamePopulator.createNewCardDTO(gameDTO, value, "NONE");2091 gameDTO.cards.push(dto);2092 }2093 });2094 GamePopulator.otherSupplyCards.forEach((value) => {2095 var cardId = value[0];2096 var numToCreate = value[1];2097 for (var i = 0; i < numToCreate; i++) {2098 var dto = GamePopulator.createNewCardDTO(gameDTO, cardId, "NONE");2099 gameDTO.cards.push(dto);2100 }2101 });2102 }2103 static populateUsers(gameDTO) {2104 var player1 = new GameDTO_Player();2105 player1.uuid = UUID();2106 player1.name = "Adam";2107 var player2 = new GameDTO_Player();2108 player2.name = "Eve";2109 player2.uuid = UUID();2110 gameDTO.players.push(player1);2111 gameDTO.players.push(player2);2112 }2113 static openingDecks(gameDTO) {2114 var _ = new LogicalUtils();2115 gameDTO.players.forEach((eachPlayer) => {2116 for (var i = 0; i < 7; i++) {2117 var nextCopper = GameDTOAccess.getNextCardInSupplyPile(gameDTO, CardIds.COPPER);2118 GameDTOAccess.setOwner(gameDTO, nextCopper, eachPlayer.uuid);2119 GameDTOAccess.setZone(gameDTO, nextCopper, Zones.DECK);2120 Log.send(eachPlayer.name + " gained a COPPER");2121 }2122 for (var i = 0; i < 3; i++) {2123 var nextEstate = GameDTOAccess.getNextCardInSupplyPile(gameDTO, CardIds.ESTATE);2124 GameDTOAccess.setOwner(gameDTO, nextEstate, eachPlayer.uuid);2125 GameDTOAccess.setZone(gameDTO, nextEstate, Zones.DECK);2126 Log.send(eachPlayer.name + " gained an ESTATE");2127 }2128 GameDTOAccess.shuffleDeck(gameDTO, eachPlayer.uuid);2129 });2130 }2131 static openingDraws(gameDTO) {2132 var _ = new LogicalUtils();2133 var lu = new LoggingUtils(gameDTO);2134 gameDTO.players.forEach((eachPlayer) => {2135 for (var i = 0; i < 5; i++) {2136 var cardUUID = GameDTOAccess.getTopCardOfDeck(gameDTO, eachPlayer.uuid);2137 GameDTOAccess.setZone(gameDTO, cardUUID, Zones.HAND);2138 Log.send(eachPlayer.name + " drew " + lu.fname(cardUUID) + ". Owner garuntee: " + lu.owner(cardUUID));2139 }2140 });2141 }2142 static createNewCardDTO(gameDTO, id, ownerUUID) {2143 var dto = new GameDTO_Card();2144 dto.definitionId = id;2145 dto.ownerUUID = ownerUUID;2146 dto.uuid = UUID();2147 dto.zoneId = Zones.SUPPLY;2148 dto.zoneIndex = GameDTOAccess.getCardsInPile(gameDTO, id).length;2149 ReactionBuffer.RegisterReactiveComponent(new ReactionKey(ReactionSourceType.CARD, dto.uuid), (gameDTOArg, uuid) => {2150 var cardDTO = GameDTOAccess.getCardDTO(gameDTOArg, uuid);2151 return CardDefinition.createFromDTO(cardDTO);2152 });2153 return dto;2154 }2155}2156GamePopulator.kingdomCards = [2157 CardIds.WORKSHOP,2158 CardIds.WITCH,2159 CardIds.MOAT,2160 CardIds.CELLAR,2161 CardIds.LIBRARY,2162 CardIds.ARTISAN,2163 CardIds.BANDIT,2164 CardIds.BUREAUCRAT,2165 CardIds.CHAPEL,2166 CardIds.COUNCIL_ROOM,2167 CardIds.FESTIVAL,2168 CardIds.HARBINGER,2169 CardIds.LABORATORY,2170 CardIds.MARKET,2171 CardIds.MERCHANT,2172 CardIds.MILITIA,2173 CardIds.MINE,2174 CardIds.MONEYLENDER,2175 CardIds.POACHER,2176 CardIds.REMODEL,2177 CardIds.SENTRY,2178 CardIds.SMITHY,2179 CardIds.THRONE_ROOM,2180 CardIds.VASSAL,2181 CardIds.VILLAGE2182];2183GamePopulator.otherSupplyCards = [2184 [CardIds.COPPER, 60],2185 [CardIds.SILVER, 40],2186 [CardIds.GOLD, 30],2187 [CardIds.ESTATE, 24],2188 [CardIds.DUCHY, 12],2189 [CardIds.PROVINCE, 12],2190 [CardIds.CURSE, 10]2191];2192class EventArgs {2193 constructor() {2194 this.data = {};2195 }2196 add(key, value) {2197 this.data[key] = value;2198 return this;2199 }2200}2201var EventIds;2202(function (EventIds) {2203 EventIds[EventIds["CARD_PLAYED"] = 0] = "CARD_PLAYED";2204 EventIds[EventIds["ADD_MONEY"] = 1] = "ADD_MONEY";2205 EventIds[EventIds["GAIN_CARD"] = 2] = "GAIN_CARD";2206 EventIds[EventIds["DRAW_CARD"] = 3] = "DRAW_CARD";2207 EventIds[EventIds["SET_UNAFFECTED"] = 4] = "SET_UNAFFECTED";2208 EventIds[EventIds["REVEAL_CARD"] = 5] = "REVEAL_CARD";2209 EventIds[EventIds["DISCARD_CARD"] = 6] = "DISCARD_CARD";2210 EventIds[EventIds["TRASH_CARD"] = 7] = "TRASH_CARD";2211 EventIds[EventIds["SET_CARD_ONTO_DECK"] = 8] = "SET_CARD_ONTO_DECK";2212 EventIds[EventIds["PLACE_IN_DECK"] = 9] = "PLACE_IN_DECK";2213 EventIds[EventIds["ADD_ACTION"] = 10] = "ADD_ACTION";2214 EventIds[EventIds["ADD_BUYS"] = 11] = "ADD_BUYS";2215 EventIds[EventIds["RESHUFFLE_DECK"] = 12] = "RESHUFFLE_DECK";2216 EventIds[EventIds["ADVANCE_PHASE"] = 13] = "ADVANCE_PHASE";2217})(EventIds || (EventIds = {}));2218var EventSourceType;2219(function (EventSourceType) {2220 EventSourceType[EventSourceType["CARD"] = 0] = "CARD";2221 EventSourceType[EventSourceType["PLAYER"] = 1] = "PLAYER";2222})(EventSourceType || (EventSourceType = {}));2223class EventStack {2224 constructor() {2225 this.events = [];2226 }2227 processAndAdvance(gameDTO) {2228 EventStack.currentOutput = new EventStackOutput();2229 var topEvent = this.events[this.events.length - 1];2230 //Log.send(EventIds[topEvent.getId()] + " " + EventStatus[topEvent.status] + " reactionsPolled? " + topEvent.reactionsPolled);2231 if (topEvent.reactionsPolled == false) {2232 var reactions = ReactionBuffer.pollReactions(topEvent, gameDTO);2233 //Log.send("EventStack: " + JSON.stringify(gameDTO.engine.eventStack));2234 //Log.send("Reactions: " + JSON.stringify(reactions));2235 if (reactions.length > 0) {2236 var newReactionBuffer = new ReactionBuffer(topEvent.uuid, topEvent.status, reactions);2237 GameDTOAccess.pushNewReactionBuffer(gameDTO, newReactionBuffer);2238 EventStack.currentOutput.reactionsGenerated = true;2239 }2240 topEvent.reactionsPolled = true;2241 GameDTOAccess.updateEvent(gameDTO, topEvent);2242 }2243 else {2244 topEvent.reactionsPolled = false;2245 if (topEvent.status == EventStatus.DECLARED) {2246 topEvent.status = EventStatus.RESOLVING;2247 GameDTOAccess.updateEvent(gameDTO, topEvent);2248 }2249 else if (topEvent.status == EventStatus.RESOLVING) {2250 topEvent.execute(gameDTO);2251 topEvent.status = EventStatus.RESOLVED;2252 GameDTOAccess.updateEvent(gameDTO, topEvent);2253 }2254 else if (topEvent.status == EventStatus.RESOLVED) {2255 EventStack.currentOutput.isCurrentBufferComplete = true;2256 GameDTOAccess.removeEvent(gameDTO, topEvent);2257 }2258 }2259 //Log.send("EventStack after EventStack.advance: " + JSON.stringify(gameDTO.engine.eventStack));2260 return EventStack.currentOutput;2261 }2262}2263class EventStackOutput {2264}2265var EventStatus;2266(function (EventStatus) {2267 EventStatus[EventStatus["DECLARED"] = 0] = "DECLARED";2268 EventStatus[EventStatus["RESOLVING"] = 1] = "RESOLVING";2269 EventStatus[EventStatus["RESOLVED"] = 2] = "RESOLVED";2270})(EventStatus || (EventStatus = {}));2271class GameEvent {2272 constructor(eventSource, eventSourceUUID, args) {2273 this.status = EventStatus.DECLARED;2274 this.reactionsPolled = false;2275 if (args != null) {2276 this.eventSource = eventSource;2277 this.eventSourceUUID = eventSourceUUID;2278 this.uuid = UUID();2279 this.args = args;2280 this.populateFromArgs(args);2281 }2282 }2283 static create(eventId, args) {2284 return GameEvent.EVENT_DEFINITION[eventId](args);2285 }2286 static createWithStatus(eventId, status, args) {2287 var event = GameEvent.EVENT_DEFINITION[eventId](args);2288 event.status = status;2289 return event;2290 }2291 static createFromDTO(dto) {2292 var event = GameEvent.EVENT_DEFINITION[dto.eventId](dto.args);2293 event.populateFromArgs(dto.args);2294 event.status = dto.status;2295 event.reactionsPolled = dto.reactionsPolled;2296 event.uuid = dto.eventUUID;2297 event.eventSourceUUID = dto.sourceUUID;2298 return event;2299 }2300 convertToDTO() {2301 var eventEntry = new GameDTO_EventEntry();2302 eventEntry.sourceType = this.eventSource;2303 eventEntry.eventId = this.getId();2304 eventEntry.sourceUUID = this.eventSourceUUID;2305 eventEntry.args = this.args;2306 eventEntry.reactionsPolled = this.reactionsPolled;2307 eventEntry.status = this.status;2308 return eventEntry;2309 }2310 static registerCardGenerator(id, generator) {2311 GameEvent.EVENT_DEFINITION[id] = generator;2312 }2313 configureGenerator() {2314 var _this = this;2315 GameEvent.registerCardGenerator(this.getId(), (args) => {2316 var instance = new _this.constructor(null, null, args);2317 return instance;2318 });2319 }2320}2321GameEvent.EVENT_DEFINITION = {};2322function RegisterEvent(gameEventType) {2323 new gameEventType().configureGenerator();2324}2325///<reference path="../GameEvent.ts" />2326///<reference path="../EventArgs.ts" />2327class AddActionEvent extends GameEvent {2328 populateFromArgs(args) {2329 this.playerToAddActionToUUID = args[AddActionEvent.PLAYER_UUID];2330 this.amount = args[AddActionEvent.AMOUNT];2331 }2332 getId() {2333 return EventIds.ADD_ACTION;2334 }2335 execute(gameDTO) {2336 var player = GameDTOAccess.getPlayerFromUUID(gameDTO, this.playerToAddActionToUUID);2337 player.turn.actions += this.amount;2338 var lu = new LoggingUtils(gameDTO);2339 Log.send(lu.fname(this.playerToAddActionToUUID) + " received +" + this.amount + " Action(s).");2340 }2341}2342AddActionEvent.PLAYER_UUID = "PLAYER_UUID";2343AddActionEvent.AMOUNT = "AMOUNT";2344class AddActionEventArgs extends EventArgs {2345 constructor(playerUUID, amount) {2346 super();2347 this.add(AddActionEvent.PLAYER_UUID, playerUUID).add(AddActionEvent.AMOUNT, amount);2348 }2349}2350RegisterEvent(AddActionEvent);2351///<reference path="../GameEvent.ts" />2352///<reference path="../EventArgs.ts" />2353class AddBuysEvent extends GameEvent {2354 populateFromArgs(args) {2355 this.playerToAddMoneyToUUID = args[AddBuysEvent.PLAYER_UUID];2356 this.amount = args[AddBuysEvent.AMOUNT];2357 }2358 getId() {2359 return EventIds.ADD_BUYS;2360 }2361 execute(gameDTO) {2362 var player = GameDTOAccess.getPlayerFromUUID(gameDTO, this.playerToAddMoneyToUUID);2363 player.turn.buys += this.amount;2364 }2365}2366AddBuysEvent.PLAYER_UUID = "PLAYER_UUID";2367AddBuysEvent.AMOUNT = "AMOUNT";2368class AddBuysEventArgs extends EventArgs {2369 constructor(playerUUID, amount) {2370 super();2371 this.add(AddBuysEvent.PLAYER_UUID, playerUUID).add(AddBuysEvent.AMOUNT, amount);2372 }2373}2374RegisterEvent(AddBuysEvent);2375///<reference path="../GameEvent.ts" />2376///<reference path="../EventArgs.ts" />2377class AddMoneyEvent extends GameEvent {2378 populateFromArgs(args) {2379 this.playerToAddMoneyToUUID = args[AddMoneyEvent.PLAYER_UUID];2380 this.amount = args[AddMoneyEvent.AMOUNT];2381 }2382 getId() {2383 return EventIds.ADD_MONEY;2384 }2385 execute(gameDTO) {2386 var player = GameDTOAccess.getPlayerFromUUID(gameDTO, this.playerToAddMoneyToUUID);2387 player.turn.money += this.amount;2388 var lu = new LoggingUtils(gameDTO);2389 if (this.amount >= 0) {2390 Log.send(lu.fname(this.playerToAddMoneyToUUID) + " +" + this.amount + " money.");2391 }2392 else {2393 Log.send(lu.fname(this.playerToAddMoneyToUUID) + " " + this.amount + " money.");2394 }2395 }2396}2397AddMoneyEvent.PLAYER_UUID = "PLAYER_UUID";2398AddMoneyEvent.AMOUNT = "AMOUNT";2399class AddMoneyEventArgs extends EventArgs {2400 constructor(playerUUID, amount) {2401 super();2402 this.add(AddMoneyEvent.PLAYER_UUID, playerUUID).add(AddMoneyEvent.AMOUNT, amount);2403 }2404}2405RegisterEvent(AddMoneyEvent);2406class AdvancePhaseEvent extends GameEvent {2407 populateFromArgs(args) {2408 }2409 getId() {2410 return EventIds.ADVANCE_PHASE;2411 }2412 execute(gameDTO) {2413 if (gameDTO.state.phase == Phase.ACTION) {2414 gameDTO.state.phase = Phase.BUY;2415 }2416 else if (gameDTO.state.phase == Phase.BUY) {2417 gameDTO.state.phase = Phase.CLEAN_UP;2418 }2419 else if (gameDTO.state.phase == Phase.CLEAN_UP) {2420 gameDTO.state.phase = Phase.ACTION;2421 GameDTOAccess.changeTurns(gameDTO);2422 }2423 Log.send("Phase is now " + Phase[gameDTO.state.phase]);2424 }2425}2426RegisterEvent(AdvancePhaseEvent);2427class CardPlayedEvent extends GameEvent {2428 execute(gameDTO) {2429 GameDTOAccess.setZone(gameDTO, this.CARD_UUID, Zones.IN_PLAY);2430 var lu = new LoggingUtils(gameDTO);2431 Log.send(lu.owner(this.CARD_UUID) + " played " + lu.fname(this.CARD_UUID));2432 }2433 populateFromArgs(args) {2434 this.CARD_UUID = args[CardPlayedEvent.CARD_UUID];2435 }2436 getId() {2437 return EventIds.CARD_PLAYED;2438 }2439}2440CardPlayedEvent.CARD_UUID = "CARD_UUID";2441class CardPlayedEventArgs extends EventArgs {2442 constructor(cardUUID) {2443 super();2444 this.add(CardPlayedEvent.CARD_UUID, cardUUID);2445 }2446}2447RegisterEvent(CardPlayedEvent);2448///<reference path="../GameEvent.ts" />2449class DiscardCardsEvent extends GameEvent {2450 populateFromArgs(args) {2451 this.chosenCard = args[DiscardCardsEvent.CHOSEN_CARD];2452 }2453 getId() {2454 return EventIds.DISCARD_CARD;2455 }2456 execute(gameDTO) {2457 var lu = new LoggingUtils(gameDTO);2458 Log.send(lu.owner(this.chosenCard) + " discards " + lu.fname(this.chosenCard));2459 GameDTOAccess.setZone(gameDTO, this.chosenCard, Zones.DISCARD_PILE);2460 }2461}2462DiscardCardsEvent.CHOSEN_CARD = "CHOSEN_CARD";2463class DiscardCardsEventArgs extends EventArgs {2464 constructor(chosenCard) {2465 super();2466 this.add(DiscardCardsEvent.CHOSEN_CARD, chosenCard);2467 }2468}2469RegisterEvent(DiscardCardsEvent);2470///<reference path="../GameEvent.ts" />2471class DrawCardsEvent extends GameEvent {2472 constructor() {2473 super(...arguments);2474 this.amount = 1;2475 }2476 populateFromArgs(args) {2477 this.recipient = args[DrawCardsEvent.RECIPIENT];2478 }2479 getId() {2480 return EventIds.DRAW_CARD;2481 }2482 execute(gameDTO) {2483 var lu = new LoggingUtils(gameDTO);2484 var deck = GameDTOAccess.getCardDTOsInZone(gameDTO, this.recipient, Zones.DECK);2485 var cardUUID = GameDTOAccess.getTopCardOfDeck(gameDTO, this.recipient);2486 GameDTOAccess.setZone(gameDTO, cardUUID, Zones.HAND);2487 Log.send(lu.owner(cardUUID) + " draws " + lu.fname(cardUUID));2488 }2489}2490DrawCardsEvent.RECIPIENT = "RECIPIENT";2491class DrawCardsEventArgs extends EventArgs {2492 constructor(recipient) {2493 super();2494 this.add(DrawCardsEvent.RECIPIENT, recipient);2495 }2496}2497RegisterEvent(DrawCardsEvent);2498/*///<reference path="../GameEvent.ts" />2499class GainActionsEvent extends GameEvent {2500 static RECIPIENT: string = "RECIPIENT";2501 static AMOUNT: string = "AMOUNT";2502 playerToAddMoneyToUUID: string;2503 amount: number;2504 populateFromArgs(args: {}): void {2505 this.playerToAddMoneyToUUID = args[GainActionsEvent.RECIPIENT];2506 this.amount = args[GainActionsEvent.AMOUNT];2507 }2508 getId(): number {2509 return EventIds.ADD_ACTION;2510 }2511 execute(gameDTO: GameDTO): void {2512 }2513}2514class GainActionsEventArgs extends EventArgs {2515 constructor(recipient: EffectBufferVariable, amount: EffectBufferVariable) {2516 super();2517 this.add(GainActionsEvent.RECIPIENT, recipient).add(GainActionsEvent.AMOUNT, amount);2518 }2519}2520RegisterEvent(GainActionsEvent);*/ 2521////<reference path="../GameEvent.ts" />2522class GainCardEvent extends GameEvent {2523 populateFromArgs(args) {2524 this.recipient = args[GainCardEvent.RECIPIENT];2525 this.chosenCard = args[GainCardEvent.CHOSEN_CARD];2526 if (args[GainCardEvent.GAIN_LOCATION] == null) {2527 this.gainLocation = Zones.DISCARD_PILE;2528 }2529 else {2530 this.gainLocation = args[GainCardEvent.GAIN_LOCATION];2531 }2532 }2533 getId() {2534 return EventIds.GAIN_CARD;2535 }2536 execute(gameDTO) {2537 GameDTOAccess.setOwner(gameDTO, this.chosenCard, this.recipient);2538 GameDTOAccess.setZone(gameDTO, this.chosenCard, this.gainLocation);2539 var lu = new LoggingUtils(gameDTO);2540 Log.send(lu.owner(this.chosenCard) + " gained a(n) " + lu.fname(this.chosenCard) + " to " + Zones[this.gainLocation]);2541 }2542}2543GainCardEvent.GAIN_LOCATION = "GAIN_LOCATION";2544GainCardEvent.RECIPIENT = "RECIPIENT";2545GainCardEvent.CHOSEN_CARD = "CHOSEN_CARD";2546class GainCardEventArgs extends EventArgs {2547 constructor(recipient, chosenCard, gainLocation) {2548 super();2549 this.add(GainCardEvent.RECIPIENT, recipient).add(GainCardEvent.CHOSEN_CARD, chosenCard).add(GainCardEvent.GAIN_LOCATION, gainLocation);2550 }2551}2552RegisterEvent(GainCardEvent);2553class PlaceInDeckEvent extends GameEvent {2554 populateFromArgs(args) {2555 this.cardUUID = args[PlaceInDeckEvent.CARD_UUID];2556 this.index = args[PlaceInDeckEvent.INDEX];2557 }2558 getId() {2559 return EventIds.PLACE_IN_DECK;2560 }2561 execute(gameDTO) {2562 GameDTOAccess.setZone(gameDTO, this.cardUUID, Zones.DECK);2563 if (this.index == PlaceInDeckEventOptions.TOP) {2564 GameDTOAccess.setDeckIndex(gameDTO, this.cardUUID, deckSize - 1);2565 }2566 else {2567 var owner = GameDTOAccess.getOwner(gameDTO, this.cardUUID);2568 var deckSize = GameDTOAccess.getCardsInZone(gameDTO, owner, Zones.DECK).length;2569 GameDTOAccess.setDeckIndex(gameDTO, this.cardUUID, 0);2570 }2571 var lu = new LoggingUtils(gameDTO);2572 Log.send(lu.owner(this.cardUUID) + " placed " + lu.fname(this.cardUUID) + " at deck position " + this.index);2573 }2574}2575PlaceInDeckEvent.CARD_UUID = "CARD_UUID";2576PlaceInDeckEvent.INDEX = "INDEX";2577class PlaceInDeckEventArgs extends EventArgs {2578 constructor(cardUUID, index) {2579 super();2580 this.add(PlaceInDeckEvent.CARD_UUID, cardUUID).add(PlaceInDeckEvent.INDEX, index);2581 }2582}2583class PlaceInDeckEventOptions {2584}2585PlaceInDeckEventOptions.TOP = "TOP";2586PlaceInDeckEventOptions.BOTTOM = "BOTTOM";2587RegisterEvent(PlaceInDeckEvent);2588///<reference path="../GameEvent.ts" />2589class ReshuffleDeckEvent extends GameEvent {2590 populateFromArgs(args) {2591 this.recipient = args[ReshuffleDeckEvent.WHOSE_DECK];2592 }2593 getId() {2594 return EventIds.RESHUFFLE_DECK;2595 }2596 execute(gameDTO) {2597 var lu = new LoggingUtils(gameDTO);2598 GameDTOAccess.getCardsInZone(gameDTO, this.recipient, Zones.DISCARD_PILE).forEach((eachUUID) => {2599 GameDTOAccess.setZone(gameDTO, eachUUID, Zones.DECK);2600 });2601 GameDTOAccess.shuffleDeck(gameDTO, this.recipient);2602 Log.send(lu.fname(this.recipient) + " reshuffles.");2603 }2604}2605ReshuffleDeckEvent.WHOSE_DECK = "WHOSE_DECK";2606class ReshuffleDeckEventArgs extends EventArgs {2607 constructor(whose) {2608 super();2609 this.add(ReshuffleDeckEvent.WHOSE_DECK, whose);2610 }2611}2612RegisterEvent(ReshuffleDeckEvent);2613///<reference path="../GameEvent.ts" />2614class RevealCardEvent extends GameEvent {2615 execute(gameDTO) {2616 var lu = new LoggingUtils(gameDTO);2617 GameDTOAccess.setZone(gameDTO, this.chosenCard, Zones.REVEALED);2618 Log.send(lu.owner(this.chosenCard) + " revealed a(n) " + lu.fname(this.chosenCard));2619 }2620 populateFromArgs(args) {2621 this.chosenCard = args[RevealCardEvent.CARD_UUID];2622 }2623 getId() {2624 return EventIds.REVEAL_CARD;2625 }2626}2627RevealCardEvent.CARD_UUID = "CARD_UUID";2628class RevealCardEventArgs extends EventArgs {2629 constructor(cardUUID) {2630 super();2631 this.add(RevealCardEvent.CARD_UUID, cardUUID);2632 }2633}2634RegisterEvent(RevealCardEvent);2635///<reference path="../GameEvent.ts" />2636class SetCardOntoDeckEvent extends GameEvent {2637 populateFromArgs(args) {2638 this.recipient = args[SetCardOntoDeckEvent.AFFECTED_PLAYER];2639 this.chosenCard = args[SetCardOntoDeckEvent.CHOSEN_CARD];2640 }2641 getId() {2642 return EventIds.SET_CARD_ONTO_DECK;2643 }2644 execute(gameDTO) {2645 var lu = new LoggingUtils(gameDTO);2646 GameDTOAccess.setZone(gameDTO, this.chosenCard, Zones.DECK);2647 var deckSize = GameDTOAccess.getCardsInZone(gameDTO, this.recipient, Zones.DECK).length;2648 GameDTOAccess.setDeckIndex(gameDTO, this.chosenCard, deckSize - 1);2649 Log.send(lu.owner(this.chosenCard) + " puts " + lu.fname(this.chosenCard) + " on top of the deck.");2650 }2651}2652SetCardOntoDeckEvent.AFFECTED_PLAYER = "RECIPIENT";2653SetCardOntoDeckEvent.CHOSEN_CARD = "CHOSEN_CARD";2654class SetCardOntoDeckEventArgs extends EventArgs {2655 constructor(affectedPlayers, chosenCard) {2656 super();2657 this.add(SetCardOntoDeckEvent.AFFECTED_PLAYER, affectedPlayers).add(SetCardOntoDeckEvent.CHOSEN_CARD, chosenCard);2658 }2659}2660RegisterEvent(SetCardOntoDeckEvent);2661///<reference path="../GameEvent.ts" />2662class SetUnaffectedEvent extends GameEvent {2663 populateFromArgs(args) {2664 this.recipient = args[SetUnaffectedEvent.PROTECTED_PLAYER];2665 this.cardProtectedFrom = args[SetUnaffectedEvent.PROTECTED_FROM];2666 this.action = args[SetUnaffectedEvent.ACTION];2667 }2668 getId() {2669 return EventIds.SET_UNAFFECTED;2670 }2671 execute(gameDTO) {2672 if (this.action == SetUnaffectedEventAction.SET) {2673 GameDTOAccess.setPlayerUnaffectedByEffect(gameDTO, this.recipient, this.cardProtectedFrom);2674 }2675 else if (this.action == SetUnaffectedEventAction.REMOVE) {2676 GameDTOAccess.removePlayerUnaffectedByEffect(gameDTO, this.recipient, this.cardProtectedFrom);2677 }2678 }2679}2680SetUnaffectedEvent.PROTECTED_PLAYER = "PROTECTED_PLAYER";2681SetUnaffectedEvent.PROTECTED_FROM = "PROTECTED_FROM";2682SetUnaffectedEvent.ACTION = "ACTION";2683class SetUnaffectedEventArgs extends EventArgs {2684 constructor(protectedPlayer, protectedFrom, action) {2685 super();2686 this.add(SetUnaffectedEvent.PROTECTED_PLAYER, protectedPlayer).add(SetUnaffectedEvent.PROTECTED_FROM, protectedFrom).add(SetUnaffectedEvent.ACTION, action);2687 }2688}2689var SetUnaffectedEventAction;2690(function (SetUnaffectedEventAction) {2691 SetUnaffectedEventAction[SetUnaffectedEventAction["SET"] = 0] = "SET";2692 SetUnaffectedEventAction[SetUnaffectedEventAction["REMOVE"] = 1] = "REMOVE";2693})(SetUnaffectedEventAction || (SetUnaffectedEventAction = {}));2694RegisterEvent(SetUnaffectedEvent);2695class TrashCardsEvent extends GameEvent {2696 populateFromArgs(args) {2697 this.chosenCard = args[TrashCardsEvent.CARD_UUID];2698 }2699 getId() {2700 return EventIds.TRASH_CARD;2701 }2702 execute(gameDTO) {2703 GameDTOAccess.setZone(gameDTO, this.chosenCard, Zones.TRASH);2704 var lu = new LoggingUtils(gameDTO);2705 Log.send(lu.owner(this.chosenCard) + " trashed a(n) " + lu.fname(this.chosenCard));2706 }2707}2708TrashCardsEvent.CARD_UUID = "CARD_UUID";2709class TrashCardsEventArgs extends EventArgs {2710 constructor(cardUUID) {2711 super();2712 this.add(PlaceInDeckEvent.CARD_UUID, cardUUID);2713 }2714}2715RegisterEvent(TrashCardsEvent);2716class LogicalBuffer {2717 constructor() {2718 this.steps = [];2719 this.storedData = {};2720 this.isComplete = false;2721 }2722 addStep(step) {2723 this.steps.push(step);2724 }2725 addSteps(...steps) {2726 var __this = this;2727 steps.forEach((value) => {2728 __this.steps.push(value);2729 });2730 }2731 addAllSteps(steps) {2732 var __this = this;2733 steps.forEach((value) => {2734 __this.steps.push(value);2735 });2736 }2737 processAndAdvance(gameDTO) {2738 if (this.currentStepUUID == null) {2739 this.currentStepUUID = this.steps[0].uuid;2740 }2741 var currentStep = this.getCurrentStep();2742 //Log.send("Executing step: " + StepId[currentStep.getStepId()])2743 var isComplete = currentStep.processAndAdvance(this, gameDTO);2744 if (isComplete) {2745 if (this.currentStepUUID == currentStep.uuid) {2746 var indexOf = this.steps.indexOf(currentStep);2747 if ((indexOf >= (this.steps.length - 1))) {2748 this.currentStepUUID = null;2749 this.isComplete = true;2750 }2751 else {2752 this.currentStepUUID = this.steps[indexOf + 1].uuid;2753 }2754 }2755 }2756 GameDTOAccess.updateLogicalBuffer(gameDTO, this);2757 return this.isComplete;2758 }2759 getCurrentStep() {2760 var result = null;2761 var __this = this;2762 if (this.currentStepUUID == null) {2763 this.currentStepUUID = this.steps[0].uuid;2764 }2765 this.steps.forEach((value) => {2766 if (value.uuid == __this.currentStepUUID) {2767 result = value;2768 }2769 });2770 return result;2771 }2772 static createFromDTO(dto, gameDTO) {2773 var obj = new LogicalBuffer();2774 obj.uuid = dto.uuid;2775 obj.currentStepUUID = dto.currentStep;2776 obj.steps = [];2777 obj.storedData = dto.storedData;2778 dto.steps.forEach((each) => {2779 obj.steps.push(LogicalStep.create(each.stepId, each, obj, gameDTO));2780 });2781 return obj;2782 }2783 convertToDTO(gameDTO) {2784 var __this = this;2785 var dto = new GameDTO_LogicalBuffer();2786 dto.uuid = this.uuid;2787 dto.currentStep = this.currentStepUUID;2788 dto.steps = [];2789 dto.storedData = this.storedData;2790 this.steps.forEach((each) => {2791 dto.steps.push(each.convertToDTO());2792 });2793 return dto;2794 }2795 reset() {2796 this.steps.forEach((eachStep) => {2797 eachStep.reset();2798 });2799 this.storedData = {};2800 }2801}2802class LogicalStack {2803 constructor() {2804 this.buffers = [];2805 }2806 processAndAdvance(gameDTO) {2807 LogicalStack.currentOutput = new LogicalStackOutput();2808 var topBuffer = this.buffers[this.buffers.length - 1];2809 var isComplete = topBuffer.processAndAdvance(gameDTO);2810 if (isComplete) {2811 LogicalStack.currentOutput.isCurrentBufferComplete = true;2812 GameDTOAccess.removeLogicalBuffer(gameDTO, topBuffer);2813 }2814 if (this.buffers.length == 0) {2815 LogicalStack.currentOutput.isEmpty = true;2816 LogicalStack.currentOutput.isCurrentBufferComplete = true;2817 }2818 return LogicalStack.currentOutput;2819 }2820}2821class LogicalStackOutput {2822}2823class LogicalStep {2824 constructor() {2825 this.uuid = UUID();2826 }2827 configureGenerator() {2828 var _this = this;2829 LogicalStep.registerCardGenerator(this.getStepId(), (dto, logicalBuffer, gameDTO) => {2830 var instance = new _this.constructor();2831 instance.constructFromDTO(dto, logicalBuffer, gameDTO);2832 return instance;2833 });2834 }2835 static createFromDTO(dto, logicalBuffer, gameDTO) {2836 return LogicalStep.create(dto.stepId, dto, logicalBuffer, gameDTO);2837 }2838 static registerCardGenerator(id, generator) {2839 LogicalStep.STEP_DEFINITION[id] = generator;2840 }2841 static create(id, dto, logicalBuffer, gameDTO) {2842 return LogicalStep.STEP_DEFINITION[id](dto, logicalBuffer, gameDTO);2843 }2844}2845LogicalStep.STEP_DEFINITION = {};2846function RegisterEventBufferStep(stepType) {2847 new stepType().configureGenerator();2848}2849class LogicalUtils {2850 Value(value) {2851 return new LogicalValue(value);2852 }2853 Reference(value) {2854 return new LogicalReference(value);2855 }2856 Exactly(value) {2857 return new PlayerChoicePreposition(PlayerChoicePrepositionValues.EXACTLY, value);2858 }2859 UpTo(value) {2860 return new PlayerChoicePreposition(PlayerChoicePrepositionValues.UP_TO, value);2861 }2862 CreateEvent(eventId, eventGeneratorArgs) {2863 return GameEvent.create(eventId, eventGeneratorArgs.data);2864 }2865 ResolveVariable(variable, logicalBuffer) {2866 if (variable.type == LogicalVariableType.VALUE) {2867 return variable.value;2868 }2869 else if (variable.type == LogicalVariableType.REFERENCE) {2870 //Log.send(variable.value + " = " + logicalBuffer.storedData[variable.value]);2871 return logicalBuffer.storedData[variable.value];2872 }2873 }2874 SerializeString2DTOMap(valueMap) {2875 var result = {};2876 for (var key in valueMap) {2877 if (valueMap.hasOwnProperty(key)) {2878 result[key] = [];2879 valueMap[key].forEach((value, index) => {2880 result[key].push(value.convertToDTO());2881 });2882 }2883 }2884 return result;2885 }2886 SerializeDTOArray(dtoArray) {2887 var result = [];2888 dtoArray.forEach((value) => {2889 result.push(value.convertToDTO());2890 });2891 return result;2892 }2893}2894var LogicalVariableType;2895(function (LogicalVariableType) {2896 LogicalVariableType[LogicalVariableType["VALUE"] = 0] = "VALUE";2897 LogicalVariableType[LogicalVariableType["REFERENCE"] = 1] = "REFERENCE";2898})(LogicalVariableType || (LogicalVariableType = {}));2899class LogicalVariable {2900 constructor(value) {2901 this.value = value;2902 }2903 convertToDTO() {2904 var dto = new GameDTO_LogicalBufferVariable();2905 dto.type = this.type;2906 dto.value = this.value;2907 return dto;2908 }2909 static generateFromDTO(dto) {2910 if (dto.type == LogicalVariableType.VALUE) {2911 return new LogicalValue(dto.value);2912 }2913 else if (dto.type == LogicalVariableType.REFERENCE) {2914 return new LogicalReference(dto.value);2915 }2916 }2917}2918class LogicalValue extends LogicalVariable {2919 constructor() {2920 super(...arguments);2921 this.type = LogicalVariableType.VALUE;2922 }2923}2924class LogicalReference extends LogicalVariable {2925 constructor() {2926 super(...arguments);2927 this.type = LogicalVariableType.REFERENCE;2928 }2929}2930var StepId;2931(function (StepId) {2932 StepId[StepId["JUMP_TO_STEP"] = 0] = "JUMP_TO_STEP";2933 StepId[StepId["CONDITIONAL"] = 1] = "CONDITIONAL";2934 StepId[StepId["CONTAINS"] = 2] = "CONTAINS";2935 StepId[StepId["DRAW_CARDS"] = 3] = "DRAW_CARDS";2936 StepId[StepId["EVENT_GENERATOR"] = 4] = "EVENT_GENERATOR";2937 StepId[StepId["FOR_EACH"] = 5] = "FOR_EACH";2938 StepId[StepId["LOAD_CARD"] = 6] = "LOAD_CARD";2939 StepId[StepId["LOAD_DECK"] = 7] = "LOAD_DECK";2940 StepId[StepId["LOAD_HAND"] = 8] = "LOAD_HAND";2941 StepId[StepId["LOOP"] = 9] = "LOOP";2942 StepId[StepId["PLAYER_CHOICE"] = 10] = "PLAYER_CHOICE";2943 StepId[StepId["RELATIONAL"] = 11] = "RELATIONAL";2944 StepId[StepId["QUERY"] = 12] = "QUERY";2945 StepId[StepId["COUNT"] = 13] = "COUNT";2946 StepId[StepId["ARRAY"] = 14] = "ARRAY";2947 StepId[StepId["MATH"] = 15] = "MATH";2948})(StepId || (StepId = {}));2949var ArrayStepOptions;2950(function (ArrayStepOptions) {2951 ArrayStepOptions[ArrayStepOptions["ADD"] = 0] = "ADD";2952})(ArrayStepOptions || (ArrayStepOptions = {}));2953class ArrayStep extends LogicalStep {2954 constructor(option, logicalBufferReferenceValue, logicalBufferReturnKey) {2955 super();2956 this.option = option;2957 this.logicalBufferReferenceValue = logicalBufferReferenceValue;2958 this.logicalBufferReturnKey = logicalBufferReturnKey;2959 }2960 processAndAdvance(logicalBuffer, gameDTO) {2961 if (logicalBuffer.storedData[this.logicalBufferReturnKey] == null) {2962 logicalBuffer.storedData[this.logicalBufferReturnKey] = [];2963 }2964 var _ = new LogicalUtils();2965 var resolvedValue = _.ResolveVariable(this.logicalBufferReferenceValue, logicalBuffer);2966 if (this.option == ArrayStepOptions.ADD) {2967 logicalBuffer.storedData[this.logicalBufferReturnKey].push(resolvedValue);2968 }2969 return true;2970 }2971 getStepId() {2972 return StepId.ARRAY;2973 }2974 constructFromDTO(dto, logicalBuffer, gameDTO) {2975 this.uuid = dto.uuid;2976 this.option = dto.args["option"];2977 this.logicalBufferReferenceValue = LogicalVariable.generateFromDTO(dto.args["logicalBufferReferenceValue"]);2978 this.logicalBufferReturnKey = dto.args["logicalBufferReturnKey"];2979 }2980 convertToDTO() {2981 var dto = new GameDTO_LogicalBuffer_Step();2982 dto.uuid = this.uuid;2983 dto.stepId = this.getStepId();2984 dto.args = {};2985 dto.args["option"] = this.option;2986 dto.args["logicalBufferReferenceValue"] = this.logicalBufferReferenceValue.convertToDTO();2987 dto.args["logicalBufferReturnKey"] = this.logicalBufferReturnKey;2988 return dto;2989 }2990 reset() {2991 }2992 hasSubsteps() {2993 return false;2994 }2995 getCurrentSubstep(logicalBuffer, gameDTO) {2996 return this;2997 }2998}2999RegisterEventBufferStep(ArrayStep);3000class CompoundStep extends LogicalStep {3001 constructor(substeps) {3002 super();3003 this.currentSubstepIndex = 0;3004 this.substeps = [];3005 this.substeps = substeps;3006 }3007 hasSubsteps() {3008 return true;3009 }3010 getCurrentSubstep(logicalBuffer, gameDTO) {3011 return this.substeps[this.currentSubstepIndex];3012 }3013 processAndAdvance(logicalBuffer, gameDTO) {3014 var _ = new LogicalUtils();3015 var currentStep = this.substeps[this.currentSubstepIndex];3016 var isSubStepComplete = currentStep.processAndAdvance(logicalBuffer, gameDTO);3017 if (isSubStepComplete) {3018 this.currentSubstepIndex++;3019 }3020 if (this.currentSubstepIndex >= this.substeps.length) {3021 return true;3022 }3023 return false;3024 }3025 reset() {3026 this.currentSubstepIndex = 0;3027 this.substeps.forEach((eachStep) => {3028 eachStep.reset();3029 });3030 }3031 constructFromDTO(dto, logicalBuffer, gameDTO) {3032 this.uuid = dto.uuid;3033 this.currentSubstepIndex = dto.args["currentSubstepIndex"];3034 this.substeps = [];3035 for (var key in dto.args["substeps"]) {3036 this.substeps[key] = LogicalStep.createFromDTO(dto.args["substeps"][key], logicalBuffer, gameDTO);3037 }3038 }3039 convertToDTO() {3040 var _ = new LogicalUtils();3041 var dto = new GameDTO_LogicalBuffer_Step();3042 dto.uuid = this.uuid;3043 dto.stepId = this.getStepId();3044 dto.args = {};3045 dto.args["currentSubstepIndex"] = this.currentSubstepIndex;3046 dto.args["substeps"] = _.SerializeDTOArray(this.substeps);3047 return dto;3048 }3049}3050///<reference path="../LogicalStep.ts" />3051class ConditionalStep extends LogicalStep {3052 constructor(conditionalBufferVariable, valueMap) {3053 super();3054 this.valueMap = {};3055 this.currentSubstepIndex = 0;3056 this.conditionalBufferVariable = conditionalBufferVariable;3057 this.valueMap = valueMap;3058 }3059 hasSubsteps() {3060 return true;3061 }3062 getCurrentSubstep(logicalBuffer, gameDTO) {3063 var _ = new LogicalUtils();3064 var conditionalBufferValue = _.ResolveVariable(this.conditionalBufferVariable, logicalBuffer);3065 var chosenPath = this.valueMap[conditionalBufferValue];3066 var currentStep = chosenPath[this.currentSubstepIndex];3067 return currentStep;3068 }3069 processAndAdvance(logicalBuffer, gameDTO) {3070 var _ = new LogicalUtils();3071 var conditionalBufferValue = _.ResolveVariable(this.conditionalBufferVariable, logicalBuffer);3072 var chosenPath = this.valueMap[conditionalBufferValue];3073 if (chosenPath != null) {3074 var currentStep = chosenPath[this.currentSubstepIndex];3075 var isSubStepComplete = currentStep.processAndAdvance(logicalBuffer, gameDTO);3076 if (isSubStepComplete) {3077 this.currentSubstepIndex++;3078 }3079 if (this.currentSubstepIndex >= chosenPath.length) {3080 return true;3081 }3082 return false;3083 }3084 return true;3085 }3086 reset() {3087 this.currentSubstepIndex = 0;3088 for (var key in this.valueMap) {3089 var chosenPath = this.valueMap[key];3090 chosenPath.forEach((eachStep) => {3091 eachStep.reset();3092 });3093 }3094 }3095 getStepId() {3096 return StepId.CONDITIONAL;3097 }3098 constructFromDTO(dto, logicalBuffer, gameDTO) {3099 this.uuid = dto.uuid;3100 this.conditionalBufferVariable = LogicalVariable.generateFromDTO(dto.args["conditionalBufferVariable"]);3101 this.valueMap = {};3102 for (var key in dto.args["valueMap"]) {3103 this.valueMap[key] = [];3104 dto.args["valueMap"][key].forEach((eachValue) => {3105 this.valueMap[key].push(LogicalStep.createFromDTO(eachValue, logicalBuffer, gameDTO));3106 });3107 }3108 this.currentSubstepIndex = dto.args["currentSubstepIndex"];3109 }3110 convertToDTO() {3111 var _ = new LogicalUtils();3112 var dto = new GameDTO_LogicalBuffer_Step();3113 dto.uuid = this.uuid;3114 dto.stepId = this.getStepId();3115 dto.args = {};3116 dto.args["conditionalBufferVariable"] = this.conditionalBufferVariable.convertToDTO();3117 dto.args["valueMap"] = _.SerializeString2DTOMap(this.valueMap);3118 dto.args["currentSubstepIndex"] = this.currentSubstepIndex;3119 return dto;3120 }3121}3122RegisterEventBufferStep(ConditionalStep);3123///<reference path="../LogicalStep.ts" />3124class ContainsStep extends LogicalStep {3125 constructor(valueToCheckFor, setToCheckIn, stepsToPerform, doesntContain) {3126 super();3127 this.currentSubstepIndex = 0;3128 this.valueToCheckFor = valueToCheckFor;3129 this.setToCheckIn = setToCheckIn;3130 this.stepsToPerform = stepsToPerform;3131 if (doesntContain != null) {3132 this.doesntContain = doesntContain;3133 }3134 else {3135 this.doesntContain = false;3136 }3137 }3138 hasSubsteps() {3139 return true;3140 }3141 reset() {3142 this.currentSubstepIndex = 0;3143 this.stepsToPerform.forEach((eachStep) => {3144 eachStep.reset();3145 });3146 }3147 getCurrentSubstep(logicalBuffer, gameDTO) {3148 return this.stepsToPerform[this.currentSubstepIndex];3149 }3150 processAndAdvance(logicalBuffer, gameDTO) {3151 var _ = new LogicalUtils();3152 var resolvedValue = _.ResolveVariable(this.valueToCheckFor, logicalBuffer);3153 var resolvedSetValue = _.ResolveVariable(this.setToCheckIn, logicalBuffer);3154 var fitsRequirement = null;3155 if (this.doesntContain) {3156 fitsRequirement = resolvedSetValue.indexOf(resolvedValue) == -1;3157 }3158 else {3159 fitsRequirement = resolvedSetValue.indexOf(resolvedValue) != -1;3160 }3161 if (fitsRequirement) {3162 var currentStep = this.stepsToPerform[this.currentSubstepIndex];3163 var isSubStepComplete = currentStep.processAndAdvance(logicalBuffer, gameDTO);3164 if (isSubStepComplete) {3165 this.currentSubstepIndex++;3166 }3167 if (this.currentSubstepIndex >= this.stepsToPerform.length) {3168 return true;3169 }3170 return false;3171 }3172 return true;3173 }3174 getStepId() {3175 return StepId.CONTAINS;3176 }3177 constructFromDTO(dto, logicalBuffer, gameDTO) {3178 this.uuid = dto.uuid;3179 this.valueToCheckFor = LogicalVariable.generateFromDTO(dto.args["valueToCheckFor"]);3180 this.setToCheckIn = LogicalVariable.generateFromDTO(dto.args["setToCheckIn"]);3181 this.stepsToPerform = [];3182 for (var key in dto.args["stepsToPerform"]) {3183 this.stepsToPerform[key] = LogicalStep.createFromDTO(dto.args["stepsToPerform"][key], logicalBuffer, gameDTO);3184 }3185 this.currentSubstepIndex = dto.args["currentSubstepIndex"];3186 this.doesntContain = dto.args["doesntContain"];3187 }3188 convertToDTO() {3189 var _ = new LogicalUtils();3190 var dto = new GameDTO_LogicalBuffer_Step();3191 dto.uuid = this.uuid;3192 dto.stepId = this.getStepId();3193 dto.args = {};3194 dto.args["valueToCheckFor"] = this.valueToCheckFor.convertToDTO();3195 dto.args["setToCheckIn"] = this.setToCheckIn.convertToDTO();3196 dto.args["stepsToPerform"] = _.SerializeDTOArray(this.stepsToPerform);3197 dto.args["currentSubstepIndex"] = this.currentSubstepIndex;3198 dto.args["doesntContain"] = this.doesntContain;3199 return dto;3200 }3201}3202ContainsStep.DOES_NOT_CONTAIN = true;3203RegisterEventBufferStep(ContainsStep);3204class CountStep extends LogicalStep {3205 constructor(setOne, logicalBufferReturnKey) {3206 super();3207 this.setOne = setOne;3208 this.logicalBufferReturnKey = logicalBufferReturnKey;3209 }3210 hasSubsteps() {3211 return true;3212 }3213 getCurrentSubstep(logicalBuffer, gameDTO) {3214 return this;3215 }3216 reset() {3217 }3218 processAndAdvance(logicalBuffer, gameDTO) {3219 var _ = new LogicalUtils();3220 var setArg = _.ResolveVariable(this.setOne, logicalBuffer);3221 if (setArg == null || setArg == undefined) {3222 logicalBuffer.storedData[this.logicalBufferReturnKey] = 0;3223 }3224 else {3225 logicalBuffer.storedData[this.logicalBufferReturnKey] = setArg.length;3226 }3227 return true;3228 }3229 getStepId() {3230 return StepId.COUNT;3231 }3232 constructFromDTO(dto, logicalBuffer, gameDTO) {3233 this.uuid = dto.uuid;3234 this.setOne = LogicalVariable.generateFromDTO(dto.args["setOne"]);3235 this.logicalBufferReturnKey = dto.args["logicalBufferReturnKey"];3236 }3237 convertToDTO() {3238 var dto = new GameDTO_LogicalBuffer_Step();3239 dto.uuid = this.uuid;3240 dto.stepId = this.getStepId();3241 dto.args = {};3242 dto.args["setOne"] = this.setOne.convertToDTO();3243 dto.args["logicalBufferReturnKey"] = this.logicalBufferReturnKey;3244 return dto;3245 }3246}3247RegisterEventBufferStep(CountStep);3248class DrawCardsStep extends CompoundStep {3249 constructor(ownerUUID, amount) {3250 var steps = [];3251 if (ownerUUID != null && amount != null) {3252 var _ = new LogicalUtils();3253 if (amount.type == LogicalVariableType.VALUE) {3254 var amountValue = amount.value;3255 for (var i = 0; i < amountValue; i++) {3256 steps.push(new LoadDeckInfoStep(LoadDeckInfoStepOptions.DECK_SIZE, _.Value(ownerUUID), "deckSize"));3257 steps.push(new RelationalStep(_.Reference("deckSize"), RelationalOptions.EQUALS, _.Value(0), [3258 new EventGeneratorStep(EventIds.RESHUFFLE_DECK, new ReshuffleDeckEventArgs(_.Value(ownerUUID)))3259 ]));3260 steps.push(new LoadDeckInfoStep(LoadDeckInfoStepOptions.DECK_SIZE, _.Value(ownerUUID), "deckSize"));3261 steps.push(new RelationalStep(_.Reference("deckSize"), RelationalOptions.GREATER_THAN, _.Value(0), [3262 new EventGeneratorStep(EventIds.DRAW_CARD, new DrawCardsEventArgs(_.Value(ownerUUID)))3263 ]));3264 }3265 }3266 else if (amount.type == LogicalVariableType.REFERENCE) {3267 steps.push(new LoopStep(amount, [3268 new LoadDeckInfoStep(LoadDeckInfoStepOptions.DECK_SIZE, _.Value(ownerUUID), "deckSize"),3269 new RelationalStep(_.Reference("deckSize"), RelationalOptions.EQUALS, _.Value(0), [3270 new EventGeneratorStep(EventIds.RESHUFFLE_DECK, new ReshuffleDeckEventArgs(_.Value(ownerUUID)))3271 ]),3272 new LoadDeckInfoStep(LoadDeckInfoStepOptions.DECK_SIZE, _.Value(ownerUUID), "deckSize"),3273 new RelationalStep(_.Reference("deckSize"), RelationalOptions.GREATER_THAN, _.Value(0), [3274 new EventGeneratorStep(EventIds.DRAW_CARD, new DrawCardsEventArgs(_.Value(ownerUUID)))3275 ])3276 ]));3277 }3278 }3279 super(steps);3280 }3281 getStepId() {3282 return StepId.DRAW_CARDS;3283 }3284}3285RegisterEventBufferStep(DrawCardsStep);3286///<reference path="../LogicalStep.ts" />3287class EventGeneratorStep extends LogicalStep {3288 constructor(eventId, eventGeneratorArgs) {3289 super();3290 this.eventId = eventId;3291 this.eventGeneratorArgs = eventGeneratorArgs;3292 }3293 processAndAdvance(logicalBuffer, gameDTO) {3294 var _ = new LogicalUtils();3295 var calculatedArgs = {};3296 for (var key in this.eventGeneratorArgs.data) {3297 if (this.eventGeneratorArgs.data[key] != null) {3298 calculatedArgs[key] = _.ResolveVariable(LogicalVariable.generateFromDTO(this.eventGeneratorArgs.data[key]), logicalBuffer);3299 }3300 //Log.send("key: " + key + " value: " + calculatedArgs[key] + " logicbuffer: " + logicalBuffer.storedData[key]);3301 }3302 var event = GameEvent.create(this.eventId, calculatedArgs);3303 GameDTOAccess.pushEventToStack(gameDTO, event);3304 LogicalStack.currentOutput.eventsGenerated = true;3305 gameDTO.state.state = GameState.RESOLVING_EVENT_STACK;3306 return true;3307 }3308 getStepId() {3309 return StepId.EVENT_GENERATOR;3310 }3311 reset() {3312 }3313 hasSubsteps() {3314 return false;3315 }3316 getCurrentSubstep(logicalBuffer, gameDTO) {3317 return this;3318 }3319 constructFromDTO(dto, logicalBuffer, gameDTO) {3320 this.uuid = dto.uuid;3321 this.eventId = dto.args["eventId"];3322 this.eventGeneratorArgs = new EventArgs();3323 this.eventGeneratorArgs.data = dto.args["eventGeneratorArgs"];3324 }3325 convertToDTO() {3326 var dto = new GameDTO_LogicalBuffer_Step();3327 dto.uuid = this.uuid;3328 dto.stepId = this.getStepId();3329 dto.args = {};3330 dto.args["eventId"] = this.eventId;3331 dto.args["eventGeneratorArgs"] = this.eventGeneratorArgs.data;3332 return dto;3333 }3334}3335RegisterEventBufferStep(EventGeneratorStep);3336class ForEachStep extends LogicalStep {3337 constructor(listVariable, eachReferenceTag, stepsToLoop) {3338 super();3339 this.listVariable = listVariable;3340 this.eachReferenceTag = eachReferenceTag;3341 this.stepsToLoop = stepsToLoop;3342 this.currentSubstepIndex = 0;3343 this.currentListIndex = 0;3344 }3345 reset() {3346 this.currentSubstepIndex = 0;3347 this.currentListIndex = 0;3348 this.stepsToLoop.forEach((eachStep) => {3349 eachStep.reset();3350 });3351 }3352 hasSubsteps() {3353 return true;3354 }3355 getCurrentSubstep(logicalBuffer, gameDTO) {3356 return this.stepsToLoop[this.currentSubstepIndex];3357 }3358 processAndAdvance(logicalBuffer, gameDTO) {3359 var _ = new LogicalUtils();3360 var listVariableParsed = _.ResolveVariable(this.listVariable, logicalBuffer);3361 listVariableParsed = Util.convertToArray(listVariableParsed);3362 //Log.send("For each will iterate " + listVariableParsed.length + " times. This is iteration " + this.currentListIndex);3363 //listVariableParsed = JSON.parse(listVariableParsed);3364 //Log.send("listVariableParsed: " + listVariableParsed + " length: " + listVariableParsed.length);3365 if (listVariableParsed.length > 0) {3366 var currentStep = this.stepsToLoop[this.currentSubstepIndex];3367 logicalBuffer.storedData[this.eachReferenceTag] = listVariableParsed[this.currentListIndex];3368 var isSubStepComplete = currentStep.processAndAdvance(logicalBuffer, gameDTO);3369 if (isSubStepComplete) {3370 this.currentSubstepIndex++;3371 }3372 if (this.currentSubstepIndex >= this.stepsToLoop.length) {3373 this.currentListIndex++;3374 if (this.currentListIndex >= listVariableParsed.length) {3375 return true;3376 }3377 else {3378 this.currentSubstepIndex = 0;3379 this.stepsToLoop.forEach((eachStep) => {3380 eachStep.reset();3381 });3382 return false;3383 }3384 }3385 }3386 else {3387 return true;3388 }3389 }3390 getStepId() {3391 return StepId.FOR_EACH;3392 }3393 constructFromDTO(dto, logicalBuffer, gameDTO) {3394 this.uuid = dto.uuid;3395 this.currentSubstepIndex = dto.args["currentSubstepIndex"];3396 this.stepsToLoop = [];3397 for (var key in dto.args["stepsToLoop"]) {3398 this.stepsToLoop[key] = LogicalStep.createFromDTO(dto.args["stepsToLoop"][key], logicalBuffer, gameDTO);3399 }3400 this.listVariable = LogicalVariable.generateFromDTO(dto.args["listVariable"]);3401 this.currentSubstepIndex = dto.args["currentSubstepIndex"];3402 this.eachReferenceTag = dto.args["eachReferenceTag"];3403 this.currentListIndex = dto.args["currentListIndex"];3404 }3405 convertToDTO() {3406 var _ = new LogicalUtils();3407 var dto = new GameDTO_LogicalBuffer_Step();3408 dto.uuid = this.uuid;3409 dto.stepId = this.getStepId();3410 dto.args = {};3411 dto.args["currentSubstepIndex"] = this.currentSubstepIndex;3412 dto.args["stepsToLoop"] = _.SerializeDTOArray(this.stepsToLoop);3413 dto.args["listVariable"] = this.listVariable;3414 dto.args["eachReferenceTag"] = this.eachReferenceTag;3415 dto.args["currentListIndex"] = this.currentListIndex;3416 return dto;3417 }3418}3419RegisterEventBufferStep(ForEachStep);3420///<reference path="../LogicalStep.ts" />3421class JumpToStep extends LogicalStep {3422 constructor(stepUUID) {3423 super();3424 this.stepUUID = stepUUID;3425 }3426 reset() {3427 }3428 hasSubsteps() {3429 return false;3430 }3431 getCurrentSubstep(logicalBuffer, gameDTO) {3432 return this;3433 }3434 processAndAdvance(logicalBuffer, gameDTO) {3435 var _ = new LogicalUtils();3436 logicalBuffer.reset();3437 logicalBuffer.currentStepUUID = _.ResolveVariable(this.stepUUID, logicalBuffer);3438 return true;3439 }3440 constructFromDTO(dto, logicalBuffer, gameDTO) {3441 this.uuid = dto.uuid;3442 this.stepUUID = LogicalVariable.generateFromDTO(dto.args["stepUUID"]);3443 }3444 convertToDTO() {3445 var dto = new GameDTO_LogicalBuffer_Step();3446 dto.uuid = this.uuid;3447 dto.stepId = this.getStepId();3448 dto.args = {};3449 dto.args["stepUUID"] = this.stepUUID.convertToDTO();3450 return dto;3451 }3452 getStepId() {3453 return StepId.JUMP_TO_STEP;3454 }3455}3456RegisterEventBufferStep(JumpToStep);3457///<reference path="../LogicalStep.ts" />3458var LoadCardInfoStepOptions;3459(function (LoadCardInfoStepOptions) {3460 LoadCardInfoStepOptions[LoadCardInfoStepOptions["TYPES"] = 0] = "TYPES";3461 LoadCardInfoStepOptions[LoadCardInfoStepOptions["CARD_ID"] = 1] = "CARD_ID";3462})(LoadCardInfoStepOptions || (LoadCardInfoStepOptions = {}));3463class LoadCardInfoStep extends LogicalStep {3464 constructor(option, logicalBufferReference, logicalBufferReturnKey) {3465 super();3466 this.option = option;3467 this.logicalBufferReference = logicalBufferReference;3468 this.logicalBufferReturnKey = logicalBufferReturnKey;3469 }3470 processAndAdvance(logicalBuffer, gameDTO) {3471 var _ = new LogicalUtils();3472 var cardID = _.ResolveVariable(this.logicalBufferReference, logicalBuffer);3473 var requestedInfo = null;3474 if (this.option == LoadCardInfoStepOptions.TYPES) {3475 requestedInfo = GameDTOAccess.getCardDefinition(gameDTO, cardID).getCardTypes();3476 var lu = new LoggingUtils(gameDTO);3477 //Log.send("Loading card type for " + lu.fname(cardID) + " : " + requestedInfo);3478 }3479 else if (this.option == LoadCardInfoStepOptions.CARD_ID) {3480 requestedInfo = GameDTOAccess.getCardDefinition(gameDTO, cardID).getCardId();3481 }3482 logicalBuffer.storedData[this.logicalBufferReturnKey] = requestedInfo;3483 return true;3484 }3485 reset() {3486 }3487 hasSubsteps() {3488 return false;3489 }3490 getCurrentSubstep(logicalBuffer, gameDTO) {3491 return this;3492 }3493 getStepId() {3494 return StepId.LOAD_CARD;3495 }3496 constructFromDTO(dto, logicalBuffer, gameDTO) {3497 this.uuid = dto.uuid;3498 this.option = dto.args["option"];3499 this.logicalBufferReference = LogicalVariable.generateFromDTO(dto.args["logicalBufferReference"]);3500 this.logicalBufferReturnKey = dto.args["logicalBufferReturnKey"];3501 }3502 convertToDTO() {3503 var dto = new GameDTO_LogicalBuffer_Step();3504 dto.uuid = this.uuid;3505 dto.stepId = this.getStepId();3506 dto.args = {};3507 dto.args["option"] = this.option;3508 dto.args["logicalBufferReference"] = this.logicalBufferReference.convertToDTO();3509 dto.args["logicalBufferReturnKey"] = this.logicalBufferReturnKey;3510 return dto;3511 }3512}3513RegisterEventBufferStep(LoadCardInfoStep);3514///<reference path="../LogicalStep.ts" />3515var LoadDeckInfoStepOptions;3516(function (LoadDeckInfoStepOptions) {3517 LoadDeckInfoStepOptions[LoadDeckInfoStepOptions["TOP_CARD"] = 0] = "TOP_CARD";3518 LoadDeckInfoStepOptions[LoadDeckInfoStepOptions["DECK_SIZE"] = 1] = "DECK_SIZE";3519})(LoadDeckInfoStepOptions || (LoadDeckInfoStepOptions = {}));3520class LoadDeckStepCardAtIndexFromTopOption {3521 constructor(indexFromTop) {3522 this.indexFromTop = indexFromTop;3523 }3524}3525class LoadDeckInfoStep extends LogicalStep {3526 constructor(option, logicalBufferReferencePlayerUUID, logicalBufferReturnKey) {3527 super();3528 this.option = option;3529 this.logicalBufferReferencePlayerUUID = logicalBufferReferencePlayerUUID;3530 this.logicalBufferReturnKey = logicalBufferReturnKey;3531 }3532 processAndAdvance(logicalBuffer, gameDTO) {3533 //Log.send("****** INSIDE LoadDeckInfoStep");3534 var _ = new LogicalUtils();3535 var playerUUID = _.ResolveVariable(this.logicalBufferReferencePlayerUUID, logicalBuffer);3536 var requestedInfo = null;3537 var deckSize = GameDTOAccess.getCardsInZone(gameDTO, playerUUID, Zones.DECK).length;3538 if (this.option instanceof LoadDeckStepCardAtIndexFromTopOption) {3539 var cardsOnDeck = GameDTOAccess.getCardsOnDeck(gameDTO, playerUUID, 1 + this.option.indexFromTop);3540 requestedInfo = cardsOnDeck[cardsOnDeck.length - 1];3541 }3542 else {3543 if (this.option == LoadDeckInfoStepOptions.TOP_CARD) {3544 requestedInfo = GameDTOAccess.getCardsOnDeck(gameDTO, playerUUID, 1)[0];3545 }3546 else if (this.option == LoadDeckInfoStepOptions.DECK_SIZE) {3547 //Log.send("Deck size requested: " + deckSize);3548 requestedInfo = deckSize;3549 }3550 }3551 logicalBuffer.storedData[this.logicalBufferReturnKey] = requestedInfo;3552 return true;3553 }3554 reset() {3555 }3556 getStepId() {3557 return StepId.LOAD_DECK;3558 }3559 constructFromDTO(dto, logicalBuffer, gameDTO) {3560 this.uuid = dto.uuid;3561 if (Util.isNumber(dto.args["option"])) {3562 this.option = dto.args["option"];3563 }3564 else {3565 this.option = new LoadDeckStepCardAtIndexFromTopOption(JSON.parse(dto.args["option"])["indexFromTop"]);3566 }3567 this.logicalBufferReferencePlayerUUID = LogicalVariable.generateFromDTO(dto.args["logicalBufferReferencePlayerUUID"]);3568 this.logicalBufferReturnKey = dto.args["logicalBufferReturnKey"];3569 }3570 convertToDTO() {3571 var dto = new GameDTO_LogicalBuffer_Step();3572 dto.uuid = this.uuid;3573 dto.stepId = this.getStepId();3574 dto.args = {};3575 if (this.option instanceof LoadDeckStepCardAtIndexFromTopOption) {3576 dto.args["option"] = JSON.stringify(this.option);3577 }3578 else {3579 dto.args["option"] = this.option;3580 }3581 dto.args["logicalBufferReferencePlayerUUID"] = this.logicalBufferReferencePlayerUUID.convertToDTO();3582 dto.args["logicalBufferReturnKey"] = this.logicalBufferReturnKey;3583 return dto;3584 }3585 hasSubsteps() {3586 return false;3587 }3588 getCurrentSubstep(logicalBuffer, gameDTO) {3589 return this;3590 }3591}3592RegisterEventBufferStep(LoadDeckInfoStep);3593///<reference path="../LogicalStep.ts" />3594var LoadHandInfoStepOptions;3595(function (LoadHandInfoStepOptions) {3596 LoadHandInfoStepOptions[LoadHandInfoStepOptions["ALL"] = 0] = "ALL";3597 LoadHandInfoStepOptions[LoadHandInfoStepOptions["SIZE"] = 1] = "SIZE";3598})(LoadHandInfoStepOptions || (LoadHandInfoStepOptions = {}));3599class LoadHandInfoStep extends LogicalStep {3600 constructor(option, logicalBufferReferencePlayerUUID, logicalBufferReturnKey) {3601 super();3602 this.option = option;3603 this.logicalBufferReferencePlayerUUID = logicalBufferReferencePlayerUUID;3604 this.logicalBufferReturnKey = logicalBufferReturnKey;3605 }3606 processAndAdvance(logicalBuffer, gameDTO) {3607 var _ = new LogicalUtils();3608 var playerUUID = _.ResolveVariable(this.logicalBufferReferencePlayerUUID, logicalBuffer);3609 var requestedInfo = null;3610 if (this.option == LoadHandInfoStepOptions.SIZE) {3611 requestedInfo = GameDTOAccess.getCardsInZone(gameDTO, playerUUID, Zones.HAND).length;3612 //Log.send("Hand size requested: " + requestedInfo);3613 }3614 else if (this.option == LoadHandInfoStepOptions.ALL) {3615 requestedInfo = GameDTOAccess.getCardsInZone(gameDTO, playerUUID, Zones.HAND);3616 }3617 logicalBuffer.storedData[this.logicalBufferReturnKey] = requestedInfo;3618 return true;3619 }3620 getStepId() {3621 return StepId.LOAD_HAND;3622 }3623 constructFromDTO(dto, logicalBuffer, gameDTO) {3624 this.uuid = dto.uuid;3625 this.option = dto.args["option"];3626 this.logicalBufferReferencePlayerUUID = LogicalVariable.generateFromDTO(dto.args["logicalBufferReferencePlayerUUID"]);3627 this.logicalBufferReturnKey = dto.args["logicalBufferReturnKey"];3628 }3629 convertToDTO() {3630 var dto = new GameDTO_LogicalBuffer_Step();3631 dto.uuid = this.uuid;3632 dto.stepId = this.getStepId();3633 dto.args = {};3634 dto.args["option"] = this.option;3635 dto.args["logicalBufferReferencePlayerUUID"] = this.logicalBufferReferencePlayerUUID.convertToDTO();3636 dto.args["logicalBufferReturnKey"] = this.logicalBufferReturnKey;3637 return dto;3638 }3639 reset() {3640 }3641 hasSubsteps() {3642 return false;3643 }3644 getCurrentSubstep(logicalBuffer, gameDTO) {3645 return this;3646 }3647}3648RegisterEventBufferStep(LoadHandInfoStep);3649class LoopStep extends LogicalStep {3650 constructor(amount, stepsToLoop) {3651 super();3652 this.amount = amount;3653 this.stepsToLoop = stepsToLoop;3654 this.currentLoopIteration = 0;3655 this.currentSubstepIndex = 0;3656 }3657 processAndAdvance(logicalBuffer, gameDTO) {3658 var _ = new LogicalUtils();3659 var amountValue = _.ResolveVariable(this.amount, logicalBuffer);3660 var currentStep = this.stepsToLoop[this.currentSubstepIndex];3661 var isSubStepComplete = currentStep.processAndAdvance(logicalBuffer, gameDTO);3662 if (isSubStepComplete) {3663 this.currentSubstepIndex++;3664 }3665 if (this.currentSubstepIndex >= this.stepsToLoop.length) {3666 this.currentLoopIteration++;3667 if (this.currentLoopIteration >= amountValue) {3668 return true;3669 }3670 else {3671 this.currentSubstepIndex = 0;3672 this.stepsToLoop.forEach((eachStep) => {3673 eachStep.reset();3674 });3675 return false;3676 }3677 }3678 }3679 reset() {3680 this.currentSubstepIndex = 0;3681 this.currentSubstepIndex = 0;3682 this.stepsToLoop.forEach((eachStep) => {3683 eachStep.reset();3684 });3685 }3686 getStepId() {3687 return StepId.LOOP;3688 }3689 constructFromDTO(dto, logicalBuffer, gameDTO) {3690 this.uuid = dto.uuid;3691 this.currentLoopIteration = dto.args["currentLoopIteration"];3692 this.currentSubstepIndex = dto.args["currentSubstepIndex"];3693 this.amount = LogicalVariable.generateFromDTO(dto.args["amount"]);3694 this.stepsToLoop = [];3695 for (var key in dto.args["stepsToLoop"]) {3696 this.stepsToLoop[key] = LogicalStep.createFromDTO(dto.args["stepsToLoop"][key], logicalBuffer, gameDTO);3697 }3698 }3699 convertToDTO() {3700 var _ = new LogicalUtils();3701 var dto = new GameDTO_LogicalBuffer_Step();3702 dto.uuid = this.uuid;3703 dto.stepId = this.getStepId();3704 dto.args = {};3705 dto.args["currentLoopIteration"] = this.currentLoopIteration;3706 dto.args["currentSubstepIndex"] = this.currentSubstepIndex;3707 dto.args["amount"] = this.amount;3708 dto.args["stepsToLoop"] = _.SerializeDTOArray(this.stepsToLoop);3709 return dto;3710 }3711 hasSubsteps() {3712 return true;3713 }3714 getCurrentSubstep(logicalBuffer, gameDTO) {3715 return this.stepsToLoop[this.currentSubstepIndex];3716 }3717}3718RegisterEventBufferStep(LoopStep);3719var MathStepOptions;3720(function (MathStepOptions) {3721 MathStepOptions[MathStepOptions["MIN"] = 0] = "MIN";3722})(MathStepOptions || (MathStepOptions = {}));3723class MathStep extends LogicalStep {3724 constructor(logicalBufferReferenceArguments, option, logicalBufferReturnKey) {3725 super();3726 this.option = option;3727 this.logicalBufferReferenceArguments = logicalBufferReferenceArguments;3728 this.logicalBufferReturnKey = logicalBufferReturnKey;3729 }3730 processAndAdvance(logicalBuffer, gameDTO) {3731 var _ = new LogicalUtils();3732 var result = null;3733 if (this.option == MathStepOptions.MIN) {3734 var resolvedArgs = [];3735 this.logicalBufferReferenceArguments.forEach((eachArg) => {3736 resolvedArgs.push(_.ResolveVariable(eachArg, logicalBuffer));3737 });3738 result = Math.min(...resolvedArgs);3739 }3740 logicalBuffer.storedData[this.logicalBufferReturnKey] = result;3741 return true;3742 }3743 getStepId() {3744 return StepId.MATH;3745 }3746 constructFromDTO(dto, logicalBuffer, gameDTO) {3747 this.uuid = dto.uuid;3748 this.option = dto.args["option"];3749 this.logicalBufferReferenceArguments = [];3750 dto.args["logicalBufferReferenceArguments"].forEach((eachArg) => {3751 this.logicalBufferReferenceArguments.push(LogicalVariable.generateFromDTO(eachArg));3752 });3753 this.logicalBufferReturnKey = dto.args["logicalBufferReturnKey"];3754 }3755 convertToDTO() {3756 var dto = new GameDTO_LogicalBuffer_Step();3757 dto.uuid = this.uuid;3758 dto.stepId = this.getStepId();3759 dto.args = {};3760 dto.args["option"] = this.option;3761 dto.args["logicalBufferReferenceArguments"] = [];3762 this.logicalBufferReferenceArguments.forEach((eachArg) => {3763 dto.args["logicalBufferReferenceArguments"].push(eachArg.convertToDTO());3764 });3765 dto.args["logicalBufferReturnKey"] = this.logicalBufferReturnKey;3766 return dto;3767 }3768 reset() {3769 }3770 hasSubsteps() {3771 return false;3772 }3773 getCurrentSubstep(logicalBuffer, gameDTO) {3774 return this;3775 }3776}3777RegisterEventBufferStep(MathStep);3778///<reference path="../LogicalStep.ts" />3779var PlayerChoiceType;3780(function (PlayerChoiceType) {3781 PlayerChoiceType[PlayerChoiceType["CARD"] = 0] = "CARD";3782 PlayerChoiceType[PlayerChoiceType["STRING"] = 1] = "STRING";3783})(PlayerChoiceType || (PlayerChoiceType = {}));3784var PlayerChoicePrepositionValues;3785(function (PlayerChoicePrepositionValues) {3786 PlayerChoicePrepositionValues[PlayerChoicePrepositionValues["EXACTLY"] = 0] = "EXACTLY";3787 PlayerChoicePrepositionValues[PlayerChoicePrepositionValues["UP_TO"] = 1] = "UP_TO";3788})(PlayerChoicePrepositionValues || (PlayerChoicePrepositionValues = {}));3789class PlayerChoicePreposition {3790 constructor(type, value) {3791 this.value = value;3792 this.type = type;3793 }3794}3795class PlayerChoiceStep extends LogicalStep {3796 constructor(playerUUID, choiceType, options, preposition, logicalBufferReturnKey, displayText) {3797 super();3798 this.hasBeenFulfilled = false;3799 this.playerUUID = playerUUID;3800 this.choiceType = choiceType;3801 this.options = options;3802 this.logicalBufferReturnKey = logicalBufferReturnKey;3803 this.preposition = preposition;3804 this.displayText = displayText;3805 }3806 processAndAdvance(logicalBuffer, gameDTO) {3807 /*var _ = new LogicalUtils();3808 PlayerChoiceNotify.send(_.ResolveVariable(this.playerUUID, logicalBuffer), _.ResolveVariable(this.options, logicalBuffer), this.preposition.type, _.ResolveVariable(this.preposition.value, logicalBuffer));3809 var lu = new LoggingUtils(gameDTO);3810 Log.send(lu.fname(_.ResolveVariable(this.playerUUID, logicalBuffer)) + " chooses " + logicalBuffer.storedData[this.logicalBufferReturnKey]);3811 var stack = GameDTOAccess.getLogicalStack(gameDTO);3812 var topBuffer = stack.buffers[stack.buffers.length - 1];3813 var currentStep = GameDTOAccess.traverseLogicalStep(gameDTO, topBuffer, topBuffer.getCurrentStep());*/3814 var lu = new LoggingUtils(gameDTO);3815 var _ = new LogicalUtils();3816 if (this.hasBeenFulfilled) {3817 Log.send(lu.fname(_.ResolveVariable(this.playerUUID, logicalBuffer)) + " chooses " + logicalBuffer.storedData[this.logicalBufferReturnKey]);3818 return true;3819 }3820 else {3821 GameDTOAccess.setState(gameDTO, GameState.WAITING_FOR_PLAYER_CHOICE);3822 return false;3823 }3824 }3825 fulfill(answers, logicalBuffer, gameDTO) {3826 if (answers.length == 1) {3827 logicalBuffer.storedData[this.logicalBufferReturnKey] = answers[0];3828 }3829 else {3830 logicalBuffer.storedData[this.logicalBufferReturnKey] = answers;3831 }3832 this.hasBeenFulfilled = true;3833 GameDTOAccess.updateLogicalBuffer(gameDTO, logicalBuffer);3834 }3835 getStepId() {3836 return StepId.PLAYER_CHOICE;3837 }3838 constructFromDTO(dto, logicalBuffer, gameDTO) {3839 this.uuid = dto.uuid;3840 this.playerUUID = LogicalVariable.generateFromDTO(dto.args["playerUUID"]);3841 this.choiceType = dto.args["choiceType"];3842 this.options = LogicalVariable.generateFromDTO(dto.args["options"]);3843 this.logicalBufferReturnKey = dto.args["logicalBufferReturnKey"];3844 this.preposition = dto.args["preposition"];3845 this.hasBeenFulfilled = dto.args["hasBeenFulfilled"];3846 this.displayText = dto.args["displayText"];3847 }3848 convertToDTO() {3849 var dto = new GameDTO_LogicalBuffer_Step();3850 dto.uuid = this.uuid;3851 dto.stepId = this.getStepId();3852 dto.args = {};3853 dto.args["choiceType"] = this.choiceType;3854 dto.args["playerUUID"] = this.playerUUID;3855 dto.args["options"] = this.options;3856 dto.args["logicalBufferReturnKey"] = this.logicalBufferReturnKey;3857 dto.args["preposition"] = this.preposition;3858 dto.args["hasBeenFulfilled"] = this.hasBeenFulfilled;3859 dto.args["displayText"] = this.displayText;3860 return dto;3861 }3862 reset() {3863 this.hasBeenFulfilled = false;3864 }3865 hasSubsteps() {3866 return false;3867 }3868 getCurrentSubstep(logicalBuffer, gameDTO) {3869 return null;3870 }3871}3872RegisterEventBufferStep(PlayerChoiceStep);3873///<reference path="../LogicalStep.ts" />3874var QueryStepOptions;3875(function (QueryStepOptions) {3876 QueryStepOptions[QueryStepOptions["NOT_IN"] = 0] = "NOT_IN";3877 QueryStepOptions[QueryStepOptions["IN"] = 1] = "IN";3878})(QueryStepOptions || (QueryStepOptions = {}));3879class QueryStep extends LogicalStep {3880 constructor(setOne, option, setTwo, logicalBufferReturnKey) {3881 super();3882 this.setOne = setOne;3883 this.setTwo = setTwo;3884 this.option = option;3885 this.logicalBufferReturnKey = logicalBufferReturnKey;3886 }3887 processAndAdvance(logicalBuffer, gameDTO) {3888 var _ = new LogicalUtils();3889 var firstOpValue = _.ResolveVariable(this.setOne, logicalBuffer);3890 var secondOpValue = _.ResolveVariable(this.setTwo, logicalBuffer);3891 firstOpValue = Util.convertToArray(firstOpValue);3892 secondOpValue = Util.convertToArray(secondOpValue);3893 var queryEval = [];3894 if (this.option == QueryStepOptions.NOT_IN) {3895 secondOpValue.forEach((innerEach) => {3896 if (firstOpValue.indexOf(innerEach) == -1) {3897 queryEval.push(innerEach);3898 }3899 });3900 }3901 else if (this.option == QueryStepOptions.IN) {3902 secondOpValue.forEach((innerEach) => {3903 if (firstOpValue.indexOf(innerEach) != -1) {3904 queryEval.push(innerEach);3905 }3906 });3907 }3908 logicalBuffer.storedData[this.logicalBufferReturnKey] = queryEval;3909 return true;3910 }3911 reset() {3912 }3913 getStepId() {3914 return StepId.QUERY;3915 }3916 constructFromDTO(dto, logicalBuffer, gameDTO) {3917 this.uuid = dto.uuid;3918 this.setOne = LogicalVariable.generateFromDTO(dto.args["setOne"]);3919 this.logicalBufferReturnKey = dto.args["logicalBufferReturnKey"];3920 this.setTwo = LogicalVariable.generateFromDTO(dto.args["setTwo"]);3921 this.option = dto.args["option"];3922 }3923 convertToDTO() {3924 var dto = new GameDTO_LogicalBuffer_Step();3925 dto.uuid = this.uuid;3926 dto.stepId = this.getStepId();3927 dto.args = {};3928 dto.args["setOne"] = this.setOne;3929 dto.args["option"] = this.option;3930 dto.args["setTwo"] = this.setTwo;3931 dto.args["logicalBufferReturnKey"] = this.logicalBufferReturnKey;3932 return dto;3933 }3934 hasSubsteps() {3935 return false;3936 }3937 getCurrentSubstep(logicalBuffer, gameDTO) {3938 return null;3939 }3940}3941RegisterEventBufferStep(QueryStep);3942///<reference path="../LogicalStep.ts" />3943var RelationalOptions;3944(function (RelationalOptions) {3945 RelationalOptions[RelationalOptions["GREATER_THAN_EQ"] = 0] = "GREATER_THAN_EQ";3946 RelationalOptions[RelationalOptions["LESS_THAN"] = 1] = "LESS_THAN";3947 RelationalOptions[RelationalOptions["EQUALS"] = 2] = "EQUALS";3948 RelationalOptions[RelationalOptions["GREATER_THAN"] = 3] = "GREATER_THAN";3949 RelationalOptions[RelationalOptions["NOT_EQ"] = 4] = "NOT_EQ";3950})(RelationalOptions || (RelationalOptions = {}));3951class RelationalStep extends LogicalStep {3952 constructor(firstOperand, relationalOption, secondOperand, stepsToPerform) {3953 super();3954 this.firstOperand = firstOperand;3955 this.relationalOption = relationalOption;3956 this.secondOperand = secondOperand;3957 this.stepsToPerform = stepsToPerform;3958 this.currentSubstepIndex = 0;3959 }3960 processAndAdvance(logicalBuffer, gameDTO) {3961 //alert("inside relational step");3962 this.hasBeenReset = false;3963 var _ = new LogicalUtils();3964 var firstOpValue = _.ResolveVariable(this.firstOperand, logicalBuffer);3965 var secondOpValue = _.ResolveVariable(this.secondOperand, logicalBuffer);3966 var relationalEval = null;3967 if (this.relationalOption == RelationalOptions.GREATER_THAN_EQ) {3968 relationalEval = firstOpValue >= secondOpValue;3969 }3970 else if (this.relationalOption == RelationalOptions.LESS_THAN) {3971 relationalEval = firstOpValue < secondOpValue;3972 }3973 else if (this.relationalOption == RelationalOptions.EQUALS) {3974 relationalEval = firstOpValue == secondOpValue;3975 }3976 else if (this.relationalOption == RelationalOptions.NOT_EQ) {3977 relationalEval = firstOpValue != secondOpValue;3978 }3979 else if (this.relationalOption == RelationalOptions.GREATER_THAN) {3980 relationalEval = firstOpValue > secondOpValue;3981 }3982 if (relationalEval) {3983 var currentStep = this.stepsToPerform[this.currentSubstepIndex];3984 var isSubStepComplete = currentStep.processAndAdvance(logicalBuffer, gameDTO);3985 if (this.hasBeenReset) {3986 this.hasBeenReset = false;3987 }3988 else {3989 if (isSubStepComplete) {3990 this.currentSubstepIndex++;3991 }3992 if (this.currentSubstepIndex >= this.stepsToPerform.length) {3993 return true;3994 }3995 }3996 return false;3997 }3998 return true;3999 }4000 getStepId() {4001 return StepId.RELATIONAL;4002 }4003 reset() {4004 this.hasBeenReset = true;4005 this.currentSubstepIndex = 0;4006 this.stepsToPerform.forEach((eachStep) => {4007 eachStep.reset();4008 });4009 }4010 constructFromDTO(dto, logicalBuffer, gameDTO) {4011 this.uuid = dto.uuid;4012 this.firstOperand = LogicalVariable.generateFromDTO(dto.args["firstOperand"]);4013 this.secondOperand = LogicalVariable.generateFromDTO(dto.args["secondOperand"]);4014 this.relationalOption = dto.args["relationalOption"];4015 this.stepsToPerform = [];4016 for (var key in dto.args["stepsToPerform"]) {4017 this.stepsToPerform[key] = LogicalStep.createFromDTO(dto.args["stepsToPerform"][key], logicalBuffer, gameDTO);4018 }4019 this.currentSubstepIndex = dto.args["currentSubstepIndex"];4020 this.hasBeenReset = dto.args["hasBeenReset"];4021 }4022 convertToDTO() {4023 var _ = new LogicalUtils();4024 var dto = new GameDTO_LogicalBuffer_Step();4025 dto.uuid = this.uuid;4026 dto.stepId = this.getStepId();4027 dto.args = {};4028 dto.args["firstOperand"] = this.firstOperand;4029 dto.args["relationalOption"] = this.relationalOption;4030 dto.args["secondOperand"] = this.secondOperand;4031 dto.args["stepsToPerform"] = _.SerializeDTOArray(this.stepsToPerform);4032 dto.args["currentSubstepIndex"] = this.currentSubstepIndex;4033 dto.args["hasBeenReset"] = this.hasBeenReset;4034 return dto;4035 }4036 hasSubsteps() {4037 return true;4038 }4039 getCurrentSubstep(logicalBuffer, gameDTO) {4040 return this.stepsToPerform[this.currentSubstepIndex];4041 }4042}4043RegisterEventBufferStep(RelationalStep);4044class Reaction {4045 constructor(status, canActivate, effectLogic) {4046 this.validStatusCheck = status;4047 this.canActivate = canActivate;4048 this.effectLogic = effectLogic;4049 }4050}4051class ReactionBuffer {4052 constructor(eventUUID, eventStatus, entries) {4053 this.eventUUID = eventUUID;4054 this.eventStatus = eventStatus;4055 this.entries = entries;4056 }4057 processAndAdvance(gameDTO) {4058 var topReaction = this.entries[this.entries.length - 1];4059 var event = GameDTOAccess.getEvent(gameDTO, this.eventUUID);4060 ReactionBuffer.GetReactiveComponent(gameDTO, topReaction).getReactions().forEach((eachReaction) => {4061 if (eachReaction.canActivate(event, gameDTO)) {4062 eachReaction.effectLogic(event, gameDTO);4063 }4064 });4065 this.entries.pop();4066 if (this.entries.length <= 0) {4067 return true;4068 }4069 return false;4070 }4071 convertToDTO() {4072 var dto = new GameDTO_ReactionBuffer();4073 dto.eventUUIDReactingTo = this.eventUUID;4074 dto.eventStatus = this.eventStatus;4075 dto.potentialReactions = this.entries;4076 return dto;4077 }4078 static pollReactions(event, gameDTO) {4079 var result = [];4080 for (var key in ReactionBuffer.REACTIVES_COMPONENTS) {4081 var reactionEntry = ReactionBuffer.REACTIVES_COMPONENTS[key](gameDTO).getReactions();4082 reactionEntry.forEach((eachReaction) => {4083 if (eachReaction.validStatusCheck == event.status) {4084 var dto = GameDTOAccess.getCardDTO(gameDTO, ReactionKey.fromString(key).id);4085 if (eachReaction.canActivate(event, gameDTO)) {4086 var dto = GameDTOAccess.getCardDTO(gameDTO, ReactionKey.fromString(key).id);4087 result.push(ReactionKey.fromString(key));4088 }4089 }4090 });4091 }4092 return result;4093 }4094}4095ReactionBuffer.REACTIVES_COMPONENTS = {};4096ReactionBuffer.RegisterReactiveComponent = (key, component) => {4097 var strKey = JSON.stringify(key);4098 ReactionBuffer.REACTIVES_COMPONENTS[strKey] = (gameDTO) => {4099 return component(gameDTO, key.id);4100 };4101};4102ReactionBuffer.GetReactiveComponent = (gameDTO, key) => {4103 var cardDTO = GameDTOAccess.getCardDTO(gameDTO, key.id);4104 return ReactionBuffer.REACTIVES_COMPONENTS[JSON.stringify(key)](gameDTO);4105};4106class ReactionKey {4107 constructor(type, id) {4108 this.type = type;4109 this.id = id;4110 }4111 static fromString(str) {4112 var obj = JSON.parse(str);4113 var newKey = new ReactionKey(obj["type"], obj["id"]);4114 return newKey;4115 }4116}4117var ReactionSourceType;4118(function (ReactionSourceType) {4119 ReactionSourceType[ReactionSourceType["CARD"] = 0] = "CARD";4120 ReactionSourceType[ReactionSourceType["SYSTEM"] = 1] = "SYSTEM";4121})(ReactionSourceType || (ReactionSourceType = {}));4122class ReactionStack {4123 processAndAdvance(gameDTO) {4124 ReactionStack.currentOutput = new ReactionStackOutput();4125 var topBuffer = this.buffers[this.buffers.length - 1];4126 var isComplete = topBuffer.processAndAdvance(gameDTO);4127 if (isComplete) {4128 GameDTOAccess.removeTopReactionBuffer(gameDTO);4129 ReactionStack.currentOutput.currentBufferFinished = true;4130 }4131 if (this.buffers.length <= 0) {4132 ReactionStack.currentOutput.isEmpty = true;4133 }4134 return ReactionStack.currentOutput;4135 }4136}4137class ReactionStackOutput {4138}4139class CleanUpReaction {4140 constructor() {4141 this.reactions = [];4142 this.reactions.push(new Reaction(EventStatus.RESOLVED, (event, gameDTO) => {4143 if (event.getId() == EventIds.ADVANCE_PHASE && gameDTO.state.phase == Phase.CLEAN_UP) {4144 return true;4145 }4146 return false;4147 }, (event, gameDTO) => {4148 var _ = new LogicalUtils();4149 var logicBuffer = new LogicalBuffer();4150 var hand = GameDTOAccess.getCardsInZone(gameDTO, gameDTO.state.turnPlayer, Zones.HAND);4151 var inPlay = GameDTOAccess.getCardsInZone(gameDTO, gameDTO.state.turnPlayer, Zones.IN_PLAY);4152 var allCards = hand.concat(inPlay);4153 var moneyToReduce = GameDTOAccess.getPlayerFromUUID(gameDTO, gameDTO.state.turnPlayer).turn.money * -1;4154 logicBuffer.addSteps(new EventGeneratorStep(EventIds.ADD_MONEY, new AddMoneyEventArgs(_.Value(gameDTO.state.turnPlayer), _.Value(moneyToReduce))), new ForEachStep(_.Value(allCards), "each_card_chosen", [4155 new EventGeneratorStep(EventIds.DISCARD_CARD, new DiscardCardsEventArgs(_.Reference("each_card_chosen")))4156 ]), new DrawCardsStep(gameDTO.state.turnPlayer, _.Value(5)));4157 GameDTOAccess.pushNewLogicalBuffer(gameDTO, logicBuffer);4158 }));4159 }4160 getReactions() {4161 return this.reactions;4162 }4163}4164ReactionBuffer.RegisterReactiveComponent(new ReactionKey(ReactionSourceType.SYSTEM, "CleanUpReaction"), (gameDTO, uuid) => { return new CleanUpReaction(); });4165class DriverNotify {4166 static ping() {4167 MessagingCenter.notify(DriverNotify.DRIVER_EVENT, {});4168 }4169 static subscribe(callback) {4170 MessagingCenter.addListener(DriverNotify.DRIVER_EVENT, callback, false);4171 }4172}4173DriverNotify.DRIVER_EVENT = "DRIVER_EVENT";4174class GameDisplayFeed {4175 static send(gameDTO, action) {4176 MessagingCenter.notify(GameDisplayFeed.GAME_FEED_EVENT, {4177 "gameDTO": gameDTO,4178 "action": action4179 });4180 }4181 static subscribe(callback) {4182 MessagingCenter.addListener(GameDisplayFeed.GAME_FEED_EVENT, (message) => {4183 callback(message["gameDTO"], message["action"]);4184 }, false);4185 }4186}4187GameDisplayFeed.GAME_FEED_EVENT = "GAME_FEED_EVENT";4188class MessagingCenter {4189 static addListener(event, callback, removeOnCompletion) {4190 if (MessagingCenter.pubSubMap[event] == null) {4191 MessagingCenter.pubSubMap[event] = [];4192 }4193 MessagingCenter.pubSubMap[event].push(new MessageCallback(callback, removeOnCompletion, MessagingCenter.pubSubMap[event].length));4194 }4195 static notify(event, payload) {4196 if (MessagingCenter.pubSubMap[event] != null) {4197 MessagingCenter.pubSubMap[event].forEach((e, eIdx) => {4198 e.callback(payload);4199 if (e.removeOnCompletion) {4200 MessagingCenter.pubSubMap[event].splice(eIdx, 1);4201 }4202 });4203 }4204 }4205}4206MessagingCenter.pubSubMap = {};4207///<reference path="MessagingCenter.ts" />4208class Log {4209 static send(messageString) {4210 MessagingCenter.notify(Log.LOG_EVENT, {4211 "message": messageString4212 });4213 }4214 static subscribe(callback) {4215 MessagingCenter.addListener(Log.LOG_EVENT, callback, false);4216 }4217}4218Log.LOG_EVENT = "LOG_EVENT";4219class MessageCallback {4220 constructor(callback, removeOnCompletion, id) {4221 this.callback = callback;4222 this.removeOnCompletion = removeOnCompletion;4223 this.id = id;4224 }4225}4226class PlayerChoiceNotify {4227 static send(playerUUID, options, prepositionType, prepositionValue) {4228 MessagingCenter.notify(PlayerChoiceNotify.PLAYER_CHOICE, {4229 "playerUUID": playerUUID,4230 "options": options,4231 "prepositionType": prepositionType,4232 "prepositionValue": prepositionValue4233 });4234 }4235 static subscribe(callback) {4236 MessagingCenter.addListener(PlayerChoiceNotify.PLAYER_CHOICE, (message) => {4237 callback(message["playerUUID"], message["options"], message["prepositionType"], message["prepositionValue"]);4238 }, false);4239 }4240}4241PlayerChoiceNotify.PLAYER_CHOICE = "PLAYER_CHOICE";4242class TurnNotify {4243 static send(turnPlayer) {4244 MessagingCenter.notify(TurnNotify.TURN_EVENT, {4245 "turnPlayer": turnPlayer4246 });4247 }4248 static subscribe(callback) {4249 MessagingCenter.addListener(TurnNotify.TURN_EVENT, (message) => {4250 callback(message["turnPlayer"]);4251 }, false);4252 }4253}4254TurnNotify.TURN_EVENT = "TURN_EVENT";4255class LoggingUtils {4256 constructor(gameDTO) {4257 this.gameDTO = gameDTO;4258 }4259 fname(objectUUID) {4260 var dto = GameDTOAccess.getObjectForUUID(this.gameDTO, objectUUID);4261 if (dto instanceof GameDTO_Card) {4262 return CardIds[dto.definitionId];4263 }4264 else if (dto instanceof GameDTO_Player) {4265 return dto.name;4266 }4267 }4268 owner(cardUUID) {4269 var ownerDto = GameDTOAccess.getOwnerDTO(this.gameDTO, cardUUID);4270 return ownerDto.name;4271 }4272}4273function UUID() {4274 return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {4275 var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);4276 return v.toString(16);4277 });4278}4279class Util {4280 static contains(a, obj) {4281 var i = a.length;4282 while (i--) {4283 if (a[i] === obj) {4284 return true;4285 }4286 }4287 return false;4288 }4289 static shuffle(array) {4290 for (var i = array.length - 1; i > 0; i--) {4291 var j = Math.floor(Math.random() * (i + 1));4292 var temp = array[i];4293 array[i] = array[j];4294 array[j] = temp;4295 }4296 return array;4297 }4298 static randomInRange(min, max) {4299 min = Math.ceil(min);4300 max = Math.floor(max);4301 return Math.floor(Math.random() * (max - min + 1)) + min;4302 }4303 static isArray(obj) {4304 return !!obj && obj.constructor === Array;4305 }4306 static convertToArray(value) {4307 if (!Util.isArray(value)) {4308 var newArray = [];4309 newArray.push(value);4310 return newArray;4311 }4312 return value;4313 }4314 static isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0); }4315}4316class DriveGameService {4317 drive() {4318 fs.readFile('gamestate.txt', function (err, data) {4319 var gameDTO = GameDTOTransform.createFromJSON(data);4320 new GameDriver(gameDTO).process();4321 fs.writeFile('gamestate.txt', JSON.stringify(gameDTO), function (err) {4322 });4323 });4324 }4325}4326class LogService {4327 constructor() {4328 Log.subscribe((message) => {4329 console.log("Log: " + message["message"]);4330 var logText = fs.readFileSync('logs.txt', { encoding: 'utf8', flag: 'r' });4331 var logs = JSON.parse(logText);4332 logs.push({4333 "message": message["message"], "timestamp": new Date().getTime()4334 });4335 fs.writeFileSync('logs.txt', JSON.stringify(logs));4336 });4337 }4338}4339new LogService();4340class API {4341 constructor(path, method) {4342 this.path = path;4343 this.method = method;4344 }4345 add(app) {4346 var handleRequest = (request, result) => {4347 if (this.validate(request)) {4348 this.process(request, result);4349 }4350 else {4351 result.sendStatus(400);4352 result.end();4353 }4354 };4355 if (this.method == HTTPMethod.GET) {4356 app.get(this.path, handleRequest);4357 }4358 else if (this.method == HTTPMethod.POST) {4359 app.post(this.path, handleRequest);4360 }4361 }4362}4363var HTTPMethod;4364(function (HTTPMethod) {4365 HTTPMethod[HTTPMethod["GET"] = 0] = "GET";4366 HTTPMethod[HTTPMethod["POST"] = 1] = "POST";4367})(HTTPMethod || (HTTPMethod = {}));4368class AddPlayerApi extends API {4369 constructor() {4370 super("/addPlayer", HTTPMethod.POST);4371 }4372 validate(request) {4373 var requiredFields = ["name"];4374 return new RequiredFieldValidator(requiredFields).check(request);4375 }4376 process(request, result) {4377 var name = request.body["name"];4378 var newPlayer = new GameDTO_Player();4379 newPlayer.uuid = UUID();4380 newPlayer.name = name;4381 fs.readFile('gamestate.txt', function (err, data) {4382 var gameDTO = GameDTOTransform.createFromJSON(data);4383 gameDTO.players.push(newPlayer);4384 var isFull = (gameDTO.players.length >= 2);4385 if (isFull) {4386 gameDTO.state.state = GameState.START;4387 }4388 fs.writeFile('gamestate.txt', JSON.stringify(gameDTO), function (err) {4389 result.writeHead(200, { 'Content-Type': 'application/json' });4390 result.write(JSON.stringify({ "uuid": newPlayer.uuid, "isGameReady": (gameDTO.players.length >= 2) }));4391 result.end();4392 new DriveGameService().drive();4393 });4394 });4395 }4396}4397class GetGameStateApi extends API {4398 constructor() {4399 super("/getGameState", HTTPMethod.GET);4400 }4401 validate(request) {4402 return true;4403 }4404 process(request, result) {4405 fs.readFile('gamestate.txt', function (err, data) {4406 result.writeHead(200, { 'Content-Type': 'application/json' });4407 result.write(data);4408 return result.end();4409 });4410 }4411}4412class GetLogsApi extends API {4413 constructor() {4414 super("/getLogs", HTTPMethod.POST);4415 }4416 validate(request) {4417 var requiredFields = ["fromTimestamp"];4418 return new RequiredFieldValidator(requiredFields).check(request);4419 }4420 process(request, result) {4421 var fromTimestamp = request.body["fromTimestamp"];4422 fs.readFile('logs.txt', function (err, data) {4423 var resultLogs = [];4424 var logs = JSON.parse(data);4425 logs.forEach((eachLog) => {4426 if (eachLog["timestamp"] >= fromTimestamp) {4427 resultLogs.push(eachLog);4428 }4429 });4430 result.writeHead(200, { 'Content-Type': 'application/json' });4431 result.write(JSON.stringify(resultLogs));4432 return result.end();4433 });4434 }4435}4436class GetPossibleMovesApi extends API {4437 constructor() {4438 super("/getPossibleMoves", HTTPMethod.POST);4439 }4440 validate(request) {4441 var requiredFields = ["playerUUID"];4442 return new RequiredFieldValidator(requiredFields).check(request);4443 }4444 process(request, result) {4445 var playerUUID = request.body["playerUUID"];4446 fs.readFile('gamestate.txt', function (err, data) {4447 var gameDTO = GameDTOTransform.createFromJSON(data);4448 var moves = new PossibleMovesGenerator().generate(playerUUID, gameDTO).map((eachMove) => { return Move.toJsonObject(eachMove); });4449 result.writeHead(200, { 'Content-Type': 'application/json' });4450 result.write(JSON.stringify(moves));4451 result.end();4452 });4453 }4454}4455class InitGameApi extends API {4456 constructor() {4457 super("/initGame", HTTPMethod.GET);4458 }4459 validate(request) {4460 return true;4461 }4462 process(request, result) {4463 if (!fs.existsSync('gamestate.txt')) {4464 fs.writeFile('gamestate.txt', JSON.stringify(gameDTO), function (err) {4465 new DriveGameService().drive();4466 });4467 }4468 if (!fs.existsSync('logs.txt')) {4469 var gameDTO = new GameDTO();4470 fs.writeFile('logs.txt', "[]", function (err) {4471 });4472 }4473 result.sendStatus(200);4474 }4475}4476class MakeMoveApi extends API {4477 constructor() {4478 super("/makeMove", HTTPMethod.POST);4479 }4480 validate(request) {4481 var requiredFields = ["move"];4482 return new RequiredFieldValidator(requiredFields).check(request);4483 }4484 process(request, result) {4485 fs.readFile('gamestate.txt', function (err, data) {4486 var gameDTO = GameDTOTransform.createFromJSON(data);4487 var moveToMake = request.body["move"];4488 var moveObj = Move.fromJson(moveToMake);4489 moveObj.execute(gameDTO);4490 fs.writeFile('gamestate.txt', JSON.stringify(gameDTO), function (err) {4491 new DriveGameService().drive();4492 result.sendStatus(200);4493 result.end();4494 });4495 });4496 }4497}4498class ResetGameApi extends API {4499 constructor() {4500 super("/resetGame", HTTPMethod.GET);4501 }4502 validate(request) {4503 return true;4504 }4505 process(request, result) {4506 var gameDTO = new GameDTO();4507 fs.writeFile('gamestate.txt', JSON.stringify(gameDTO), function (err) {4508 //new DriveGameService().drive();4509 });4510 fs.writeFile('logs.txt', "[]", function (err) {4511 });4512 result.sendStatus(200);4513 return result.end();4514 }4515}4516class Server {4517 createServer() {4518 var app = express();4519 app.use(bodyParser.json());4520 app.use(cors());4521 this.addAPIs(app);4522 return app;4523 }4524 addAPIs(app) {4525 new GetLogsApi().add(app);4526 new InitGameApi().add(app);4527 new GetGameStateApi().add(app);4528 new MakeMoveApi().add(app);4529 new ResetGameApi().add(app);4530 new GetPossibleMovesApi().add(app);4531 new AddPlayerApi().add(app);4532 }4533 startServer(app) {4534 var server = app.listen(8082, function () {4535 var host = server.address().address;4536 var port = server.address().port;4537 console.log("Example app listening at http://%s:%s", host, port);4538 });4539 }4540 init() {4541 var app = this.createServer();4542 this.startServer(app);4543 }4544}4545new Server().init();4546class RequiredFieldValidator {4547 constructor(requiredFields) {4548 this.requiredFields = requiredFields;4549 }4550 check(request) {4551 var result = true;4552 this.requiredFields.forEach((eachField) => {4553 if (request.body[eachField] == null || request.body[eachField] == undefined) {4554 result = false;4555 }4556 });4557 return result;4558 }...
api.js
Source:api.js
1class API {2 constructor(path, method) {3 this.path = path;4 this.method = method;5 }6 add(app) {7 var handleRequest = (request, result) => {8 if (this.validate(request)) {9 this.process(request, result);10 }11 else {12 result.sendStatus(400);13 result.end();14 }15 };16 if (this.method == HTTPMethod.GET) {17 app.get(this.path, handleRequest);18 }19 else if (this.method == HTTPMethod.POST) {20 app.post(this.path, handleRequest);21 }22 }23}24var HTTPMethod;25(function (HTTPMethod) {26 HTTPMethod[HTTPMethod["GET"] = 0] = "GET";27 HTTPMethod[HTTPMethod["POST"] = 1] = "POST";28})(HTTPMethod || (HTTPMethod = {}));29class AddPlayerApi extends API {30 constructor() {31 super("/addPlayer", HTTPMethod.POST);32 }33 validate(request) {34 var requiredFields = ["name"];35 return new RequiredFieldValidator(requiredFields).check(request);36 }37 process(request, result) {38 var name = request.body["name"];39 var newPlayer = new GameDTO_Player();40 newPlayer.uuid = UUID();41 newPlayer.name = name;42 fs.readFile('gamestate.txt', function (err, data) {43 var gameDTO = GameDTOTransform.createFromJSON(data);44 gameDTO.players.push(newPlayer);45 var isFull = (gameDTO.players.length >= 2);46 if (isFull) {47 gameDTO.state.state = GameState.START;48 }49 fs.writeFile('gamestate.txt', JSON.stringify(gameDTO), function (err) {50 result.writeHead(200, { 'Content-Type': 'application/json' });51 result.write(JSON.stringify({ "uuid": newPlayer.uuid, "isGameReady": (gameDTO.players.length >= 2) }));52 result.end();53 new DriveGameService().drive();54 });55 });56 }57}58class GetGameStateApi extends API {59 constructor() {60 super("/getGameState", HTTPMethod.GET);61 }62 validate(request) {63 return true;64 }65 process(request, result) {66 fs.readFile('gamestate.txt', function (err, data) {67 result.writeHead(200, { 'Content-Type': 'application/json' });68 result.write(data);69 return result.end();70 });71 }72}73class GetLogsApi extends API {74 constructor() {75 super("/getLogs", HTTPMethod.POST);76 }77 validate(request) {78 var requiredFields = ["fromTimestamp"];79 return new RequiredFieldValidator(requiredFields).check(request);80 }81 process(request, result) {82 var fromTimestamp = request.body["fromTimestamp"];83 fs.readFile('logs.txt', function (err, data) {84 var resultLogs = [];85 var logs = JSON.parse(data);86 logs.forEach((eachLog) => {87 if (eachLog["timestamp"] >= fromTimestamp) {88 resultLogs.push(eachLog);89 }90 });91 result.writeHead(200, { 'Content-Type': 'application/json' });92 result.write(JSON.stringify(resultLogs));93 return result.end();94 });95 }96}97class GetPossibleMovesApi extends API {98 constructor() {99 super("/getPossibleMoves", HTTPMethod.POST);100 }101 validate(request) {102 var requiredFields = ["playerUUID"];103 return new RequiredFieldValidator(requiredFields).check(request);104 }105 process(request, result) {106 var playerUUID = request.body["playerUUID"];107 fs.readFile('gamestate.txt', function (err, data) {108 var gameDTO = GameDTOTransform.createFromJSON(data);109 var moves = new PossibleMovesGenerator().generate(playerUUID, gameDTO).map((eachMove) => { return Move.toJsonObject(eachMove); });110 result.writeHead(200, { 'Content-Type': 'application/json' });111 result.write(JSON.stringify(moves));112 result.end();113 });114 }115}116class InitGameApi extends API {117 constructor() {118 super("/initGame", HTTPMethod.GET);119 }120 validate(request) {121 return true;122 }123 process(request, result) {124 if (!fs.existsSync('gamestate.txt')) {125 fs.writeFile('gamestate.txt', JSON.stringify(gameDTO), function (err) {126 new DriveGameService().drive();127 });128 }129 if (!fs.existsSync('logs.txt')) {130 var gameDTO = new GameDTO();131 fs.writeFile('logs.txt', "[]", function (err) {132 });133 }134 result.sendStatus(200);135 }136}137class MakeMoveApi extends API {138 constructor() {139 super("/makeMove", HTTPMethod.POST);140 }141 validate(request) {142 var requiredFields = ["move"];143 return new RequiredFieldValidator(requiredFields).check(request);144 }145 process(request, result) {146 fs.readFile('gamestate.txt', function (err, data) {147 var gameDTO = GameDTOTransform.createFromJSON(data);148 var moveToMake = request.body["move"];149 var moveObj = Move.fromJson(moveToMake);150 moveObj.execute(gameDTO);151 fs.writeFile('gamestate.txt', JSON.stringify(gameDTO), function (err) {152 new DriveGameService().drive();153 result.sendStatus(200);154 result.end();155 });156 });157 }158}159class ResetGameApi extends API {160 constructor() {161 super("/resetGame", HTTPMethod.GET);162 }163 validate(request) {164 return true;165 }166 process(request, result) {167 var gameDTO = new GameDTO();168 fs.writeFile('gamestate.txt', JSON.stringify(gameDTO), function (err) {169 //new DriveGameService().drive();170 });171 fs.writeFile('logs.txt', "[]", function (err) {172 });173 result.sendStatus(200);174 return result.end();175 }176}177class Server {178 createServer() {179 var app = express();180 app.use(bodyParser.json());181 app.use(cors());182 this.addAPIs(app);183 return app;184 }185 addAPIs(app) {186 new GetLogsApi().add(app);187 new InitGameApi().add(app);188 new GetGameStateApi().add(app);189 new MakeMoveApi().add(app);190 new ResetGameApi().add(app);191 new GetPossibleMovesApi().add(app);192 new AddPlayerApi().add(app);193 }194 startServer(app) {195 var server = app.listen(8082, function () {196 var host = server.address().address;197 var port = server.address().port;198 console.log("Example app listening at http://%s:%s", host, port);199 });200 }201 init() {202 var app = this.createServer();203 this.startServer(app);204 }205}206new Server().init();207class RequiredFieldValidator {208 constructor(requiredFields) {209 this.requiredFields = requiredFields;210 }211 check(request) {212 var result = true;213 this.requiredFields.forEach((eachField) => {214 if (request.body[eachField] == null || request.body[eachField] == undefined) {215 result = false;216 }217 });218 return result;219 }...
safari-network-log.js
Source:safari-network-log.js
...153 this.log.debug(` Cancelled: ${cancelled}`);154 }155 }156 async getLogs () {157 const logs = await super.getLogs();158 // in order to satisfy certain clients, we need to have a basic structure159 // to the results, with `level`, `timestamp`, and `message`, which is160 // all the information stringified161 return logs.map(function adjustEntry (entry) {162 return Object.assign({}, entry, {163 level: 'INFO',164 timestamp: Date.now(),165 message: JSON.stringify(entry),166 });167 });168 }169}170export { SafariNetworkLog };171export default SafariNetworkLog;
Using AI Code Generation
1const wdio = require('webdriverio');2const options = {3 desiredCapabilities: {4 }5};6const client = wdio.remote(options);7client.init();8client.getLogs('syslog').then(function (logs) {9 console.log(logs);10});11client.end();12I am trying to use getLogs() method of Appium XCUITest Driver to get the logs of iOS device. But it is not working. I am using webdriverio to run my tests on iOS device. I have tried using the following code:13const wdio = require('webdriverio');14const options = {15 desiredCapabilities: {16 }17};18const client = wdio.remote(options);19client.init();20client.getLogs('syslog').then(function (logs) {21 console.log(logs);22});23client.end();24I am trying to use getLogs() method of Appium XCUITest Driver to get the logs of iOS device. But it is not working. I am using webdriverio to run my tests on iOS device. I have tried using the following code:25const wdio = require('webdriverio');26const options = {27 desiredCapabilities: {28 }29};
Using AI Code Generation
1const { AppiumDriver } = require('appium-base-driver');2const { XCUITestDriver } = require('appium-xcuitest-driver');3const { XCUITestDriverExtension } = require('appium-xcuitest-driver/lib/commands/recordscreen');4const { XCUITestDriverExtension } = require('appium-xcuitest-driver/lib/commands/log');5class MyXCUITestDriver extends XCUITestDriver {6 async getLogs (logType) {7 return await super.getLogs(logType);8 }9}10class MyXCUITestDriverExtension extends XCUITestDriverExtension {11 constructor (driver) {12 super(driver);13 }14 async getLogs (logType) {15 return await super.getLogs(logType);16 }17}18class MyXCUITestDriverExtension extends XCUITestDriverExtension {19 constructor (driver) {20 super(driver);21 }22 async getLogs (logType) {23 return await super.getLogs(logType);24 }25}26class MyXCUITestDriverExtension extends XCUITestDriverExtension {27 constructor (driver) {28 super(driver);29 }30 async getLogs (logType) {31 return await super.getLogs(logType);32 }33}34class MyXCUITestDriverExtension extends XCUITestDriverExtension {35 constructor (driver) {36 super(driver);37 }38 async getLogs (logType) {39 return await super.getLogs(logType);40 }41}42class MyXCUITestDriverExtension extends XCUITestDriverExtension {43 constructor (driver) {44 super(driver);45 }46 async getLogs (logType) {47 return await super.getLogs(logType);48 }49}50class MyXCUITestDriverExtension extends XCUITestDriverExtension {
Using AI Code Generation
1const { XCUITestDriver } = require('appium-xcuitest-driver');2const { XCUITestDriver } = require('appium-xcuitest-driver');3const { BaseDriver } = require('appium-base-driver');4const { BaseDriver } = require('appium-base-driver');5class MyDriver extends XCUITestDriver {6 async getLogs (logType) {7 }8}9module.exports = MyDriver;10[debug] [BaseDriver] Event 'newSessionStarted' logged at 1530002165900 (22:02:45 GMT+0530 (IST))11 at Object.wrappedLogger.errorAndThrow (../../lib/logging.js:60:13)12 at XCUITestDriver.startRealDevice$ (../../lib/driver.js:318:9)13 at tryCatch (/Users/xxxxx/node_modules/babel-runtime/regenerator/runtime.js:67:40)14 at GeneratorFunctionPrototype.invoke [as _invoke] (/Users/xxxxx/node_modules/babel-runtime/regenerator/runtime.js:315:22)15 at GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (/Users/xxxxx/node_modules/babel-runtime/regenerator/runtime.js:100:21)16 at GeneratorFunctionPrototype.invoke (/Users/xxxxx/node_modules/babel-runtime/regenerator/runtime.js:136:37)17[debug] [BaseDriver] Event 'newSessionStarted' logged at 1530002165900 (22:02:45 GMT+0530 (IST))18 at Object.wrappedLogger.errorAndThrow (../../lib/logging.js:60:
Using AI Code Generation
1var wd = require('wd');2var path = require('path');3var desiredCaps = {4 app: path.resolve(__dirname, 'app', 'TestApp.app')5};6var driver = wd.promiseChainRemote('localhost', 4723);7 .init(desiredCaps)8 .getLogs('syslog')9 .then(function(logs) {10 console.log(logs);11 })12 .finally(function() {13 driver.quit();14 });
Using AI Code Generation
1const wd = require('wd');2const { XCUITestDriver } = require('appium-xcuitest-driver');3async function main() {4 const xDriver = new XCUITestDriver(driver);5 await driver.init({6 });7 console.log(logs);8}9main();
Using AI Code Generation
1const wdio = require("webdriverio");2const superagent = require("superagent");3const superagentPromise = require("superagent-promise");4const agent = superagentPromise(superagent, global.Promise);5const assert = require("assert");6const opts = {7 capabilities: {8 }9};10(async function main() {11 try {12 const client = await wdio.remote(opts);13 const logs = await client.getLogs("syslog");14 console.log("logs", logs);15 client.deleteSession();16 } catch (err) {17 console.error("Error occurred: ", err);18 }19})();
Using AI Code Generation
1const request = require('request');2const fs = require('fs');3const path = require('path');4const logPath = path.resolve(__dirname, 'logs');5const logFile = path.resolve(logPath, 'log.txt');6const logFile2 = path.resolve(logPath, 'log2.txt');7const logFile3 = path.resolve(logPath, 'log3.txt');8const logFile4 = path.resolve(logPath, 'log4.txt');9const logFile5 = path.resolve(logPath, 'log5.txt');10const logFile6 = path.resolve(logPath, 'log6.txt');11const logFile7 = path.resolve(logPath, 'log7.txt');12const logFile8 = path.resolve(logPath, 'log8.txt');13const logFile9 = path.resolve(logPath, 'log9.txt');14const logFile10 = path.resolve(logPath, 'log10.txt');15const logFile11 = path.resolve(logPath, 'log11.txt');16const logFile12 = path.resolve(logPath, 'log12.txt');17const logFile13 = path.resolve(logPath, 'log13.txt');18const logFile14 = path.resolve(logPath, 'log14.txt');19const logFile15 = path.resolve(logPath, 'log15.txt');20const logFile16 = path.resolve(logPath, 'log16.txt');21const logFile17 = path.resolve(logPath, 'log17.txt');22const logFile18 = path.resolve(logPath, 'log18.txt');23const logFile19 = path.resolve(logPath, 'log19.txt');24const logFile20 = path.resolve(logPath, 'log20.txt');25const logFile21 = path.resolve(logPath, 'log21.txt');26const logFile22 = path.resolve(logPath, 'log22.txt');27const logFile23 = path.resolve(logPath, 'log23.txt');28const logFile24 = path.resolve(logPath, 'log24.txt');29const logFile25 = path.resolve(logPath, 'log25.txt');30const logFile26 = path.resolve(logPath, 'log26.txt');31const logFile27 = path.resolve(logPath, 'log27.txt');32const logFile28 = path.resolve(logPath, 'log28.txt');33const logFile29 = path.resolve(logPath, 'log29.txt');34const logFile30 = path.resolve(logPath, 'log30.txt');35const logFile31 = path.resolve(logPath, 'log31.txt');
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!