Beispiel #1
0
        public Guid CreateGame(Guid player, Guid room)
        {
            using (var context = new MilleBornesEntities())
            {
                var playerEntity = context.User
                    .Where(us => us.LoggedInUser != null)
                    .SingleOrDefault(us => us.LoggedInUser.Token == player);
                if (playerEntity == null)
                {
                    throw new FaultException("Le joueur n'est pas valide ou est hors-ligne.");
                }

                var roomEntity = context.Room
                    .SingleOrDefault(rm => rm.Token == room);
                if (roomEntity == null)
                {
                    throw new FaultException("La salle n'est pas trouvée.");
                }

                if (roomEntity.MasterUserId != playerEntity.UserId)
                {
                    throw new FaultException("Seul le maître de la salle peut démarrer la partie.");
                }

                var newGame = new Game()
                {
                    Token = Guid.NewGuid(),
                    StartDate = DateTime.UtcNow,
                    IsTakingDisconnectDecision = false
                };

                FillPlayerConfig(context, roomEntity, newGame);

                roomEntity.Game = newGame;
                roomEntity.Started = true;
                context.Game.Add(newGame);
                try
                {
                    context.SaveChanges();
                }
                catch (System.Data.Entity.Infrastructure.DbUpdateException dbue)
                {
                    throw;
                }

                InitializeGame(newGame);
                try
                {
                    context.SaveChanges();
                }
                catch (System.Data.Entity.Infrastructure.DbUpdateException dbue)
                {
                    throw;
                }

                return newGame.Token;
            }
        }
Beispiel #2
0
        private static void FillPlayerConfig(MilleBornesEntities context, Room roomEntity, Game newGame)
        {
            // Essayer en premier lieu avec le service, sinon
            // regarder directement dans la base de données.

            List<PlayerGame> playerGameSource = new List<PlayerGame>();
#if false
            try
            {
                using (var client = new LobbyGameProxy.LobbyServiceClient())
                {
                    var configEntries = client.GetPlayerConfig(roomEntity.Token);

                    foreach (var entry in configEntries)
                    {
                        var user = context.User
                            .Where(us => us.LoggedInUser != null)
                            .SingleOrDefault(us => us.LoggedInUser.Token == entry.UserToken);

                        if (user == null)
                        {
                            continue;
                        }

                        var playerGame = new PlayerGame()
                        {
                            Game = newGame,
                            UserId = user.UserId,
                            User = user,
                            LastHeartbeat = DateTime.UtcNow,
                            Order = entry.Order,
                            Team = entry.Team + 1,
                            HasJoined = user.UserId == roomEntity.MasterUserId
                        };
                    }
                }
            }
#endif
            //catch (Exception ex)
            //{
                playerGameSource = roomEntity.PlayerRoomState.Select((prs, inx) => new PlayerGame()
                {
                    Game = newGame,
                    UserId = prs.UserId,
                    User = prs.User,
                    LastHeartbeat = DateTime.UtcNow,
                    Order = inx,
                    Team = prs.Team + 1,
                    HasJoined = prs.UserId == roomEntity.MasterUserId
                })
                .ToList();
            //}

            newGame.PlayerGame = playerGameSource;
        }
Beispiel #3
0
        /// <summary>
        /// Crée la room avec le master associé.
        /// </summary>
        /// <param name="name">Nom de la salle</param>
        /// <param name="roomMaster">Guid du créateur.</param>
        /// <returns>Le guid de la room. </returns>
        public Guid? CreateRoom(string name, Guid roomMaster)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    // Fetch le master id. 
                    int mId = context.LoggedInUser.First(p => p.Token == roomMaster).UserId;
                    // Vérifie si déjà master d'une room ou membre d'une room.
                    bool alreadyInRoom = context.Room
                        .Where(p => p.MasterUserId == mId)
                        .Count() > 0;

                    if (alreadyInRoom)
                        return null;

                    alreadyInRoom = context.PlayerRoomState
                        .Where(p => p.UserId == mId)
                        .Count() > 0;

                    if (alreadyInRoom)
                        return null;

                    Guid roomGuid = Guid.NewGuid();
                    Room r = new Room();
                    r.Name = name;
                    r.Started = false;
                    r.Token = roomGuid;
                    r.MasterUserId = mId;
                    r.GameInProgressId = null;

                    // Crée le playerroomstate du roommaster
                    PlayerRoomState prs = new PlayerRoomState();
                    prs.Room = r;
                    prs.UserId = mId;
                    prs.IsReady = false;
                    prs.Order = 0;
                    prs.Team = 0;
                    prs.LastHeartbeat = DateTime.UtcNow;

                    context.Room.Add(r);
                    context.PlayerRoomState.Add(prs);
                    context.SaveChanges();

                    return roomGuid;
                }
            }
            catch
            {
                return null;
            }
        }
