コード例 #1
0
        /// <summary>
        /// This returns any unread messages for the User.
        /// If no unread messages exist an empty array is returned.
        /// </summary>
        /// <remarks>This function always fetches fresh values from database and is not cached.</remarks>
        /// <returns>Array of Message objects</returns>
        public virtual IEnumerable <Message> GetUnreadMessages()
        {
            // Ensure that the messages are freshly loaded from the database by querying database directly
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            return((from m in db.Messages
                    where m.RecipientUserId == this.UserId &&
                    !m.Received &&
                    m.VisibleToRecipient
                    select m).AsEnumerable());
        }
コード例 #2
0
        /// <summary>
        /// Completely repairs this ship.
        /// </summary>
        public void Repair()
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            this.DamageEngine = 0;
            this.DamageHull   = 0;
            this.DamageShield = 0;
            this.DamageWeapon = 0;

            db.SaveChanges();
        }
コード例 #3
0
        /// <summary>
        /// Clears the reset password code fields
        /// </summary>
        public virtual void ClearResetPasswordCode()
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // Clear out code (it's been used)
            this.user.PasswordResetCode       = null;
            this.user.PasswordResetExpiration = null;

            // Save database changes
            db.SaveChanges();
        }
コード例 #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GameManager"/> class.
        /// </summary>
        /// <param name="username">The username of the currently logged in user.</param>
        public GameManager(string username)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();
            var matchingUsers           = (from u in db.Users where u.UserName == username select u);

            if (!matchingUsers.Any())
            {
                throw new ArgumentException("Invalid username in GameManager", "username");
            }

            this.currentUser = matchingUsers.Single();
        }
コード例 #5
0
ファイル: Player.cs プロジェクト: jcsston/CosmoMonger
        /// <summary>
        /// Creates the starting ship.
        /// Note, changes are not submitted to database
        /// </summary>
        /// <param name="startingSystem">The starting system.</param>
        public void CreateStartingShip(CosmoSystem startingSystem)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            if (this.Ship != null)
            {
                throw new InvalidOperationException("Player already has a ship");
            }

            // Create new player ship
            this.Ship = startingSystem.CreateShip(Player.StartingShip);
        }
コード例 #6
0
        /// <summary>
        /// Removes a user from the membership data source.
        /// </summary>
        /// <param name="username">The name of the user to delete.</param>
        /// <param name="deleteAllRelatedData">Must be true. Only supports deleting all user data from database.</param>
        /// <exception cref="ArgumentException">An ArgumentException for deleteAllRelatedData is thrown if deleteAllRelatedData is false.</exception>
        /// <returns>
        /// true if the user was successfully deleted; otherwise, false.
        /// </returns>
        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            if (!deleteAllRelatedData)
            {
                throw new ArgumentException("Must delete all related data to user", "deleteAllRelatedData");
            }

            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();
            User matchingUser           = (from u in db.Users
                                           where u.UserName == username
                                           select u).SingleOrDefault();

            if (matchingUser != null)
            {
                ////db.Log = Console.Out;

                // We have to delete all objects in the database related to this user
                var playerShips   = (from p in db.Players where p.User == matchingUser select p.Ship);
                var playerShipIds = (from p in db.Players where p.User == matchingUser select p.Ship.ShipId);
                db.PlayerRecords.DeleteAllOnSubmit(from r in db.PlayerRecords where r.Player.User == matchingUser select r);
                db.Players.DeleteAllOnSubmit(from p in db.Players where p.User == matchingUser select p);
                List <int> playerCombatIds = (from c in db.Combats
                                              where playerShipIds.Contains(c.AttackerShipId) ||
                                              playerShipIds.Contains(c.DefenderShipId)
                                              select c.CombatId).ToList();
                db.CombatGoods.DeleteAllOnSubmit(from g in db.CombatGoods where playerCombatIds.Contains(g.CombatId) select g);
                db.Combats.DeleteAllOnSubmit(from c in db.Combats where playerCombatIds.Contains(c.CombatId) select c);
                db.ShipGoods.DeleteAllOnSubmit(from g in db.ShipGoods where playerShips.Contains(g.Ship) select g);
                db.Ships.DeleteAllOnSubmit(playerShips);
                db.BuddyLists.DeleteAllOnSubmit(from b in db.BuddyLists
                                                where b.FriendId == matchingUser.UserId ||
                                                b.UserId == matchingUser.UserId
                                                select b);
                db.IgnoreLists.DeleteAllOnSubmit(from i in db.IgnoreLists
                                                 where i.AntiFriendId == matchingUser.UserId ||
                                                 i.UserId == matchingUser.UserId
                                                 select i);
                db.Messages.DeleteAllOnSubmit(from m in db.Messages
                                              where m.RecipientUserId == matchingUser.UserId ||
                                              m.SenderUserId == matchingUser.UserId
                                              select m);
                db.Users.DeleteOnSubmit(matchingUser);

                // Save database changes
                db.SaveChanges();

                ////db.Log = null;

                return(true);
            }

            return(false);
        }
