// Регистрация с помощью электронной почты public bool RegistrationEmail(string Email, string Password, string Nickname, string Sex, string Country) { Message regMessage = new Message(Messages.MESSAGE_AUTORIZATION_REGISTRATION_EMAIL, String.Format("Nickname={0},Email={1},Password={2},Country={3},Sex={4}", Nickname, Email, Password, Country, Sex)); MessageResult res = ServerConnection.ExecuteMessage(regMessage); return (res["Registration"] == "1"); }
// Авторизация через VK public bool AuthorizationVK(string ID, string Name, string Sex, string Country, out int PlayerID) { Message regMessage = new Message(Messages.MESSAGE_AUTORIZATION_AUTORIZATION_VK, String.Format("Name={0},ID={1},Country={3},Sex={4}", Name, ID, Country, Sex)); MessageResult res = ServerConnection.ExecuteMessage(regMessage); PlayerID = Int32.Parse(res["PlayerID"]); return (PlayerID != -1); }
// Авторизация с помощью электронной почты public bool AutorizationEmail(string Email, string Password, out int PlayerID) { Message autMessage = new Message(Messages.MESSAGE_AUTORIZATION_AUTORIZATION_EMAIL, String.Format("Email={0},Password={1}", Email, Password)); MessageResult res = ServerConnection.ExecuteMessage(autMessage); PlayerID = Int32.Parse(res["PlayerID"]); return (PlayerID != -1); }
// Получение информации об игроке public Player GetPlayer(int PlayerID) { if (PlayerID < 0) return null; Message playerMessage = new Message(Messages.MESSAGE_PLAYER_GET_INFORMATION, String.Format("PlayerID={0}", PlayerID)); MessageResult pParams = ServerConnection.ExecuteMessage(playerMessage); if (pParams != null) { return new Player(pParams); } else { return null; } }
// Обработчик удаление другого игрока со стола private void PlayerDeleteHandler(Message Msg) { MessageResult pParams = new MessageResult(Msg); int PlayerPlace = Int32.Parse(pParams["Place"]); Players.Delete(Players[currentTable[PlayerPlace]]); currentTable.SetPlayerAtPlace(-1, PlayerPlace); if (OnUpdateWaitingTable != null) OnUpdateWaitingTable(); }
// Переход хода к игроку private void NextPlayerHandler(Message Msg) { try { // Если это первый ход, то нужно огласить бонусы if (gameData.Bonuses != null) { // Если есть неоглашенные бонусы, то предлагаем их огласить if (gameData.Bonuses.Count != 0) { if (OnAnnounceBonuses != null) OnAnnounceBonuses(); serverActions.Game.PlayerAnnounceBonuses(gameData.Bonuses); // Обнуляем бонусы gameData.Bonuses = null; } } MessageResult cParams = new MessageResult(Msg); // Получаем список возможных карт gameData.PossibleCards = new CardList(cParams["Cards"]); // Разрешаем игроку сделать ход gameData.IsMakingMove = true; if (OnUpdateGraphics != null) OnUpdateGraphics(); } catch (Exception Ex) { throw new BeloteClientException("Произошла ошибка во время перехода хода к игроку", Ex); } }
//********************************************************************************************************************************************************************************** // Обработчики доигровых событий: посадка игрока на стол, удаление игрока со стола, старт игры //********************************************************************************************************************************************************************************** // Обработчик добавления другого игрока на стол private void PlayerAddHandler(Message Msg) { MessageResult pParams = new MessageResult(Msg); int PlayerID = Int32.Parse(pParams["Player"]); int PlayerPlace = Int32.Parse(pParams["Place"]); currentTable.SetPlayerAtPlace(PlayerID, PlayerPlace); if (!Players.PlayerExists(PlayerID)) { Player p = serverActions.Players.GetPlayer(PlayerID); if (p != null) Players.Add(p); } if (OnUpdateWaitingTable != null) OnUpdateWaitingTable(); }
// Завершение игры private void GameEndHandler(Message Msg) { try { MessageResult gParams = new MessageResult(Msg); gameData.TotalScores[BeloteTeam.TEAM1_1_3] = Int32.Parse(gParams["Scores1"]); gameData.TotalScores[BeloteTeam.TEAM2_2_4] = Int32.Parse(gParams["Scores2"]); SetGameHandlers(false); ChangeCurrentTable(null); if (OnGameEnd != null) OnGameEnd(); } catch (Exception Ex) { throw new BeloteClientException("Произошла ошибка при завершении игры", Ex); } }
//********************************************************************************************************************************************************************************** // Обработчики основных игровых событийf //********************************************************************************************************************************************************************************** // Обработчик получения списка карт private void GetCardsHandler(Message Msg) { try { MessageResult cParams = new MessageResult(Msg); string cardsStr = cParams["Cards"]; int totalScore1 = Int32.Parse(cParams["Scores1"]); int totalScore2 = Int32.Parse(cParams["Scores2"]); gameData.NewDistribution(new CardList(cardsStr), totalScore1, totalScore2); if (OnUpdateGraphics != null) OnUpdateGraphics(); } catch (Exception Ex) { throw new BeloteClientException("Произошла ошибка при получении списка карт", Ex); } }
// Обработка начала игры private void StartGameHandler(Message Msg) { if (OnGameStart != null) OnGameStart(); SetPreGameHandlers(false); Status = GameStatus.GAMING; gameData = new GameData(); SetGameHandlers(true); }
// Обработка сообщения private bool ProcessMessage(Message Msg) { List<MessageDelegate> msgHandlers; if (Msg.Command == null) return true; if (messageHandlers.TryGetValue(Msg.Command, out msgHandlers)) { if (msgHandlers.Count > 0) { foreach (MessageDelegate md in msgHandlers) { Device.BeginInvokeOnMainThread (new Action (() => md (Msg))); } return true; } } return false; }
// Получение списка возможных бонусов private void BonusesGetAllHandler(Message Msg) { gameData.Bonuses = new BonusList(Msg.Msg); }
// Выполнение команды на сервере и возврат результата в виде "сообщения" public Message ExecuteMessageGetMessage(Message msg) { SendDataToServer(msg.Command + msg.Msg); Message result = null; Thread worker = new Thread(delegate () { while (true) { lock (messagesList) { result = messagesList.Find(m => m.Command == msg.Command); if (result != null) { messagesList.Remove(result); break; } } Thread.Sleep(20); } }); worker.Start(); worker.Join(); return result; }
// Завершение торговли без заявки козыря private void BazarPassHandler(Message Msg) { }
// Произношение заявки сделанной одним из игроков private void BazarPlayerSayHandler(Message Msg) { try { MessageResult bParams = new MessageResult(Msg); int playerNum = Int32.Parse(bParams["Player"]); OrderType orderType = (OrderType)Int32.Parse(bParams["Type"]); int orderSize = Int32.Parse(bParams["Size"]); CardSuit orderSuit = Helpers.StringToSuit(bParams["Trump"]); gameData.Orders[playerNum] = new Order(orderType, orderSize, orderSuit); if (OnUpdateGraphics != null) OnUpdateGraphics(); } catch (Exception Ex) { throw new BeloteClientException("Произошла ошибка во время информирования игрока о ставке другого игрока", Ex); } }
// Переход хода к игроку во время торговли private void BazarNextPlayerHandler(Message Msg) { try { gameData.IsMakingMove = true; MessageResult bParams = new MessageResult(Msg); gameData.Orders.PossibleBetType = (BetType)Int32.Parse(bParams["Type"]); gameData.Orders.PossibleBetSize = Int32.Parse(bParams["MinSize"]); if (OnBazarMakingBet != null) OnBazarMakingBet(); } catch (Exception Ex) { throw new BeloteClientException("Произошла ошибка при переходе хода во время торговли к игроку", Ex); } }
// Завершение процесса торговли private void BazarEndHandler(Message Msg) { try { MessageResult bParams = new MessageResult(Msg); BeloteTeam oTeam = (BeloteTeam)Int32.Parse(bParams["Team"]); OrderType oType = (OrderType)Int32.Parse(bParams["Type"]); CardSuit oSuit = (CardSuit)Int32.Parse(bParams["Trump"]); int oSize = Int32.Parse(bParams["Size"]); gameData.Orders.SetEndOrder(new Order(oType, oSize, oSuit)); gameData.Orders.EndOrder.ChangeTeam(oTeam); gameData.ChangeGameStatus(TableStatus.BONUSES); if (OnUpdateGraphics != null) OnUpdateGraphics(); } catch (Exception Ex) { throw new BeloteClientException("Произошла ошибка во время завершения процесса торговли", Ex); } }
// Обработка сообщений от сервера private void ProcessServer() { while (true) { try { byte[] data = new byte[64]; StringBuilder builder = new StringBuilder(); do { int bytes = stream.Read(data, 0, data.Length); builder.Append(Encoding.Unicode.GetString(data, 0, bytes)); } while (stream.DataAvailable); // Разделение полученных сообщений string[] messages = builder.ToString().Split(Constants.MESSAGE_DELIMITER); foreach (string str in messages) { if (str != "") { Message msg = new Message(str); // Если это сообщение теста соединения, то игнорируем его if (msg.Command == Messages.MESSAGE_CLIENT_TEST_CONNECTION) continue; lock (messageHandlers) { if (!ProcessMessage(msg)) { lock (messagesList) { messagesList.Add(new Message(str)); } } } } } } catch (Exception Ex) { Disconnect(); throw new BeloteClientException("Ошибка обработки сообщения от сервера", Ex); } } }
// Выход игрока со стола во время игры private void PlayerQuitHandler(Message Msg) { try { MessageResult qParams = new MessageResult(Msg); // Продолжаем игру if (qParams["Continue"] == "1") { int BotPlace = Int32.Parse(qParams["Place"]); if (BotPlace != place) { currentTable.SetPlayerAtPlace(-BotPlace, BotPlace); if (OnUpdateGraphics != null) OnUpdateGraphics(); return; } } SetGameHandlers(false); ChangeCurrentTable(null); if (OnPlayerQuit != null) OnPlayerQuit(); } catch (Exception Ex) { throw new BeloteClientException("Произошла ошибка во время выхода кого-то со стола", Ex); } }
// Выполнение команды на сервере и получение результата в виде словаря public MessageResult ExecuteMessage(Message msg) { return new MessageResult(ExecuteMessageGetMessage(msg)); }
// Ход другого игрока private void RemindCardHandler(Message Msg) { try { MessageResult cParams = new MessageResult(Msg); int cardPlace = Int32.Parse(cParams["Place"]); Card newCard = new Card(cParams["Card"]); int beloteRemind = Int32.Parse(cParams["Belote"]); gameData.Bribes.PutCard(newCard, cardPlace); gameData.LocalScores[BeloteTeam.TEAM1_1_3] = Int32.Parse(cParams["Scores1"]); gameData.LocalScores[BeloteTeam.TEAM2_2_4] = Int32.Parse(cParams["Scores2"]); if (beloteRemind == 1) gameData.Bribes.CurrentBribe.BelotePlace = cardPlace; else if (beloteRemind == 2) gameData.Bribes.CurrentBribe.RebelotePlace = cardPlace; if (OnUpdateGraphics != null) OnUpdateGraphics(); } catch (Exception Ex) { throw new BeloteClientException("Произошла ошибка во время оповещения о карте, которой походил кто-то из игроков", Ex); } }
// Обработчик выхода со стола создателя private void CreatorLeaveHandler(Message Msg) { ExitFromTable(false); if (OnExitFromTable != null) OnExitFromTable(); }
// Объявление о типах объявленных бонусов одного из игроков private void BonusesShowTypesHandler(Message Msg) { try { MessageResult tParams = new MessageResult(Msg); int count = Int32.Parse(tParams["Count"]); int place = Int32.Parse(tParams["Place"]); if (count == 0) return; for (var i = 0; i < count; i++) { BonusType nextB = (BonusType)Int32.Parse(tParams["Type" + i.ToString()]); gameData.AnnouncedBonuses.AddBonus(place, nextB); } if (OnUpdateGraphics != null) OnUpdateGraphics(); } catch (Exception Ex) { throw new BeloteClientException("Произошла ошибка при получении типов объявленныъ другим игроком бонусов", Ex); } }
// Выполняет сообщение без ожидания результата public void ExecuteMessageWithoutResult(Message msg) { SendDataToServer(msg.Command + msg.Msg); }
public MessageResult(Message message) { mParams = Helpers.SplitCommandString(message.Msg); }
// Объявление победителя по бонусам private void BonusesShowWinnerHandler(Message Msg) { try { gameData.ChangeGameStatus(TableStatus.PLAY); MessageResult wParams = new MessageResult(Msg); BeloteTeam winner = (BeloteTeam)Int32.Parse(wParams["Winner"]); int scores = Int32.Parse(wParams["Scores"]); gameData.AnnouncedBonuses.SetWinner(winner, scores); if (OnShowBonusesWinner != null) OnShowBonusesWinner(); gameData.AnnouncedBonuses.Clear(); if (OnUpdateGraphics != null) OnUpdateGraphics(); } catch (Exception Ex) { throw new BeloteClientException("Произошла ошибка во время объявления команды попедителя по бонусам", Ex); } }