コード例 #1
0
        private async Task ConnectToPeers(PeerInformation peer)
        {
            try
            {
                progressBar.Visibility = Visibility.Visible;

                UpdatePlayerStatus(peer, " - connecting...");
                StreamSocket s = await PeerFinder.ConnectAsync(peer);

                ConnectedPeer temp = new ConnectedPeer(peer.DisplayName);
                connectedPeers[temp] = new SocketReaderWriter(s, this);
                connectedPeers[temp].ReadMessage();

                UpdatePlayerStatus(peer, " - ready");
                ConnectedPlayers.Items.Add(peer.DisplayName);

                startGameButton.Visibility = Visibility.Visible;
            }
            catch (Exception)
            {
                sendInvitationsText.Text = "Cannot connect to " + peer.DisplayName;
            }

            // PeerFinder.ConnectAsync aborts PeerWatcher
            // restart PeerWatcher whether connect failed or succeeded
            StartPeerWatcher();
        }
コード例 #2
0
        // Used to display state of the connection (i.e. connecting, connected, disconnected) when two PCs are tapped.
        private async void TriggeredConnectionStateChanged(object sender, TriggeredConnectionStateChangedEventArgs e)
        {
            await messageDispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                bool tapIsProcessed = false;
                switch (e.State)
                {
                case TriggeredConnectState.PeerFound:
                    directions.Visibility    = Visibility.Collapsed;
                    nfcStatusText.Visibility = Visibility.Visible;
                    foundPeers.IsEnabled     = false;

                    progressBar.Visibility = Visibility.Visible;
                    backButton.Visibility  = Visibility.Collapsed;

                    break;

                case TriggeredConnectState.Completed:
                    // Associate socket handed back by TriggeredConnectionStateChanged event with player connectedPeers.
                    socket = new SocketReaderWriter(e.Socket, this);
                    socket.ReadMessage();
                    socket.WriteMessage(string.Format("{0} {1}", Constants.OpCodeSendDisplayName, PeerFinder.DisplayName));
                    startGameButton.Visibility = Visibility.Visible;
                    tapIsProcessed             = true;

                    break;

                case TriggeredConnectState.Failed:
                    tapIsProcessed = true;

                    break;
                }

                // Reset UI
                if (tapIsProcessed)
                {
                    nfcStatusText.Visibility = Visibility.Collapsed;
                    foundPeers.IsEnabled     = true;

                    lock (availablePeers)
                    {
                        if (availablePeers.Count > 0)
                        {
                            directions.Visibility = Visibility.Visible;
                        }
                    }

                    // Progress bar should be visible as long as PeerWatcher is running
                    progressBar.Visibility = Visibility.Collapsed;
                    if (peerWatcher != null)
                    {
                        PeerWatcherStatus status = peerWatcher.Status;
                        if (status == PeerWatcherStatus.EnumerationCompleted || status == PeerWatcherStatus.Started)
                        {
                            progressBar.Visibility = Visibility.Visible;
                        }
                    }
                }
            });
        }
コード例 #3
0
 public void SendParams(SocketReaderWriter socket, int id)
 {
     // Should only be called if the app is a host.
     // Otherwise it has no idea which socket is being used.
     if (PeerFinder.Role == PeerRole.Host)
     {
         // Write the op code, number of players, time limit.
         socket.WriteMessage(string.Format("{0} {1} {2} {3}", Constants.OpCodeParams, playerCount, timesToTick, id));
     }
 }