コード例 #7
0
        /// <summary>
        /// Gets the nearest system with a bank. May return the system the ship currently is in.
        /// </summary>
        /// <returns>The a reference to the nearest system with a bank</returns>
        public CosmoSystem GetNearestBankSystem()
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            var systemsWithBank = (from s in db.CosmoSystems
                                   where s.HasBank
                                   orderby Math.Sqrt(Math.Pow(this.CosmoSystem.PositionX - s.PositionX, 2)
                                                     + Math.Pow(this.CosmoSystem.PositionY - s.PositionY, 2))
                                   select s);

            return(systemsWithBank.First());
        }
コード例 #8
0
        /// <summary>
        /// Checks the reset password code and returns if the code is valid or not.
        /// </summary>
        /// <param name="resetPasswordCode">The reset password code to check.</param>
        /// <returns>
        /// true if code is valid (code can only be used once), false if code is invalid/expired.
        /// </returns>
        public virtual bool CheckResetPasswordCode(string resetPasswordCode)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // Check if the passed in code matches the one in the database and code has not expired
            if (resetPasswordCode == this.user.PasswordResetCode && this.user.PasswordResetExpiration > DateTime.UtcNow)
            {
                // Code is good
                return(true);
            }

            return(false);
        }
コード例 #9
0
        /// <summary>
        /// Removes the passed in user from the users buddy list.
        /// If the user is not in the buddy list, an ArgumentException is thrown.
        /// </summary>
        /// <param name="buddy">The buddy to remove.</param>
        /// <exception cref="ArgumentException">Thrown when buddy not in the buddy list</exception>
        public virtual void RemoveBuddy(User buddy)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();
            BuddyList buddyToRemove     = (from bl in this.BuddyLists where bl.FriendId == buddy.UserId select bl).SingleOrDefault();

            if (buddyToRemove == null)
            {
                throw new ArgumentException("User is not in the buddy list", "buddy");
            }

            db.BuddyLists.DeleteOnSubmit(buddyToRemove);
            db.SaveChanges();
        }
コード例 #10
0
        /// <summary>
        /// Removes the passed in user from the users ignore list. If the user is not in the ignore list, an ArgumentException is thrown.
        /// </summary>
        /// <param name="ignoreUser">The ignore user.</param>
        /// <exception cref="ArgumentException">Thrown when the ignore user is not in the ignore list</exception>
        public virtual void RemoveIgnore(User ignoreUser)
        {
            CosmoMongerDbDataContext db   = CosmoManager.GetDbContext();
            IgnoreList antiFriendToRemove = (from il in this.IgnoreLists where il.AntiFriendId == ignoreUser.UserId select il).SingleOrDefault();

            if (antiFriendToRemove == null)
            {
                throw new ArgumentException("User is not in the ignore list", "ignoreUser");
            }

            db.IgnoreLists.DeleteOnSubmit(antiFriendToRemove);
            db.SaveChanges();
        }
