private void JoinGame_Click(object sender, RoutedEventArgs e)
        {
            if (dgMatchesDataGrid.SelectedIndex < 0)
            {
                return;
            }
            int selectedId = ((MatchesBind)dgMatchesDataGrid.Items[dgMatchesDataGrid.SelectedIndex]).GetMatchId();

            Task.Run(() => {
                var token = _joinGameTokenSource.Token;
                try
                {
                    MatchResult = _connection.Call.JoinGame(new ChessCom.JoinGameRequest
                    {
                        Id     = selectedId,
                        Joiner = _userdata
                    }, null, null, _joinGameTokenSource.Token);
                    Dispatcher.Invoke(() => Close());
                }
                catch (Grpc.Core.RpcException ex)
                {
                    if (!token.IsCancellationRequested)
                    {
                        throw ex;
                    }
                }
            });
        }
        public void Runner()
        {
            ChessCom.LookForMatchResult result = _connection.Call.LookForMatch(new ChessCom.UserIdentity {
                UserToken = _userToken
            });
            if (result.Succes)
            {
                _isSingelplayer            = false;
                Instance._matchToken       = result.MatchToken;
                Instance._opponentUsername = result.OpponentUsername;
                Instance.Dispatcher.Invoke(() => {
                    _mediaPlayer.Stop();
                    _mediaPlayer.Open(MatchStartSoundUri);
                    _mediaPlayer.Play();
                    StartMatch(result.IsWhitePlayer, result.MatchToken, result.Rules, result.Timerules);
                });

                var matchStream = _connection.Call.Match();
                _matchStream = matchStream;
                //Open match stream call
                _matchStream.RequestStream.WriteAsync(new ChessCom.MovePacket {
                    AskingForDraw = false, DoingMove = false, MatchToken = _matchToken, UserToken = _userToken
                });
                bool matchEnded = false;
                while (!matchEnded)
                {
                    if (!matchStream.ResponseStream.MoveNext().Result)
                    {
                        matchEnded = true;
                    }
                    if (matchEnded)
                    {
                        continue;
                    }
                    ChessCom.MoveResult move = matchStream.ResponseStream.Current;

                    //if (move.)
                    //{

                    //}

                    if (move.MoveHappned)
                    {
                        if (move.Move.AvailableMoves.Count > 0) //Prossess board from server
                        {
                            Instance.Dispatcher.Invoke(() => {
                                if (move.Move.From != _myLastMove.From || move.Move.To != _myLastMove.To)
                                {
                                    WriteTextNonInvoke("Opponent did move other!");
                                }
                                //Pices killedPice = _globalState.DoMoveTo(move.Move.To);
                                _globalState.UpdateFromMove(move.Move);
                                if ((Pices)move.Move.CapturedPice != Pices.Non)
                                {
                                    _killedPices.Add((Pices)move.Move.CapturedPice);
                                }
                                _lastMoveFrom = _globalState.CanSeeField(_clientIsPlayer, move.Move.From) ? move.Move.From : "";
                                _lastMoveTo   = _globalState.CanSeeField(_clientIsPlayer, move.Move.To) ? move.Move.To : "";
                                ClearBoard();
                                UpdateBoardFromGlobalState();

                                _mediaPlayer.Stop();
                                _mediaPlayer.Open(MoveSoundUri);
                                _mediaPlayer.Play();
                            });
                        }
                        else //Prossess board self
                        {
                            if (move.Move.From != _myLastMove.From || move.Move.To != _myLastMove.To)
                            {
                                Instance.Dispatcher.Invoke(() => {
                                    WriteTextNonInvoke("Opponent did move!");
                                    //messageBox.AppendText("Opponent did move!\n");
                                    //messageBox.CaretPosition = messageBox.CaretPosition.DocumentEnd;
                                    //messageBox.BringIntoView();
                                    //messageBox.Focus();
                                    _globalState.Selected = move.Move.From;
                                    Pices killedPice      = _globalState.DoMoveTo(move.Move.To);
                                    if (killedPice != Pices.Non)
                                    {
                                        _killedPices.Add(killedPice);
                                    }
                                    _globalState.Selected = null;
                                    _lastMoveFrom         = _globalState.CanSeeField(_clientIsPlayer, move.Move.From) ? move.Move.From : "";
                                    _lastMoveTo           = _globalState.CanSeeField(_clientIsPlayer, move.Move.To) ? move.Move.To : "";
                                    ClearBoard();
                                    UpdateBoardFromGlobalState();

                                    _mediaPlayer.Stop();
                                    _mediaPlayer.Open(MoveSoundUri);
                                    _mediaPlayer.Play();
                                });
                            }
                        }

                        if (_globalState.WhiteTurn)
                        {
                            _timer?.Stop();
                            //WriteTextInvoke("Black time before: " + _blackStaticTimeLeft.ToString(@"mm\:ss") + $" secSpent {move.Move.SecSpent} secs left {move.SecsLeft}" );
                            _blackStaticTimeLeft = TimeSpan.FromSeconds(move.SecsLeft);
                            _blackTimeSpan       = _blackStaticTimeLeft;
                            //WriteTextInvoke("Black time after: " + _blackStaticTimeLeft.ToString(@"mm\:ss"));
                            Instance.Dispatcher.Invoke(() => { lbBlackTimeLeft.Content = _blackTimeSpan.ToString(@"mm\:ss"); });
                            _timer = new DispatcherTimer(new TimeSpan(0, 0, 1), DispatcherPriority.Normal, delegate
                            {
                                lbWhiteTimeLeft.Content = _whiteTimeSpan.ToString(@"mm\:ss");
                                if (_whiteTimeSpan == TimeSpan.Zero)
                                {
                                    _timer.Stop();
                                    InvokedRanoutOfTime();
                                }
                                else if (_whiteTimeSpan < TimeSpan.FromSeconds(10))
                                {
                                    _mediaPlayerTimeRunningOut.Stop();
                                    _mediaPlayerTimeRunningOut.Play();
                                }
                                _whiteTimeSpan = _whiteTimeSpan.Add(TimeSpan.FromSeconds(-1));
                            }, Application.Current.Dispatcher);

                            _timer.Start();
                        }
                        else
                        {
                            _timer?.Stop();
                            _whiteStaticTimeLeft = TimeSpan.FromSeconds(move.SecsLeft);
                            _whiteTimeSpan       = _whiteStaticTimeLeft;
                            Instance.Dispatcher.Invoke(() => { lbWhiteTimeLeft.Content = _whiteTimeSpan.ToString(@"mm\:ss"); });
                            _timer = new DispatcherTimer(new TimeSpan(0, 0, 1), DispatcherPriority.Normal, delegate
                            {
                                lbBlackTimeLeft.Content = _blackTimeSpan.ToString(@"mm\:ss");
                                if (_blackTimeSpan == TimeSpan.Zero)
                                {
                                    _timer.Stop();
                                    InvokedRanoutOfTime();
                                }
                                else if (_blackTimeSpan < TimeSpan.FromSeconds(10))
                                {
                                    _mediaPlayerTimeRunningOut.Stop();
                                    _mediaPlayerTimeRunningOut.Play();
                                }
                                _blackTimeSpan = _blackTimeSpan.Add(TimeSpan.FromSeconds(-1));
                            }, Application.Current.Dispatcher);

                            _timer.Start();
                        }
                    }
                    if (move.OpponentAskingForDraw)
                    {
                        Instance.Dispatcher.Invoke(() =>
                        {
                            string popupText        = "Draw?";
                            string textBoxText      = "Opponent is asking for draw. Do you accept?";
                            MessageBoxButton button = MessageBoxButton.YesNo;
                            MessageBoxImage icon    = MessageBoxImage.Error;
                            var drawResult          = MessageBox.Show(textBoxText, popupText, button, icon);
                            if (drawResult == MessageBoxResult.Yes)
                            {
                                _matchStream.RequestStream.WriteAsync(new ChessCom.MovePacket {
                                    AskingForDraw = true
                                });
                                matchEnded = true;
                            }
                        });
                    }
                    else if (move.MatchEvent == ChessCom.MatchEvent.UnexpectedClosing)
                    {
                        Instance.Dispatcher.Invoke(() =>
                        {
                            string popupText   = "UnexpextedClosing";
                            string textBoxText = "Opponents client unexpectedly closed";
                            WriteTextNonInvoke(textBoxText);
                            MessageBoxButton button = MessageBoxButton.OK;
                            MessageBoxImage icon    = MessageBoxImage.Exclamation;
                            MessageBox.Show(textBoxText, popupText, button, icon);
                            EndOfMatch(_clientIsPlayer == ClientIsPlayer.White?ChessCom.MatchEvent.WhiteWin: ChessCom.MatchEvent.BlackWin);
                            matchEnded = true;
                        });
                    }
                    else if (move.MatchEvent == ChessCom.MatchEvent.WhiteWin || move.MatchEvent == ChessCom.MatchEvent.BlackWin)
                    {
                        Instance.Dispatcher.Invoke(() =>
                        {
                            EndOfMatch(move.MatchEvent);
                            matchEnded = true;
                        });
                        _matchStream.RequestStream.WriteAsync(new ChessCom.MovePacket {
                            CheatMatchEvent = ChessCom.MatchEvent.ExpectedClosing, AskingForDraw = false, DoingMove = false, MatchToken = _matchToken, UserToken = _userToken
                        }).Wait();
                        _matchStream.RequestStream.CompleteAsync();
                    }
                }
                _matchStream = null;
            }
            else
            {
                string           popupText   = "Failed";
                string           textBoxText = "Failed to find match";
                MessageBoxButton button      = MessageBoxButton.OK;
                MessageBoxImage  icon        = MessageBoxImage.Error;
                MessageBox.Show(textBoxText, popupText, button, icon);
            }
        }