コード例 #4
0
ファイル: ScorePage.xaml.cs プロジェクト: ckc/WinApp
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        private void LoadState(Object navigationParameter, Dictionary <String, Object> pageState)
        {
            ScorePageParameters parameters = (ScorePageParameters)navigationParameter;

            gameScore = parameters.Score;
            gameMode  = parameters.GameMode;

            if (gameMode == Constants.SinglePlayer)
            {
                finalScoreDisplay.Text = "You scored " + parameters.Score.ToString();
                progressBar.Visibility = Visibility.Collapsed;
            }
            else
            {
                // Each player starts with an empty list of scores
                // Hosts populate their lists as they receive scores
                // Clients populate their lists when the host sends them scores
                playerScores = new Dictionary <string, string>();

                connectedPeers = parameters.ConnectedPeers;

                foreach (ConnectedPeer peer in connectedPeers.Keys)
                {
                    try
                    {
                        // Set each socket's current page to ScorePage.
                        connectedPeers[peer].currentPage = this;
                        connectedPeers[peer].UpdateCurrentPageType();

                        if (gameMode != Constants.SinglePlayer)
                        {
                            if (PeerFinder.Role == PeerRole.Client)
                            {
                                socket = connectedPeers[peer];
                            }
                            else if (PeerFinder.Role == PeerRole.Host)
                            {
                                numPlayers    = connectedPeers.Count + 1;
                                closedSockets = 0;
                                playerScores[PeerFinder.DisplayName] = gameScore.ToString();
                                connectedPeers[peer].WriteMessage(Message.Navigated);
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        infoText.Text += "\nError loading scores: \n" + err.ToString();
                    }
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        private async void LoadState(Object navigationParameter, Dictionary <String, Object> pageState)
        {
            // Users wait (i.e. watch progress) on this page until the connection has succeeded/failed.
            backButton.Visibility = Visibility.Collapsed;
            if (navigationParameter != null)
            {
                WaitingForHostParameters parameters = (WaitingForHostParameters)navigationParameter;
                if (parameters.Peer != null)
                {
                    pageTitle.Text = "Connecting to " + parameters.Peer.DisplayName.ToString() + "...";
                    try
                    {
                        StreamSocket socket = await PeerFinder.ConnectAsync(parameters.Peer);

                        pageTitle.Text = "Connected! Waiting for Host...";
                        this.socket    = new SocketReaderWriter(socket, this);
                        ConnectedPeer tempPeer = new ConnectedPeer(parameters.Peer.DisplayName);
                        connectedPeers[tempPeer] = this.socket;

                        PeerFinder.Stop();
                        StartReading();
                    }
                    catch (Exception)
                    {
                        pageTitle.Text = "Cannot connect to " + parameters.Peer.DisplayName;
                        PeerFinder.Stop();
                    }
                    progressBar.Visibility = Visibility.Collapsed;
                    backButton.Visibility  = Visibility.Visible;
                }
                else if (parameters.Socket != null)
                {
                    try
                    {
                        this.socket    = new SocketReaderWriter(parameters.Socket, this);
                        pageTitle.Text = "Waiting for Host...";
                        socket.WriteMessage(string.Format("{0} {1}", Constants.OpCodeSendDisplayName, PeerFinder.DisplayName));

                        PeerFinder.Stop();
                        StartReading();
                    }
                    catch (Exception)
                    {
                        pageTitle.Text = "Cannot connect";
                        PeerFinder.Stop();
                    }
                    backButton.Visibility  = Visibility.Visible;
                    progressBar.Visibility = Visibility.Collapsed;
                }
            }
        }
コード例 #6
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        private async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            // Users wait (i.e. watch progress) on this page until the connection has succeeded/failed.
            backButton.Visibility = Visibility.Collapsed;
            if (navigationParameter != null)
            {
                WaitingForHostParameters parameters = (WaitingForHostParameters)navigationParameter;
                if (parameters.Peer != null)
                {
                    pageTitle.Text = "Connecting to " + parameters.Peer.DisplayName.ToString() + "...";
                    try
                    {
                        StreamSocket socket = await PeerFinder.ConnectAsync(parameters.Peer);
                        pageTitle.Text = "Connected! Waiting for Host...";
                        this.socket = new SocketReaderWriter(socket, this);
                        ConnectedPeer tempPeer = new ConnectedPeer(parameters.Peer.DisplayName);
                        connectedPeers[tempPeer] = this.socket;

                        PeerFinder.Stop();
                        StartReading();
                    }
                    catch (Exception)
                    {
                        pageTitle.Text = "Cannot connect to " + parameters.Peer.DisplayName;
                        PeerFinder.Stop();
                    }
                    progressBar.Visibility = Visibility.Collapsed;
                    backButton.Visibility = Visibility.Visible;
                }
                else if (parameters.Socket != null)
                {
                    try
                    {
                        this.socket = new SocketReaderWriter(parameters.Socket, this);
                        pageTitle.Text = "Waiting for Host...";
                        socket.WriteMessage(string.Format("{0} {1}", Constants.OpCodeSendDisplayName, PeerFinder.DisplayName));

                        PeerFinder.Stop();
                        StartReading();
                    }
                    catch (Exception)
                    {
                        pageTitle.Text = "Cannot connect";
                        PeerFinder.Stop();
                    }
                    backButton.Visibility = Visibility.Visible;
                    progressBar.Visibility = Visibility.Collapsed;
                }
            }
        }
コード例 #7
0
        private void LoadState(object navigationParameter, Dictionary<string, object> pageState)
        {
            // Unpack the navigation parameters passed from either the Main Page (singleplayer mode)
            // or the Invite Players page (singlePair, multiplayer mode).

            GamePageParameters parameters = (GamePageParameters)navigationParameter;

            if (PeerFinder.Role == PeerRole.Host)
            {
                timesToTick = Constants.PlayTime * Constants.TimeUnitsPerSecond;
            }

            gameMode = parameters.GameMode;

            if (gameMode != Constants.SinglePlayer)
            {
                // Not for single player games.

                connectedPeers = parameters.ConnectedPeers;

                // You should only have one socket if you're a client
                // Regardless, update each socket's current page to the game page
                foreach (ConnectedPeer host in connectedPeers.Keys)
                {
                    socket = connectedPeers[host];
                    socket.currentPage = this;
                    socket.UpdateCurrentPageType();
                }

                playerCount = parameters.PlayerCount;
            }

            images = new Image[Constants.GridRows, Constants.GridColumns];
            random = new Random();

            gameTimer = new DispatcherTimer();
            gameTimer.Interval = TimeSpan.FromMilliseconds(Constants.TimeUnit);
            gameTimer.Tick += UpdateTimer;

            if (gameMode == Constants.SinglePlayer)
            {
                InitImages();

                timesToTick = Constants.PlayTime * Constants.TimeUnitsPerSecond;
                StartGame();
            }
            else if (gameMode == Constants.MultiPlayer)
            {
                // See what your role is.
                if (PeerFinder.Role == PeerRole.Host)
                {
                    playerList = new Dictionary<int, string>();
                    playerList[0] = PeerFinder.DisplayName;
                    playerID = 0;

                    int counter = 1;

                    foreach (ConnectedPeer peer in connectedPeers.Keys)
                    {
                        playerList[counter] = peer.DisplayName;
                        SendParams(connectedPeers[peer], counter);
                        counter++;
                    }

                    InitImages();
                }
            }
        }
コード例 #8
0
 public void SendParams(SocketReaderWriter socket, int id)
 {
     // Should only be called if the app is a host.
     // Otherwise it has no idea which socket is being used.
     if (PeerFinder.Role == PeerRole.Host)
     {
         // Write the op code, number of players, time limit.
         socket.WriteMessage(string.Format("{0} {1} {2} {3}", Constants.OpCodeParams, playerCount, timesToTick, id));
     }
 }
コード例 #9
0
        private async Task ConnectToPeers(PeerInformation peer)
        {            
            try
            {
                progressBar.Visibility = Visibility.Visible;

                UpdatePlayerStatus(peer, " - connecting...");                  
                StreamSocket s = await PeerFinder.ConnectAsync(peer);
                ConnectedPeer temp = new ConnectedPeer(peer.DisplayName);
                connectedPeers[temp] = new SocketReaderWriter(s, this);
                connectedPeers[temp].ReadMessage();

                UpdatePlayerStatus(peer, " - ready");
                ConnectedPlayers.Items.Add(peer.DisplayName);
                
                startGameButton.Visibility = Visibility.Visible;
            }
            catch (Exception)
            {
                sendInvitationsText.Text = "Cannot connect to " + peer.DisplayName;
            }
        
            // PeerFinder.ConnectAsync aborts PeerWatcher
            // restart PeerWatcher whether connect failed or succeeded
            StartPeerWatcher();
        }
コード例 #10
0
        // Used to display state of the connection (i.e. connecting, connected, disconnected) when two PCs are tapped.
        private async void TriggeredConnectionStateChanged(object sender, TriggeredConnectionStateChangedEventArgs e)
        {
            await messageDispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                bool tapIsProcessed = false;
                switch (e.State)
                {
                    case TriggeredConnectState.PeerFound:
                        directions.Visibility = Visibility.Collapsed;
                        nfcStatusText.Visibility = Visibility.Visible;
                        foundPeers.IsEnabled = false;

                        progressBar.Visibility = Visibility.Visible;
                        backButton.Visibility = Visibility.Collapsed;

                        break;
                    case TriggeredConnectState.Completed:
                        // Associate socket handed back by TriggeredConnectionStateChanged event with player connectedPeers.
                        socket = new SocketReaderWriter(e.Socket, this);
                        socket.ReadMessage();
                        socket.WriteMessage(string.Format("{0} {1}", Constants.OpCodeSendDisplayName, PeerFinder.DisplayName));
                        startGameButton.Visibility = Visibility.Visible;
                        tapIsProcessed = true;

                        break;
                    case TriggeredConnectState.Failed:
                        tapIsProcessed = true;
                        
                        break;
                }

                // Reset UI
                if (tapIsProcessed)
                {
                    nfcStatusText.Visibility = Visibility.Collapsed;
                    foundPeers.IsEnabled = true;

                    lock (availablePeers)
                    {
                        if (availablePeers.Count > 0)
                        {
                            directions.Visibility = Visibility.Visible;
                        }
                    }

                    // Progress bar should be visible as long as PeerWatcher is running
                    progressBar.Visibility = Visibility.Collapsed;
                    if (peerWatcher != null)
                    {
                        PeerWatcherStatus status = peerWatcher.Status;
                        if (status == PeerWatcherStatus.EnumerationCompleted || status == PeerWatcherStatus.Started)
                        {
                            progressBar.Visibility = Visibility.Visible;
                        }
                    }
                }
            });
        }
コード例 #11
0
        private void LoadState(object navigationParameter, Dictionary <string, object> pageState)
        {
            // Unpack the navigation parameters passed from either the Main Page (singleplayer mode)
            // or the Invite Players page (singlePair, multiplayer mode).

            GamePageParameters parameters = (GamePageParameters)navigationParameter;

            if (PeerFinder.Role == PeerRole.Host)
            {
                timesToTick = Constants.PlayTime * Constants.TimeUnitsPerSecond;
            }

            gameMode = parameters.GameMode;

            if (gameMode != Constants.SinglePlayer)
            {
                // Not for single player games.

                connectedPeers = parameters.ConnectedPeers;

                // You should only have one socket if you're a client
                // Regardless, update each socket's current page to the game page
                foreach (ConnectedPeer host in connectedPeers.Keys)
                {
                    socket             = connectedPeers[host];
                    socket.currentPage = this;
                    socket.UpdateCurrentPageType();
                }

                playerCount = parameters.PlayerCount;
            }

            images = new Image[Constants.GridRows, Constants.GridColumns];
            random = new Random();

            gameTimer          = new DispatcherTimer();
            gameTimer.Interval = TimeSpan.FromMilliseconds(Constants.TimeUnit);
            gameTimer.Tick    += UpdateTimer;

            if (gameMode == Constants.SinglePlayer)
            {
                InitImages();

                timesToTick = Constants.PlayTime * Constants.TimeUnitsPerSecond;
                StartGame();
            }
            else if (gameMode == Constants.MultiPlayer)
            {
                // See what your role is.
                if (PeerFinder.Role == PeerRole.Host)
                {
                    playerList    = new Dictionary <int, string>();
                    playerList[0] = PeerFinder.DisplayName;
                    playerID      = 0;

                    int counter = 1;

                    foreach (ConnectedPeer peer in connectedPeers.Keys)
                    {
                        playerList[counter] = peer.DisplayName;
                        SendParams(connectedPeers[peer], counter);
                        counter++;
                    }

                    InitImages();
                }
            }
        }
コード例 #12
0
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        private void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            ScorePageParameters parameters = (ScorePageParameters)navigationParameter;

            gameScore = parameters.Score;
            gameMode = parameters.GameMode;

            if (gameMode == Constants.SinglePlayer)
            {
                finalScoreDisplay.Text = "You scored " + parameters.Score.ToString();
                progressBar.Visibility = Visibility.Collapsed;
            }
            else
            {
                // Each player starts with an empty list of scores 
                // Hosts populate their lists as they receive scores
                // Clients populate their lists when the host sends them scores
                playerScores = new Dictionary<string, string>();

                connectedPeers = parameters.ConnectedPeers;

                foreach (ConnectedPeer peer in connectedPeers.Keys)
                {
                    try
                    {
                        // Set each socket's current page to ScorePage.
                        connectedPeers[peer].currentPage = this;
                        connectedPeers[peer].UpdateCurrentPageType();

                        if (gameMode != Constants.SinglePlayer)
                        {
                            if (PeerFinder.Role == PeerRole.Client)
                            {
                                socket = connectedPeers[peer];
                            }
                            else if (PeerFinder.Role == PeerRole.Host)
                            {
                                numPlayers = connectedPeers.Count + 1;
                                closedSockets = 0;
                                playerScores[PeerFinder.DisplayName] = gameScore.ToString();
                                connectedPeers[peer].WriteMessage(Message.Navigated);
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        infoText.Text += "\nError loading scores: \n" + err.ToString();
                    }
                }
            }
        }