コード例 #11
0
        /// <summary>
        /// Sends the forgotten password link which allows the user to click it and have their password reset
        /// to a new random password.
        /// </summary>
        /// <param name="baseResetPasswordUrl">The base reset password URL. Example: http://localhost:54084/Account/ResetPassword?username=jcsston&amp;resetPasswordCode=</param>
        public virtual void SendForgotPasswordLink(string baseResetPasswordUrl)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // Generate new password reset code
            Random rnd = new Random();

            byte[] passwordResetBytes = new byte[16];
            rnd.NextBytes(passwordResetBytes);
            this.user.PasswordResetCode       = Convert.ToBase64String(passwordResetBytes, Base64FormattingOptions.None);
            this.user.PasswordResetExpiration = DateTime.UtcNow.AddHours(5);

            // Build e-mail message
            MailMessage msg = new MailMessage();

            msg.From = new MailAddress("*****@*****.**", "CosmoMonger");
            msg.To.Add(this.Email);
            msg.Subject = "Reset Password Link for CosmoMonger";
            msg.Body    =
                "This email is a response to your request for a new password for your\n" +
                "CosmoMonger account. To confirm that you really want to change your\n" +
                "password, please click on the following link:\n\n" +
                baseResetPasswordUrl + this.user.PasswordResetCode + "\n\n" +
                "Clicking on this link will take you to a web page that will let you\n" +
                "reset your password. Once you've rest your password, you'll\n" +
                "be able to log in to your CosmoMonger account.\n" +
                "If you did not request a new password you can safely ignore this e-mail.\n" +
                "\nThank you for playing CosmoMonger.";
            try
            {
                // Send e-mail
                SmtpClient smtp = new SmtpClient();
                smtp.Send(msg);
            }
            catch (SmtpException ex)
            {
                Dictionary <string, object> props = new Dictionary <string, object>
                {
                    { "Error", ex },
                    { "UserId", this.user.UserId },
                    { "Email", this.Email },
                    { "Message", msg }
                };
                Logger.Write("Failed to send e-mail with password reset link", "Model", 700, 0, TraceEventType.Error, "SmtpException in CosmoMongerMemebershipUser.SendForgotPasswordLink", props);

                throw new InvalidOperationException("Failed to send password reset e-mail. Please try again, if the problem persists, please contact [email protected].", ex);
            }

            // Save database changes
            db.SaveChanges();
        }
コード例 #12
0
        /// <summary>
        /// This creates a player in the database and returns a reference to the new player.
        /// If the player already exists an ArgumentException will be thrown, referencing the name argument.
        /// </summary>
        /// <param name="name">The player name.</param>
        /// <param name="race">The race of the new Player.</param>
        /// <returns>The newly created Player</returns>
        public virtual Player CreatePlayer(string name, Race race)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();
            bool otherPlayerName        = (from p in db.Players
                                           where p.Name == name &&
                                           p.User != this
                                           select p).Any();

            if (otherPlayerName)
            {
                throw new ArgumentException("Player by another user with the same name already exists", "name");
            }

            Dictionary <string, object> props = new Dictionary <string, object>
            {
                { "Name", name },
                { "Race", race.Name }
            };

            Logger.Write("Creating player in User.CreatePlayer", "Model", 700, 0, TraceEventType.Information, "Creating Player", props);

            Player player = new Player();

            player.User       = this;
            player.Name       = name;
            player.Race       = race;
            player.Alive      = true;
            player.LastPlayed = DateTime.UtcNow;

            // Assign the default starting location based on the race
            CosmoSystem startingSystem = race.HomeSystem;

            if (startingSystem == null)
            {
                Logger.Write("Unable to load player starting system from database", "Model", 1000, 0, TraceEventType.Critical);
                return(null);
            }

            // Create a new ship for this player
            player.CreateStartingShip(startingSystem);

            // Starting credits is 2000
            player.Ship.Credits = 2000;

            player.UpdateNetWorth();

            db.Players.InsertOnSubmit(player);
            db.SaveChanges();

            return(player);
        }
コード例 #13
0
        /// <summary>
        /// Finds a user by username or past player name
        /// </summary>
        /// <param name="name">The name to search for.</param>
        /// <returns>The IEnumerable of User objects for the matching users.</returns>
        public virtual IEnumerable <User> FindUser(string name)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // We search users and their player names
            return((from u in db.Users
                    where u.UserName.Contains(name) ||
                    u.Email.Contains(name)
                    select u)
                   .Union(
                       (from p in db.Players
                        where p.Name.Contains(name)
                        select p.User)).AsEnumerable());
        }
コード例 #14
0
        /// <summary>
        /// Gets the user name associated with the specified e-mail address.
        /// </summary>
        /// <param name="email">The e-mail address to search for.</param>
        /// <returns>
        /// The user name associated with the specified e-mail address.
        /// If no match is found, return empty string.
        /// </returns>
        public override string GetUserNameByEmail(string email)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();
            User matchingUser           = (from u in db.Users
                                           where u.Email == email
                                           select u).SingleOrDefault();

            if (matchingUser != null)
            {
                return(matchingUser.UserName);
            }

            return(String.Empty);
        }
コード例 #15
0
        /// <summary>
        /// Clears the locked-out state of the user so that the user can login.
        /// </summary>
        /// <returns>
        /// true if the membership user was successfully unlocked; otherwise, false.
        /// </returns>
        public override bool UnlockUser()
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            if (this.user != null)
            {
                this.user.Active = true;

                // Save database changes
                db.SaveChanges();
                return(true);
            }

            return(false);
        }
コード例 #16
0
        /// <summary>
        /// Gets a list of Systems within traveling range of the Ship. Excluding the current system.
        /// </summary>
        /// <returns>Array of CosmoSystems within JumpDrive distance</returns>
        public virtual CosmoSystem[] GetInRangeSystems()
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // Find all systems within range of the JumpDrive
            // We use the distance formula, sqrt((x2 - x1)^2 + (y2 - y1)^2)
            var systems = (from s in db.CosmoSystems
                           where s != this.CosmoSystem &&
                           Math.Sqrt(Math.Pow(this.CosmoSystem.PositionX - s.PositionX, 2)
                                     + Math.Pow(this.CosmoSystem.PositionY - s.PositionY, 2))
                           < this.JumpDrive.Range
                           select s);

            return(systems.ToArray());
        }
コード例 #17
0
        /// <summary>
        /// Change the password for a user
        /// </summary>
        /// <param name="newPassword">The new password for the specified user.</param>
        /// <returns>
        /// true if the password was updated successfully; otherwise, false.
        /// </returns>
        public bool ChangePassword(string newPassword)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            if (this.user != null)
            {
                // Update the users password
                this.user.Password = Cryptographer.CreateHash("SHA512", newPassword);

                // Save database changes
                db.SaveChanges();
                return(true);
            }

            return(false);
        }
コード例 #18
0
ファイル: Combat.cs プロジェクト: jcsston/CosmoMonger
        /// <summary>
        /// Steals the other players credits.
        /// </summary>
        private void StealCredits()
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            Dictionary <string, object> props = new Dictionary <string, object>
            {
                { "CombatId", this.CombatId },
                { "TurnShipId", this.ShipTurn.ShipId },
                { "OtherShipId", this.ShipOther.ShipId },
                { "TurnShipCredits", this.ShipTurn.Credits },
                { "OtherShipCredits", this.ShipOther.Credits }
            };

            Logger.Write("Transfering losing ship credits to winner", "Model", 150, 0, TraceEventType.Verbose, "InProgressCombat.OtherShipDestroyed", props);

            // Take the other ship credits
            this.CreditsLooted     = this.ShipOther.Credits;
            this.ShipOther.Credits = 0;

            // Give to the winner ship
            this.ShipTurn.Credits += this.CreditsLooted;

            // If loser is player, give him starting credits
            Player otherPlayer = this.ShipOther.Players.SingleOrDefault();

            if (otherPlayer != null)
            {
                // Give the player some starting credits
                double cloneCredits = 2000 - ((otherPlayer.BankCredits + 1) / 5000.0 * 2000);

                // Ignore negative values
                cloneCredits           = Math.Max(cloneCredits, 0);
                this.ShipOther.Credits = (int)cloneCredits;

                props = new Dictionary <string, object>
                {
                    { "CombatId", this.CombatId },
                    { "TurnShipId", this.ShipTurn.ShipId },
                    { "OtherPlayerId", otherPlayer.PlayerId },
                    { "Credits", this.ShipOther.Credits }
                };
                Logger.Write("Giving losing player starting credits", "Model", 150, 0, TraceEventType.Verbose, "InProgressCombat.OtherShipDestroyed", props);
            }

            // Save database changes
            db.SaveChanges();
        }
コード例 #19
0
ファイル: Combat.cs プロジェクト: jcsston/CosmoMonger
        /// <summary>
        /// Jettison all of the ships current cargo.
        /// This will allow the ship to escape if the opposing ship picks up the cargo.
        /// </summary>
        /// <exception cref="InvalidOperationException">Thrown when combat is over or there is no cargo to jettison or cargo has already need jettisoned</exception>
        public virtual void JettisonCargo()
        {
            // Check that the combat is still in-progress
            if (this.Status != CombatStatus.Incomplete)
            {
                throw new InvalidOperationException("Combat is over");
            }

            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // Jettison Cargo flag must be not set
            if (this.CargoJettisoned)
            {
                throw new InvalidOperationException("There is already cargo jettisoned");
            }

            // Check that the ship has cargo to jettison
            if (this.ShipTurn.ShipGoods.Sum(g => g.Quantity) == 0)
            {
                throw new InvalidOperationException("No ship cargo to jettison");
            }

            // Sending cargo into space
            this.SendCargoIntoSpace(this.ShipTurn);

            this.CargoJettisoned = true;

            Dictionary <string, object> props = new Dictionary <string, object>
            {
                { "CombatId", this.CombatId },
                { "TurnShipId", this.ShipTurn.ShipId },
                { "OtherShipId", this.ShipOther.ShipId }
            };

            Logger.Write("Jettisoned cargo", "Model", 150, 0, TraceEventType.Verbose, "Combat.JettisonShipCargo", props);

            // Update turn action time
            this.LastActionTime = DateTime.UtcNow;

            // Save database changes
            db.SaveChanges();

            // Swap Turn to other player
            this.SwapTurn();
        }
コード例 #20
0
ファイル: Player.cs プロジェクト: jcsston/CosmoMonger
        /// <summary>
        /// Kills this player.
        /// </summary>
        public virtual void Kill()
        {
            Dictionary <string, object> props = new Dictionary <string, object>
            {
                { "PlayerId", this.PlayerId },
                { "Alive", this.Alive }
            };

            Logger.Write("Killing player in Player.Kill", "Model", 600, 0, TraceEventType.Verbose, "Kill Player", props);

            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // Kill this player
            this.Alive = false;

            // Save database changes
            db.SaveChanges();
        }
コード例 #21
0
        /// <summary>
        /// Verifies that the verification code matches this users verification code.
        /// Used to verify the users e-mail and approve the user account.
        /// </summary>
        /// <param name="verificationCode">The verification code to check.</param>
        /// <returns>
        /// true if the specified verification code is valid and the user has been approved; otherwise, false.
        /// </returns>
        public bool VerifyEmail(string verificationCode)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            if (this.user.VerificationCode == verificationCode)
            {
                // Verify the user
                this.user.Validated = true;

                // Save database changes
                db.SaveChanges();
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #22
0
ファイル: Player.cs プロジェクト: jcsston/CosmoMonger
        /// <summary>
        /// Updates the player profile with the new player name.
        /// Throws an ArgumentException if an existing player with the same name already exists.
        /// </summary>
        /// <param name="name">The new name of the player.</param>
        public virtual void UpdateProfile(string name)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // Check for another living player with same name
            bool matchingName = (from p in db.Players where p.Name == name && p.Alive && p != this select p).Any();

            if (matchingName)
            {
                throw new ArgumentException("Another player has the same name", "name");
            }

            // Update this player
            this.Name = name;

            // Save database changes
            db.SaveChanges();
        }
コード例 #23
0
        /// <summary>
        /// Gets the user associated with the specified username.
        /// </summary>
        /// <param name="username">The username to search for.</param>
        /// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param>
        /// <returns>
        /// The user associated with the specified username
        /// If no match is found, return null.
        /// </returns>
        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();
            User matchingUser           = (from u in db.Users
                                           where u.UserName == username
                                           select u).SingleOrDefault();

            if (matchingUser != null)
            {
                if (userIsOnline)
                {
                    matchingUser.LastActivity = DateTime.UtcNow;
                }

                return(new CosmoMongerMembershipUser(matchingUser));
            }

            return(null);
        }
コード例 #24
0
        /// <summary>
        /// Starts the ship traveling to the target system.
        /// </summary>
        /// <param name="targetSystem">The target system to travel to.</param>
        /// <returns>The number of seconds before the ship arrives at the target system</returns>
        /// <exception cref="ArgumentException">Thrown if the ship is already in the target system</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown if the target system is out of range of the ship</exception>
        /// <exception cref="InvalidOperationException">Thrown if the ship is already traveling</exception>
        public virtual int Travel(CosmoSystem targetSystem)
        {
            // Check if ship is in the target system
            if (this.CosmoSystem == targetSystem)
            {
                throw new ArgumentException("Ship is already in the target system", "targetSystem");
            }

            // Check that the system is within range
            CosmoSystem[] inRangeSystems = this.GetInRangeSystems();
            if (!inRangeSystems.Contains(targetSystem))
            {
                throw new ArgumentOutOfRangeException("targetSystem", "Target system is out of JumpDrive range");
            }

            // Check that the ship is not already traveling
            if (this.TargetSystemId != null || this.TargetSystemArrivalTime != null)
            {
                throw new InvalidOperationException("Ship is already traveling");
            }

            // Get the travel time
            int travelTime = this.JumpDrive.ChargeTime;

            // Update the player stats
            Player shipPlayer = this.Players.SingleOrDefault();

            if (shipPlayer != null)
            {
                shipPlayer.DistanceTraveled += this.GetSystemDistance(targetSystem);
            }

            // Update the database
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            this.TargetSystemId          = targetSystem.SystemId;
            this.TargetSystemArrivalTime = DateTime.UtcNow.AddSeconds(travelTime);
            db.SaveChanges();

            return(travelTime);
        }
コード例 #25
0
        /// <summary>
        /// Calls DoAction on all NPCs in the galaxy.
        /// This method will be called every 5 seconds to keep the NPCs
        /// busy in the galaxy.
        /// </summary>
        /// <param name="ignore">Ignore this parameter, added so that the method sig would match WaitCallback.</param>
        public static void DoPendingNPCActions(object ignore)
        {
            lock (npcLock)
            {
                CosmoMongerDbDataContext db = CosmoManager.GetDbContextNew();

                // Process the 10 oldest Npc actions at a time to keep load down
                IQueryable <Npc> npcsNeedingAction = (from n in db.Npcs
                                                      where n.NextActionTime < DateTime.UtcNow
                                                      orderby n.NextActionTime
                                                      select n);
                Logger.Write(string.Format("Processing 10 out of {0} pending NPCs", npcsNeedingAction.Count()), "Model", 200, 0, TraceEventType.Start, "CosmoMonger.DoPendingNPCActions");

                foreach (Npc npc in npcsNeedingAction.Take(10))
                {
                    npc.DoAction();
                }

                db.SaveChanges();
            }
        }