示例#3
0
        private void BtHostGame_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var starttime = Convert.ToInt32(tbStarttime.Text);
                var movetime  = Convert.ToInt32(tbMovetime.Text);
                ChessCom.ChessType chessType = cbChesType.SelectedIndex == 0 ? ChessCom.ChessType.Classic :
                                               cbChesType.SelectedIndex == 1 ? ChessCom.ChessType.FisherRandom :
                                               ChessCom.ChessType.SlugRandom;
                ChessCom.SideType sideType = cbHostColor.SelectedIndex == 0 ? ChessCom.SideType.HostIsWhite :
                                             cbHostColor.SelectedIndex == 1 ? ChessCom.SideType.HostIsBlack :
                                             ChessCom.SideType.Random;
                ChessCom.VisionRules vr = new ChessCom.VisionRules();
                switch (cbVisionRules.SelectedIndex)
                {
                case 0:     //Standard
                {
                    vr.Enabled          = true;
                    vr.ViewCaptureField = true;
                    vr.ViewMoveFields   = false;
                    vr.ViewRange        = 2;
                    ChessCom.VisionRules overwrite = new ChessCom.VisionRules
                    {
                        ViewRange      = 1,
                        ViewMoveFields = false
                    };
                    vr.PiceOverwriter.Add((int)ChessCom.Pices.WhitePawn, overwrite);
                    vr.PiceOverwriter.Add((int)ChessCom.Pices.BlackPawn, overwrite);
                }
                break;

                case 1:     //Sea
                {
                    vr.Enabled          = true;
                    vr.ViewCaptureField = true;
                    vr.ViewMoveFields   = true;
                    vr.ViewRange        = 0;
                    ChessCom.VisionRules overwrite = new ChessCom.VisionRules
                    {
                        ViewRange      = 1,
                        ViewMoveFields = true
                    };
                    vr.PiceOverwriter.Add((int)ChessCom.Pices.WhiteKnight, overwrite);
                    vr.PiceOverwriter.Add((int)ChessCom.Pices.BlackKnight, overwrite);
                    vr.PiceOverwriter.Add((int)ChessCom.Pices.WhitePawn, overwrite);
                    vr.PiceOverwriter.Add((int)ChessCom.Pices.BlackPawn, overwrite);
                }
                break;

                case 2:     //No Vision
                {
                    vr.Enabled = false;
                }
                break;
                }
                btHostGame.IsEnabled          = false;
                cbChesType.IsEnabled          = false;
                cbHostColor.IsEnabled         = false;
                cbVisionRules.IsEnabled       = false;
                tbStarttime.IsEnabled         = false;
                tbMovetime.IsEnabled          = false;
                tbHostingMatchText.Visibility = Visibility.Visible;

                Task.Run(() => {
                    var token = _hostGameTokenSource.Token;
                    try
                    {
                        MatchResult = _connection.Call.HostGame(new ChessCom.HostedGame
                        {
                            Host      = _userdata,
                            GameRules = new ChessCom.GameRules
                            {
                                ChessType   = chessType,
                                SideType    = sideType,
                                VisionRules = vr,
                                TimeRules   = new ChessCom.TimeRules {
                                    PlayerTime = new ChessCom.Time {
                                        Minutes = starttime
                                    }, SecondsPerMove = movetime
                                }
                            }
                        }, null, null, _hostGameTokenSource.Token);
                        Dispatcher.Invoke(() => Close());
                    }
                    catch (Grpc.Core.RpcException ex)
                    {
                        if (!token.IsCancellationRequested)
                        {
                            throw ex;
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }