Ejemplo n.º 1
0
        public static byte[] Write(Deck deck)
        {
            using (var stream = new MemoryStream())
            {
                using (var writer = new StreamWriter(stream))
                {
                    if (!String.IsNullOrEmpty(deck.Description))
                        writer.WriteLine("# Description: {0}", deck.Description);

                    if (deck.Rating.HasValue)
                        writer.WriteLine("# Rating: {0}", deck.Rating);

                    if (deck.LimitedCode.HasValue)
                        writer.WriteLine("# Limited: {0}", deck.LimitedCode);

                    foreach (var row in DeckRow.Group(deck))
                    {
                        if (string.IsNullOrEmpty(row.Card.Set))
                        {
                            writer.WriteLine("{0} {1}", row.Count, row.Card.Name);
                        }
                        else
                        {
                            writer.WriteLine("{0} {1} ({2}, {3})", row.Count, row.Card.Name, row.Card.Rarity, row.Card.Set);
                        }
                    }
                }
                return stream.ToArray();
            }
        }
Ejemplo n.º 2
0
		private static async Task<Deck> ImportIcyVeins(string url)
		{
			try
			{
				string json;
				using(var wc = new WebClient())
					json = await wc.DownloadStringTaskAsync(url + ".json");
				var wrapper = JsonConvert.DeserializeObject<IcyVeinsWrapper>(json);
				var deck = new Deck {Name = wrapper.deck_name};
				foreach(var cardObj in wrapper.deck_cards)
				{
					var cardName = cardObj.name;
					if(cardName.EndsWith(" Naxx"))
						cardName = cardName.Replace(" Naxx", "");
					if(cardName.EndsWith(" GvG"))
						cardName = cardName.Replace(" GvG", "");
					if(cardName.EndsWith(" BrM"))
						cardName = cardName.Replace(" BrM", "");
					var card = Database.GetCardFromName(cardName);
					card.Count = cardObj.quantity;
					deck.Cards.Add(card);
					if(string.IsNullOrEmpty(deck.Class) && card.PlayerClass != "Neutral")
						deck.Class = card.PlayerClass;
				}
				return deck;
			}
			catch(Exception e)
			{
				Logger.WriteLine(e.ToString(), "DeckImporter");
				return null;
			}
		}
Ejemplo n.º 3
0
        public void TestDeckToHave24CardsAtStart()
        {
            int expectedNumberOfCards = 24;
            var deck = new Deck();

            Assert.AreEqual(expectedNumberOfCards, deck.CardsLeft, "Initial number of cards is not correct");
        }
    public void ExpectGetTrumpCardMethodToReturnACard()
    {
        var deck = new Deck();
        var card = deck.GetTrumpCard;

        Assert.IsInstanceOf(typeof(Card), card);
    }
Ejemplo n.º 5
0
        public void TestIfTrumpCardReturnsACard()
        {
            var deck = new Deck();
            var card = deck.GetTrumpCard;

            Assert.IsInstanceOf(typeof(Card), card, "The method does not return an instace of Card class");
        }
Ejemplo n.º 6
0
 public void GetNextCardShouldRemoveTheCardFromTheDeck()
 {
     Deck testDeck = new Deck();
     int initialNumberOfCards = testDeck.CardsLeft;
     testDeck.GetNextCard();
     Assert.AreEqual((initialNumberOfCards - 1), testDeck.CardsLeft, "GetNextCard() should remove 1 card from the deck");
 }
		private async void ExportDeck(Deck deck)
		{
			var export = true;
			if(Config.Instance.ShowExportingDialog)
			{
				var message =
					string.Format(
					              "1) create a new, empty {0}-Deck {1}.\n\n2) leave the deck creation screen open.\n\n3)do not move your mouse or type after clicking \"export\"",
					              deck.Class, (Config.Instance.AutoClearDeck ? "(or open an existing one to be cleared automatically)" : ""));

				if(deck.GetSelectedDeckVersion().Cards.Any(c => c.Name == "Stalagg" || c.Name == "Feugen"))
				{
					message +=
						"\n\nIMPORTANT: If you own golden versions of Feugen or Stalagg please make sure to configure\nOptions > Other > Exporting";
				}

				var settings = new MetroDialogSettings {AffirmativeButtonText = "export"};
				var result =
					await
					this.ShowMessageAsync("Export " + deck.Name + " to Hearthstone", message, MessageDialogStyle.AffirmativeAndNegative, settings);
				export = result == MessageDialogResult.Affirmative;
			}
			if(export)
			{
				var controller = await this.ShowProgressAsync("Creating Deck", "Please do not move your mouse or type.");
				Topmost = false;
				await Task.Delay(500);
				await DeckExporter.Export(deck);
				await controller.CloseAsync();

				if(deck.MissingCards.Any())
					this.ShowMissingCardsMessage(deck);
			}
		}
Ejemplo n.º 8
0
        public async Task Export(Deck deck)
        {
            if (deck == null) return;

            var hsHandle = User32.FindWindow("UnityWndClass", "Hearthstone");

            if (!User32.IsForegroundWindow("Hearthstone"))
            {
                //restore window and bring to foreground
                User32.ShowWindow(hsHandle, User32.SwRestore);
                User32.SetForegroundWindow(hsHandle);
                //wait it to actually be in foreground, else the rect might be wrong
                await Task.Delay(500);
            }
            if (!User32.IsForegroundWindow("Hearthstone"))
            {
                MessageBox.Show("Can't find Heartstone window.");
                return;
            }

            var hsRect = User32.GetHearthstoneRect(false);

            var bounds = Screen.FromHandle(hsHandle).Bounds;
            
            bool isFullscreen = bounds.Width == hsRect.Width && bounds.Height == hsRect.Height;

            if(_config.ExportSetDeckName)
                await SetDeckName(deck.Name, hsRect.Width, hsRect.Height, hsHandle);

            foreach (var card in deck.Cards)
            {
                await AddCardToDeck(card, hsRect.Width, hsRect.Height, hsHandle, isFullscreen);
            }
        }
Ejemplo n.º 9
0
 public void Handle(GameStartedEvent startedEvent, GameState gameState)
 {
     var deck = new Deck().ToList();
     gameState.Id = startedEvent.GameId;
     gameState.GameRules = startedEvent.Rules;
     gameState.StartedAt = startedEvent.Occurred;
     gameState.LastUpdated = startedEvent.Occurred;
     gameState.OpeningRound = new OpeningRound
     {
         Deck = deck,
         Complete = false,
         CutCards = new List<PlayerIdCard>(),
         WinningPlayerCut = null
     };
     gameState.IndividualScores = new List<PlayerScore>(startedEvent.Players.Select(player => new PlayerScore { Player = player, Score = 0 }));
     gameState.PlayerIds = startedEvent.Players.ToList();
     gameState.TeamScores = startedEvent.Players.Count == 2
         ? startedEvent.Players.Select(p => new TeamScore {Players = new List<int> {p}}).ToList()
         : new List<TeamScore>
         {
             new TeamScore {Players = new List<int> {startedEvent.Players[0], startedEvent.Players[2]}},
             new TeamScore {Players = new List<int> {startedEvent.Players[1], startedEvent.Players[3]}}
         };
     gameState.Rounds = new List<RoundState>();
 }