Beispiel #4
0
        /// <summary>
        /// Permet de joindre une room!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        /// </summary>
        /// <param name="player"></param>
        /// <param name="room"></param>
        /// <returns>True si succès, false autrement.</returns>
        public bool JoinRoom(Guid player, Guid room)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    LoggedInUser liu = context.LoggedInUser.First(p => p.Token == player);

                    // On vérifie si le user est dans la room... 
                    // vérifie si déjà dans une room
                    bool alreadyInRoom = context.PlayerRoomState
                        .Where(p => p.UserId == liu.UserId)
                        .Count() > 0;

                    Room r = context.Room.First(p => p.Token == room);

                    // Si il est dans une autre room.
                    if (alreadyInRoom)
                    {
                        if (r.MasterUserId == liu.UserId || r.PlayerRoomState.First(p => p.UserId == liu.UserId).Room.Token == room)
                        {
                            SendRoomMessage(Guid.ParseExact("00000000-0000-0000-0000-000000000000", "D"), room, "**Le joueur " + liu.User.Name + " revenu dans la partie ☺**");
                            return true;
                        }

                        return false;
                    }

                    PlayerRoomState prsUser = new PlayerRoomState();
                    prsUser.UserId = liu.UserId;
                    prsUser.RoomId = r.RoomId;
                    prsUser.IsReady = false;
                    prsUser.Order = 0;
                    prsUser.Team = 0;
                    prsUser.LastHeartbeat = DateTime.UtcNow;

                    context.PlayerRoomState.Add(prsUser);
                    context.SaveChanges();
                    SendRoomMessage(Guid.ParseExact("00000000-0000-0000-0000-000000000000", "D"), room, "**Le joueur " + liu.User.Name + " a join la partie ☺**");
                }

                return true;
            }
            catch
            {
                return false;
            }
        }
Beispiel #5
0
        /// <summary>
        /// Crée l'utilisateur en fonction des informations fournies.
        /// </summary>
        /// <param name="info"></param>
        /// <returns>True si créé avec succès. False autrement.</returns>
        public bool CreateUser(Models.CreateUserInfo info)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    // Vérification basiques.
                    if (info.Email.Trim() == "" || !info.Email.Contains("@"))
                        return false;

                    if (info.Username.Trim().Length < 2 || info.Password.Length < 3)
                        return false;

                    User user = new User();
                    user.Name = info.Username.Trim();
                    user.PasswordHash = GetSHA1HashString(info.Password);
                    user.EmailAddress = info.Email.Trim();

                    // Si l'utilisateur est déjà présent, soit email soit name.
                    if (context.User.Where(p => p.Name == user.Name
                        || user.EmailAddress == p.EmailAddress).Count() > 0)
                    {
                        return false;
                    }


                    context.User.Add(user);
                    context.SaveChanges();
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }
Beispiel #6
0
        /// <summary>
        /// Récupère les messages globaux.
        /// </summary>
        /// <param name="limit"></param>
        /// <returns>Liste des messages.</returns>
        public List<Models.UserMessage> GetGlobalMessages(int limit)
        {
            List<Models.UserMessage> lstUMessages = new List<UserMessage>();

            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    var lstMessages = context.Message
                        .Where(p => p.Type == MessageType.GLOBAL)
                        .OrderByDescending(o => o.MessageId).ToList();

                    foreach (Message msg in lstMessages)
                    {
                        if (limit == 0)
                            break;

                        UserMessage uMsg = new UserMessage();
                        uMsg.Content = msg.Content;
                        uMsg.Date = msg.Date;
                        uMsg.Username = msg.User.Name;

                        lstUMessages.Add(uMsg);

                        limit--;
                    }
                }
            }
            catch
            {
            }

            return lstUMessages;
        }
Beispiel #7
0
        /// <summary>
        /// Obtient la liste des joueurs dans la salle spécifiée
        /// </summary>
        /// <param name="room"></param>
        /// <returns>Liste des joueurs</returns>
        public List<string> GetRoomPlayers(Guid room)
        {
            List<string> lstPlayers = new List<string>();

            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    int rId = context.Room.First(p => p.Token == room).RoomId;
                    var lstPrs = context.PlayerRoomState.Where(p => p.RoomId == rId);

                    foreach (PlayerRoomState prs in lstPrs)
                        lstPlayers.Add(prs.User.Name);
                }
            }
            catch
            {
            }

            return lstPlayers;
        }
