public async Task PopulateGrid(string savedState)
 {
     char[]   sep    = new char[] { '|' };
     string[] tokens = savedState.Split(sep, StringSplitOptions.RemoveEmptyEntries);
     if (tokens.Count() < 8)
     {
         throw new InvalidDataException();
     }
     _player      = (PlayerType)Enum.Parse(typeof(PlayerType), tokens[0]);
     _scoreType   = (ScoreType)Enum.Parse(typeof(ScoreType), tokens[1]);
     _score       = new ScoreInstance(tokens[2]);
     _index       = Convert.ToInt32(tokens[3]);
     _total       = Convert.ToInt32(tokens[4]);
     _actualScore = Convert.ToInt32(tokens[5]);
     _gameScore   = tokens[6];
     _cards       = StaticHelpers.DeserializeToList(tokens[7], MainPage.Current.Deck);
     await PopulateGrid();
 }
예제 #2
0
        private async void OnNewGame(object sender, RoutedEventArgs e)
        {
            MyMenu.IsPaneOpen = false;
            await Task.Delay(500);

            try
            {
                if (_game != null)
                {
                    if (_game.State != GameState.None)
                    {
                        if (await StaticHelpers.AskUserYesNoQuestion("Cribbage", "Start a new game?", "Yes", "No") ==
                            false)
                        {
                            return;
                        }
                    }

                    _game = null; // what happens if we are in an await???
                }

                await Reset();

                _txtInstructions.Text = "";
                var player   = new InteractivePlayer(_cgDiscarded, _cgCrib, 0);
                var computer = new DefaultPlayer(0);
                computer.Init("-usedroptable");
                _game = new Game(this, computer, player, 0);
                ((Button)sender).IsEnabled = true;
                await StartGame(GameState.Start);
            }
            catch
            {
                // eat this - user won't be able to do anythign anyway
            }
            finally
            {
                ((Button)sender).IsEnabled = true;
            }
        }
예제 #3
0
        private async void OnGetSuggestion(object sender, RoutedEventArgs e)
        {
            if (_game == null)
            {
                await StaticHelpers.ShowErrorText("Hit + to start a game.", "Cribbage");

                return;
            }

            if (_game.State == GameState.PlayerSelectsCribCards)
            {
                if (_cgPlayer.Cards.Count != 6)
                {
                    return;
                }

                foreach (var c in _cgPlayer.Cards)
                {
                    c.Selected = false;
                }

                _cgPlayer.SelectedCards?.Clear();
                _cgPlayer.SelectedCards = _game.ComputerSelectCrib(_cgPlayer.Cards, _game.Dealer == PlayerType.Player);

                if (_cgPlayer.SelectedCards?.Count == 2)
                {
                    _cgPlayer.SelectedCards[0].Selected = true;
                    _cgPlayer.SelectedCards[1].Selected = true;
                }

                return;
            }

            if (_game.State == GameState.CountPlayer)
            {
                var cardPlayed = await _game.GetSuggestionForCount();

                _cgPlayer.SelectCard(cardPlayed);
            }
        }
        public string Save()
        {
            //
            //  Score Instance and Cards use "," as a seperator.  This is level 2, use "|"

            string s = String.Format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|",
                                     _player, _scoreType, _score.Save(), _index, _total, _actualScore, _gameScore, StaticHelpers.SerializeFromList(_cards));

            return(s);
        }
예제 #5
0
 static public Task RunStoryBoard(Storyboard sb, bool callStop = true, double ms = 500, bool setDuration = true)
 {
     return(StaticHelpers.RunStoryBoard(sb, callStop, ms, setDuration));
 }
 public async Task Hide()
 {
     Animation_X_RollIn.To     = 0;
     Animation_Angle_RollIn.To = 0;
     await StaticHelpers.RunStoryBoard(RollInScore, false);
 }
 public async Task Show()
 {
     Animation_X_RollIn.To     = this.ActualWidth;
     Animation_Angle_RollIn.To = 360;
     await StaticHelpers.RunStoryBoard(RollInScore, false);
 }