Ejemplo n.º 10
0
		public static async Task Export(Deck deck)
		{
			if(deck == null) return;

			var hsHandle = User32.GetHearthstoneWindow();

			if(!User32.IsHearthstoneInForeground())
			{
				//restore window and bring to foreground
				User32.ShowWindow(hsHandle, User32.SwRestore);
				User32.SetForegroundWindow(hsHandle);
				//wait it to actually be in foreground, else the rect might be wrong
				await Task.Delay(500);
			}
			if(!User32.IsHearthstoneInForeground())
			{
				MessageBox.Show("Can't find Heartstone window.");
				return;
			}

			var hsRect = User32.GetHearthstoneRect(false);
			var ratio = (4.0 / 3.0) / ((double)hsRect.Width / hsRect.Height);

			string oldClipboardContent = null;
			try
			{
				oldClipboardContent = Clipboard.GetText();
			}
			catch
			{
			}

			var searchBoxPos = new Point((int)(GetXPos(Config.Instance.ExportSearchBoxX, hsRect.Width, ratio)), (int)(Config.Instance.ExportSearchBoxY * hsRect.Height));
			var cardPosX = GetXPos(Config.Instance.ExportCard1X, hsRect.Width, ratio);
			var card2PosX = GetXPos(Config.Instance.ExportCard2X, hsRect.Width, ratio);
			var cardPosY = Config.Instance.ExportCardsY * hsRect.Height;

			if(Config.Instance.ExportSetDeckName)
				await SetDeckName(deck.Name, ratio, hsRect.Width, hsRect.Height, hsHandle);

			await ClickAllCrystal(ratio, hsRect.Width, hsRect.Height, hsHandle);

			foreach(var card in deck.Cards)
				await AddCardToDeck(card, searchBoxPos, cardPosX, card2PosX, cardPosY, hsRect.Height, hsHandle);


			// Clear search field now all cards have been entered

			await ClickOnPoint(hsHandle, searchBoxPos);
			SendKeys.SendWait("{DELETE}");
			SendKeys.SendWait("{ENTER}");
			try
			{
				if(oldClipboardContent != null)
					Clipboard.SetText(oldClipboardContent);
			}
			catch
			{
			}
		}
Ejemplo n.º 11
0
        public WrapTest()
        {
            ClearColor = Color.White;

            foreach (CardLoader.CardDeck deck in CardLoader.Decks)
                deck.Include = true;

            CardLoader.LoadCards();

            blackDeck = new Deck(CardType.Black);

            card = null;

            Input.Key.Add(Keyboard.Key.Return,  args =>
            {
                if (!args.Pressed)
                    return true;

                if (card != null)
                    Entities.Remove(card);

                card = blackDeck.Cards.Count == 0 ? null : new Card(blackDeck.Cards.Pop());
                if (card != null)
                {
                    card.Position = new Vector2f(GameOptions.Width / 2.0f - 256.0f, GameOptions.Height / 2.0f - 256.0f);
                    Entities.Add(card);
                }

                return true;
            });
        }
Ejemplo n.º 12
0
        public override void Attack(Deck currentPlayerDeck, Deck currentEnemyDeck, Card skillOwnerCard)
        {
            Logger.Log($"{currentPlayerDeck?.GetDeckName()} Card {skillOwnerCard?.Name} : {this.SkillType} attack ({this.Power})");

            if (this.CanAttack())
            {
                var enemyTargetCards = currentEnemyDeck?.PlayedCards.Select(c => c).Where(c => c.CardType == this.GetTargetCardType()).ToList();

                // Attack first target skillOwnerCard, if there are no target cards, skip
                if (enemyTargetCards?.Count > 0)
                {
                    // Get enemy target card
                    var enemyTargetCard = enemyTargetCards.First();

                    // Attack
                    var originalCardHealth = enemyTargetCard.Health;
                    enemyTargetCard.Health -= this.Power;

                    Logger.Log(
                        $"{currentEnemyDeck?.GetDeckName()} card '{enemyTargetCard.Name}' health: {enemyTargetCard.Health} ({originalCardHealth}-{this.Power})");

                    currentEnemyDeck.EvaluateCard(enemyTargetCard);

                    this.ResetCounter();
                }

            }
            else
            {
                this.RaiseCounter();
            }
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            Deck deck1 = new Deck();
            Deck deck2 = new Deck();

            int step = 0;
            bool flag = false;
            while (!flag)
            {
                deck2.Shuffle();
                for (int j = 0; j < 52; j++)
                {
                    if (deck1[j].ShortName == deck2[j].ShortName) flag = true;
                }
                step++;
            }

            for (int j = 0; j < 52; j++)
            {
                Console.WriteLine(String.Format("{0} \t{2}\t {1}", deck1[j].ShortName, deck2[j].ShortName, (deck1[j].ShortName == deck2[j].ShortName)?"-----":"     "));
            }
            Console.WriteLine(step);

            Console.ReadLine();
        }
Ejemplo n.º 14
0
    public static void Main(string[] args)
    {
        int simCount = 5000;
        if (args.Length == 1)
            simCount = int.Parse(args[0]);

        Deck d = new Deck();
        PokerHand hand = new PokerHand(d);

        Stats stats = new Stats();
        stats.simCount = simCount;
        for (int i=0;i<simCount;i++)
        {
            // worry counter
            if ((i%1000)==0)
                Console.Write("*");
            d.shuffle();
            hand.pullCards();
            hand.Sort();
            POKERSCORE ps = PokerLogic.score(hand);
            stats.Append(ps);
        }
        Console.WriteLine();
        stats.Report();
    }
Ejemplo n.º 15
0
 public DeckImage(Deck deck)
 {
     DeckId = deck.Id;
     Deck = deck;
     Created = DateTime.Now;
     Modified = DateTime.Now;
 }
Ejemplo n.º 16
0
    /**
     * Functions to configure the deck generation
     */
    /**
     * Compile the deck
     */
    public Deck generateDeck()
    {
        Deck result = new Deck ();

        /**
         * Generate the deck here
         * TODO:
         * X - Random implementation first.
         *   - Sorted implementation based on weights.
         *   - ???
         *   - PROFIT!
         */

        /**
         * Doing it randomly is kinky.
         * We keep picking cards until the amount of cards in the drawPile
         * is that of the numberOfCards in preferences.
         *
         * In the future, this code will need to be refactored elsewhere
         * depending on the user's preferences in sorting.
         */
        /*
         * This function does several things: first, it computes the sum of all the binder weights.
         * Second, it randomly selects a binder based on its weight.
         * Third, it randomly selects a card in the randomly selected binder.
         * FINALLY, it adds the randomly chosen card into the deck for play.
         * Some time later down the road, this function may need to be refactored, but for now, it appears to be working.
         *
         * TODO: The random weighting system seems to be off. The last deck is ignored.
         *       Please fix regarding that.
         */

        int sum = 0;

        /*
         * Apply the
         */
        for (int i = 0; i < loadedBinders.Count; i++)
            sum += loadedBinders[i].weight;

        if (sum < 0)
            Debug.Log ("Cannot have a weight below 0! You suck. Nothing happens.");
        else {
            while (result.cardsLeft() < deckPreferences.numberOfCards) {
                int randomCard = Random.Range (0, sum+1);
                int i = 0;
                while (randomCard > loadedBinders[i].weight) {
                    randomCard -= loadedBinders [i].weight;
                    i++;
                }
                Card newCard = loadedBinders [i].getCard (-1);

                if (!(result.cardMatch (newCard)))
                    result.addCard (newCard);

            }
            result.shuffleDeck ();
        }
        return result;
    }
Ejemplo n.º 17
0
 public void getShowAndDealCard(Deck a_deck, bool shouldShow, Player player)
 {
     Card c;
     c = a_deck.GetCard();
     c.Show(shouldShow);
     player.DealCard(c);
 }
Ejemplo n.º 18
0
        public void GetCardsForBattle()
        {
            var result = false;
            try
            {
                var dec = new Deck(GenerateCards());
                var cards = dec.GetRandomizedCardsToBattle();

                if (cards.Any(x => x.CardType == CardTypeEnum.General))
                {
                    var soldiers = cards.Where(x => x.CardType == CardTypeEnum.Soldier).Select(x => x.IdCard);
                    var soldiersCount = soldiers.Count();
                    var soldiersRepeated = soldiers.Distinct().Count();

                    if (soldiersRepeated == soldiersCount)
                        result = true;
                }
            }
            catch (InvalidOperationException)
            {
                result = false;
            }

            Assert.IsTrue(result);
        }
		public static async Task Export(Deck deck)
		{
			if(deck == null) return;

			var hsHandle = User32.FindWindow("UnityWndClass", "Hearthstone");

			if(!User32.IsForegroundWindow("Hearthstone"))
			{
				//restore window and bring to foreground
				User32.ShowWindow(hsHandle, User32.SwRestore);
				User32.SetForegroundWindow(hsHandle);
				//wait it to actually be in foreground, else the rect might be wrong
				await Task.Delay(500);
			}
			if(!User32.IsForegroundWindow("Hearthstone"))
			{
				MessageBox.Show("Can't find Heartstone window.");
				return;
			}

			var hsRect = User32.GetHearthstoneRect(false);
			var bounds = Screen.FromHandle(hsHandle).Bounds;
			var ratio = (4.0 / 3.0) / ((double)hsRect.Width / hsRect.Height);

			if(Config.Instance.ExportSetDeckName)
				await SetDeckName(deck.Name, ratio, hsRect.Width, hsRect.Height, hsHandle);

			await ClickAllCrystal(ratio, hsRect.Width, hsRect.Height, hsHandle);

			foreach(var card in deck.Cards)
				await AddCardToDeck(card, ratio, hsRect.Width, hsRect.Height, hsHandle);
		}
Ejemplo n.º 20
0
 public void DealCards(Deck deck)
 {
     rwl.AcquireWriterLock(10000);
     string filename = AppDomain.CurrentDomain.BaseDirectory.ToString() + @"/Table1.xml";
     XmlDocument xmlDoc = new XmlDocument();
     xmlDoc.Load(filename);
     XmlNodeList players = xmlDoc.SelectNodes("/Table/Players/Player");
     for(int i = 0; i < 2; i++)
     {
         int count = 0;
         foreach (XmlNode player in players)
         {
             count++;
             XmlElement card = xmlDoc.CreateElement("Card");
             card.SetAttribute("CardRank", deck[0].Rank);
             card.SetAttribute("CardSuit", deck[0].Suit);
             card.SetAttribute("CardValue", deck[0].CardValue.ToString());
             player.FirstChild.FirstChild.FirstChild.AppendChild(card);
             deck.RemoveAt(0);
         }
         XmlElement dealerCard = xmlDoc.CreateElement("Card");
         dealerCard.SetAttribute("CardRank", deck[0].Rank);
         dealerCard.SetAttribute("CardSuit", deck[0].Suit);
         dealerCard.SetAttribute("CardValue", deck[0].CardValue.ToString());
         XmlNode dealerCards = xmlDoc.SelectSingleNode("Table/Dealer/DealerCards");
         dealerCards.AppendChild(dealerCard);
         deck.RemoveAt(0);
     }
     xmlDoc.Save(filename);
     rwl.ReleaseWriterLock();
 }
Ejemplo n.º 21
0
	public AceExorcistGame()
	{
        //Create Deck and Hand for Exorcist, and draw 5 cards from Deck to Hand
        ExorcistLibrary = new Deck(IsExorcist);
        ExorcistHand = new Hand();
        for (int i = 1; i < 6; i++)
        {
            ExorcistHand.addCard( ExorcistLibrary.TakeCard() );
        }

        //Create Deck and Hand for Exorcist, and draw 5 cards from Deck to Hand
        IsExorcist = false;
        SummonerLibrary = new Deck(IsExorcist);
        for (int i = 1; i < 6; i++)
        {
            SummonerHand.addCard(SummonerLibrary.TakeCard());
        }


        //Create Summon Zone
        SummonZone = new Hand();

        //Create Discards (as a Hand - but not in this implementation)

	}
Ejemplo n.º 22
0
		private void LoadActiveDeck()
		{
			var deck = Decks.FirstOrDefault(d => d.DeckId == Config.Instance.ActiveDeckId);
			if(deck != null && deck.Archived)
				deck = null;
			_activeDeck = deck;
		}
Ejemplo n.º 23
0
    void Awake()
    {
        Deck deck1 = new Deck();
        deck1.Shuffle();
        Card card1 = deck1.TakeCard();
        Card[] hand1 = new Card[5];
        hand1Size = hand1.Length;  // atribui o numero de cartas na mao

        for (i = 0; i < hand1.Length; i++)
        {
            hand1[i] = deck1.TakeCard();
        }

        //hand1[] = deck1.TakeCards(3);

        //IEnumerable < Card > = deck1.TakeCards();
        //Card mao1[] = deck1.TakeCards();

        //Debug.Log( card1.Suit.ToString() + card1.CardNumber.ToString() );
        for (i = 0; i < hand1.Length; i++)
        {
            Debug.Log(hand1[i].Suit.ToString() + hand1[i].CardNumber.ToString());
        }

        Debug.Log("tamanho da mao: " + hand1Size);
    }
Ejemplo n.º 24
0
 public void Deck_TrumpCardChange_ShouldChangeTrump()
 {
     var deck = new Deck();
     var card = new Card(CardSuit.Club, CardType.Ace);
     deck.ChangeTrumpCard(card);
     Assert.AreEqual(card, deck.TrumpCard);
 }
Ejemplo n.º 25
0
 public void Play(Deck gameDeck)
 {
     if (!this.HasBlackJack() && !this.IsBusted() && Hand.GetTotal() < 17)
     {
         gameDeck.Draw(this);
     }
 }
		private async void BtnIdString_Click(object sender, RoutedEventArgs e)
		{
			var settings = new MetroDialogSettings();
			var clipboard = Clipboard.GetText();
			if(clipboard.Count(c => c == ':') > 0 && clipboard.Count(c => c == ';') > 0)
				settings.DefaultText = clipboard;

			//import dialog
			var idString = await this.ShowInputAsync("Import deck", "id:count;id2:count2;... (e.g. EX1_050:2;EX1_556:1;)\nObtained from: \nEXPORT > COPY IDS TO CLIPBOARD", settings);
			if(string.IsNullOrEmpty(idString))
				return;
			var deck = new Deck();
			foreach(var entry in idString.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries))
			{
				var splitEntry = entry.Split(':');
				if(splitEntry.Length != 2)
					continue;
				var card = Game.GetCardFromId(splitEntry[0]);
				if(card.Id == "UNKNOWN")
					continue;
				int count;
				int.TryParse(splitEntry[1], out count);
				card.Count = count;

				if(string.IsNullOrEmpty(deck.Class) && card.GetPlayerClass != "Neutral")
					deck.Class = card.GetPlayerClass;

				deck.Cards.Add(card);
			}
			SetNewDeck(deck);
		}
		private void ListViewDecks_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			var item = ListViewDecks.SelectedItem as DeckPickerItem;
			if(item != null)
				SelectedDeck = item.Deck;
			Close();
		}
Ejemplo n.º 28
0
        private static void Main()
        {
            if (!StartGame()) return;

            string playerName = GetPlayerName();
            Deckpile shoe = new Deckpile();

            for (int i = 0; i < 4; i++)
            {
                Deck deck = new Deck();
                deck.AddToStack(shoe);
                shoe.Shuffle();
            }

            BlackjackDealer dealer = new ConsoleDealer("DEALER", shoe, Console.Instance);
            PlayerBase player = new ConsolePlayer(playerName, Console.Instance, new Bank(1000));

            dealer.Hand.HandChanged += (sender, changedArgs) => Console.Instance.Print(changedArgs.Player.ToString());
            player.Hand.HandChanged += (sender, changedArgs) => Console.Instance.Print(changedArgs.Player.ToString());

            dealer.AddPlayer(player);

            do
            {
                dealer.NewGame();
            } while (PlayAgain());
        }
        public bool NewGame(Deck a_deck, Dealer a_dealer, Player a_player)
        {
            a_dealer.NewCard(a_player, true);

            a_dealer.NewCard(a_dealer, true);

            a_dealer.NewCard(a_player, true);

            a_dealer.NewCard(a_dealer, false);

            //Card c;

            //c = a_deck.GetCard();
            //c.Show(true);
            //a_player.DealCard(c);

            //c = a_deck.GetCard();
            //c.Show(true);
            //a_dealer.DealCard(c);

            //c = a_deck.GetCard();
            //c.Show(true);
            //a_player.DealCard(c);

            return true;
        }
