コード例 #1
0
        public override void Execute(Session session, CommandContext context)
        {
            if (string.IsNullOrWhiteSpace(context.ArgumentString))
            {
                session.WriteLine("Buy what?");
                return;
            }

            // find shopkeeper
            var room       = RoomHelper.GetPlayerRoom(session.Player.Location);
            var shopkeeper = room.GetNpcs().FirstOrDefault(s => s.IsShopkeeper);

            if (shopkeeper == null)
            {
                session.WriteLine("There is notihng to buy here.");
                return;
            }

            int qty = 1;

            if (!int.TryParse(context.Arguments[0], out qty))
            {
                qty = 1;
            }
            else
            {
                context.Arguments.RemoveAt(0);
            }

            // get item
            PlayerItem item = null;

            foreach (var key in shopkeeper.Inventory.Keys)
            {
                var template = Server.Current.Database.Get <PlayerItem>(key);
                if (template.Keywords.Contains(context.Arguments[0].ToLower()))
                {
                    item = template;
                    break;
                }
            }

            if (item == null)
            {
                session.WriteLine("They don't sell that here.");
                return;
            }

            // calculate price
            var price = item.Value * qty;

            if (session.Player.Gold < price)
            {
                session.WriteLine("You can't afford that much.");
                return;
            }

            session.Player.Gold -= price;

            // duplicate in inventory, minding inventory and weight limits
            // if over weight/inventory, dump on the floor
            for (int i = 0; i < qty; i++)
            {
                var dupedItem = item.Copy();
                if (session.Player.Inventory.Count + 1 <= session.Player.MaxInventory &&
                    session.Player.Weight + dupedItem.Weight <= session.Player.MaxWeight)
                {
                    session.Player.Inventory[dupedItem.Key] = dupedItem.Name;
                }
                else
                {
                    room.AddItem(dupedItem);
                }

                Server.Current.Database.Save(dupedItem);
                Server.Current.Database.Save(session.Player);
            }

            session.WriteLine("You buy {0} {1}", qty, item.Name);
            room.SendPlayers("%d buys something.", session.Player, null, session.Player);
        }