示例#1
0
        /// <summary>Translates from <see cref="PlayerDocument"/> to a <see cref="Thing"/>.</summary>
        /// <param name="player">The player.</param>
        /// <param name="playerDocument">The player document.</param>
        private void TranslateFromPlayerDocument(ref Thing player, PlayerDocument playerDocument)
        {
            foreach (var persistedAsBehavior in playerDocument.Behaviors.ToArray())
            {
                player.Behaviors.Add(persistedAsBehavior as Behavior);
            }

            foreach (var persistedStat in playerDocument.Stats)
            {
                player.Stats.Add(persistedStat.Key, persistedStat.Value as GameStat);
            }

            foreach (var persistedSecondary in playerDocument.SecondaryStats)
            {
                player.Attributes.Add(persistedSecondary.Key, persistedSecondary.Value as GameAttribute);
            }

            foreach (var persistedSkill in playerDocument.Skills)
            {
                player.Skills.Add(persistedSkill.Key, persistedSkill.Value as GameSkill);
            }

            foreach (var persistedChild in playerDocument.SubThings)
            {
                player.Children.Add(persistedChild as Thing);
            }
        }
示例#2
0
        public async Task AddAsync(PlayerAdd player)
        {
            if (player == null)
            {
                throw new ArgumentNullException(nameof(player), "Player add model must be provided.");
            }

            var collectionName = CollectionResolver.GetName <PlayerDocument>();

            PlayerDocument document = PlayerDocument.FromCoreAddEntity(player);

            await GetMongoDbContext().InsertOneAsync(document);

            Logger.LogDebug($"Added player '{player.NflId}' as '{document.Id}' to '{collectionName}' collection.");
        }
        void initPlayer(int source)
        {
            Player         player = new PlayerList()[source];
            PlayerDocument user   = connection.Players.PlayerInDatabase(source);

            if (user != null)
            {
                // Load player information
                Debug.WriteLine("We know that dude");
            }
            else
            {
                connection.Players.AddNewUser(player);
            }
        }
        public PlayerViewModel(PlayerDocument doc, string myUserId)
        {
            Position     = doc.Position;
            Cash         = doc.Cash;
            Bet          = doc.Bet;
            UserId       = doc.UserId;
            Name         = doc.Name;
            IsMe         = UserId == myUserId;
            CurrentTurn  = doc.CurrentTurn;
            IsSmallBlind = doc.IsSmallBlind;
            IsBigBlind   = doc.IsBigBlind;
            IsInGame     = doc.Cards.Count != 0;
            AvatarUrl    = AvatarsService.GetUrlById(doc.AvatarId);

            if (IsMe)
            {
                Cards = doc.Cards.Select(x => new CardViewModel(x)).ToList();
            }
            else
            {
                Cards = new List <CardViewModel>();
            }
        }
示例#5
0
        /// <summary>Save the whole player Thing (not just this PlayerBehavior).</summary>
        public void SaveWholePlayer()
        {
            var player = this.Parent;

            if (player != null)
            {
                this.Save();

                // Set the behavior id to correspond to the database id of the player.
                // @@@ TODO: Why? Shouldn't Behavior IDs be unique too?
                var playerBehaviors = player.Behaviors.AllBehaviors;
                foreach (var behavior in playerBehaviors)
                {
                    behavior.ID = this.PlayerData.ID;
                }

                // Link our unique player ID and PlayerBehavior ID but in a RavenDB-friendly format.
                player.ID = "player/" + this.PlayerData.ID;

                // Create a PlayerDocument to be saved.
                var bundle = new PlayerDocument
                {
                    DatabaseId      = this.PlayerData.ID,
                    Name            = player.Name,
                    LastUpdatedDate = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ"),
                    Behaviors       = new List <IPersistsWithPlayer>(),
                    Stats           = new Dictionary <string, IPersistsWithPlayer>(),
                    SecondaryStats  = new Dictionary <string, IPersistsWithPlayer>(),
                    Skills          = new Dictionary <string, IPersistsWithPlayer>(),
                    SubThings       = new List <IThing>(),
                    PlayerPrompt    = this.Prompt,
                };

                bundle.Behaviors.AddRange(playerBehaviors);

                foreach (var stat in player.Stats)
                {
                    bundle.Stats.Add(stat.Key, stat.Value);
                }

                foreach (var attribute in player.Attributes)
                {
                    bundle.SecondaryStats.Add(attribute.Key, attribute.Value);
                }

                foreach (var skill in player.Skills)
                {
                    bundle.Skills.Add(skill.Key, skill.Value);
                }

                foreach (var child in player.Children)
                {
                    // Do not save any player as a sub-document of this one.
                    if (child.Behaviors.FindFirst <PlayerBehavior>() == null)
                    {
                        bundle.SubThings.Add(child);
                    }
                }

                // Save to the document database
                DocumentManager.SavePlayerDocument(bundle);
            }
        }