Ejemplo n.º 30
0
 public override void Bet(Deck deck, Board board, Pot pot, ArrayList players)
 {
     ArrayList peekedHands = pokerAI.PeekHands(players);
     currentHandStrength = HandStrengthEvaluator.EvaluateHandStrength(
             hand, board.GetCards(), peekedHands, deck);
     pokerAI.Bet(currentHandStrength, pot);
 }
Ejemplo n.º 31
0
        public override string Generate(Deck deck)
        {
            List <DeckCard> creatureList  = new List <DeckCard>();
            List <DeckCard> spellList     = new List <DeckCard>();
            List <DeckCard> landList      = new List <DeckCard>();
            List <DeckCard> sideboardList = new List <DeckCard>();

            foreach (DeckCard card in deck.CardList)
            {
                if (card.Sideboard)
                {
                    sideboardList.Add(card);
                }
                else
                {
                    switch (card.Card.MainType)
                    {
                    case "Creature":
                        creatureList.Add(card);
                        break;

                    case "Land":
                        landList.Add(card);
                        break;

                    default:
                        spellList.Add(card);
                        break;
                    }
                }
            }

            // generate header
            StringBuilder header = new StringBuilder();

            header.AppendLine("// Deck file for Magic Workstation (http://www.magicworkstation.com)");

            if (!deck.Name.IsNullOrTrimmedEmpty() ||
                !deck.Author.IsNullOrTrimmedEmpty())
            {
                header.Append("// NAME: ");
            }

            if (!deck.Name.IsNullOrTrimmedEmpty())
            {
                header.Append(deck.Name);
            }
            else
            {
                header.Append(Path.GetFileNameWithoutExtension(deck.Filename));
            }

            if (!deck.ArcheType.IsNullOrTrimmedEmpty())
            {
                header.Append(" (");
                header.Append(deck.ArcheType);
                header.Append(") ");
            }

            if (!deck.Author.IsNullOrTrimmedEmpty())
            {
                header.Append(" by ");
                header.Append(deck.Author);
            }

            if (!deck.Name.IsNullOrTrimmedEmpty() ||
                !deck.ArcheType.IsNullOrTrimmedEmpty() ||
                !deck.Author.IsNullOrTrimmedEmpty())
            {
                header.AppendLine();
            }

            header.AppendLine("// Exported by Lhurgoyf Deck Library");

            if (!deck.Comment.IsNullOrTrimmedEmpty())
            {
                header.Append("// COMMENT: ");
                header.AppendLine(deck.Comment);
            }

            // generate sideboard
            StringBuilder maindeck = new StringBuilder();

            if (creatureList.Count > 0)
            {
                maindeck.AppendLine("// Creatures");

                foreach (DeckCard card in creatureList.OrderBy(item => item.Card.ConvertedCastingCost))
                {
                    maindeck.Append("    ");
                    maindeck.Append(card.Amount.ToString());
                    maindeck.Append(" [");
                    maindeck.Append(card.Card.FirstEditionFromList.Shortname);
                    maindeck.Append("] ");
                    maindeck.Append(card.Card.Name);
                    maindeck.AppendLine();
                }

                maindeck.AppendLine();
            }

            if (spellList.Count > 0)
            {
                maindeck.AppendLine("// Spells");

                foreach (DeckCard card in spellList.OrderBy(item => item.Card.ConvertedCastingCost))
                {
                    maindeck.Append("    ");
                    maindeck.Append(card.Amount.ToString());
                    maindeck.Append(" [");
                    maindeck.Append(card.Card.FirstEditionFromList.Shortname);
                    maindeck.Append("] ");
                    maindeck.Append(card.Card.Name);
                    maindeck.AppendLine();
                }

                maindeck.AppendLine();
            }

            if (landList.Count > 0)
            {
                maindeck.AppendLine("// Lands");

                foreach (DeckCard card in landList.OrderBy(item => item.Card.ConvertedCastingCost))
                {
                    maindeck.Append("    ");
                    maindeck.Append(card.Amount.ToString());
                    maindeck.Append(" [");
                    maindeck.Append(card.Card.FirstEditionFromList.Shortname);
                    maindeck.Append("] ");
                    maindeck.Append(card.Card.Name);
                    maindeck.AppendLine();
                }

                //maindeck.AppendLine();
            }

            // generate sideboard
            StringBuilder sideboard = new StringBuilder();

            if (sideboardList.Count > 0)
            {
                sideboard.AppendLine("// Sideboard");

                foreach (DeckCard card in sideboardList.OrderBy(item => item.Card.ConvertedCastingCost))
                {
                    sideboard.Append("SB: ");
                    sideboard.Append(card.Amount.ToString());
                    sideboard.Append(" [");
                    sideboard.Append(card.Card.FirstEditionFromList.Shortname);
                    sideboard.Append("] ");
                    sideboard.Append(card.Card.Name);
                    sideboard.AppendLine();
                }
            }

            // generate full file content
            StringBuilder full = new StringBuilder();

            full.Append(header.ToString());
            full.AppendLine();
            full.Append(maindeck.ToString());
            full.AppendLine();
            full.Append(sideboard.ToString());

            return(full.ToString());
        }
Ejemplo n.º 32
0
 public Deck SaveCollectionBackup(Deck collection)
 {
     return(save(collection, "collection"));
 }
Ejemplo n.º 33
0
 public Deck SaveDeck(Deck deck)
 {
     return(save(deck, "deck"));
 }
Ejemplo n.º 34
0
 // Use this for initialization
 void Start()
 {
     deck  = GameObject.FindObjectOfType <Deck>();
     cards = new List <Card>();
 }
Ejemplo n.º 35
0
 private void OnDeckChanged(Deck deck, DataChangeCode changeCode)
 {
     RenderAllDeck();
 }
Ejemplo n.º 36
0
 public void SetUpTest()
 {
     deck = new Deck();
 }
Ejemplo n.º 37
0
 public void PublishDeck(Deck deck)
 {
     onPublishDeck?.Invoke(deck);
 }
Ejemplo n.º 38
0
        public static async Task <Deck> Import(string url)
        {
            try
            {
                var doc = await ImportingHelper.GetHtmlDoc(url);

                var deck  = new Deck();
                var dname = HttpUtility.HtmlDecode(doc.DocumentNode.SelectSingleNode(
                                                       "//h1[contains(@class, 'panel-title')]").InnerText);
                deck.Name = Regex.Replace(dname, @"\s+", " ");                 // remove sequence of tabs

                var cards = doc.DocumentNode.SelectNodes("//div[contains(@class, 'cardname')]/span");

                var deckExtra = doc.DocumentNode.SelectSingleNode("//div[contains(@class, 'deck_banner_description')]");
                var deckInfo  = deckExtra.SelectNodes("//span[contains(@class, 'midlarge')]/span");

                // get class and tags
                if (deckInfo.Count == 3)
                {
                    deck.Class = HttpUtility.HtmlDecode(deckInfo[1].InnerText).Trim();

                    var decktype = HttpUtility.HtmlDecode(deckInfo[2].InnerText).Trim();
                    if (!string.IsNullOrWhiteSpace(decktype) &&
                        decktype != "None" && Config.Instance.TagDecksOnImport)
                    {
                        if (!DeckList.Instance.AllTags.Contains(decktype))
                        {
                            DeckList.Instance.AllTags.Add(decktype);
                            DeckList.Save();
                            if (Core.MainWindow != null)                            // to avoid errors when running tests
                            {
                                Core.MainWindow.ReloadTags();
                            }
                        }
                        deck.Tags.Add(decktype);
                    }
                }

                // TODO uncomment for standard/wild tags

                /*
                 * var deckFormat = deckExtra.SelectSingleNode("//span[contains(@class, 'small')]").InnerText.Trim();
                 * if(!string.IsNullOrWhiteSpace(deckFormat) && Config.Instance.TagDecksOnImport)
                 * {
                 *      var format = "Standard";
                 *      if(Regex.IsMatch(deckFormat, @"Format:\s*Wild"))
                 *              format = "Wild";
                 *      if(!DeckList.Instance.AllTags.Contains(format))
                 *      {
                 *              DeckList.Instance.AllTags.Add(format);
                 *              DeckList.Save();
                 *              if(Core.MainWindow != null) // to avoid errors when running tests
                 *                      Core.MainWindow.ReloadTags();
                 *      }
                 *      deck.Tags.Add(format);
                 * }
                 */

                foreach (var cardNode in cards)
                {
                    var nameString = HttpUtility.HtmlDecode(cardNode.InnerText);
                    var match      = Regex.Match(nameString, @"^\s*(\d+)\s+(.*)\s*$");

                    if (match.Success)
                    {
                        var count = match.Groups[1].Value;
                        var name  = match.Groups[2].Value;

                        var card = Database.GetCardFromName(name);
                        card.Count = count.Equals("2") ? 2 : 1;
                        deck.Cards.Add(card);
                        if (string.IsNullOrEmpty(deck.Class) && card.PlayerClass != "Neutral")
                        {
                            deck.Class = card.PlayerClass;
                        }
                    }
                }

                return(deck);
            }
            catch (Exception e)
            {
                Log.Error(e);
                return(null);
            }
        }