Beispiel #8
0
        public void TakePlayerDisconnectionDecision(Guid playerToken, Guid gameToken, bool continueGame)
        {
            using (var context = new MilleBornesEntities())
            {
                var playerEntity = context.User
                    .Where(us => us.LoggedInUser != null)
                    .SingleOrDefault(us => us.LoggedInUser.Token == playerToken);
                if (playerEntity == null)
                {
                    throw new FaultException("Le joueur n'est pas valide ou est hors-ligne.");
                }

                var game = context.Game
                    .SingleOrDefault(rm => rm.Token == gameToken);
                if (game == null)
                {
                    throw new FaultException("La partie n'est pas trouvée.");
                }

                if (game.Room == null)
                {
                    throw new FaultException("La partie n'est pas associée à une salle.");
                }

                if (game.Room.Count > 1)
                {
                    throw new FaultException("La partie est associée à plusieurs salles.");
                }

                if (game.Room.First().MasterUserId != playerEntity.UserId)
                {
                    throw new FaultException("Seul le maître de la salle peut prendre la décision.");
                }

                if (!game.IsTakingDisconnectDecision)
                {
                    throw new FaultException("La partie n'est pas en attente d'une décision.");
                }

                if (continueGame)
                {
                    var disconnectedPlayers = GetPlayersInGame(game)
                        .Where(pg => !ValidatePlayerHeartbeat(pg));

                    foreach (var player in disconnectedPlayers)
                    {
                        player.Order = -player.Order;
                    }

                    game.IsTakingDisconnectDecision = false;
                }
                else
                {
                    EndGame(game, GameEndReason.PLAYER_DISCONNECTION);
                    game.IsTakingDisconnectDecision = false;
                }

                context.SaveChanges();
            }
        }
Beispiel #9
0
        public bool SendGameMessage(Guid playerToken, Guid gameToken, string message)
        {
            using (var context = new MilleBornesEntities())
            {
                var player = GetPlayerFromToken(context, playerToken);

                if (player == null)
                {
                    throw new FaultException("Le joueur n'est pas trouvé.");
                }

                var game = context.Game
                    .SingleOrDefault(gm => gm.Token == gameToken);

                if (game == null)
                {
                    throw new FaultException("La partie n'est pas trouvée.");
                }

                if (!GetPlayersInGame(game).Any(pg => pg.UserId == player.UserId))
                {
                    throw new FaultException("Le joueur n'est pas dans la partie.");
                }

                game.Message.Add(new Message() 
                {
                    UserId = player.UserId,
                    Type = MessageType.GAME,
                    Date = DateTime.UtcNow,
                    Content = message
                });

                try
                {
                    context.SaveChanges();
                    return true;
                }
                catch (System.Data.Entity.Infrastructure.DbUpdateException dbue)
                {
                    return false;
                }
            }
        }
Beispiel #10
0
        public GameState GetState(Guid playerToken, Guid gameToken)
        {
            using (var context = new MilleBornesEntities())
            {
                var player = GetPlayerFromToken(context, playerToken);

                if (player == null)
                {
                    throw new FaultException("Le joueur n'est pas trouvé.");
                }

                var game = context.Game
                    .SingleOrDefault(gm => gm.Token == gameToken);

                if (game == null)
                {
                    throw new FaultException("La partie n'est pas trouvée.");
                }

                var playerGame = GetPlayersInGame(game)
                    .SingleOrDefault(pg => pg.UserId == player.UserId);
                if (playerGame == null)
                {
                    throw new FaultException("Le joueur n'est pas dans la partie.");
                }

                if (!playerGame.HasJoined)
                {
                    throw new FaultException("Le joueur n'a pas rejoint la partie.");
                }

                if (!ValidatePlayerHeartbeat(playerGame))
                {
                    throw new FaultException("Le heartbeat du joueur a expiré.");
                }

                var drawCardEvents = game.GameEvent
                    .Where(ge => ge.Type == GameEventType.DRAW_CARD)
                    .Cast<DrawCardEvent>()
                    .Where(dc => dc.PlayerId == player.UserId)
                    .Where(dc => dc.PlayCardEvent.Count == 0);

                var teamStates = GetTeamsState(game);

                var ownTeamState = teamStates
                    .Single(ts => ts.TeamIndex == playerGame.Team);
                var opponentsTeamStates = teamStates
                    .Where(ts => ts.TeamIndex != playerGame.Team)
                    .ToArray();

                var currentTurnPlayer = GetLastPlayerChangeEvent(game);
                var currentTurnPlayerGame = GetPlayersInGame(game)
                    .SingleOrDefault(pg => pg.UserId == currentTurnPlayer.NewPlayerId);

                GameState gameState = new GameState()
                {
                    GameEnd = game.EndReason.HasValue,
                    GameEndReason = game.EndReason,
                    WaitingForDecision = game.IsTakingDisconnectDecision,
                    CardsInHand = drawCardEvents.Select(dc => new GameCard()
                    {
                        CardId = dc.CardIndex,
                        Token = dc.Token
                    })
                    .ToArray(),
                    OwnTeamState = ownTeamState,
                    OpponentsTeamStates = opponentsTeamStates,
                    Players = game.PlayerGame.Select(pg => new GamePlayer()
                    {
                        Name = pg.User.Name,
                        Order = pg.Order,
                        TeamIndex = pg.Team
                    })
                    .ToArray(),
                    CurrentTeam = currentTurnPlayerGame.Team,
                    CurrentPlayer = currentTurnPlayerGame.Order,
                    IsOwnTeamTurn = currentTurnPlayerGame.Order == playerGame.Order,
                    IsOwnTurn = currentTurnPlayerGame.Team == playerGame.Team,
                    OwnTeamIndex = playerGame.Team,
                    OwnPlayerOrder = playerGame.Order
                };

                return gameState;
            }
        }
Beispiel #11
0
        /// <summary>
        /// Obtient les utilisateurs connectés.
        /// </summary>
        /// <returns>[UserName] => [Connected?]</returns>
        public Dictionary<string, byte> GetLoggedUsers()
        {
            Dictionary<string, byte> users = new Dictionary<string, byte>();

            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    IQueryable<LoggedInUser> lstLogged = context.LoggedInUser;
                    Dictionary<string, byte> lstUsers = new Dictionary<string, byte>();

                    foreach (LoggedInUser u in lstLogged)
                    {
                        KeyValuePair<string, byte> kp;

                        if (GetHeartBeat(u.Token))
                        {
                            if (u.User.PlayerGame.Count(p => (DateTime.UtcNow - p.LastHeartbeat).TotalMilliseconds < DELAY_MS_HEARTBEAT * 10) > 0)
                                kp = new KeyValuePair<string, byte>(u.User.Name, 2);
                            else if (u.User.PlayerRoomState.Count > 0)
                                kp = new KeyValuePair<string, byte>(u.User.Name, 1);
                            else
                                kp = new KeyValuePair<string, byte>(u.User.Name, 0);

                            lstUsers.Add(kp.Key, kp.Value);
                        }
                    }

                    foreach (var uu in lstUsers.OrderBy(p => p.Value))
                        users.Add(uu.Key, uu.Value);
                }
            }
            catch
            {
            }

            return users;
        }
Beispiel #12
0
        /// <summary>
        /// Obtient le token de la game en cours.
        /// </summary>
        /// <param name="room">Room</param>
        /// <returns>null si aucune partie. Sinon le Guid :^)</returns>
        public Guid? GetCurrentGameToken(Guid room)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    Room r = context.Room.First(p => p.Token == room);

                    if (!r.Started)
                        return null;

                    var lstPRS = r.PlayerRoomState;

                    foreach (PlayerRoomState prs in lstPRS)
                    {
                        DateTime hb = context.LoggedInUser.First(p => p.UserId == prs.UserId).LastHeartbeat;
                        hb.AddSeconds(30);
                    }

                    return r.Game.Token;
                }
            }
            catch
            {
            }

            return null;
        }
Beispiel #13
0
        /// <summary>
        /// Définit le nom de la salle.
        /// </summary>
        /// <param name="room"></param>
        /// <param name="newName"></param>
        /// <returns></returns>
        public bool SetRoomName(Guid room, string newName)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    context.Room.First(p => p.Token == room).Name = newName;
                    context.SaveChanges();

                    return true;
                }
            }
            catch
            {
            }

            return false;
        }
Beispiel #14
0
        /// <summary>
        /// Obtient l'index de l'équipe courante (0-1-2)
        /// </summary>
        /// <param name="player"></param>
        /// <returns></returns>
        public int GetCurrentTeamIndex(Guid player)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    int uId = context.LoggedInUser
                        .First(p => p.Token == player)
                        .UserId;

                    return context.PlayerRoomState.First(p => p.UserId == uId).Team;
                }
            }
            catch
            {
            }

            return -1;
        }
Beispiel #15
0
        /// <summary>
        /// Défini l'équipe laquelle le joueur join.
        /// </summary>
        /// <param name="player"></param>
        /// <param name="room"></param>
        /// <param name="team"></param>
        /// <returns></returns>
        public bool SetTeam(Guid player, Guid room, int team)
        {
            if (team > 2)
                return false;

            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    var user = context.LoggedInUser
                        .First(p => p.Token == player);

                    PlayerRoomState prs = context.PlayerRoomState.First(p => p.UserId == user.UserId);
                    prs.Team = team;

                    context.SaveChanges();

                    SendRoomMessage(Guid.ParseExact("00000000-0000-0000-0000-000000000000", "D"),
                        room,
                        "**Le joueur " + user.User.Name + " a rejoint l'équipe #" + (team + 1).ToString() + ". **");

                    return true;
                }
            }
            catch
            {
            }

            return false;
        }
Beispiel #16
0
        /// <summary>
        /// Obtient le nom du master muahahahahaha
        /// </summary>
        /// <param name="room"></param>
        /// <returns></returns>
        public string GetMasterName(Guid room)
        {
            try
            {
                using (MilleBornesEntities tities = new MilleBornesEntities())
                {
                    int mid = tities.Room.First(p => p.Token == room).MasterUserId;

                    return tities.User
                        .First(p => p.UserId == mid)
                        .Name;
                }
            }
            catch
            {
            }

            return "";
        }
Beispiel #17
0
        /// <summary>
        /// Vérifie la connexion de l'utilisateur.
        /// </summary>
        /// <param name="username">Nom d'utilisateur</param>
        /// <param name="password">Mot de passe</param>
        /// <returns>Retourne le Guid de l'utilisateur.</returns>
        /// <remarks>Si cet appel retourne null, c'est que l'utilisateur n'a pas réussi à se logger.</remarks>
        public Guid? Login(string username, string password)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    string hashedPassword = GetSHA1HashString(password);
                    var lstUsers = new List<User>();

                    lstUsers = new List<User>(context.User
                        .Where(p => p.Name == username.Trim()
                        && p.PasswordHash.ToLower() == hashedPassword.ToLower()));

                    if (lstUsers.Count() < 1)
                        return null;

                    User user = lstUsers.First();

                    LoggedInUser loggedInfo = new LoggedInUser();
                    loggedInfo.LoginDate = DateTime.UtcNow;
                    Guid guid = Guid.NewGuid();

                    loggedInfo.Token = guid;
                    loggedInfo.UserId = user.UserId;
                    DateTime hb = DateTime.UtcNow;
                    loggedInfo.LastHeartbeat = hb.AddMilliseconds(DELAY_MS_HEARTBEAT * 10);

                    LoggedInUser old = context.LoggedInUser.Find(loggedInfo.UserId);

                    if (old == null)
                    {
                        context.LoggedInUser.Add(loggedInfo);
                    }
                    else
                    {
                        old.Token = loggedInfo.Token;
                        old.LoginDate = DateTime.UtcNow;
                        old.LastHeartbeat = DateTime.UtcNow;
                    }

                    context.SaveChanges();
                    return guid;
                }
            }
            catch
            {
                return null;
            }
        }
Beispiel #18
0
        /// <summary>
        /// Obtient les nouveaux messages de name
        /// </summary>
        /// <param name="name">Utilisateur</param>
        /// <returns>Liste des nouveaux messages.</returns>
        public List<UserMessage> GetNewMessageFrom(Guid player, string name)
        {
            List<UserMessage> lstMessages = new List<UserMessage>();
            
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    // Récupère les ids...
                    LoggedInUser receiver = context.LoggedInUser.First(p => p.Token == player);
                    User sender = context.User.First(p => p.Name.Trim() == name.Trim());

                    IQueryable<PrivateMessage> lstNewMessages = context.PrivateMessage.Where(p => p.ReceiverUserId == receiver.UserId
                                                                && p.SenderUserId == sender.UserId
                                                                && p.Read == false);

                    foreach (PrivateMessage pm in lstNewMessages)
                    {
                        UserMessage um = new UserMessage();
                        um.Content = pm.Message;
                        um.Date = pm.SentTime;
                        um.Username = name;

                        lstMessages.Add(um);
                        pm.Read = true;
                    }

                    context.SaveChanges();
                }
            }
            catch
            {
            }

            return lstMessages;
        }
Beispiel #19
0
        public Guid JoinGame(Guid player, Guid room)
        {
            using (var context = new MilleBornesEntities())
            {
                var playerEntity = context.User
                    .Where(us => us.LoggedInUser != null)
                    .SingleOrDefault(us => us.LoggedInUser.Token == player);
                if (playerEntity == null)
                {
                    throw new FaultException("Le joueur n'est pas valide ou est hors-ligne.");
                }

                var roomEntity = context.Room
                    .SingleOrDefault(rm => rm.Token == room);
                if (roomEntity == null)
                {
                    throw new FaultException("La salle n'est pas trouvée.");
                }

                var game = roomEntity.Game;
                if (game == null)
                {
                    throw new FaultException("Celle salle n'est pas associée à une partie en cours.");
                }

                var playerGame = game.PlayerGame
                    .SingleOrDefault(pg => pg.UserId == playerEntity.UserId);
                if (playerGame == null)
                {
                    throw new FaultException("Le joueur n'est pas dans cette partie.");
                }

                if (playerGame.HasJoined)
                {
                    throw new FaultException("Le joueur a déja rejoint la partie.");
                }

                playerGame.HasJoined = true;
                playerGame.LastHeartbeat = DateTime.UtcNow;
                context.SaveChanges();

                return game.Token;
            }
        }
Beispiel #20
0
        /// <summary>
        /// Vérifie si il y a de nouveaux messages pour l'utilisateur.
        /// </summary>
        /// <param name="player"></param>
        /// <returns>Renvoie une liste de username de gens qui ont des messages.</returns>
        public List<string> DoTheBigBastardThatWaveHisFlagHasNewMessageFromSomeoneIfSoTellMeLad(Guid player)
        {
            List<string> lstUsers = new List<string>();
            
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    LoggedInUser liu = context.LoggedInUser.First(p => p.Token == player);

                    var pms = context.PrivateMessage.Where(p => p.Receiver.UserId == liu.UserId
                                                 && p.Read == false);

                    HashSet<string> temp = new HashSet<string>();

                    foreach (PrivateMessage pm in pms)
                    {
                        temp.Add(pm.Sender.Name);
                    }

                    lstUsers = temp.ToList();
                }
            }
            catch
            {
            }

            return lstUsers;
        }
Beispiel #21
0
        public bool DoHeartbeat(Guid playerToken, Guid gameToken)
        {
            using (var context = new MilleBornesEntities())
            {
                var player = GetPlayerFromToken(context, playerToken);

                if (player == null)
                {
                    throw new FaultException("Le joueur n'est pas trouvé.");
                }

                var game = context.Game
                    .SingleOrDefault(gm => gm.Token == gameToken);

                if (game == null)
                {
                    throw new FaultException("La partie n'est pas trouvée.");
                }

                var playerGame = game.PlayerGame
                    .SingleOrDefault(pg => pg.UserId == player.UserId);
                if (playerGame == null)
                {
                    throw new FaultException("Le joueur n'est pas dans la partie.");
                }

                if (!playerGame.HasJoined)
                {
                    throw new FaultException("Le joueur n'a pas rejoint la partie.");
                }

                bool validPlayerHeartbeat = ValidatePlayerHeartbeat(playerGame);
                if (validPlayerHeartbeat)
                {
                    playerGame.LastHeartbeat = DateTime.UtcNow;
                    context.SaveChanges();
                }

                if (!CheckAllPlayersHeartbeat(game))
                {
                    context.SaveChanges();
                }

                return validPlayerHeartbeat;
            }
        }
Beispiel #22
0
        /// <summary>
        /// Envoie un nouveau message.
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="message"></param>
        /// <returns>True si succès.</returns>
        public bool SendPrivateMessage(Guid from, string to, string message)
        {
            bool ok = false;

            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    LoggedInUser user = context.LoggedInUser.First(p => p.Token == from);
                    int receiverId = context.User.First(p => p.Name.Trim() == to.Trim()).UserId;

                    PrivateMessage pm = new PrivateMessage();
                    pm.Message = message.Trim();
                    pm.Read = false;
                    pm.ReceiverUserId = receiverId;
                    pm.SenderUserId = user.UserId;
                    pm.SentTime = DateTime.UtcNow;

                    context.PrivateMessage.Add(pm);
                    context.SaveChanges();

                    ok = true;
                }
            }
            catch 
            {
            }

            return ok;
        }
Beispiel #23
0
        public PlayCardResult PlayCard(Guid gameToken, Guid playerToken, Guid cardToken, int targetTeamIndex)
        {
            using (var context = new MilleBornesEntities())
            {
                var player = GetPlayerFromToken(context, playerToken);

                if (player == null)
                {
                    throw new FaultException("Le joueur n'est pas trouvé.");
                }

                var game = context.Game
                    .SingleOrDefault(gm => gm.Token == gameToken);

                if (game == null)
                {
                    throw new FaultException("La partie n'est pas trouvée.");
                }

                if (!GetPlayersInGame(game).All(pg => pg.HasJoined))
                {
                    return PlayCardResult.NOT_ALL_PLAYERS_PRESENT;
                }

                if (game.IsTakingDisconnectDecision)
                {
                    throw new FaultException("La partie est en attente de décison de déconnection d'un joueur.");
                }

                var playerGame = GetPlayersInGame(game)
                    .SingleOrDefault(pg => pg.UserId == player.UserId);
                if (playerGame == null)
                {
                    throw new FaultException("Le joueur n'est pas dans la partie.");
                }

                if (!playerGame.HasJoined)
                {
                    throw new FaultException("Le joueur n'a pas rejoint la partie.");
                }

                if (!ValidatePlayerHeartbeat(playerGame))
                {
                    throw new FaultException("Le heartbeat du joueur à expiré.");
                }

                if (game.EndReason != null)
                {
                    throw new FaultException("La partie est terminée.");
                }

                var currentPlayerId = GetCurrentPlayerUserId(game);
                if (currentPlayerId != player.UserId)
                {
                    LogPlayCardError(
                        "ce n'est pas le tour du joueur {0}({1})",
                        playerToken.ToString("B"),
                        player.Name
                    );

                    return PlayCardResult.WRONG_TURN;
                }

                var card = game.GameEvent
                    .Where(ge => ge.Type == GameEventType.DRAW_CARD)
                    .Cast<DrawCardEvent>()
                    .Where(dc => dc.Token == cardToken)
                    .SingleOrDefault();

                if (card == null)
                {
                    LogPlayCardError(
                        "le jeton de carte {0} est introuvable pour la partie {1}",
                        cardToken.ToString("B"),
                        gameToken.ToString("B")
                    );

                    return PlayCardResult.WRONG_TOKEN;
                }

                if (card.PlayerId != player.UserId)
                {
                    LogPlayCardError(
                        "le jeton de carte {0} est introuvable pour le joueur {1}",
                        cardToken.ToString("B"),
                        playerToken.ToString("B")
                    );

                    return PlayCardResult.WRONG_TOKEN_PLAYER;
                }

                if (card.PlayCardEvent.Count != 0)
                {
                    LogPlayCardError(
                        "le joueur {0} à joué la carte {1} déja jouée",
                        playerToken.ToString("B"),
                        cardToken.ToString("B")
                    );
                    return PlayCardResult.ALREADY_PLAYED;
                }

                if (!CanPlayCard(game, card, playerGame.Team, targetTeamIndex))
                {
                    LogPlayCardError(
                        "le joueur {0} à tenté de jouer la carte {1} sur l'équipe {2} dans un état invalide.",
                        playerToken.ToString("B"),
                        cardToken.ToString("B"),
                        targetTeamIndex
                    );
                    return PlayCardResult.CANNOT_PLAY;
                }

                PlayCardInGame(game, card, targetTeamIndex);
                context.SaveChanges();
                if (CheckGameEnd(game))
                {
                    context.SaveChanges();

                    LogMessage(
                        "Le joueur {0} joue la carte {1} sur l'équipe {2}",
                        playerToken.ToString("B"),
                        cardToken.ToString("B"),
                        targetTeamIndex
                    );
                    LogMessage(
                        "La partie {0} est terminée par la raison {1}",
                        game.Token,
                        game.EndReason
                    );

                    return PlayCardResult.SUCCESS;
                }

                DrawNewCardToPlayer(game, player);

                var newPlayer = player;
                var playedCardDef = CardDefinitions.Cards
                    .Single(cd => cd.CardId == card.CardIndex);
                if (playedCardDef.CardType != CardType.EFFECT_INVINCIBLE)
                {
                    newPlayer = GoToNextPlayer(game);
                }

                context.SaveChanges();
                LogMessage(
                    "Le joueur {0} joue la carte {1} sur l'équipe {2}, le nouveau joueur est {3}",
                    playerToken.ToString("B"),
                    cardToken.ToString("B"),
                    targetTeamIndex,
                    newPlayer.LoggedInUser.Token.ToString("B")
                );
                return PlayCardResult.SUCCESS;
            }
        }
Beispiel #24
0
        private User GetPlayerFromToken(MilleBornesEntities context, Guid playerToken)
        {
            var loggedInUser = context.LoggedInUser
                .SingleOrDefault(lu => lu.Token == playerToken);

            if (loggedInUser == null)
            {
                return null;
            }

            return loggedInUser.User;
        }