예제 #8
0
        private async void OnOpenGame(object sender, RoutedEventArgs e)
        {
            MyMenu.IsPaneOpen = false;

            if (_game != null)
            {
                if (_game.State != GameState.None)
                {
                    if (await StaticHelpers.AskUserYesNoQuestion("Cribbage", "End this game and open an old one?",
                                                                 "yes", "no") == false)
                    {
                        return;
                    }
                }
            }

            var openPicker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };

            openPicker.FileTypeFilter.Add(".crib");

            var file = await openPicker.PickSingleFileAsync();

            if (file == null)
            {
                return;
            }

            await Reset();

            _txtInstructions.Text = "";
            var player   = new InteractivePlayer(_cgDiscarded, _cgCrib, 0);
            var computer = new DefaultPlayer(0);

            computer.Init("-usedroptable");
            _game = new Game(this, computer, player, 0);


            try
            {
                var contents = await FileIO.ReadTextAsync(file);

                var settings = await StaticHelpers.LoadSettingsFile(contents, file.Name);

                if (settings["Game"]["Version"] != "1.0")
                {
                    await StaticHelpers.ShowErrorText($"Bad Version {settings["Game"]["Version"]}");

                    return;
                }

                _game.CurrentCount   = int.Parse(settings["Game"]["CurrentCount"]);
                _game.Player.Score   = int.Parse(settings["Game"]["PlayerBackScore"]);
                _game.AutoEnterScore = bool.Parse(settings["Game"]["AutoEnterScore"]);

                _board.AnimateScoreAsync(PlayerType.Player, _game.Player.Score);
                var scoreDelta = int.Parse(settings["Game"]["PlayerScoreDelta"]);
                _board.AnimateScoreAsync(PlayerType.Player, scoreDelta);
                _game.Player.Score += scoreDelta;

                _game.Computer.Score = int.Parse(settings["Game"]["ComputerBackScore"]);
                _board.AnimateScoreAsync(PlayerType.Computer, _game.Computer.Score);
                scoreDelta = int.Parse(settings["Game"]["ComputerScoreDelta"]);
                _board.AnimateScoreAsync(PlayerType.Computer, scoreDelta);
                _game.Computer.Score += scoreDelta;

                _game.Dealer = StaticHelpers.ParseEnum <PlayerType>(settings["Game"]["Dealer"]);
                _game.State  = StaticHelpers.ParseEnum <GameState>(settings["Game"]["State"]);
                SetState(_game.State);
                await MoveCrib(_game.Dealer);

                var retTuple = LoadCardsIntoGrid(_cgComputer, settings["Cards"]["Computer"]);
                if (!retTuple.ret)
                {
                    throw new Exception(retTuple.badToken);
                }

                retTuple = LoadCardsIntoGrid(_cgPlayer, settings["Cards"]["Player"]);
                if (!retTuple.ret)
                {
                    throw new Exception(retTuple.badToken);
                }

                retTuple = LoadCardsIntoGrid(_cgDiscarded, settings["Cards"]["Counted"]);
                if (!retTuple.ret)
                {
                    throw new Exception(retTuple.badToken);
                }

                var countedCards = new List <CardCtrl>();
                var count        = 0;
                foreach (var card in _cgDiscarded.Cards)
                {
                    count += card.Value;
                    if (count <= 31)
                    {
                        countedCards.Add(card);
                    }
                    else
                    {
                        foreach (var cc in countedCards)
                        {
                            cc.Counted = true;
                            cc.Opacity = 0.8;
                        }

                        countedCards.Clear();
                        count = 0;
                    }
                }

                retTuple = LoadCardsIntoGrid(_cgCrib, settings["Cards"]["Crib"]);
                if (!retTuple.ret)
                {
                    throw new Exception(retTuple.badToken);
                }

                retTuple = LoadCardsIntoGrid(_cgDeck, settings["Cards"]["SharedCard"]);
                if (!retTuple.ret)
                {
                    throw new Exception(retTuple.badToken);
                }

                var  taskList = new List <Task>();
                Task t        = null;

                if ((int)_game.State > (int)GameState.GiveToCrib)
                {
                    t = _cgDeck.Cards[0].SetOrientationTask(CardOrientation.FaceUp, 500, 0);
                    taskList.Add(t);
                }

                foreach (var card in _cgPlayer.Cards)
                {
                    t = card.SetOrientationTask(CardOrientation.FaceUp, 0, 0);
                    taskList.Add(t);
                }

                foreach (var card in _cgDiscarded.Cards)
                {
                    t = card.SetOrientationTask(CardOrientation.FaceUp, 0, 0);
                    taskList.Add(t);
                }

                if ((int)_game.State >= (int)GameState.ScoreComputerHand)
                {
                    foreach (var card in _cgComputer.Cards)
                    {
                        t = card.SetOrientationTask(CardOrientation.FaceUp, 0, 0);
                        taskList.Add(t);
                    }
                }

                await Task.WhenAll(taskList);

                await StartGame(_game.State);
            }
            catch (Exception ex)
            {
                await StaticHelpers.ShowErrorText(
                    $"Error loading file {file.Name}\n\nYou should delete the file.\n\nTechnical details:\n{ex}");
            }
        }
        public async Task <Dictionary <string, string> > Load(string s)
        {
            if (s == "")
            {
                return(null);
            }

            Dictionary <string, string> sections = StaticHelpers.GetSections(s);

            if (_game.Deserialize(sections, _view.Deck) == false)
            {
                return(null);
            }

            Dictionary <string, string> game = StaticHelpers.DeserializeDictionary(sections["State"]);

            if (sections == null)
            {
                return(null);
            }

            if (game["Version"] != SERIALIZATION_VERSION)
            {
                return(null);
            }

            _gameState               = (GameState)Enum.Parse(typeof(GameState), game["GameState"]);
            _dealer                  = (PlayerType)Enum.Parse(typeof(PlayerType), game["Dealer"]);
            _totalCardsDropped       = Convert.ToInt32(game["TotalCardsDropped"]);
            _nPlayerCountingPoint    = Convert.ToInt32(game["PlayerCountingPoints"]);
            _nPlayerPointsThisTurn   = Convert.ToInt32(game["PlayerPointsThisTurn"]);
            _nComputerCountingPoint  = Convert.ToInt32(game["ComputerCountingPoints"]);
            _nComputerPointsThisTurn = Convert.ToInt32(game["ComputerPointsThisTurn"]);
            _nCribPointsThisTurn     = Convert.ToInt32(game["CribPointsThisTurn"]);
            int playerScore   = Convert.ToInt32(game["PlayerScore"]);
            int computerScore = Convert.ToInt32(game["ComputerScore"]);


            _hfs      = _game.GetHfs();
            _view.Hfs = _hfs;

            Dictionary <string, string> grids = StaticHelpers.DeserializeDictionary(sections["Grids"]);

            List <CardView> PlayerCards   = StaticHelpers.DeserializeToList(grids["Player"], _view.Deck);
            List <CardView> ComputerCards = StaticHelpers.DeserializeToList(grids["Computer"], _view.Deck);
            List <CardView> cribCards     = StaticHelpers.DeserializeToList(grids["Crib"], _view.Deck);



            CardView        SharedCard  = StaticHelpers.CardFromString(grids["SharedCard"], _view.Deck);
            List <CardView> playedCards = StaticHelpers.DeserializeToList(grids["Played"], _view.Deck);

            List <Task <object> > taskList = new List <Task <object> >();

            _view.MoveCards(taskList, playedCards, _view.GridPlayedCards);
            _view.MoveCards(taskList, cribCards, _view.GridCrib);
            _view.MoveCards(taskList, PlayerCards, _view.GridPlayer);
            _view.MoveCards(taskList, ComputerCards, _view.GridComputer);

            if (_gameState == GameState.PlayerGiveToCrib)
            {
                _crib.AddRange(playedCards);
            }

            await Task.WhenAll(taskList);

            SharedCard.BoostZindex(ZIndexBoost.SmallBoost);

            _game.UpdateScoreDirect(PlayerType.Player, ScoreType.Saved, playerScore);     // give the points to the player
            _game.UpdateScoreDirect(PlayerType.Computer, ScoreType.Saved, computerScore); // give the points to the player

            await UiState.AddScore(PlayerType.Player, playerScore);

            await UiState.AddScore(PlayerType.Computer, computerScore);

            _view.CountControl.Count = _game.CurrentCount;

            await FixUpUiState();

            string scoreHistory = "";

            if (sections.TryGetValue("Score History", out scoreHistory))
            {
                await _view.Load(scoreHistory);
            }

            if (_gameState == GameState.PlayerScoreHand)
            {
                //
                //  if we saved in the state where the player is supposed to score the hard, we need to drive the state machine
                //  through the completion of the GameState.ScoreHand states
                if (_dealer == PlayerType.Player)
                {
                    await SetState(GameState.PlayerScoreHand);
                    await SetState(GameState.ShowCrib);
                    await SetState(GameState.PlayerScoreCrib);

                    _gameState = GameState.EndOfHand;
                }
                else
                {
                    _gameState = GameState.ScoreHands;
                }
            }
            else if (_gameState == GameState.PlayerScoreCrib)
            {
                await SetState(GameState.PlayerScoreCrib);

                _gameState = GameState.EndOfHand;
            }



            SetStateAsync(_gameState);


            return(sections);
        }
예제 #10
0
 public void Hide()
 {
     _daOpacity.To = 0.0;
     StaticHelpers.RunStoryBoardAsync(_sbOpacity, MainPage.AnimationSpeeds.Slow, true);
 }