コード例 #26
0
        /// <summary>
        /// Add the good to this ship.
        /// </summary>
        /// <param name="goodId">The good type to add to this ship.</param>
        /// <param name="quantity">The quantity of the good to add.</param>
        /// <returns>The number of goods actually added to the ship. 0 is returned when ship cargo is full.</returns>
        public virtual int AddGood(int goodId, int quantity)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // Limit the quantity to the amount of free cargo space
            int actualQuantity = Math.Min(quantity, this.CargoSpaceFree);

            Dictionary <string, object> props = new Dictionary <string, object>
            {
                { "GoodId", goodId },
                { "Quantity", quantity },
                { "ActualQuantity", actualQuantity },
                { "ShipId", this.ShipId }
            };

            Logger.Write("Adding Good to Ship in Ship.AddGood", "Model", 150, 0, TraceEventType.Verbose, "Adding Good to Ship", props);

            ShipGood shipGood = this.GetGood(goodId);

            if (shipGood == null)
            {
                // Ship is not already carrying this good, so we have to create a new ShipGood
                shipGood          = new ShipGood();
                shipGood.Ship     = this;
                shipGood.GoodId   = goodId;
                shipGood.Quantity = actualQuantity;

                db.ShipGoods.InsertOnSubmit(shipGood);
            }
            else
            {
                // Add the correct number of goods to the ship
                shipGood.Quantity += actualQuantity;
            }

            db.SaveChanges();

            // Return the number of goods added to the ship
            return(actualQuantity);
        }
コード例 #27
0
ファイル: Player.cs プロジェクト: jcsston/CosmoMonger
        /// <summary>
        /// Deposit credits in the Bank.
        /// </summary>
        /// <param name="credits">The amount of credits to deposit.</param>
        /// <exception cref="InvalidOperationException">Thrown in the system the player currently is in doesn't have a bank</exception>
        /// /// <exception cref="ArgumentOutOfRangeException">Thrown if more credits than available are deposited</exception>
        public virtual void BankDeposit(int credits)
        {
            // Check that there is a bank in the current system
            if (!this.Ship.CosmoSystem.HasBank)
            {
                throw new InvalidOperationException("No bank available to deposit in");
            }

            // Check that the credits is postive
            if (0 >= credits)
            {
                throw new ArgumentOutOfRangeException("credits", "Cannot deposit a negative number of credits");
            }

            // Check that the player has enough credits to deposit
            if (this.Ship.Credits < credits)
            {
                throw new ArgumentOutOfRangeException("credits", "Cannot deposit more credits than available in cash");
            }

            Dictionary <string, object> props = new Dictionary <string, object>
            {
                { "PlayerId", this.PlayerId },
                { "Credits", credits },
                { "BankCredits", this.BankCredits },
                { "ShipCredits", this.Ship.Credits }
            };

            Logger.Write("Depositing credits into bank in Player.BankDeposit", "Model", 500, 0, TraceEventType.Verbose, "Depositing credits", props);

            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            this.Ship.Credits -= credits;
            this.BankCredits  += credits;

            // Save database changes
            db.SaveChanges();
        }