Ejemplo n.º 39
0
 public void AddTopCardFromDeckToHand()
 {
     Hand.AddLast(Deck.First());
 }
Ejemplo n.º 40
0
        public override Deck Load(string filename)
        {
            if (File.Exists(filename))
            {
                StreamReader reader = new StreamReader(filename);

                List <string> list = new List <string>();

                while (!reader.EndOfStream)
                {
                    list.Add(reader.ReadLine());
                }

                reader.Close();
                reader.Dispose();

                Deck deck = new Deck();
                deck.Filename = filename;
                deck.Name     = Path.GetFileNameWithoutExtension(filename);

                bool isSideboard = false;

                foreach (string line in list)
                {
                    string correctLine = line;

                    // kill spaces and tabs inside of the string
                    correctLine = correctLine.Replace("\t", " ").Trim();

                    // name
                    if (correctLine.Contains("//") &&
                        correctLine.ToLower().Contains("name"))
                    {
                        string nameLine = correctLine.Substring(correctLine.IndexOf("NAME") + 4)
                                          .Replace(":", "")
                                          .Trim();

                        if (correctLine.Contains(" by "))
                        {
                            string[] splitted = nameLine.Split(new string[] { " by " }, StringSplitOptions.RemoveEmptyEntries);

                            deck.Name = splitted[0].Trim();

                            if (splitted.Length > 1)
                            {
                                deck.Author = splitted[1].Trim();
                            }
                        }
                        else
                        {
                            deck.Name = nameLine;
                        }
                    }

                    // comment
                    if (correctLine.Contains("//") &&
                        correctLine.ToLower().Contains("comment"))
                    {
                        string nameLine = correctLine.Substring(correctLine.IndexOf("COMMENT") + 7)
                                          .Replace(":", "")
                                          .Trim();

                        deck.Comment = nameLine;
                    }

                    // sb?
                    if (correctLine.Contains("//") &&
                        correctLine.ToLower().Contains("sideboard"))
                    {
                        isSideboard = true;
                    }

                    // add
                    if (!correctLine.IsNullOrTrimmedEmpty() &&
                        !correctLine.StartsWith("//"))
                    {
                        string amount = "";
                        string name   = "";

                        if (correctLine.StartsWith("SB: "))
                        {
                            correctLine = correctLine.Replace("SB: ", "");
                            isSideboard = true;
                        }

                        if (correctLine[0].ToString().IsNumeric())
                        {
                            amount = correctLine.Substring(0, correctLine.IndexOf(" ")).Trim();
                            name   = correctLine.Substring(correctLine.IndexOf(" ")).Trim();
                        }
                        else
                        {
                            amount = "1";
                            name   = correctLine.Trim();
                        }

                        string editionShortName = "";

                        if (name.Contains("[") &&
                            name.Contains("]"))
                        {
                            editionShortName = name.Substring(0, name.IndexOf("] ") + 1)
                                               .Replace("[", "")
                                               .Replace("]", "")
                                               .Trim();

                            name = name.Substring(name.IndexOf("] ") + 1).Trim();
                        }

                        if (name.Contains("(") &&
                            name.Contains(")"))
                        {
                            name = name.Substring(0, name.IndexOf("("))
                                   .Trim();
                        }

                        DeckCard dc = new DeckCard();
                        dc.Amount           = amount.ToInt32();
                        dc.EditionShortName = editionShortName;

                        // the card object will be laoded by setting the name (part of the property)
                        dc.Name = name;

                        dc.Sideboard = isSideboard;

                        deck.CardList.Add(dc);
                    }
                }

                return(deck);
            }

            return(null);
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Метод заполнения бд значениями.
        /// </summary>
        /// <param name="context">контекст бд.</param>
        public static void Initialize(ModelContext context)
        {
            context.Database.EnsureCreated();
            if (context.Decks.Any())
            {
                return;
            }

            var users = new User[]
            {
                new User {
                    Name = "Alex"
                }, new User {
                    Name = "Dima"
                }, new User {
                    Name = "Andrey"
                }, new User {
                    Name = "Ilia"
                }
            };

            foreach (User user in users)
            {
                context.Users.Add(user);
            }

            context.SaveChanges();

            var rooms = new Room[]
            {
                new Room {
                    Name = "Room1", OwnerID = 1
                }, new Room {
                    Name = "Room2", OwnerID = 2
                }, new Room {
                    Name = "Room3", OwnerID = 3
                }, new Room {
                    Name = "Room4", OwnerID = 4
                }
            };

            foreach (Room room in rooms)
            {
                context.Rooms.Add(room);
            }

            context.SaveChanges();
            var cards = new Card[]
            {
                new Card {
                    Value = 0, Description = "zero"
                }, new Card {
                    Value = 1, Description = "one"
                }, new Card {
                    Value = 2, Description = "two"
                }, new Card {
                    Value = 4, Description = "four"
                }
            };
            var deck = new Deck {
                Name = "1st deck", Description = "this is 1st deck"
            };

            foreach (Card card in cards)
            {
                context.Cards.Add(card);
                deck.Cards.Add(card);
            }

            context.SaveChanges();
            context.Decks.Add(deck);
            context.SaveChanges();
        }
Ejemplo n.º 42
0
 public void RemoveTopCardFromDeck()
 {
     Deck.RemoveFirst();
 }
Ejemplo n.º 43
0
        public void Deck_ShouldReturnAnObjectWhichIsNotNull()
        {
            var newDeckObject = new Deck();

            Assert.NotNull(newDeckObject);
        }
Ejemplo n.º 44
0
 public Detonate(Deck parentDeck) : base(parentDeck)
 {
     this.cardName     = "Detonate";
     this.castTime     = 1.2f;
     this.resourceCost = 3f;
 }
Ejemplo n.º 45
0
 private void UpdatePanelVersionComboBox(Deck deck)
 {
     ComboBoxDeckVersion.ItemsSource  = deck?.VersionsIncludingSelf;
     ComboBoxDeckVersion.SelectedItem = deck?.SelectedVersion;
     PanelVersionComboBox.Visibility  = deck != null && deck.HasVersions ? Visible : Collapsed;
 }
Ejemplo n.º 46
0
        public void TestPlayRound()
        {
            var deck = new Deck();

            deck.Clear();
            var cardsToAdd = new List <Card>()
            {
                // Cards the game will deal to Owen
                new Card(Values.Jack, Suits.Spades),
                new Card(Values.Jack, Suits.Hearts),
                new Card(Values.Six, Suits.Spades),
                new Card(Values.Jack, Suits.Diamonds),
                new Card(Values.Six, Suits.Hearts),

                // Cards the game will deal to Brittney
                new Card(Values.Six, Suits.Diamonds),
                new Card(Values.Six, Suits.Clubs),
                new Card(Values.Seven, Suits.Spades),
                new Card(Values.Jack, Suits.Clubs),
                new Card(Values.Nine, Suits.Spades),

                // Two more cards in the deck for Owen to draw when he runs out
                new Card(Values.Queen, Suits.Hearts),
                new Card(Values.King, Suits.Spades),
            };

            foreach (var card in cardsToAdd)
            {
                deck.Add(card);
            }

            var gameState = new GameState("Owen", new List <string>()
            {
                "Brittney"
            }, deck);

            var owen     = gameState.HumanPlayer;
            var brittney = gameState.Opponents.First();

            Assert.AreEqual("Owen", owen.Name);
            Assert.AreEqual(5, owen.Hand.Count());
            Assert.AreEqual("Brittney", brittney.Name);
            Assert.AreEqual(5, brittney.Hand.Count());

            var message = gameState.PlayRound(owen, brittney, Values.Jack, deck);

            Assert.AreEqual("Owen asked Brittney for Jacks" + Environment.NewLine +
                            "Brittney has 1 Jack card", message);
            Assert.AreEqual(1, owen.Books.Count());
            Assert.AreEqual(2, owen.Hand.Count());
            Assert.AreEqual(0, brittney.Books.Count());
            Assert.AreEqual(4, brittney.Hand.Count());

            message = gameState.PlayRound(brittney, owen, Values.Six, deck);
            Assert.AreEqual("Brittney asked Owen for Sixes" + Environment.NewLine +
                            "Owen has 2 Six cards", message);
            Assert.AreEqual(1, owen.Books.Count());
            Assert.AreEqual(2, owen.Hand.Count());
            Assert.AreEqual(1, brittney.Books.Count());
            Assert.AreEqual(2, brittney.Hand.Count());

            message = gameState.PlayRound(owen, brittney, Values.Queen, deck);
            Assert.AreEqual("Owen asked Brittney for Queens" + Environment.NewLine +
                            "Owen drew a card", message);
            Assert.AreEqual(1, owen.Books.Count());
            Assert.AreEqual(2, owen.Hand.Count());
        }
Ejemplo n.º 47
0
    public GameObject cardPrefab;   //instantiateするプレファブ

    private void Start()
    {
        deck = GetComponent <Deck>();   //Deck.csの取得
        ShowCards();                    //下記メソッドの実行
    }
Ejemplo n.º 48
0
 public abstract string Generate(Deck deck);
Ejemplo n.º 49
0
 int IComparable <FluxxCardInformation> .CompareTo(FluxxCardInformation other)
 {
     return(Deck.CompareTo(other.Deck)); //maybe cardcategory does not matter after all.
 }
Ejemplo n.º 50
0
        public void SelectDeck(Deck deck, bool setActive)
        {
            if (DeckList.Instance.ActiveDeck != null)
            {
                DeckPickerList.ClearFromCache(DeckList.Instance.ActiveDeck);
            }
            if (deck != null)
            {
                //set up tags
                TagControlEdit.SetSelectedTags(DeckPickerList.SelectedDecks);
                DeckPickerList.MenuItemQuickSetTag.ItemsSource = TagControlEdit.Tags;
                DeckPickerList.MenuItemQuickSetTag.Items.Refresh();

                OnPropertyChanged(nameof(HsReplayButtonVisibility));

                //set and save last used deck for class
                if (setActive)
                {
                    while (DeckList.Instance.LastDeckClass.Any(ldc => ldc.Class == deck.Class))
                    {
                        var lastSelected = DeckList.Instance.LastDeckClass.FirstOrDefault(ldc => ldc.Class == deck.Class);
                        if (lastSelected != null)
                        {
                            DeckList.Instance.LastDeckClass.Remove(lastSelected);
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (Core.Initialized)
                    {
                        DeckList.Instance.LastDeckClass.Add(new DeckInfo {
                            Class = deck.Class, Name = deck.Name, Id = deck.DeckId
                        });
                        DeckList.Save();
                    }

                    Log.Info($"Switched to deck: {deck.Name} ({deck.SelectedVersion.ShortVersionString})");
                    Core.TrayIcon.MenuItemUseNoDeck.Checked = false;
                }

                if (FlyoutDeckScreenshot.IsOpen)
                {
                    DeckScreenshotFlyout.Deck = deck.GetSelectedDeckVersion();
                }
                if (FlyoutDeckExport.IsOpen)
                {
                    DeckExportFlyout.Deck = deck.GetSelectedDeckVersion();
                }

                if (FlyoutDeckHistory.IsOpen)
                {
                    if (deck.HasVersions)
                    {
                        DeckHistoryFlyout.Deck = deck;
                    }
                    else
                    {
                        FlyoutDeckHistory.IsOpen = false;
                    }
                }
            }
            else
            {
                Core.Game.IsUsingPremade = false;

                if (DeckList.Instance.ActiveDeck != null)
                {
                    DeckList.Instance.ActiveDeck.IsSelectedInGui = false;
                }

                DeckList.Instance.ActiveDeck = null;
                if (setActive)
                {
                    DeckPickerList.DeselectDeck();
                }

                Core.TrayIcon.MenuItemUseNoDeck.Checked = true;
            }

            if (setActive)
            {
                UseDeck(deck);
            }
            DeckPickerList.SelectDeck(deck);
            UpdateDeckList(deck);
            ManaCurveMyDecks.SetDeck(deck);
            UpdatePanelVersionComboBox(deck);
            GroupBoxHsReplayDeckInfo.Visibility = deck?.IsArenaDeck == true ? Collapsed : Visible;
            if (setActive)
            {
                Core.Overlay.ListViewPlayer.Items.Refresh();
                Core.Windows.PlayerWindow.ListViewPlayer.Items.Refresh();
            }
            DeckManagerEvents.OnDeckSelected.Execute(deck);
        }
Ejemplo n.º 51
0
        private static void GenerateDeckZip(Guid deckGuid, bool generateMissingCards, bool singleDoc, Deck deck)
        {
            using (FileStream zipToOpen = new FileStream(Repository.GetDeckZipFile(deckGuid), FileMode.Create))
            {
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
                {
                    var licfiles = Directory.GetFiles(Repository.LicPath);
                    foreach (var licfile in licfiles)
                    {
                        var licName = Path.GetFileName(licfile);
                        archive.CreateEntryFromFile(licfile, licName);
                    }

                    foreach (var deckCard in deck.DeckCards)
                    {
                        var cardPdf = Repository.GetPdfFile(deckCard.Card.Guid);
                        if (!File.Exists(cardPdf))
                        {
                            if (generateMissingCards)
                            {
                                CardGenerator.CreatePngJob(deckCard.Card.Guid, deckCard.Card.Faction.Name,
                                                           deckCard.Card.Type.Name);
                            }
                            else
                            {
                                continue;
                            }
                        }

                        if (!singleDoc)
                        {
                            var entryName = SanitizeName(deckCard.Card.Name);

                            for (var i = 0; i < deckCard.Quantity; i++)
                            {
                                archive.CreateEntryFromFile(cardPdf, $"{entryName}_{i + 1}.pdf");
                            }
                        }
                    }

                    var cardBackPdfFile = Repository.GetBackPdfFile();
                    if (!File.Exists(cardBackPdfFile))
                    {
                        if (generateMissingCards)
                        {
                            CardGenerator.CreateBackPdfJob();
                        }
                    }

                    if (!singleDoc)
                    {
                        if (File.Exists(cardBackPdfFile))
                        {
                            archive.CreateEntryFromFile(cardBackPdfFile, $"back.pdf");
                        }
                    }

                    var deckFormatFile = Repository.GetDeckFormatFile(deckGuid);
                    if (File.Exists(deckFormatFile))
                    {
                        archive.CreateEntryFromFile(deckFormatFile, $"deck.txt");
                    }

                    if (singleDoc)
                    {
                        var deckpdf = Repository.GetDeckFile(deck.Guid);
                        using (FileStream stream = new FileStream(deckpdf, FileMode.Create))
                        {
                            using (PdfDocument pdf = new PdfDocument(new PdfWriter(stream)))
                            {
                                var documentInfo = pdf.GetDocumentInfo();
                                documentInfo.SetAuthor($"{deck.Creator.Name}");
                                documentInfo.SetCreator($"{deck.Creator.Name} - arcmage.org");
                                documentInfo.SetTitle($"{deck.Name} - arcmage.org");


                                foreach (var deckCard in deck.DeckCards)
                                {
                                    var cardPdf = Repository.GetPdfFile(deckCard.Card.Guid);
                                    using (var cardDocument = new PdfDocument(new PdfReader(cardPdf)))
                                    {
                                        for (var i = 0; i < deckCard.Quantity; i++)
                                        {
                                            cardDocument.CopyPagesTo(1, 1, pdf);
                                        }
                                    }
                                }

                                using (var backDocument = new PdfDocument(new PdfReader(cardBackPdfFile)))
                                {
                                    backDocument.CopyPagesTo(1, 1, pdf);
                                }
                            }

                            archive.CreateEntryFromFile(deckpdf, $"deck.pdf");
                        }
                    }
                }
            }
        }
Ejemplo n.º 52
0
 public void setCurrentDeck(Deck curDeck)
 {
     currentDeck = curDeck;
 }
Ejemplo n.º 53
0
        public static IDeck Load(this IDeck deck, Game game, string path, bool cloneCards = true)
        {
            var ret = new Deck();

            ret.Sections = new List <ISection>();
            try
            {
                var cards = game.Sets().SelectMany(x => x.Cards).ToArray();
                using (var fs = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                {
                    var doc    = XDocument.Load(fs);
                    var gameId = Guid.Parse(doc.Descendants("deck").First().Attribute("game").Value);
                    var shared = doc.Descendants("deck").First().Attr <bool>("shared");
                    foreach (var sectionelem in doc.Descendants("section"))
                    {
                        var section = new Section();
                        section.Cards  = new List <IMultiCard>();
                        section.Name   = sectionelem.Attribute("name").Value;
                        section.Shared = sectionelem.Attr <bool>("shared");
                        // On old style decks, if it's shared, then all subsequent sections are shared
                        if (shared)
                        {
                            section.Shared = true;
                        }
                        foreach (var cardelem in sectionelem.Descendants("card"))
                        {
                            var cardId = Guid.Parse(cardelem.Attribute("id").Value);
                            var cardq  = Int32.Parse(cardelem.Attribute("qty").Value);
                            var card   = cards.FirstOrDefault(x => x.Id == cardId);
                            if (card == null)
                            {
                                var cardN = cardelem.Value;
                                card = cards.FirstOrDefault(x => x.Name.Equals(cardN, StringComparison.CurrentCultureIgnoreCase));
                                if (card == null)
                                {
                                    throw new UserMessageException(
                                              "Problem loading deck {0}. The card with id: {1} and name: {2} is not installed.", path, cardId, cardN);
                                }
                            }
                            (section.Cards as IList <IMultiCard>).Add(card.ToMultiCard(cardq, cloneCards));
                        }
                        if (section.Cards.Any())
                        {
                            (ret.Sections as List <ISection>).Add(section);
                        }
                    }
                    // Add deck notes
                    var notesElem = doc.Descendants("notes").FirstOrDefault();
                    if (notesElem != null)
                    {
                        var cd = (notesElem.FirstNode as XCData);
                        if (cd != null)
                        {
                            ret.Notes = cd.Value.Clone() as string;
                        }
                    }
                    if (ret.Notes == null)
                    {
                        ret.Notes = "";
                    }

                    // Add all missing sections so that the game doesn't get pissed off
                    {
                        var combinedList =
                            game.DeckSections.Select(x => x.Value).Concat(game.SharedDeckSections.Select(y => y.Value));
                        foreach (var section in combinedList)
                        {
                            if (ret.Sections.Any(x => x.Name.Equals(section.Name, StringComparison.InvariantCultureIgnoreCase) && x.Shared == section.Shared) == false)
                            {
                                // Section not defined in the deck, so add an empty version of it.
                                (ret.Sections as List <ISection>).Add(
                                    new Section
                                {
                                    Name   = section.Name.Clone() as string,
                                    Cards  = new List <IMultiCard>(),
                                    Shared = section.Shared
                                });
                            }
                        }
                    }
                    ret.GameId   = gameId;
                    ret.IsShared = shared;
                }
                // This is an old style shared deck file, we need to convert it now, for posterity sake.
                if (ret.IsShared)
                {
                    ret.IsShared = false;
                    ret.Save(game, path);
                }
                deck = ret;
                return(deck);
            }
            catch (UserMessageException)
            {
                throw;
            }
            catch (FormatException e)
            {
                Log.Error(String.Format("Problem loading deck from path {0}", path), e);
                throw new UserMessageException("The deck {0} is corrupt.", path);
            }
            catch (NullReferenceException e)
            {
                Log.Error(String.Format("Problem loading deck from path {0}", path), e);
                throw new UserMessageException("The deck {0} is corrupt.", path);
            }
            catch (XmlException e)
            {
                Log.Error(String.Format("Problem loading deck from path {0}", path), e);
                throw new UserMessageException("The deck {0} is corrupt.", path);
            }
            catch (FileNotFoundException)
            {
                throw new UserMessageException("Could not save deck to {0}, could not file the file.", path);
            }
            catch (IOException e)
            {
                Log.Error(String.Format("Problem loading deck from path {0}", path), e);
                throw new UserMessageException("Could not load deck from {0}, {1}", path, e.Message);
            }
            catch (Exception e)
            {
                Log.Error(String.Format("Problem loading deck from path {0}", path), e);
                throw new UserMessageException("Could not load deck from {0}, there was an unspecified problem.", path);
            }
            return(ret);
        }
Ejemplo n.º 54
0
        private static void GenerateDeckTiles(Guid deckGuid, bool generateMissingCards, bool singleDoc, Deck deck)
        {
            var tilesWidth  = 723;
            var tilesHeight = 1024;

            var numberOfCards   = deck.DeckCards.Sum(x => x.Quantity);
            var numberOfColumns = 6;
            var number0fRows    = 5;

            var totalTilesWidth      = tilesWidth * numberOfColumns;
            var totalTilesHeight     = tilesHeight * number0fRows;
            var numberOfCardsPerTile = numberOfColumns * number0fRows - 1; // Last cards is back
            var numberOfTiles        = (int)Math.Ceiling((double)numberOfCards / numberOfCardsPerTile);

            var totalCards = 0;
            var cardIndex  = 0;
            var tileIndex  = 1;

            using (MagickImage backSide = new MagickImage(Repository.GetBackPngFile()))
            {
                backSide.SetProfile(ColorProfile.SRGB);
                backSide.SetProfile(ColorProfile.USWebCoatedSWOP);
                backSide.Scale(tilesWidth, tilesHeight);

                var backSideX = (numberOfColumns - 1) * tilesWidth;
                var backSideY = (number0fRows - 1) * tilesHeight;

                var tileImage = new MagickImage(MagickColors.Black, totalTilesWidth, totalTilesHeight);
                tileImage.SetProfile(ColorProfile.SRGB);
                tileImage.SetProfile(ColorProfile.USWebCoatedSWOP);
                tileImage.Composite(backSide, backSideX, backSideY);

                foreach (var deckCard in deck.DeckCards)
                {
                    using (MagickImage card = new MagickImage(Repository.GetPngFile(deckCard.Card.Guid)))
                    {
                        card.SetProfile(ColorProfile.SRGB);
                        card.SetProfile(ColorProfile.USWebCoatedSWOP);
                        card.Scale(tilesWidth, tilesHeight);

                        for (int i = 0; i < deckCard.Quantity; i++)
                        {
                            var row    = cardIndex / numberOfColumns;
                            var column = cardIndex % numberOfColumns;

                            var x = column * tilesWidth;
                            var y = row * tilesHeight;

                            tileImage.Composite(card, x, y);

                            cardIndex++;
                            totalCards++;

                            if (cardIndex >= numberOfCardsPerTile || totalCards >= numberOfCards)
                            {
                                var tileFile = Repository.GetDeckTilesFile(deckGuid, tileIndex);
                                if (File.Exists(tileFile))
                                {
                                    File.Delete(tileFile);
                                }

                                // Save the result
                                tileImage.Write(tileFile);
                                tileImage.Dispose();
                            }

                            if (cardIndex >= numberOfCardsPerTile && totalCards < numberOfCards)
                            {
                                cardIndex = 0;
                                tileIndex++;

                                tileImage = new MagickImage(MagickColors.Black, totalTilesWidth, totalTilesHeight);
                                tileImage.SetProfile(ColorProfile.SRGB);
                                tileImage.SetProfile(ColorProfile.USWebCoatedSWOP);
                                tileImage.Composite(backSide, backSideX, backSideY);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 55
0
        public void FlushNullHand()
        {
            Cards hand = null;

            Assert.IsFalse(Deck.IsFlush(hand));
        }
Ejemplo n.º 56
0
        /// <summary>
        /// Fonction crée et qui affiche les labels contenant les informations d'un deck, soit les exemplaires et leurs quantités
        /// </summary>
        /// <param name="deck"></param>
        /// <param name="posOnglet"></param>
        private void CreerLabels(Deck deck, int posOnglet)
        {
            int compteurRow = 1;
            List <Exemplaire> lstExemplairesDeck = MySqlCarteService.RetrieveExemplairesDeckUser(deck.Nom, Main.UtilisateurConnecte.IdUtilisateur);

            LstNomExemplaire = new List <Label>();
            LstQteExemplaire = new List <Label>();
            LstBtnPlus       = new List <Button>();
            LstBtnMoins      = new List <Button>();
            LstBtnEnlever    = new List <Button>();

            // Pour chaque exemplaire dans les decks, on instancie la grille avec leur nom et leur quantité, ainsi qu'avec des boutons pour incrémenter de 1, soustraire de 1 et enlever complètement l'exemplaire
            foreach (Exemplaire e in lstExemplairesDeck)
            {
                RowDefinition rwdRangee = new RowDefinition();
                rwdRangee.Height = GridLength.Auto;

                Label lblCarte = new Label();
                lblCarte.Content             = e.Carte.Nom;
                lblCarte.FontWeight          = FontWeights.Bold;
                lblCarte.FontSize            = 15;
                lblCarte.HorizontalAlignment = HorizontalAlignment.Center;

                Label   lblQuantite = new Label();
                Binding myBinding   = new Binding("Quantite");
                myBinding.Source = e;
                lblQuantite.SetBinding(Label.ContentProperty, myBinding);
                lblQuantite.FontWeight          = FontWeights.Bold;
                lblQuantite.FontSize            = 15;
                lblQuantite.HorizontalAlignment = HorizontalAlignment.Center;

                #region Boutons
                Button btnPlus = new Button();
                btnPlus.ToolTip             = "Ajouter un exemplaire de cette carte au deck.";
                btnPlus.Click              += new RoutedEventHandler(btnPlus_Click);
                btnPlus.Width               = 30;
                btnPlus.Height              = 30;
                btnPlus.Content             = "+";
                btnPlus.FontSize            = 18;
                btnPlus.FontWeight          = FontWeights.Bold;
                btnPlus.HorizontalAlignment = HorizontalAlignment.Left;

                Button btnMoins = new Button();
                btnMoins.ToolTip             = "Enlever un exemplaire de cette carte au deck.";
                btnMoins.Click              += new RoutedEventHandler(btnMoins_Click);
                btnMoins.Width               = 30;
                btnMoins.Height              = 30;
                btnMoins.Content             = "-";
                btnMoins.FontSize            = 18;
                btnMoins.FontWeight          = FontWeights.Bold;
                btnMoins.HorizontalAlignment = HorizontalAlignment.Center;

                Button btnEnlever = new Button();
                btnEnlever.ToolTip             = "Enlever tous les exemplaires de cette carte.";
                btnEnlever.Click              += new RoutedEventHandler(btnEnlever_Click);
                btnEnlever.Width               = 30;
                btnEnlever.Height              = 30;
                btnEnlever.Content             = "x";
                btnEnlever.FontSize            = 18;
                btnEnlever.FontWeight          = FontWeights.Bold;
                btnEnlever.Foreground          = Brushes.Red;
                btnEnlever.HorizontalAlignment = HorizontalAlignment.Right;
                #endregion


                switch (posOnglet)
                {
                case 0:
                    grdDeck1.RowDefinitions.Add(rwdRangee);
                    grdDeck1.Children.Add(lblCarte);
                    grdDeck1.Children.Add(lblQuantite);
                    grdDeck1.Children.Add(btnPlus);
                    grdDeck1.Children.Add(btnMoins);
                    grdDeck1.Children.Add(btnEnlever);
                    break;

                case 1:
                    grdDeck2.RowDefinitions.Add(rwdRangee);
                    grdDeck2.Children.Add(lblCarte);
                    grdDeck2.Children.Add(lblQuantite);
                    grdDeck2.Children.Add(btnPlus);
                    grdDeck2.Children.Add(btnMoins);
                    grdDeck2.Children.Add(btnEnlever);
                    break;

                case 2:
                    grdDeck3.RowDefinitions.Add(rwdRangee);
                    grdDeck3.Children.Add(lblCarte);
                    grdDeck3.Children.Add(lblQuantite);
                    grdDeck3.Children.Add(btnPlus);
                    grdDeck3.Children.Add(btnMoins);
                    grdDeck3.Children.Add(btnEnlever);
                    break;
                }

                // Placer label Nom Carte
                Grid.SetRow(lblCarte, compteurRow);
                Grid.SetColumn(lblCarte, 0);
                // Placer label Quantité
                Grid.SetRow(lblQuantite, compteurRow);
                Grid.SetColumn(lblQuantite, 1);
                // Placer Bouton +
                Grid.SetRow(btnPlus, compteurRow);
                Grid.SetColumn(btnPlus, 2);
                // Placer Bouton -
                Grid.SetRow(btnMoins, compteurRow);
                Grid.SetColumn(btnMoins, 2);
                // Placer Bouton x
                Grid.SetRow(btnEnlever, compteurRow);
                Grid.SetColumn(btnEnlever, 2);

                compteurRow++;

                LstNomExemplaire.Add(lblCarte);
                LstQteExemplaire.Add(lblQuantite);
                LstBtnPlus.Add(btnPlus);
                LstBtnMoins.Add(btnMoins);
                LstBtnEnlever.Add(btnEnlever);
            }
        }
Ejemplo n.º 57
0
 public BotPokerClient(Deck deck, IEventBroker events, string botName) : base(deck, events)
 {
     this.botName = botName;
 }
Ejemplo n.º 58
0
        public void CountRemainingCardsTest()
        {
            var testDeck = new Deck();

            Assert.AreEqual(testDeck.CountRemainingCards(), 52);
        }
Ejemplo n.º 59
0
 public PlayerData(Deck deck, Team team, byte id)
 {
     Deck = deck;
     Team = team;
     Id   = id;
 }
Ejemplo n.º 60
0
        public void FlushEmptyHand()
        {
            var hand = new Cards();

            Assert.IsFalse(Deck.IsFlush(hand));
        }