public async void Multiplayer_Tapped(object sender, EventArgs e) { BGMusics.Clicking_Sound().Play(); BGMusics.Menu_BGM().Stop(); BGMusics.InGame_BGM().Play(); Flow.GetPlayerMode(true); SaveOrLoad.ALoadedGame(false); if (TapCounter > 1) { return; } LoadingBit.IsVisible = true; Fetch.IsRunning = true; string CacheEmail = Application.Current.Properties["UserEmail"].ToString(); string CachePassword = Application.Current.Properties["UserPassword"].ToString(); try { if (string.IsNullOrEmpty(CacheEmail) || string.IsNullOrEmpty(CachePassword)) { await DisplayAlert("No Account", "Please Log in", "OK"); LoadingBit.IsVisible = false; Fetch.IsRunning = false; return; } var link = await apiClient.LoginEmailPasswordAsync(CacheEmail, CachePassword); var userdata = await apiClient.GetUserAsync(link.User.LocalId); } catch (Exception ex) { LoadingBit.IsVisible = false; Fetch.IsRunning = false; await DisplayAlert("No Account", "Please Log in", "OK"); return; } if (string.IsNullOrEmpty(UserData.GetUserLabel())) { LoadingBit.IsVisible = false; Fetch.IsRunning = false; await DisplayAlert("No Account", "Please Log in", "OK"); return; } try { me.UserName = UserData.GetUserLabel()?.Trim(); me.UserId = Application.Current.Properties["UserId"].ToString(); lblMessages.Text = "Getting connection info..."; SignalRConnectionInfo connectionInfo = await SignalRService.GetSignalRConnectionInfo(); var url = connectionInfo.Url; lblMessages.Text = $"Connecting..."; connection = new HubConnectionBuilder() .WithUrl(url, options => { options.AccessTokenProvider = () => Task.FromResult(connectionInfo.AccessToken); }) .Build(); //connection.Closed += async (error) => //{ // //Optional code: only used for retrying to connect // //await Task.Delay(new Random().Next(0, 5) * 1000); // //await connection.StartAsync(); //}; #region Connection //Waiting for other player connection.On <GamePlayer>("waiting", (player) => { Device.BeginInvokeOnMainThread(() => { if (player.UserId == me.UserId) { Fetch.IsRunning = true; lblMessages.Text = "Waiting for players..."; } }); }); //2 player game successfully created (method name MUST be 'newgame' connection.On <GameInfo>("newgame", (info) => { Device.BeginInvokeOnMainThread(() => { gameInfo = info; var currentPlayer = info.Players.Find(x => x.UserId == me.UserId); if (currentPlayer.PlayerNumber == 1) { isPlayer1 = true; /// btnStartTimer.IsEnabled = true; } else { isPlayer1 = false; // btnStartTimer.IsEnabled = false; } MultiPlayerSettings.IsThisPlayer1(isPlayer1); //Fill label with game content // lblGameContent.Text = $"Room Id: {info.RoomId}{Environment.NewLine}Player 1: {info.Players[0].UserName}{Environment.NewLine}Player 2: {info.Players[1].UserName}{Environment.NewLine}Toks:{Environment.NewLine}"; lblMessages.Text = $"Room Id: {info.RoomId}{Environment.NewLine}Player 1: {info.Players[0].UserName}{Environment.NewLine}Player 2: {info.Players[1].UserName}{Environment.NewLine}Toks:{Environment.NewLine}"; if (MultiPlayerSettings.YupThisIsPlayer1()) { MultiPlayerSettings.OtherPlayersData(info.Players[1].UserName, info.Players[1].UserPhoto); } else { MultiPlayerSettings.OtherPlayersData(info.Players[0].UserName, info.Players[0].UserPhoto); } for (int i = 0; i < info.Toks.Count; ++i) { mainv.OnlineQoutes.Add(new OnlineQoutes() { QouteID = info.Toks[i].Id, QoutePhrase = info.Toks[i].PrimaryFieldText, QoutesSource = info.Toks[i].SecondaryFieldText, Category = info.Toks[i].Category }); } MultiPlayerSettings.GetGameInfo(gameInfo); Selection.GetOnlineList(mainv.OnlineQoutes); var navPage = new NavigationPage(new Blank2()); Application.Current.MainPage = navPage; }); }); #endregion BGMusics.Loading_Sound().Play(); await connection.StartAsync(); Fetch.IsRunning = false; lblMessages.Text = $"Connected."; await SignalRService.MultiplayerSetup(me); Btn_Find.IsVisible = true; } catch (Exception ex) { // lblMessages.Text = ex.Message; await DisplayAlert("Error", ex.ToString(), "Ok"); } /* * var navPage = new NavigationPage(new Multiplayer()); * await Task.Delay(200); * await navPage.FadeTo(0, 250); * await Task.Delay(200); * await navPage.FadeTo(1, 250); * Application.Current.MainPage = navPage; * */ }
private async void btnConnect_Clicked(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtUserName.Text)) { return; } try { me.UserName = txtUserName.Text?.Trim(); me.UserId = Guid.NewGuid().ToString(); spinner.IsVisible = true; spinner.IsRunning = true; lblMessages.Text = "Getting connection info..."; SignalRConnectionInfo connectionInfo = await SignalRService.GetSignalRConnectionInfo(); var url = connectionInfo.Url; lblMessages.Text = $"Connecting..."; connection = new HubConnectionBuilder() .WithUrl(url, options => { options.AccessTokenProvider = () => Task.FromResult(connectionInfo.AccessToken); }) .Build(); //connection.Closed += async (error) => //{ // //Optional code: only used for retrying to connect // //await Task.Delay(new Random().Next(0, 5) * 1000); // //await connection.StartAsync(); //}; //Waiting for other player connection.On <GamePlayer>("waiting", (player) => { Device.BeginInvokeOnMainThread(() => { if (player.UserId == me.UserId) { lblStatus.Text = "Waiting for players..."; waitingSpinner.IsVisible = true; waitingSpinner.IsRunning = true; btnSetup.IsVisible = false; btnStopWaiting.IsEnabled = true; btnStopWaiting.IsVisible = true; } }); }); //2 player game successfully created (method name MUST be 'newgame' connection.On <GameInfo>("newgame", (info) => { Device.BeginInvokeOnMainThread(() => { gameInfo = info; var currentPlayer = info.Players.Find(x => x.UserId == me.UserId); multiplayerGameContent.IsVisible = true; lblStatus.Text = $"Game setup successful, you are player {currentPlayer.PlayerNumber}"; if (currentPlayer.PlayerNumber == 1) { isPlayer1 = true; btnStartTimer.IsEnabled = true; } else { isPlayer1 = false; btnStartTimer.IsEnabled = false; } //Fill label with game content lblGameContent.Text = $"Room Id: {info.RoomId}{Environment.NewLine}Player 1: {info.Players[0].UserName}{Environment.NewLine}Player 2: {info.Players[1].UserName}{Environment.NewLine}Toks:{Environment.NewLine}"; for (int i = 0; i < info.Toks.Count; ++i) { lblGameContent.Text += $"- {info.Toks[i].PrimaryFieldText}{Environment.NewLine}"; } btnStopWaiting.IsEnabled = false; btnStopWaiting.IsVisible = false; waitingSpinner.IsVisible = false; waitingSpinner.IsRunning = true; }); }); #region Rounds and guesses connection.On <GameMessage>("log", (message) => { Device.BeginInvokeOnMainThread(() => { bool allowMessage = true; if (onlyAllowRoomId == true && gameInfo.RoomId != message.RoomId && !string.IsNullOrEmpty(gameInfo.RoomId)) { allowMessage = false; } if (allowMessage) { var newMessage = $"{message.Player.UserName}: {message.Type}"; lblMessages.Text += Environment.NewLine + newMessage; } }); }); connection.On <GameMessage>("round_p1", (message) => { Device.BeginInvokeOnMainThread(() => { bool allowMessage = true; if (onlyAllowRoomId == true && gameInfo.RoomId != message.RoomId && !string.IsNullOrEmpty(gameInfo.RoomId)) { allowMessage = false; } if (allowMessage) { var num = ++roundNumP1; lblRoundP1.Text = (num).ToString(); } }); }); connection.On <GameMessage>("guess_p1", (message) => { Device.BeginInvokeOnMainThread(() => { bool allowMessage = true; if (onlyAllowRoomId == true && gameInfo.RoomId != message.RoomId && !string.IsNullOrEmpty(gameInfo.RoomId)) { allowMessage = false; } if (allowMessage) { var num = ++guessNumP1; lblGuessP1.Text = (num).ToString(); } }); }); connection.On <GameMessage>("round_p2", (message) => { Device.BeginInvokeOnMainThread(() => { bool allowMessage = true; if (onlyAllowRoomId == true && gameInfo.RoomId != message.RoomId && !string.IsNullOrEmpty(gameInfo.RoomId)) { allowMessage = false; } if (allowMessage) { var num = ++roundNumP2; lblRoundP2.Text = (num).ToString(); } }); }); connection.On <GameMessage>("guess_p2", (message) => { Device.BeginInvokeOnMainThread(() => { bool allowMessage = true; if (onlyAllowRoomId == true && gameInfo.RoomId != message.RoomId && !string.IsNullOrEmpty(gameInfo.RoomId)) { allowMessage = false; } if (allowMessage) { var num = ++guessNumP2; lblGuessP2.Text = (num).ToString(); } }); }); #endregion //2 player "Elapsed" function connection.On <GameMessage>("time", (message) => { Device.BeginInvokeOnMainThread(() => { bool allowMessage = true; if (onlyAllowRoomId == true && gameInfo.RoomId != message.RoomId && !string.IsNullOrEmpty(gameInfo.RoomId)) { allowMessage = false; } if (allowMessage) { var num = (int)message.Content; timeCount += num; lblTimer.Text = (timeCount).ToString(); } }); }); //2 player "Start/Stop" function connection.On <GameMessage>("startstoptimer", (message) => { Device.BeginInvokeOnMainThread(() => { bool allowMessage = true; if (onlyAllowRoomId == true && gameInfo.RoomId != message.RoomId && !string.IsNullOrEmpty(gameInfo.RoomId)) { allowMessage = false; } if (allowMessage) { var timerIsRunning = Convert.ToBoolean(message.Content); if (timerIsRunning) { if (isPlayer1) { GameTimer.Stop(); } TimerIsRunning = false; btnStartTimer.Text = "Start Timer"; } else { if (isPlayer1) { GameTimer.Start(); } TimerIsRunning = true; btnStartTimer.Text = "Stop Timer"; } } }); }); await connection.StartAsync(); lblMessages.Text = $"Connected.{Environment.NewLine}Id: {me.UserId}{Environment.NewLine}Name: {me.UserName}"; //btnConnect.Text = connectionInfo.AccessToken; btnConnect.IsEnabled = false; gridRoundGuess.IsVisible = true; btnGuessP1.IsEnabled = true; btnGuessP2.IsEnabled = true; btnRoundP1.IsEnabled = true; btnRoundP2.IsEnabled = true; lblStatus.Text = "Click below to start a game:"; btnSetup.IsEnabled = true; spinner.IsVisible = false; spinner.IsEnabled = false; } catch (Exception ex) { lblMessages.Text = ex.Message; } }