コード例 #28
0
ファイル: Player.cs プロジェクト: jcsston/CosmoMonger
        /// <summary>
        /// Updates the player record snapshot, creating a new one if needed.
        /// </summary>
        public virtual void UpdateRecordSnapshot()
        {
            int currentSnapshotAge = (int)(this.TimePlayed - this.LastRecordSnapshotAge);

            // If the last snap is older than 1min, we need to create a new one
            if (currentSnapshotAge > 60)
            {
                CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

                // Create new PlayerRecord row
                PlayerRecord record = new PlayerRecord();
                record.PlayerId   = this.PlayerId;
                record.RecordTime = DateTime.UtcNow;
                record.TimePlayed = this.TimePlayed;

                // Copy record values
                record.CargoLootedWorth = this.CargoLootedWorth;
                record.CargoLostWorth   = this.CargoLostWorth;
                record.FleeCount        = this.FleeCount;
                record.ForcedFlees      = this.ForcedFlees;
                record.ForcedSurrenders = this.ForcedSurrenders;
                record.NetWorth         = this.NetWorth;
                record.ShipsDestroyed   = this.ShipsDestroyed;
                record.ShipsLost        = this.ShipsLost;
                record.SurrenderCount   = this.SurrenderCount;
                record.GoodsTraded      = this.GoodsTraded;
                record.DistanceTraveled = this.DistanceTraveled;

                // Insert record
                db.PlayerRecords.InsertOnSubmit(record);

                // Update snapshot age
                this.LastRecordSnapshotAge = (int)this.TimePlayed;

                // Save database changes
                db.SaveChanges();
            }
        }
コード例 #29
0
ファイル: Combat.cs プロジェクト: jcsston/CosmoMonger
        /// <summary>
        /// Sends all the cargo on the ship into space.
        /// </summary>
        /// <param name="sourceShip">The source ship to throw the cargo out of.</param>
        private void SendCargoIntoSpace(Ship sourceShip)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // We will unload all the cargo off of the source ship and move it into the combat 'space'
            foreach (ShipGood shipGood in sourceShip.ShipGoods.Where(g => g.Quantity > 0))
            {
                CombatGood good = (from g in this.CombatGoods
                                   where g.Good == shipGood.Good
                                   select g).SingleOrDefault();
                if (good == null)
                {
                    good        = new CombatGood();
                    good.Combat = this;
                    good.Good   = shipGood.Good;
                    db.CombatGoods.InsertOnSubmit(good);
                }

                // Into space the good goes...
                good.Quantity += shipGood.Quantity;

                // The good is no longer on the ship
                shipGood.Quantity = 0;
            }

            // Update the player stats on lost cargo
            Player shipPlayer = sourceShip.Players.SingleOrDefault();

            if (shipPlayer != null)
            {
                int cargoWorth = this.CombatGoods.Sum(g => (g.Quantity * g.Good.BasePrice));
                shipPlayer.CargoLostWorth += cargoWorth;
            }

            // Save database changes
            db.SaveChanges();
        }
コード例 #30
0
        /// <summary>
        /// Creates a new user.
        /// </summary>
        /// <param name="username">The username of the new user.</param>
        /// <param name="password">The password for the new user.</param>
        /// <param name="email">The email address for the new user.</param>
        /// <exception cref="ArgumentException">
        /// Throws an ArgumentException for the username param if there is another user
        /// already in the system with the same username.
        /// Throws an ArgumentException for the email param if there is another user
        /// already in the system with the same e-mail.
        /// </exception>
        /// <returns>A new CosmoMongerMembershipUser object for the newly created user.</returns>
        public static CosmoMongerMembershipUser CreateUser(string username, string password, string email)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // Check for an existing user
            bool matchingUsername = (from u in db.Users where u.UserName == username select u).Any();

            if (matchingUsername)
            {
                throw new ArgumentException("Duplicate username", "username");
            }

            bool matchingEmail = (from u in db.Users where u.Email == email select u).Any();

            if (matchingEmail)
            {
                throw new ArgumentException("Duplicate email", "email");
            }

            // Create the new user
            User user = new User();

            user.UserName  = username;
            user.Email     = email;
            user.Password  = Cryptographer.CreateHash("SHA512", password);
            user.Active    = true;
            user.Validated = false;
            user.Joined    = DateTime.UtcNow;

            // Insert the user record into the database
            db.Users.InsertOnSubmit(user);

            // Save database changes
            db.SaveChanges();

            return(new CosmoMongerMembershipUser(user));
        }