Beispiel #25
0
        public UserMessage[] GetGameMessagesSinceDate(Guid gameToken, DateTime sinceDateUtc)
        {
            using (var context = new MilleBornesEntities())
            {
                var game = context.Game
                    .SingleOrDefault(gm => gm.Token == gameToken);

                if (game == null)
                {
                    throw new FaultException("La partie n'est pas trouvée.");
                }

                var messagesSinceDate = game.Message
                    .Where(msg => msg.Date > sinceDateUtc)
                    .Select(msg => new UserMessage()
                    {
                        Username = msg.User.Name,
                        Date = msg.Date,
                        Content = msg.Content
                    })
                    .ToArray();

                return messagesSinceDate;
            }
        }
Beispiel #26
0
        /// <summary>
        /// Détermine si on est toujours en ligne.
        /// </summary>
        /// <remarks>Contrairement à celui dans UserService, celui là ne rafraichi pas le hearbeat.</remarks>
        /// <param name="userToken"></param>
        /// <returns></returns>
        private bool GetHeartBeat(Guid userToken)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    LoggedInUser loggedUser = context.LoggedInUser.First(p => p.Token == userToken);

                    // Différence de temps.
                    TimeSpan dt = DateTime.UtcNow - loggedUser.LastHeartbeat;
                    return (dt.TotalMilliseconds <= DELAY_MS_HEARTBEAT * 10);
                }
            }
            catch
            {
                return false;
            }
        }
Beispiel #27
0
        /// <summary>
        /// Détermine si la connexion est toujours vivante.
        /// </summary>
        /// <param name="userToken"></param>
        /// <returns>True si c'est le cas, false autrement.</returns>
        /// <remarks>Tolérance d'un skip de heartbeat. 
        /// Valeur par défaut 1 heartbeat == 2000ms</remarks>
        public bool Heartbeat(Guid userToken)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    var lstLoggedUsers = context.LoggedInUser.Where(p => p.Token == userToken);
                    LoggedInUser liu = lstLoggedUsers.First();

                    // Différence de temps.
                    TimeSpan dt = DateTime.UtcNow - liu.LastHeartbeat;

                    liu.LastHeartbeat = DateTime.UtcNow;
                    context.SaveChanges();

                    return (dt.TotalMilliseconds <= DELAY_MS_HEARTBEAT * 10);
                }
            }
            catch
            {
                return false;
            }
        }
Beispiel #28
0
        /// <summary>
        /// Obtient les messages de la salle sélectionnée.
        /// </summary>
        /// <param name="room"></param>
        /// <param name="limit"></param>
        /// <returns>Liste de message.</returns>
        public List<UserMessage> GetRoomMessages(Guid room, int limit)
        {
            List<Models.UserMessage> lstUMessages = new List<UserMessage>();

            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    //var lstMessages = context.Room.First(p => p.Token == room)
                    //    .Message;

                    //    //.OrderByDescending(o => o.MessageId)
                    //    //.ToList();
                    
                    //foreach (Message msg in lstMessages)
                    //{
                    //    if (limit == 0)
                    //        break;

                    //    UserMessage uMsg = new UserMessage();
                    //    uMsg.Content = msg.Content;
                    //    uMsg.Date = msg.Date;
                    //    uMsg.Username = msg.User.Name;

                    //    lstUMessages.Add(uMsg);

                    //    limit--;
                    //}
                }
            }
            catch
            {
            }

            return lstUMessages;
        }
        public Models.PlayerConfigEntry[] GetPlayerConfig(Guid roomToken)
        {
            using (var context = new MilleBornesEntities())
            {
                var room = context.Room
                    .SingleOrDefault(rm => rm.Token == roomToken);
                if (room == null)
                {
                    throw new FaultException("La salle n'est pas trouvée.");
                }

                var playerConfig = room.PlayerRoomState
                    .Select((prs, inx) => new PlayerConfigEntry()
                    {
                        UserToken = prs.User.LoggedInUser.Token,
                        Order = prs.Order,
                        Team = prs.Team
                    })
                    .ToArray();

                return playerConfig;
            }
        }
Beispiel #30
0
        /// <summary>
        /// Envoie un mess
        /// </summary>
        /// <param name="player"></param>
        /// <param name="room"></param>
        /// <param name="message"></param>
        /// <returns>True si envoyé avec succès.</returns>
        public bool SendGlobalMessage(Guid player, string message)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    int userId = context.LoggedInUser.Where(p => p.Token == player)
                        .ToList().First().UserId;

                    Message msg = new Message();
                    msg.Content = message;
                    msg.Date = DateTime.UtcNow;
                    msg.UserId = userId;
                    msg.Type = MessageType.GLOBAL;

                    context.Message.Add(msg);
                    context.SaveChanges();
                }

                return true;
            }
            catch
            {
                return false;
            }
        }