示例#6
0
        /// <summary>Called upon authentication of a session.</summary>
        /// <param name="session">The authenticated session.</param>
        public void OnSessionAuthenticated(Session session)
        {
            // If there was already a connected player for this new, authentic user session,
            // kick the old one (as it may have been a prior disconnect or whatnot).
            PlayerBehavior previousPlayer = this.FindLoggedInPlayer(session.UserName);

            if (previousPlayer != null)
            {
                var msg = "Duplicate player match, kicking session id " + previousPlayer.SessionId;
                this.SystemHost.UpdateSystemHost(this, msg);

                var existingUserControlledBehavior = previousPlayer.Parent.Behaviors.FindFirst <UserControlledBehavior>();
                if (existingUserControlledBehavior != null)
                {
                    existingUserControlledBehavior.Controller.Write("Another connection has logged in as you; closing this connection.");
                }

                // @@@ TEST: Ensure this closes the connection correctly, etc; used to be rigged
                //     dangerously directly through the ServerManager.
                previousPlayer.LogOut();
                this.RemovePlayer(previousPlayer.Parent);
            }

            bool wasPlayerMissingDocument = false;

            // If this session doesn't have a player thing attached yet, load it up.  Note that
            // for situations like character creation, we might already have our Thing, so we
            // don't want to load a duplicate version of the just-created player Thing.
            if (session.Thing == null)
            {
                var playerBehavior = new PlayerBehavior();
                playerBehavior.Load(session.UserName);

                var player = new Thing(null)
                {
                    Name = playerBehavior.PlayerData.DisplayName
                };

                // Make sure that the playerBehavior has a parent set.
                playerBehavior.Parent = player;

                // Load game data from disk (RavenDb/NoSQL)
                PlayerDocument pd = this.LoadPlayerDocument(playerBehavior.PlayerData.ID);
                if (pd == null)
                {
                    // If we are here, this means that the player that we are trying to
                    // load does not have a corresponding player document in the NoSQL
                    // (RavenDb) store. Let's go and create a player document with default
                    // values.
                    player                = PrepareBaseCharacter(session);
                    player.Name           = playerBehavior.PlayerData.DisplayName;
                    playerBehavior.Parent = player;
                    playerBehavior.CreateMissingPlayerDocument();

                    var sb = new StringBuilder();

                    sb.AppendLine("This character is missing gaming data.");
                    sb.AppendFormat("The MUD engine is creating a default game settings for {0}.", playerBehavior.PlayerData.DisplayName);
                    sb.Append(Environment.NewLine);
                    sb.AppendLine("The system will now log you out. Please login again, to continue playing.");

                    session.Write(sb.ToString());

                    playerBehavior.LogOut();
                }

                // Get SensesBehavior and UserControlledBehavior from the PlayerDocument.
                var sensesBehavior         = pd.Behaviors.OfType <SensesBehavior>().FirstOrDefault();
                var userControlledBehavior = pd.Behaviors.OfType <UserControlledBehavior>().FirstOrDefault();

                // Setup the controlled behavior controller.
                userControlledBehavior.Controller = session;

                // Initialize the player behavior event processor.
                playerBehavior.InitEventProcessor(sensesBehavior, userControlledBehavior);

                // Get the player behavior with the game data
                var persistedPlayerBehavior = pd.Behaviors.OfType <PlayerBehavior>().FirstOrDefault();

                // Get data from the persisted player behavior and merge it into the manually created one
                playerBehavior.Gender    = persistedPlayerBehavior.Gender;
                playerBehavior.Race      = persistedPlayerBehavior.Race;
                playerBehavior.SessionId = session.ID;
                playerBehavior.Name      = session.UserName;
                playerBehavior.Prompt    = pd.PlayerPrompt;
                playerBehavior.RoleData  = persistedPlayerBehavior.RoleData;
                playerBehavior.ID        = persistedPlayerBehavior.ID;

                // We don't need the persisted player behavior anymore, so remove it
                pd.Behaviors.Remove(persistedPlayerBehavior);

                if (!wasPlayerMissingDocument)
                {
                    // Put all the persisted game data onto the right objects.
                    this.TranslateFromPlayerDocument(ref player, pd);

                    // Make sure to add the player behavior to the player Thing object.
                    playerBehavior.Parent = player;
                    player.Behaviors.Add(playerBehavior);
                    player.ID = "player/" + playerBehavior.ID;
                }

                if (playerBehavior.LogIn(session))
                {
                    lock (this.lockObject)
                    {
                        if (!this.playersList.Contains(playerBehavior))
                        {
                            this.playersList.Add(playerBehavior);
                        }
                    }

                    // Determine the screen buffer size.
                    if (session.Connection != null)
                    {
                        if (userControlledBehavior.PagingRowLimit >= 0)
                        {
                            session.Connection.PagingRowLimit = userControlledBehavior.PagingRowLimit;
                        }
                        else
                        {
                            int terminalHeight = session.Terminal.Height;

                            // If a broken client doesn't provide a valid terminal height, who knows
                            // what it might contain. In that case, default to 0 (no paging).
                            // 100 is an arbitrary realistic number. If this changes, the "buffer"
                            // command should also be changed for consistency. Or define the
                            // max/min as constants somewhere.
                            if (terminalHeight >= 0 && terminalHeight <= 100)
                            {
                                session.Connection.PagingRowLimit = session.Terminal.Height;
                            }
                            else
                            {
                                session.Connection.PagingRowLimit = 0;
                            }
                        }
                    }

                    session.Thing = player;

                    // @@@ HACK: Add player to Krondor's first room
                    PlacesManager.Instance.World.Children[0].Children[0].Add(player);

                    // Finally give the player some initial sensory feedback by having them look.
                    CommandManager.Instance.EnqueueAction(new ActionInput("look", userControlledBehavior.Controller));
                }
                else
                {
                    // @@@ TODO: Login denied? Back out of the session, disconnect, etc.
                    throw new NotImplementedException("Cancellation of login event is not yet supported.");
                }
            }

            // Finally, if the newly-logged in character replaced an old connection, notify the new
            // user of the problem.  We could also vary behavior/logging based on whether the IP
            // addresses match; same IP is safer to assume as replaced connection instead of breach.
            if (previousPlayer != null)
            {
                // @@@ TODO: Implement
            }
        }
示例#7
0
 public async Task UpdatePlayerInformation(string id, Player player)
 {
     _validation.ValidatePlayer(player);
     var playerDoc = PlayerDocument.GenerateFromDomain(id, player);
     await _cosmosStore.UpdateAsync(playerDoc);
 }
示例#8
0
 public async Task AddPlayer(Player player)
 {
     _validation.ValidatePlayer(player);
     var playerDoc = PlayerDocument.GenerateFromDomain(Guid.NewGuid().ToString(), player);
     await _cosmosStore.UpsertAsync(playerDoc);
 }