/// <summary> /// Sends to server the player answers and retries operation if it fails. /// </summary> private void SendCategoryAnswers() { IsEnabled = false; DialogHost.Show(loadingStackPanel, "GameWindow_WindowDialogHost", (openSender, openEventArgs) => { List <CategoryPlayerAnswer> categoryPlayerAnswers = new List <CategoryPlayerAnswer>(); for (int index = 0; index < categoriesTextBox.Count; index++) { categoryPlayerAnswers.Add(new CategoryPlayerAnswer(0, player, game.Categories[index], categoriesTextBox[index].Text, game.Round)); } EngineNetwork.DoNetworkOperation(onExecute: () => { return(player.SendCategoryAnswers(categoryPlayerAnswers)); }, onSuccess: () => { Thread.Sleep(2500); game = Session.AllGamesAvailable.Find(thisGame => thisGame.ActiveGuidGame == game.ActiveGuidGame); DateTime waitingTimeout = DateTime.Now.AddSeconds(8); while (game.Categories[0].CategoryPlayerAnswer.Count < game.Players.Count) { if (DateTime.Now >= waitingTimeout) { break; } } Application.Current.Dispatcher.Invoke(delegate { openEventArgs.Session.Close(true); Session.GameWindow.Close(); Session.GameWindow = null; new GameWindow_EndRound(game).Show(); }); }, onFinish: null, onFail: null, true); }, null); }
/// <summary> /// Establishes a connection with game service to get all the games in course and waiting for players to be joined. /// </summary> public static void GetGamesList() { while (true) { bool valueReturned = EngineNetwork.EstablishChannel <IGameService>((service) => { while (mainMenuWindow != null) { if (IsPlayerInGame) { GetGameBeingPlayedData(service); continue; } List <Services.Game> serviceGamesList = service.GetGamesList(); foreach (Services.Game serviceGame in serviceGamesList) { SetServiceGame(serviceGame); } RemoveUnnecesaryGames(serviceGamesList); } return(true); }); if (valueReturned) { break; } } }
private void LoginButton_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrWhiteSpace(usernameTextBox.Text) || string.IsNullOrWhiteSpace(passwordPasswordBox.Password)) { MessageBox.Show(Properties.Resources.EmptyFieldsErrorText); return; } EngineNetwork.EstablishConnection(); Session.Cuenta = new Cuenta(usernameTextBox.Text, passwordPasswordBox.Password); byte codeResponse = 0; if (Session.Cuenta.Login(out codeResponse)) { Session.MainMenu = new MainMenuWindow();; Session.Login = this; passwordPasswordBox.Password = ""; Session.MainMenu.Show(); Hide(); } else { switch (codeResponse) { case (byte)NetworkServerResponses.AccountNotConfirmed: MessageBox.Show(Properties.Resources.AccountNotConfirmedErrorText); break; case (byte)NetworkServerResponses.LoginError: MessageBox.Show(Properties.Resources.LoginErrorText); break; } } }
public Cuenta(int id) { this.id = id; EngineNetwork.Send(EngineNetwork.CreatePackage(new object[] { (byte)NetworkClientRequests.GetAccountData, id })); var package = EngineNetwork.ReceiveMultipleData(); if (package.Count < 1) { return; } if (!package[0].ContainsKey("code")) { return; } else if (byte.Parse(package[0]["code"]) != (byte)NetworkServerResponses.AccountData) { return; } package.RemoveAll(x => x.ContainsKey("code")); var accountData = package[0]; if (accountData.Count > 0) { id = int.Parse(accountData["idcuenta"]); usuario = accountData["usuario"]; password = accountData["password"]; correo = accountData["correo"]; monedas = int.Parse(accountData["monedas"]); fechaCreacion = DateTime.Parse(accountData["fechaCreacion"]); confirmada = (accountData["confirmado"] == "1") ? true : false; codigoValidacion = accountData["codigoValidacion"]; } }
public bool Register() { if (!string.IsNullOrWhiteSpace(codigoValidacion)) { return(false); } var registerRequest = EngineNetwork.CreatePackage(new object[] { (byte)NetworkClientRequests.Register, usuario, password, correo }); EngineNetwork.Send(registerRequest); Dictionary <string, string> packageReceived = EngineNetwork.ReceiveAsDictionary(); if (packageReceived.Count == 0) { return(false); } else if (packageReceived.Count == 1) { if (byte.Parse(packageReceived["code"]) != (byte)NetworkServerResponses.RegisterSuccess) { return(false); } } return(true); }
/// <summary> /// Handles reduceTimeButton click event. /// </summary> /// <param name="sender">Button object</param> /// <param name="e">Button click event</param> private void ReduceTimeButton_Click(object sender, RoutedEventArgs e) { if (!didPressDostButton) { return; } player = game.Players.Find(playerInGame => playerInGame.Account.Id == Session.Account.Id); if (player == null) { return; } if (Session.Account.Coins < Session.ROUND_REDUCE_TIME_COST) { MessageBox.Show(Properties.Resources.YouDontHaveEnoughCoinsErrorText); return; } else if (timeRemaining <= Session.ROUND_REDUCE_TIME_SECONDS) { return; } EngineNetwork.DoNetworkOperation <CommunicationException>(onExecute: () => { inGameService.ReduceTime(game.ActiveGuidGame, player.ActivePlayerGuid); return(true); }, onSuccess: () => { Application.Current.Dispatcher.Invoke(delegate { reduceTimeButton.IsEnabled = false; Session.Account.Coins -= Session.ROUND_REDUCE_TIME_COST; }); }); }
public void SendChatMessage(Partida game, string message) { var sendChatMessageRequest = EngineNetwork.CreatePackage(new object[] { (byte)NetworkClientRequests.SendChatMessage, game.Id, usuario, message }); EngineNetwork.Send(sendChatMessageRequest); }
public void Logout() { var logoutRequest = EngineNetwork.CreatePackage(new object[] { (byte)NetworkClientRequests.Logout, id }); EngineNetwork.Send(logoutRequest); }
/// <summary> /// Establishes a connection with account service to try to register an account /// with the data stored in this account instance. /// </summary> /// <returns>True if account was registered successfully; False if not</returns> public bool Register() { return(EngineNetwork.EstablishChannel <IAccountService>((registerService) => { Services.Account account = new Services.Account( 0, username, password, email, 0, DateTime.Now, false, null ); return registerService.SignUp(account); })); }
/// <summary> /// Establishes a connection with game service to get a game category word. /// </summary> /// <param name="category">GameCategory that needs the word</param> /// <returns> /// Empty string if word couldn't be found; otherwise, a random word whose /// first letter is accord to the selected for the actual round. /// </returns> public string GetCategoryWord(GameCategory category) { var word = string.Empty; EngineNetwork.EstablishChannel <IGameService>((service) => { word = service.GetCategoryWord(game.ActiveGuidGame, activePlayerGuid, category.Name); return(true); }); return(word); }
/// <summary> /// Establishes a connnection with game service to try to join to a game. /// </summary> /// <param name="game">Game to join in</param> /// <param name="asAnfitrion">True to join as host; False to join as guest</param> /// <param name="guidPlayer">Player global unique identifier generated</param> /// <returns>True if join request was successful; False if not</returns> public bool JoinGame(Game game, bool asAnfitrion, out string guidPlayer) { string guidNewPlayer = ""; bool returnedValue = EngineNetwork.EstablishChannel <IGameService>((service) => { return(service.AddPlayer(id, game.ActiveGuidGame, asAnfitrion, out guidNewPlayer)); }); guidPlayer = guidNewPlayer; return(returnedValue); }
/// <summary> /// Establishes a connnection with game service to try to create a new game. /// </summary> /// <param name="guidGame"> /// Stores a global unique identifier that identifies the new game created. /// If game couldn't be created, this value will be empty. /// </param> /// <returns>True if creation request was successful; False if not</returns> public bool CreateGame(out string guidGame) { string guidNewGame = ""; bool returnedValue = EngineNetwork.EstablishChannel <IGameService>((service) => { return(service.CreateGame(out guidNewGame, App.Language)); }); guidGame = guidNewGame; return(returnedValue); }
/// <summary> /// Establishes a connection with game service to start the game, increasing round value in 1. /// </summary> /// <returns>True if game was started successfully; False if not, or if round value was higher or equal to max rounds per game value</returns> public bool Start() { if (round >= Session.MAX_ROUNDS_PER_GAME) { return(false); } round += 1; return(EngineNetwork.EstablishChannel <IGameService>((service) => { return service.StartGame(ActiveGuidGame); })); }
/// <summary> /// Establishes a connnection with account service to get the account rank. /// </summary> /// <returns> /// If this account has games played, will return rank as #N, where N is the place. /// If it has no games played, will return a "Not ranked" string. /// </returns> public string GetRank() { var rank = Properties.Resources.NotRankedText; EngineNetwork.EstablishChannel <IAccountService>((service) => { var accountRank = service.GetRank(id); rank = string.IsNullOrEmpty(accountRank) ? rank : accountRank; return(true); }); return(rank); }
public static void GetGamesList() { if (cuenta != null) { EngineNetwork.Send(EngineNetwork.CreatePackage(new object[] { (byte)NetworkClientRequests.GetGames })); var gamesPackage = EngineNetwork.ReceiveMultipleData(); if (gamesPackage.Count == 0) { return; } if (!gamesPackage[0].ContainsKey("code")) { return; } else if (byte.Parse(gamesPackage[0]["code"]) != (byte)NetworkServerResponses.GamesList) { return; } gamesPackage.RemoveAll(x => x.ContainsKey("code")); foreach (var gamePackage in gamesPackage) { System.Windows.Application.Current.Dispatcher.Invoke(delegate { if (!GamesList.ToList().Exists(x => x.Id == int.Parse(gamePackage["idpartida"]))) { var game = new Partida( int.Parse(gamePackage["idpartida"]), int.Parse(gamePackage["ronda"]), Convert.ToDateTime(gamePackage["fecha"]) ); game.PropertyChanged += Game_PropertyChanged; GamesList.Add(game); } else { GamesList.ToList().Find(x => x.Id == int.Parse(gamePackage["idpartida"])).LoadJugadores(); } }); } List <Partida> gamesToRemove = new List <Partida>(); foreach (var game in GamesList) { var checkGame = gamesPackage.ToList().Find(x => int.Parse(x["idpartida"]) == game.Id); if (checkGame == null) { gamesToRemove.Add(game); } } System.Windows.Application.Current.Dispatcher.Invoke(delegate { gamesToRemove.ForEach(x => GamesList.Remove(x)); }); } }
/// <summary> /// Opens a new GameWindow. /// </summary> private void StartGame() { DialogHost.Show(loadingStackPanel, "GameWindow_LetterSelection_WindowDialogHost", (openSender, openEventArgs) => { EngineNetwork.DoNetworkOperation(onExecute: () => { Thread.Sleep(2000); // allows session thread to load latest game data return(true); }, onSuccess: () => { Application.Current.Dispatcher.Invoke(delegate { openEventArgs.Session.Close(true); Session.GameWindow = new GameWindow(game); Session.GameWindow.Show(); Close(); }); }, onFinish: null, null, false); }, null); }
/// <summary> /// Establishes a connection with game service to try to send the player answers from each game category. /// </summary> /// <param name="categoryPlayerAnswers">Category answers</param> /// <returns>True if operation was successful; False if not</returns> public bool SendCategoryAnswers(List <CategoryPlayerAnswer> categoryPlayerAnswers) { List <Services.CategoryPlayerAnswer> categoryPlayerAnswersService = new List <Services.CategoryPlayerAnswer>(); foreach (var categoryPlayerAnswer in categoryPlayerAnswers) { categoryPlayerAnswersService.Add(new Services.CategoryPlayerAnswer { Answer = categoryPlayerAnswer.Answer, Round = categoryPlayerAnswer.Round, GameCategory = new Services.GameCategory(0, null, categoryPlayerAnswer.GameCategory.Name) }); } return(EngineNetwork.EstablishChannel <IGameService>((service) => { return service.SendCategoryAnswers(game.ActiveGuidGame, activePlayerGuid, categoryPlayerAnswersService); })); }
/// <summary> /// Handles ChatMessageTextBox key enter down. Sends through network a chat message. /// </summary> /// <param name="sender">TextBox object</param> /// <param name="e">TextBox key event</param> private void ChatMessageTextBox_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { if (string.IsNullOrWhiteSpace(chatMessageTextBox.Text)) { return; } EngineNetwork.DoNetworkOperation <CommunicationException>(onExecute: () => { Application.Current.Dispatcher.Invoke(delegate { chatService.BroadcastMessage(game.ActiveGuidGame, player.Account.Username, chatMessageTextBox.Text); chatMessageTextBox.Clear(); }); return(true); }); } }
/// <summary> /// Establishes a connection with account service to try to reload account data. /// </summary> /// <returns>True if account data was reloaded successfully; False if not</returns> public bool Reload() { return(EngineNetwork.EstablishChannel <IAccountService>((loginService) => { var account = loginService.GetAccount(id); if (account.Id == 0) { return false; } username = account.Username; password = account.Password; email = account.Email; coins = account.Coins; creationDate = account.CreationDate; isVerified = account.IsVerified; validationCode = account.ValidationCode; return true; })); }
/// <summary> /// Handles ShowGameResultsButton click event. Sends data to all players to indicate that game results is about to show up. /// </summary> /// <param name="sender">Button object</param> /// <param name="e">Button click event</param> private void ShowGameResultsButton_Click(object sender, RoutedEventArgs e) { this.game = Session.AllGamesAvailable.First(gameList => gameList.ActiveGuidGame == game.ActiveGuidGame); if (game.Players.Find(playerInGame => playerInGame.IsReady == false && playerInGame.ActivePlayerGuid != player.ActivePlayerGuid) != null) { MessageBox.Show(Properties.Resources.PlayersNotReadyErrorText); return; } showGameResultsButton.IsEnabled = false; EngineNetwork.DoNetworkOperation(onExecute: () => { if (player.SetPlayerReady(true)) { inGameService.EndGame(game.ActiveGuidGame); return(true); } return(false); }, null, null, null, true); }
/// <summary> /// Establishes a connection with account service to load the scores list. /// </summary> private void LoadScoresList() { if (!EngineNetwork.EstablishChannel <IAccountService>((service) => { var scoresList = service.GetBestScores(); scoresList.ForEach((userScore) => { bestScoresList.Add(new UserScore { Ranking = userScore.Ranking, Username = userScore.Username, Score = userScore.Score }); }); return(true); })) { MessageBox.Show(Properties.Resources.AnErrorHasOcurredErrorText); Close(); } }
/// <summary> /// Handles ReadyButton click event. Sends data to all players to indicate that this player is ready. /// </summary> /// <param name="sender">Button object</param> /// <param name="e">Button click event</param> private void ReadyButton_Click(object sender, RoutedEventArgs e) { if (player.IsHost) { return; } EngineNetwork.DoNetworkOperation <CommunicationException>(onExecute: () => { if (player.SetPlayerReady(true)) { inGameService.SetPlayerReady(game.ActiveGuidGame, player.ActivePlayerGuid, true); return(true); } return(false); }, onSuccess: () => { Application.Current.Dispatcher.Invoke(delegate { readyButton.IsEnabled = false; }); }, null, onFail: null, true); }
/// <summary> /// Handles SelectRandomLetterButton click event. Sends through network data to indicate that a random letter /// was set and game should start. /// </summary> /// <param name="sender">Button object</param> /// <param name="e">Button click event</param> private void SelectRandomLetterButton_Click(object sender, RoutedEventArgs e) { IsEnabled = false; EngineNetwork.DoNetworkOperation <CommunicationException>(onExecute: () => { if (game.SetLetter(true, Session.Account.Id)) { inGameService.StartGame(game.ActiveGuidGame); return(true); } else { Application.Current.Dispatcher.Invoke(delegate { MessageBox.Show(Properties.Resources.CouldntSelectLetterErrorText); IsEnabled = true; }); return(false); } }, null, null, null, true); }
/// <summary> /// Handles LoginButton click event. Establishes a connection with account service to try login with /// entered credentials. /// </summary> /// <param name="sender">Button object</param> /// <param name="e">Button click event</param> private void LoginButton_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrWhiteSpace(usernameTextBox.Text) || string.IsNullOrWhiteSpace(passwordPasswordBox.Password)) { MessageBox.Show(Properties.Resources.UncompletedFieldsErrorText); return; } IsEnabled = false; Account account = new Account(usernameTextBox.Text, passwordPasswordBox.Password); DialogHost.Show(loadingStackPanel, "LoginWindow_WindowDialogHost", (openSender, openEventArgs) => { EngineNetwork.DoNetworkOperation(onExecute: () => { if (!account.Login()) { if (account.Id == 0) { MessageBox.Show(Properties.Resources.LoginErrorText); } else if (!account.IsVerified) { MessageBox.Show(Properties.Resources.AccountNotConfirmedErrorText); } return(false); } return(true); }, onSuccess: () => { Application.Current.Dispatcher.Invoke(delegate { passwordPasswordBox.Password = ""; Session.Account = account; Session.MainMenuWindow = new MainMenuWindow(); Session.LoginWindow = this; Session.MainMenuWindow.Show(); Hide(); }); }, onFinish: () => { Application.Current.Dispatcher.Invoke(delegate { openEventArgs.Session.Close(true); IsEnabled = true; }); }, null, false); }, null); }
public bool LeaveGame(Partida game) { EngineNetwork.Send(EngineNetwork.CreatePackage(new object[] { (byte)NetworkClientRequests.LeaveGame, id, game.Id })); var packageReceived = EngineNetwork.ReceiveMultipleData(); if (packageReceived.Count == 0) { return(false); } else if (packageReceived.Count == 1) { if (byte.Parse(packageReceived[0]["code"]) != (byte)NetworkServerResponses.PlayerLeft) { return(false); } } return(true); }
public bool JoinGame(Partida game) { var joinGameRequest = EngineNetwork.CreatePackage(new object[] { (byte)NetworkClientRequests.JoinGame, id, game.Id, }); EngineNetwork.Send(joinGameRequest); List <string> packageReceived = EngineNetwork.Receive(); if (packageReceived.Count == 0) { return(false); } else if (packageReceived.Count == 1) { if (byte.Parse(packageReceived[0]) != (byte)NetworkServerResponses.PlayerJoined) { return(false); } } return(true); }
/// <summary> /// Handles DialogHost loaded event. Tries to execute get games list method until it gets successful. /// </summary> /// <param name="sender">DialogHost object</param> /// <param name="e">DialogHost event</param> private void DialogHost_Loaded(object sender, RoutedEventArgs e) { IsEnabled = false; var dialog = DialogHost.Show(loadingStackPanel, "MainMenuWindow_WindowDialogHost", (openSender, openEventArgs) => { EngineNetwork.DoNetworkOperation(onExecute: () => { var getGamesListTask = Task.Run(() => { Session.GetGamesList(); }); Thread.Sleep(1000); if (getGamesListTask.Status != TaskStatus.Running) { return(false); } new Thread(JoinGameIfNeeded).Start(); return(true); }, onSuccess: () => { Application.Current.Dispatcher.Invoke(delegate { openEventArgs.Session.Close(true); IsEnabled = true; }); }, null, null, true); }, null); }
public bool Login(out byte codeResponse) { var loginRequest = EngineNetwork.CreatePackage(new object[] { (byte)NetworkClientRequests.Login, usuario, password }); EngineNetwork.Send(loginRequest); Dictionary <string, string> packageReceived = EngineNetwork.ReceiveAsDictionary(); codeResponse = (byte)NetworkServerResponses.LoginError; if (packageReceived.Count == 0) { return(false); } else if (packageReceived.Count == 1) { if (byte.Parse(packageReceived["code"]) == (byte)NetworkServerResponses.LoginError) { return(false); } else if (byte.Parse(packageReceived["code"]) == (byte)NetworkServerResponses.AccountNotConfirmed) { codeResponse = (byte)NetworkServerResponses.AccountNotConfirmed; return(false); } } Session.Cuenta.id = int.Parse(packageReceived["idcuenta"]); Session.Cuenta.usuario = packageReceived["usuario"]; Session.Cuenta.password = packageReceived["password"]; Session.Cuenta.correo = packageReceived["correo"]; Session.Cuenta.monedas = int.Parse(packageReceived["monedas"]); Session.Cuenta.fechaCreacion = DateTime.Parse(packageReceived["fechaCreacion"]); Session.Cuenta.confirmada = (packageReceived["confirmado"] == "1") ? true : false; Session.Cuenta.codigoValidacion = packageReceived["codigoValidacion"]; codeResponse = 1; return(true); }
public void ReceiveChatMessages() { var messagePackage = EngineNetwork.ReceiveMultipleData(); if (messagePackage.Count == 0) { return; } var message = messagePackage[0]; if (!message.ContainsKey("code")) { return; } if (byte.Parse(message["code"]) == (byte)NetworkServerResponses.ChatMessage) { Application.Current.Dispatcher.Invoke(delegate { chatListBox.Items.Add(new TextBlock() { Text = message["username"] + ": " + message["message"] }); }); } }
public void LoadJugadores() { jugadores.Clear(); EngineNetwork.Send(EngineNetwork.CreatePackage(new object[] { (byte)NetworkClientRequests.GetGamePlayers, id })); List <Dictionary <string, string> > players = EngineNetwork.ReceiveMultipleData(); if (players.Count == 0) { return; } if (!players[0].ContainsKey("code")) { return; } else if (byte.Parse(players[0]["code"]) != (byte)NetworkServerResponses.GamePlayersList) { return; } players.RemoveAll(x => x.ContainsKey("code")); foreach (var player in players) { jugadores.Add(new Jugador( int.Parse(player["idjugador"]), new Cuenta(int.Parse(player["idcuenta"])), this, int.Parse(player["puntuacion"]), (player["anfitrion"] == "1") ? true : false )); } if (numeroJugadores != jugadores.Count) { NumeroJugadores = jugadores.Count.ToString(); } }