/// <summary>
 /// Updates the room coordinates
 /// </summary>
 /// <param name="room">The room that needs coordinates set</param>
 /// <param name="coords">The coordinates to set to the room</param>
 public static void SetCoords(Room.Room room, Coordinates coords)
 {
     if (room != null)
     {
         room.coords = coords;
     }
 }
Example #2
0
        private static void EvokeEvent(Room.Room room, PlayerSetup.Player player, string option)
        {
            if (!string.IsNullOrEmpty(room.EventWear))
            {
                var triggerEvent = room.EventWear;

                Event.ParseCommand(triggerEvent, player, null, room, option, "player");
            }

            foreach (var mob in room.mobs)
            {
                if (!string.IsNullOrEmpty(mob.EventWear))
                {
                    var triggerEvent = mob.EventWear;

                    Event.ParseCommand(triggerEvent, player, mob, room, option, "player");
                }


                if (!string.IsNullOrEmpty(mob.EventDeath))
                {
                    var triggerEvent = mob.EventDeath;

                    Event.ParseCommand(triggerEvent, player, mob, room, option, "player");
                }
            }


            if (!string.IsNullOrEmpty(room.EventLook))
            {
                var triggerEvent = room.EventLook;

                Event.ParseCommand(triggerEvent, player, null, room, option, "player");
            }
        }
Example #3
0
File: Shop.cs Project: sizzles/MIM
        public static void listItems(PlayerSetup.Player player, Room.Room room)
        {
            var itemsForSell = "<table><thead><tr><td>Item</td><td>Price</td></tr></thead><tbody>";
            var mob          = room.mobs.FirstOrDefault(x => x.Shop.Equals(true));

            if (mob != null)
            {
                if (mob.itemsToSell.Count > 0)
                {
                    foreach (var item in mob.itemsToSell)
                    {
                        itemsForSell += "<tr><td>" + item.name + "</td> <td>" + item.Gold + " GP</td></tr>";
                    }

                    itemsForSell += "</tbody></table>";
                }
                else
                {
                    HubContext.SendToClient("Sorry I have nothing to sell you.", player.HubGuid);
                    return;
                }

                //e.g Yes sure here are my wares.
                HubContext.SendToClient(mob.Name + " says to you " + mob.sellerMessage, player.HubGuid);

                //show player items
                HubContext.SendToClient(itemsForSell, player.HubGuid);
            }
            else
            {
                HubContext.SendToClient("There is no merchant here", player.HubGuid);
            }
        }
Example #4
0
        public static void fleeCombat(PlayerSetup.Player player, Room.Room room)
        {
            if (player.Status == PlayerSetup.Player.PlayerStatus.Fighting)
            {
                //hardcode 50% flee success rate

                if (Helpers.Rand(1, 100) >= 50)
                {
                    HubContext.SendToClient("You Flee", player.HubGuid);

                    var exit = Helpers.diceRoll.Next(room.exits.Count);

                    player.Status = PlayerSetup.Player.PlayerStatus.Standing;

                    HubContext.SendToClient(player.Name + " Flee's from combat", player.Target.HubGuid);

                    player.Target = null;

                    Room.Movement.Move(player, room, room.exits[exit].name);
                }
                else
                {
                    HubContext.SendToClient("You fail to flee", player.HubGuid);
                }
            }
            else
            {
                HubContext.SendToClient("Flee from whom, you're not fighting anyone", player.HubGuid);
            }
        }
Example #5
0
        public static void AddRelatives(Room.Room child)
        {
            foreach (Room.Room item in listOfRoom)
            {
                int result = Compute.HasTwoCommonPoint(child, item);
                switch (result)
                {
                case 1:
                    child.LeftRoomId = item.Id;
                    item.RightRoomId = child.Id;
                    break;

                case 2:
                    child.TopRoomId = item.Id;
                    item.BotRoomId  = child.Id;
                    break;

                case 3:
                    child.RightRoomId = item.Id;
                    item.LeftRoomId   = child.Id;
                    break;

                case 4:
                    child.BotRoomId = item.Id;
                    item.TopRoomId  = child.Id;
                    break;

                default:
                    break;
                }
            }
        }
Example #6
0
        public static Room.Room TutorialRoom2()
        {
            var room = new Room.Room
            {
                region      = "Tutorial",
                area        = "Tutorial",
                areaId      = 1,
                title       = "Deep in the forest",
                description = "<p>You run forward, fleeing the ambush. You look back for one last time to see Wilhelm let out an ear piercing scream as he is over run by the goblins. " +
                              "Turning back around you greet a club that whacks you in the face sending you sprawling across the floor, your ears are ringing then everything goes black.</p>",

                //Defaults
                exits        = new List <Exit>(),
                items        = new List <Item.Item>(),
                mobs         = new List <PlayerSetup.Player>(),
                terrain      = Room.Room.Terrain.Field,
                keywords     = new List <RoomObject>(),
                corpses      = new List <PlayerSetup.Player>(),
                players      = new List <PlayerSetup.Player>(),
                fighting     = new List <string>(),
                clean        = true,
                EventOnEnter = "rescue"
            };



            return(room);
        }
Example #7
0
        public static string DisplayMap(Room.Room currentRoom)
        {
            var map  = new StringBuilder();
            var grid = ReturnMap(currentRoom);
            var rows = 5;
            var cols = 5;
            var num  = 0;

            for (int i = 0; i != rows; i++)
            {
                for (int j = 0; j != cols; j++)
                {
                    if (i == rows && j == cols)
                    {
                        map.Append("\n");
                        map.Append(grid[i, j]);
                    }
                    map.Append(grid[i, j]);


                    num++;
                }
            }

            return(map.ToString());
        }
Example #8
0
        public static string buildMap(Room.Room currentRoom)
        {
            if (currentRoom == null)
            {
                return(" ");
            }



            if (currentRoom?.exits.FirstOrDefault(x => x.name == "East") != null && currentRoom?.exits.FirstOrDefault(x => x.name == "North") != null)
            {
                return(" | \n[ ]--");
            }


            if (currentRoom?.exits.FirstOrDefault(x => x.name == "East") != null && currentRoom?.exits.FirstOrDefault(x => x.name == "North") == null)
            {
                return("[ ]--");
            }


            if (currentRoom?.exits.FirstOrDefault(x => x.name == "North") != null && currentRoom?.exits.FirstOrDefault(x => x.name == "East") == null)
            {
                return(" | \n" + "[ ]");
            }

            return("");
        }
Example #9
0
        public static Room.Room TutorialRoom2()
        {
            var room = new Room.Room
            {
                region      = "Tutorial",
                area        = "Tutorial",
                areaId      = 10,
                title       = "Deep in the forest",
                description = "<p>You turn your head as you hear an ear piercing scream in the distant. No doubt in your mind that it was Wilhelm. " +
                              "Turning back around you greet a club that whacks you in the face sending you sprawling across the floor, your ears are ringing then everything goes black.</p>",

                //Defaults
                exits         = new List <Exit>(),
                items         = new List <Item.Item>(),
                mobs          = new List <PlayerSetup.Player>(),
                terrain       = Room.Room.Terrain.Field,
                keywords      = new List <RoomObject>(),
                corpses       = new List <PlayerSetup.Player>(),
                players       = new List <PlayerSetup.Player>(),
                fighting      = new List <string>(),
                clean         = true,
                EventOnEnter  = "rescue",
                updateMessage = "A loud screech echos through the forest."
            };



            return(room);
        }
Example #10
0
        public static void SleepPlayer(PlayerSetup.Player player, Room.Room room)
        {
            if (player.Status != PlayerSetup.Player.PlayerStatus.Sleeping)
            {
                player.Status = PlayerSetup.Player.PlayerStatus.Sleeping;

                HubContext.SendToClient("You laydown and go to sleep", player.HubGuid);

                if (!string.IsNullOrEmpty(room.EventWake))
                {
                    Event.ParseCommand(room.EventWake, player, null, room, "sleep");
                }


                foreach (var mob in room.mobs)
                {
                    if (!string.IsNullOrEmpty(mob.EventWake))
                    {
                        Event.ParseCommand(mob.EventWake, player, mob, room, "sleep");
                    }
                }
            }

            else
            {
                HubContext.SendToClient("You are already asleep", player.HubGuid);
            }
        }
Example #11
0
        public static void WakePlayer(PlayerSetup.Player player, Room.Room room)
        {
            if (player.Status == PlayerSetup.Player.PlayerStatus.Sleeping)
            {
                player.Status = PlayerSetup.Player.PlayerStatus.Standing;

                HubContext.SendToClient("You wake and stand up", player.HubGuid);

                if (!string.IsNullOrEmpty(room.EventWake))
                {
                    Event.ParseCommand(room.EventWake, player, null, room, "wake");
                }


                foreach (var mob in room.mobs)
                {
                    if (!string.IsNullOrEmpty(mob.EventWake))
                    {
                        Event.ParseCommand(mob.EventWake, player, mob, room, "wake");
                    }
                }

                Command.ParseCommand("look", player, room);
            }

            else
            {
                HubContext.SendToClient("You are already awake", player.HubGuid);
            }
        }
Example #12
0
        public static Room.Room TutorialLostInTheWoods2()
        {
            var room = new Room.Room
            {
                region      = "Tutorial",
                area        = "Tutorial",
                areaId      = 2,
                title       = "Deep in the forest",
                description = "<p>Shadows flicker off the trees and shrubs caused by the glow of the camp fire to the east. All around you are tall thick tree, and impassable bushes, the fire is your only beceon of hope in this dense woodland.</p>",

                //Defaults
                exits    = new List <Exit>(),
                items    = new List <Item.Item>(),
                mobs     = new List <PlayerSetup.Player>(),
                terrain  = Room.Room.Terrain.Field,
                keywords = new List <RoomObject>(),
                corpses  = new List <PlayerSetup.Player>(),
                players  = new List <PlayerSetup.Player>(),
                fighting = new List <string>(),
                clean    = true
            };


            var east = new Exit
            {
                name     = "East",
                area     = "Tutorial",
                region   = "Tutorial",
                areaId   = 3,
                keywords = new List <string>(),
                hidden   = false,
                locked   = false,
                canLock  = true,
                canOpen  = true,
                open     = true,
                doorName = null
            };

            var south = new Exit
            {
                name     = "South",
                area     = "Tutorial",
                region   = "Tutorial",
                areaId   = 1,
                keywords = new List <string>(),
                hidden   = false,
                locked   = false,
                canLock  = true,
                canOpen  = true,
                open     = true,
                doorName = null
            };



            room.exits.Add(east);
            room.exits.Add(south);

            return(room);
        }
Example #13
0
        public static void greet(PlayerSetup.Player player, PlayerSetup.Player mob, Room.Room room, string message = "")
        {
            var isMobHere = room.mobs.FirstOrDefault(x => x.Name.Equals(mob.Name));

            if (isMobHere == null)
            {
                return;
            }

            if (player.Type == PlayerSetup.Player.PlayerTypes.Player && message == string.Empty)
            {
                if (!string.IsNullOrEmpty(mob.GreetMessage))
                {
                    string greetMessageToRoom = mob.GreetMessage + " " + player.Name;

                    foreach (var character in room.players)
                    {
                        var roomMessage = $"{ Helpers.ReturnName(mob, character, string.Empty)} says \"{greetMessageToRoom}\"";

                        HubContext.Instance.SendToClient(roomMessage, character.HubGuid);
                    }
                }
            }
            else
            {
            }
        }
Example #14
0
File: Shop.cs Project: sizzles/MIM
        public static void buyItems(PlayerSetup.Player player, Room.Room room, string itemName)
        {
            var mob = room.mobs.FirstOrDefault(x => x.Shop.Equals(true));

            if (mob != null)
            {
                if (mob.Shop)
                {
                    if (string.IsNullOrEmpty(itemName))
                    {
                        HubContext.SendToClient("Buy? Buy what?", player.HubGuid);
                        return;
                    }

                    var itemToBuy = mob.itemsToSell.FirstOrDefault(x => x.name.ToLower().Contains(itemName.ToLower()));

                    if (itemToBuy != null)
                    {
                        var    result  = AvsAnLib.AvsAn.Query(itemToBuy.name);
                        string article = result.Article;

                        //Can afford

                        if (player.Gold >= itemToBuy.Gold)
                        {
                            itemToBuy.location = Item.Item.ItemLocation.Inventory;
                            player.Inventory.Add(itemToBuy);
                            HubContext.SendToClient(
                                "You buy " + article + itemToBuy.name + " from " + mob.Name,
                                player.HubGuid);

                            foreach (var character in room.players)
                            {
                                if (player != character)
                                {
                                    var hisOrHer    = Helpers.ReturnHisOrHers(player, character);
                                    var roomMessage = $"{ Helpers.ReturnName(player, character, string.Empty)} buys {article} {itemToBuy.name} from {mob.Name}";

                                    HubContext.SendToClient(roomMessage, character.HubGuid);
                                }
                            }

                            Score.UpdateUiInventory(player);
                            //deduct gold

                            player.Gold -= itemToBuy.Gold;
                        }
                        else
                        {
                            HubContext.SendToClient("You can't afford " + article + " " + itemToBuy.name, player.HubGuid);
                        }
                    }
                }
                else
                {
                    HubContext.SendToClient("Sorry I don't sell that", player.HubGuid);
                }
            }
        }
Example #15
0
        public static Room.Room TutorialLostInTheWoods3()
        {
            var room = new Room.Room
            {
                region      = "Tutorial",
                area        = "Tutorial",
                areaId      = 6,
                title       = "Deep in the forest",
                description = "<p>The only light source is the faint light from the camp fire to the west. Errie shaped shadows flicker off the trees and shrubs. A path to the west leads deeper in to the forest.</p>",

                //Defaults
                exits         = new List <Exit>(),
                items         = new List <Item.Item>(),
                mobs          = new List <PlayerSetup.Player>(),
                terrain       = Room.Room.Terrain.Field,
                keywords      = new List <RoomObject>(),
                corpses       = new List <PlayerSetup.Player>(),
                players       = new List <PlayerSetup.Player>(),
                fighting      = new List <string>(),
                clean         = true,
                updateMessage = "A loud screech echos through the forest."
            };

            var east = new Exit
            {
                name     = "East",
                area     = "Tutorial",
                region   = "Tutorial",
                areaId   = 7,
                keywords = new List <string>(),
                hidden   = false,
                locked   = false,
                canLock  = false,
                canOpen  = false,
                open     = true,
                doorName = null
            };


            var west = new Exit
            {
                name     = "West",
                area     = "Tutorial",
                region   = "Tutorial",
                areaId   = 3,
                keywords = new List <string>(),
                hidden   = false,
                locked   = false,
                canLock  = false,
                canOpen  = false,
                open     = true,
                doorName = null
            };

            room.exits.Add(east);
            room.exits.Add(west);

            return(room);
        }
 /// <summary>
 /// Searches the completed list of rooms and
 /// returns the room that is an exit of getRoom (AreaList.Last())
 /// </summary>
 /// <param name="getRoom">The last room from AreaList</param>
 /// <returns>The room next to getRoom</returns>
 public Room.Room GetNeighbour(Room.Room getRoom)
 {
     return(CompletedRooms.FirstOrDefault(x =>
     {
         var lastOrDefault = getRoom.exits.LastOrDefault();
         return lastOrDefault != null && x.areaId == lastOrDefault.areaId;
     }));
 }
Example #17
0
        public static void FollowThing(PlayerSetup.Player follower, Room.Room room, string thingToFollow)
        {
            string[] options      = thingToFollow.Split(' ');
            int      nth          = -1;
            string   getNth       = string.Empty;
            string   objectToFind = String.Empty;


            if (options.Length == 3)
            {
                objectToFind = options[2];

                if (objectToFind.IndexOf('.') != -1)
                {
                    getNth = objectToFind.Substring(0, objectToFind.IndexOf('.'));
                    int.TryParse(getNth, out nth);
                }
            }

            var findPerson = FindItem.Player(room.players, nth, objectToFind);

            if (findPerson == null)
            {
                return;
            }

            if (findPerson.Followers == null)
            {
                findPerson.Followers = new List <PlayerSetup.Player>();
            }

            //check if player already following player

            if (findPerson.Followers.Contains(follower))
            {
                if (follower.HubGuid != null)
                {
                    HubContext.SendToClient("You are already following them.", follower.HubGuid);
                }
            }
            else
            {
                HubContext.SendToClient($"{Helpers.ReturnName(follower, findPerson, String.Empty)} begins following you", findPerson.HubGuid);

                foreach (var character in room.players)
                {
                    if (character != follower || character != findPerson)
                    {
                        HubContext.SendToClient($"{Helpers.ReturnName(follower, findPerson, String.Empty)} begins following {Helpers.ReturnName(findPerson, follower, String.Empty)}", character.HubGuid);
                    }
                }

                findPerson.Followers.Add(follower);
            }
        }
Example #18
0
        public IRoom AddRoom(Guid guid, RoomBlueprint blueprint, IArea area)
        {
            if (blueprint == null)
            {
                throw new ArgumentNullException(nameof(blueprint));
            }
            IRoom room = new Room.Room(Guid.NewGuid(), blueprint, area);

            _rooms.Add(room);
            return(room);
        }
Example #19
0
 public static void greet(PlayerSetup.Player player, PlayerSetup.Player mob, Room.Room room)
 {
     if (player.Type == PlayerSetup.Player.PlayerTypes.Player)
     {
         string greetMessageToRoom = string.Format(mob.GreetMessage, player.Name);
         HubContext.broadcastToRoom(mob.Name + " Says " + greetMessageToRoom, room.players, player.HubGuid);
     }
     else
     {
         //Greet other mob
     }
 }
Example #20
0
        /// <summary>
        /// Searches the completed list of rooms and
        /// returns the room that is an exit of getRoom (AreaList.Last())
        /// </summary>
        /// <param name="getRoom">The last room from AreaList</param>
        /// <returns>The room next to getRoom</returns>
        public Room.Room GetNeighbour(Room.Room getRoom)
        {
            foreach (var connectingNode in getRoom.exits)
            {
                var connectedRoom = CompletedRooms.FirstOrDefault(x => x.areaId.Equals(connectingNode.areaId) && x.area.Equals(connectingNode.area));
                if (connectedRoom != null)
                {
                    return(connectedRoom);
                }
            }

            return(null);
        }
Example #21
0
        public static void DoSpell(PlayerSetup.Player playerData, Room.Room room, string commandOptions)
        {
            var spell =
                playerData.Skills.Where(
                    x =>
                    x.Name.StartsWith(commandOptions, StringComparison.CurrentCultureIgnoreCase) &&
                    x.LevelObtained <= playerData.Level);

            if (spell != null)
            {
                // spell.FirstOrDefault()
            }
        }
Example #22
0
        public static void buyItems(PlayerSetup.Player player, Room.Room room, string itemName)
        {
            var mob = room.mobs.FirstOrDefault(x => x.Shop.Equals(true));

            if (mob != null)
            {
                if (mob.Shop)
                {
                    if (string.IsNullOrEmpty(itemName))
                    {
                        HubContext.SendToClient("Buy? Buy what?", player.HubGuid);
                        return;
                    }

                    var itemToBuy = mob.itemsToSell.FirstOrDefault(x => x.name.ToLower().Contains(itemName.ToLower()));

                    if (itemToBuy != null)
                    {
                        var    result  = AvsAnLib.AvsAn.Query(itemToBuy.name);
                        string article = result.Article;

                        //Can afford

                        if (player.Gold >= itemToBuy.Gold)
                        {
                            itemToBuy.location = Item.Item.ItemLocation.Inventory;
                            player.Inventory.Add(itemToBuy);
                            HubContext.SendToClient(
                                "You buy " + article + itemToBuy.name + " from " + mob.Name,
                                player.HubGuid);
                            HubContext.broadcastToRoom(
                                player.Name + " buys " + article + " " + itemToBuy.name +
                                " from " +
                                mob.Name, room.players, player.HubGuid, true);
                            Score.UpdateUiInventory(player);
                            //deduct gold

                            player.Gold -= itemToBuy.Gold;
                        }
                        else
                        {
                            HubContext.SendToClient("You can't afford " + article + " " + itemToBuy.name, player.HubGuid);
                        }
                    }
                }
                else
                {
                    HubContext.SendToClient("Sorry I don't sell that", player.HubGuid);
                }
            }
        }
Example #23
0
 public static void greet(PlayerSetup.Player player, PlayerSetup.Player mob, Room.Room room, string message = "")
 {
     if (player.Type == PlayerSetup.Player.PlayerTypes.Player && message == string.Empty)
     {
         if (mob.GreetMessage != null)
         {
             string greetMessageToRoom = mob.GreetMessage + " " + player.Name;
             HubContext.broadcastToRoom(mob.Name + " says " + greetMessageToRoom, room.players, player.HubGuid);
         }
     }
     else
     {
     }
 }
Example #24
0
        protected Player(Room.Room room)
        {
            _room = room;

            NumLife = 3;
            InBattle = false;

            Direction = Direction.Up;

            Position = new Point(0, 0);
            Weapon = WeaponFactory.Create(WeaponType.NullWeapon);
            Drink = DrinkFactory.Create(DrinkType.NullDrink);

            Drinks = new List<Drink.Drink>();
            FoodItems = new List<Food>();
        }
Example #25
0
        public static void SaveRoom(Room.Room room)
        {
            try
            {
                using (var db = new LiteDatabase(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MyData.db")))
                {
                    var col = db.GetCollection <Room.Room>("Room");

                    col.Upsert(room);
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Error Saving room " + ex.Message);
            }
        }
        public static void Annoy(PlayerSetup.Player player, PlayerSetup.Player mob, Room.Room room)
        {
            var phrase = RandomResponses();

            HubContext.SendToClient($"<span class='sayColor'>{mob.Name} says to you \"{phrase}\"</span>", player.HubGuid);

            foreach (var character in room.players)
            {
                if (character != player)
                {
                    HubContext.SendToClient($"<span class='sayColor'>{mob.Name} says to {Helpers.ReturnName(player, character, String.Empty)} \"{phrase}\"</span>", character.HubGuid);
                }
            }

            Follow.MobStalk(mob, player, room);
        }
Example #27
0
        public static Room.Room TutorialLostInTheWoods()
        {
            var room = new Room.Room
            {
                region      = "Tutorial",
                area        = "Tutorial",
                areaId      = 1,
                title       = "Deep in the forest",
                description = "<p>Behind you the sounds of swords clashing fill the night air along with never ending goblin screams echoing through the tall thick trees all around you. " +
                              "Between the trees to the north west you see what looks to be a small camp with a fire, Maybe you can get some help there.</p>",

                //Defaults
                exits         = new List <Exit>(),
                items         = new List <Item.Item>(),
                mobs          = new List <PlayerSetup.Player>(),
                terrain       = Room.Room.Terrain.Field,
                keywords      = new List <RoomObject>(),
                corpses       = new List <PlayerSetup.Player>(),
                players       = new List <PlayerSetup.Player>(),
                fighting      = new List <string>(),
                clean         = true,
                updateMessage = "A loud screech echos through the forest."
            };


            var north = new Exit
            {
                name     = "North",
                area     = "Tutorial",
                region   = "Tutorial",
                areaId   = 2,
                keywords = new List <string>(),
                hidden   = false,
                locked   = false,
                canLock  = true,
                canOpen  = true,
                open     = true,
                doorName = null
            };


            room.exits.Add(north);

            return(room);
        }
Example #28
0
File: Flee.cs Project: xjuantxu/MIM
        public static void fleeCombat(PlayerSetup.Player player, Room.Room room)
        {
            if (player.Status == PlayerSetup.Player.PlayerStatus.Fighting)
            {
                HubContext.SendToClient("You Flee", player.HubGuid);

                //var exit = room.exits.Find(x => x.name.Equals("north", StringComparison.InvariantCultureIgnoreCase));

                player.Status = PlayerSetup.Player.PlayerStatus.Standing;
                HubContext.SendToClient(player.Name + " Flee's from combat", player.Target.HubGuid);

                Room.Movement.Move(player, room, "North");
            }
            else
            {
                HubContext.SendToClient("Flee from whom, you're not fighting anyone", player.HubGuid);
            }
        }
Example #29
0
        public static void listItems(PlayerSetup.Player player, Room.Room room)
        {
            var itemsForSell = "<table><thead><tr><td>Item</td><td>Price</td></tr></thead><tbody>";
            var mob          = room.mobs.FirstOrDefault(x => x.Shop.Equals(true));

            if (mob != null)
            {
                if (mob.itemsToSell.Count > 0)
                {
                    Regex rgx = new Regex(@"\s[a-z][0-9]*$");


                    foreach (var item in ItemContainer.List(mob.itemsToSell))
                    {
                        var cleanItemName = rgx.Replace(item, string.Empty);
                        var goldAmount    = mob.itemsToSell.FirstOrDefault(x => x.name.Equals(cleanItemName)).Gold;

                        if (goldAmount <= 0)
                        {
                            goldAmount = 10;
                        }

                        itemsForSell += "<tr><td>" + item + "</td> <td>" + (int)(goldAmount + (goldAmount * 0.15)) + " GP</td></tr>";
                    }

                    itemsForSell += "</tbody></table>";
                }
                else
                {
                    HubContext.Instance.SendToClient("<span class='sayColor'>" + mob.Name + "says, \"Sorry I have nothing to sell you.\"</span>", player.HubGuid);
                    return;
                }

                //e.g Yes sure here are my wares.
                HubContext.Instance.SendToClient("<span class='sayColor'>" + mob.Name + " says to you \"" + mob.sellerMessage + "\"</span>", player.HubGuid);

                //show player items
                HubContext.Instance.SendToClient(itemsForSell, player.HubGuid);
            }
            else
            {
                HubContext.Instance.SendToClient("There is no merchant here", player.HubGuid);
            }
        }
Example #30
0
File: Skill.cs Project: sizzles/MIM
        public static PlayerSetup.Player FindTarget(string target, Room.Room room)
        {
            //Find target if it's specified
            if (target == "")
            {
                return(null);
            }

            var getTargetName = Skill.GetSkillTarget(target);

            if (getTargetName != string.Empty)
            {
                var foundTarget = Fight2.FindTarget(room, getTargetName);

                return(foundTarget);
            }

            return(null);
        }
        /// <summary>
        /// loops through the exits of getRoom looking for adjacent rooms in AreaList
        /// then assigns coords to getRoom relating to the adjacent room
        ///
        /// For example:
        /// getRoom is (0,0,0) and has an exit which leads to areaId 1
        ///
        /// nextRoom is a room that has the matching areaId of one of getRoom's exits
        /// in this case 1.
        ///
        /// So the coordinates it will assign to nextRoom is (1,0,0)
        ///
        /// Because GetNewCoord(getRoom.coords, exit.name);
        /// would look like this:
        /// GetNewCoord((0,0,0), "North");
        ///
        /// Once the coord has been given to a room it adds it to the completed
        /// list and removes it from area list
        ///
        /// </summary>
        /// <param name="getRoom">Last room from area list</param>
        public void ProcessRoom(Room.Room getRoom)
        {
            foreach (var exit in getRoom.exits)
            {
                var nextRoom       = AreaList.FirstOrDefault(x => x.areaId == exit.areaId);
                var nextRoomCoords = GetNewCoord(getRoom.coords, exit.name);

                if (nextRoom != null && nextRoom.visited == false)
                {
                    SetCoords(nextRoom, nextRoomCoords);
                    nextRoom.visited = true;
                    CompletedRooms.Add(nextRoom);
                    AreaList.Remove(nextRoom);
                }
            }

            getRoom.visited = true;
            CompletedRooms.Add(getRoom);
            AreaList.Remove(getRoom);
        }
Example #32
0
        private void processPacket(string currentPacket)
        {
            Config.Debug.WriteLine("[" + connectionID + "] RECV " + currentPacket);

            int packetHeader = int.Parse(currentPacket.Substring(0, 3));
            string packetBody = currentPacket.Substring(3);

            if (_isLoggedIn == false)
            {
                switch (packetHeader)
                {
                    case 2:
                        // client: connection is about to be closed
                        Disconnect();
                        break;

                    case 5:
                        // ping request
                        sendData("006#");
                        break;

                    case 6:
                        // ping answer
                        pingOK = true;
                        break;
                    #region Login
                    case 17:
                        LogInPacket LoginRequest = (LogInPacket)JsonConvert.DeserializeObject(packetBody, typeof(LogInPacket));

                        LoginRequest.U = MySQL.Stripslash(LoginRequest.U);
                        LoginRequest.P = MySQL.Stripslash(LoginRequest.P);

                        if (logintry < 3)
                        {
                            int myID = MySQL.runRead("SELECT id FROM members WHERE username = '******' AND password = '******'", null);
                            if (myID == 0)
                            {
                                LoginFailurePacket LoginMessage = new LoginFailurePacket();

                                LoginMessage.R = "wrong";

                                string LoginMessageString = JsonConvert.SerializeObject(LoginMessage);
                                sendData("019" + LoginMessageString + "#");

                                logintry++;
                                return;
                            }
                            else if (MySQL.runRead("SELECT ban FROM members WHERE username = '******' AND password = '******'") == "yes")
                            {
                                LoginFailurePacket LoginMessage = new LoginFailurePacket();

                                LoginMessage.R = "ban";

                                string LoginMessageString = JsonConvert.SerializeObject(LoginMessage);
                                sendData("019" + LoginMessageString + "#");

                                logintry++;
                                return;
                            }
                            /*
                            else if (MySQL.runRead("SELECT activated FROM members WHERE username = '******' AND password = '******'") == "nee")
                            {
                                LF LoginMessage = new LF();

                                LoginMessage.R = "mail";

                                string LoginMessageString = JsonConvert.SerializeObject(LoginMessage);
                                sendData("019" + LoginMessageString + "#");

                                logintry++;
                                return;
                            }
                            */
                            else if (SocketServer.acceptedConnections > Config.maxconn - 10)
                            {
                                LoginFailurePacket LoginMessage = new LoginFailurePacket();

                                LoginMessage.R = "full";

                                string LoginMessageString = JsonConvert.SerializeObject(LoginMessage);
                                sendData("019" + LoginMessageString + "#");

                                Disconnect(2000);

                                return;
                            }
                            else if (myID != 0)
                            {
                                string[] userData = MySQL.runReadRow("SELECT username, rank, money, logins, minutes, mission, figure, badge, messenger FROM members WHERE id = '" + myID + "'");
                                _UserID = myID;
                                _Username = userData[0];
                                _Rank = byte.Parse(userData[1]);
                                _Money = int.Parse(userData[2]);
                                _Logins = int.Parse(userData[3]);
                                _Minutes = int.Parse(userData[4]);

                                _Mission = userData[5];
                                _Figure = userData[6];
                                _Badge = userData[7];
                                _MessengerMission = userData[8];
                                _Badges = MySQL.runReadRow("SELECT badge FROM badges WHERE owner = '" + _UserID + "'");

                                UserManager.addUser(_UserID, this);
                                _isLoggedIn = true;

                                UserDataPacket UserData = new UserDataPacket();
                                UserData.I = _UserID;
                                UserData.R = RankManager.Rights(_Rank);
                                UserData.MY = _Money;
                                UserData.CB = _Badge;
                                UserData.B = _Badges;
                                UserData.MM = _MessengerMission;
                                UserData.C = _Figure;
                                UserData.M = _Mission;
                                UserData.UN = _Username;
                                UserData.ID = getInventoryData();

                                Messenger = new Messenger.Messenger(_UserID);

                                string UserDataString = JsonConvert.SerializeObject(UserData);
                                sendData("020" + UserDataString + "#" + "018#");

                                MySQL.runQuery("UPDATE members SET logins = '" + ++_Logins + "' WHERE id = '" + _UserID + "'");
                                return;
                            }
                            else
                            {
                                LoginFailurePacket LoginMessage = new LoginFailurePacket();
                                LoginMessage.R = "error";
                                string LoginMessageString = JsonConvert.SerializeObject(LoginMessage);
                                sendData("019" + LoginMessageString + "#");
                            }
                        }
                        else
                        {
                            LoginFailurePacket LoginMessage = new LoginFailurePacket();
                            LoginMessage.R = "try";
                            string LoginMessageString = JsonConvert.SerializeObject(LoginMessage);
                            sendData("019" + LoginMessageString + "#");
                            return;
                        }
                        break;
                    #endregion

                    #region Registering
                    case 15:
                        RegisterCheckAnswerPacket RegisterCheckAnswer = new RegisterCheckAnswerPacket();
                        RegisterCheckAnswer.A = "closed";
                        string RegisterCheckAnswerString = JsonConvert.SerializeObject(RegisterCheckAnswer);
                        sendData("016" + RegisterCheckAnswerString + "#");
                        break;
                    #endregion

                    default:
                        sendData("003#");
                        Disconnect(2000);
                        break;
                }
            }
            else
            {
                switch (packetHeader)
                {
                    case 2:
                        // client: connection is about to be closed
                        Disconnect();
                        break;

                    case 5:
                        // ping request
                        sendData("006#");
                        break;

                    case 6:
                        // ping ok
                        pingOK = true;
                        break;

                    case 9:
                        // user is inactive
                        active = false;
                        if (_Room != null)
                        {
                            _Room.updateBrb(1, this);
                        }
                        break;
                    case 10:
                        // user is active again
                        active = true;
                        if (_Room != null)
                        {
                            _Room.updateBrb(0, this);
                        }
                        break;

                    #region Mod tools
                    case 11:
                        // request server RAM
                        if (RankManager.containsRight(_Rank, "server_ram"))
                        {
                            long memUsage = GC.GetTotalMemory(false) / 1024;
                            ServerRAMPacket ServerRam = new ServerRAMPacket();
                            ServerRam.R = (int)memUsage;
                            string ServerRamString = JsonConvert.SerializeObject(ServerRam);
                            sendData("012" + ServerRamString + "#");
                        }
                        break;

                    case 14:
                        // global alert
                        GlobalAlertPacket GlobalAlertdata = (GlobalAlertPacket)JsonConvert.DeserializeObject(packetBody, typeof(GlobalAlertPacket));
                        if (RankManager.containsRight(_Rank, "global_alert"))
                        {
                            MessagePacket GlobalAlert = new MessagePacket();
                            GlobalAlert.M = GlobalAlertdata.M;
                            GlobalAlert.T = "";
                            string GlobalAlertString = JsonConvert.SerializeObject(GlobalAlert);

                            UserManager.sendData("013" + GlobalAlertString + "#");
                        }
                        else
                        {
                            sendData("003#");
                            Disconnect(2000);
                        }
                        break;
                    case 62:
                        // open the chatbox
                        if (RankManager.containsRight(_Rank, "open_chatbox_forall"))
                        {
                            UserManager.sendData("063#");
                        }
                        else
                        {
                            sendData("003#");
                            Disconnect(2000);
                        }
                        break;
                    #endregion;

                    #region Logged in
                    case 21:
                        FriendListPacket FriendList = new FriendListPacket();
                        FriendList.F = Messenger.friendListInit();
                        string FriendListString = JsonConvert.SerializeObject(FriendList);

                        MessengerRequestPacket MessengerRequests = new MessengerRequestPacket();
                        MessengerRequests.R = Messenger.friendRequests();
                        string MessengerRequestsString = JsonConvert.SerializeObject(MessengerRequests);

                        sendData(refreshClub()+Messenger.messagesInit()+"029" + FriendListString + "#027" + MessengerRequestsString + "#040" + NavigatorManager.dataPacket(this) + "#");
                        break;
                    #endregion

                    #region Messenger

                    case 23: // Messenger - search
                        MessengerSearchPacket searchPacket = (MessengerSearchPacket)JsonConvert.DeserializeObject(packetBody, typeof(MessengerSearchPacket));
                        string[] userData = MySQL.runReadRow("SELECT id, messenger, figure, last_online FROM members WHERE username = '******'");
                        if (userData.Length == 0)
                        {
                            MessengerSearchedPacket MessengerPacket = new MessengerSearchedPacket();
                            MessengerPacket.I = 0;
                            MessengerPacket.M = "";
                            MessengerPacket.C = "";
                            MessengerPacket.L = "";
                            MessengerPacket.O = false;
                            MessengerPacket.A = false;
                            string MessengerPacketString = JsonConvert.SerializeObject(MessengerPacket);
                            sendData("024" + MessengerPacketString + "#");
                        }
                        else
                        {
                            int searchId = int.Parse(userData[0]);
                            bool addable = false;
                            if (searchId != _UserID)
                            {
                                if ((!Messenger.hasFriendship(searchId)) && (!Messenger.hasFriendRequests(searchId)))
                                {
                                    addable = true;
                                }
                            }
                            MessengerSearchedPacket MessengerPacket = new MessengerSearchedPacket();
                            MessengerPacket.I = searchId;
                            MessengerPacket.M = userData[1];
                            MessengerPacket.C = userData[2];
                            MessengerPacket.L = userData[3];
                            MessengerPacket.O = UserManager.containsUser(searchId);
                            MessengerPacket.A = addable;
                            string MessengerPacketString = JsonConvert.SerializeObject(MessengerPacket);
                            sendData("024" + MessengerPacketString + "#");
                        }
                        break;
                    case 25: // Messenger - request user as a friend
                        MessengerAddBuddyPacket addBuddyPacket = (MessengerAddBuddyPacket)JsonConvert.DeserializeObject(packetBody, typeof(MessengerAddBuddyPacket));
                        if (addBuddyPacket.I > 0 && Messenger.hasFriendRequests(addBuddyPacket.I) == false && Messenger.hasFriendship(addBuddyPacket.I) == false)
                        {
                            int requestID = MySQL.runRead("SELECT MAX(requestid) FROM messenger_friendrequests WHERE userid_to = '" + addBuddyPacket.I + "'", null) + 1;

                            MySQL.runQuery("INSERT INTO messenger_friendrequests(userid_to,userid_from,requestid) VALUES ('" + addBuddyPacket.I + "','" + _UserID + "','" + requestID + "')");

                            MessengerRequestArrayPacket[] request = new MessengerRequestArrayPacket[1];
                            MessengerRequestArrayPacket newRequest = new MessengerRequestArrayPacket();
                            newRequest.I = requestID;
                            newRequest.N = _Username;
                            request[0] = newRequest;
                            MessengerRequestPacket NewMessengerRequest = new MessengerRequestPacket();
                            NewMessengerRequest.R = request;
                            string NewMessengerRequestString = JsonConvert.SerializeObject(NewMessengerRequest);
                            UserManager.sendToUser(addBuddyPacket.I, "027" + NewMessengerRequestString + "#");
                        }
                        break;
                    case 22: // Messenger - change mission
                        MessengerMissionPacket missionPacket = (MessengerMissionPacket)JsonConvert.DeserializeObject(packetBody, typeof(MessengerMissionPacket));
                        string newMission = Regex.Replace(missionPacket.M, "<(.|\n)*?>", ""); // html check, removes tags
                        if (missionPacket.M.Length < 22)
                        {
                            MySQL.runQuery("UPDATE members SET messenger = '" + MySQL.Stripslash(newMission) + "' WHERE id = '" + _UserID + "'");
                        }
                        Messenger.changeMission(newMission); // let the others know!
                        break;
                    case 28: // Messenger - accept/decline friendrequest
                        MessengerRequestAnswer requestAnswer = (MessengerRequestAnswer)JsonConvert.DeserializeObject(packetBody, typeof(MessengerRequestAnswer));
                        if (requestAnswer.A)
                        {
                            // friendship accepted
                            Buddy Me = new Buddy(_UserID, _Username, _MessengerMission, "");
                            int fromUserID = MySQL.runRead("SELECT userid_from FROM messenger_friendrequests WHERE userid_to = '" + this._UserID + "' AND requestid = '" + requestAnswer.I + "'", null);
                            if (fromUserID == 0) // Corrupt data
                                return;
                            string[] buddyInfo = MySQL.runReadRow("SELECT username, messenger, last_online FROM members WHERE id = '" + fromUserID + "'");
                            Buddy Buddy = new Buddy(fromUserID, buddyInfo[0], buddyInfo[1], buddyInfo[2]);
                            Messenger.addBuddy(Buddy);
                            if (UserManager.containsUser(fromUserID))
                            {
                                UserManager.getUser(fromUserID).Messenger.addBuddy(Me);
                            }
                            MySQL.runQuery("INSERT INTO messenger_friendships(userid,friendid) VALUES ('" + fromUserID + "','" + this._UserID + "')");
                            MySQL.runQuery("DELETE FROM messenger_friendrequests WHERE userid_to = '" + this._UserID + "' AND requestid = '" + requestAnswer.I + "' LIMIT 1");
                        }
                        else
                        {
                            // friendship declined
                            MySQL.runQuery("DELETE FROM messenger_friendrequests WHERE userid_to = '" + this._UserID + "' AND requestid = '" + requestAnswer.I + "' LIMIT 1");
                        }
                        break;
                    case 26: // Messenger - remove buddy
                        MessengerRemoveBuddyPacket removeBuddyPacket = (MessengerRemoveBuddyPacket)JsonConvert.DeserializeObject(packetBody, typeof(MessengerRemoveBuddyPacket));
                        Messenger.removeBuddy(removeBuddyPacket.I);
                        if (UserManager.containsUser(removeBuddyPacket.I))
                        {
                            UserManager.getUser(removeBuddyPacket.I).Messenger.removeBuddy(_UserID);
                        }
                        MySQL.runQuery("DELETE FROM messenger_friendships WHERE (userid = '" + _UserID + "' AND friendid = '" + removeBuddyPacket.I + "') OR (userid = '" + removeBuddyPacket.I + "' AND friendid = '" + _UserID + "') LIMIT 1");
                        break;
                    case 30: // Messenger - send message to buddy
                        MessengerSendMessagePacket sendMessagePacket = (MessengerSendMessagePacket)JsonConvert.DeserializeObject(packetBody, typeof(MessengerSendMessagePacket));
                        if (Messenger.hasFriendship(sendMessagePacket.I))
                        {
                            MySQL.runQuery("INSERT INTO messenger_messages SET userid=" + sendMessagePacket.I + ", friendid='" + _UserID + "', sent_on=NOW(), message='" + MySQL.Stripslash((Regex.Replace(sendMessagePacket.M, "<(.|\n)*?>", "")).Replace("\n", "<br>")) + "';");
                            int messageID = int.Parse(MySQL.runRead("SELECT MAX(messageid) FROM messenger_messages"));
                            if (UserManager.containsUser(sendMessagePacket.I))
                            {
                                UserManager.getUser(sendMessagePacket.I).Messenger.incomingMessage(messageID);
                            }
                        }
                        break;
                    case 32: // Messenger - delete message
                        MessengerDelMessagePacket delMessagePacket = (MessengerDelMessagePacket)JsonConvert.DeserializeObject(packetBody, typeof(MessengerDelMessagePacket));
                        MySQL.runQuery("UPDATE messenger_messages SET `read`='1' WHERE messageid=" + delMessagePacket.I + " AND userid='" + _UserID + "' AND `read`='0' LIMIT 1;");
                        break;
                    #endregion

                    #region Rooms
                    #region Change room
                    case 42:
                        RoomChangePacket ChangeRoomRequest = (RoomChangePacket)JsonConvert.DeserializeObject(packetBody, typeof(RoomChangePacket));

                        if (_Room != null)
                        {
                            _Room.removeUser(this);
                            _Room = null;
                        }

                        if (MySQL.runRead("SELECT id FROM rooms WHERE id = '" + MySQL.Stripslash(ChangeRoomRequest.I.ToString()) + "'", null) == 0)
                        {
                            sendData("043#");
                            return;
                        }
                        else
                        {
                           _Room = RoomManager.joinRoom(this, ChangeRoomRequest.I);
                        }
                        break;
                    #endregion

                    #region Room Leave
                    case 46:
                        _Room.removeUser(this);
                        _Room = null;
                        break;
                        #endregion

                    #region Room chat
                    case 51:
                        if (_Room == null)
                            return;

                        SendMessagePacket ChatMessage = (SendMessagePacket)JsonConvert.DeserializeObject(packetBody, typeof(SendMessagePacket));

                        DateTime epochh = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
                        TimeSpan spann = (DateTime.Now.ToLocalTime() - epochh);

                        if (((int)spann.TotalSeconds - lastmessage) > 0.5)
                        {
                            if (ChatMessage.M.Substring(0, 1) != ":")
                            {
                                if (ChatMessage.T == "R")
                                {
                                    _Room.userChat(this, Regex.Replace(ChatMessage.M, "<(.|\n)*?>", ""), _Username);
                                }
                                else
                                {
                                    if (UserManager.containsUser(ChatMessage.T))
                                    {
                                        SendMessageReplyPacket ToSendChatMessage = new SendMessageReplyPacket();

                                        ToSendChatMessage.U = _Username;
                                        ToSendChatMessage.M = Regex.Replace(ChatMessage.M, "<(.|\n)*?>", "");

                                        string ToSendChatMessageString = JsonConvert.SerializeObject(ToSendChatMessage);

                                        UserManager.sendToUser(ChatMessage.T, "052" + ToSendChatMessageString + "#");
                                    }
                                }

                                lastmessage = (int)spann.TotalSeconds;
                            }
                            else
                            {
                                string[] args = ChatMessage.M.Substring(1).Split(' ');
                                switch (args[0])
                                {
                                    case "whereami":
                                        string IAmIn;

                                        try { IAmIn = _Room.RoomID.ToString(); }
                                        catch { IAmIn = "Nowhere"; }

                                        MessagePacket IAmInAlertMessage = new MessagePacket();

                                        IAmInAlertMessage.T = "User warning";
                                        IAmInAlertMessage.M = IAmIn;

                                        string IAmInAlertMessageString = JsonConvert.SerializeObject(IAmInAlertMessage);

                                        UserManager.sendData("013" + IAmInAlertMessageString + "#");

                                        break;

                                    case "roomalert":
                                        if (RankManager.containsRight(_Rank, "room_alert"))
                                        {
                                            if (_Room != null)
                                            {
                                                MessagePacket AlertMessage = new MessagePacket();

                                                AlertMessage.T = "Room watrnint";
                                                AlertMessage.M = ChatMessage.M.Substring(7);

                                                string AlertMessageString = JsonConvert.SerializeObject(AlertMessage);

                                                _Room.sendData("013" + AlertMessageString + "#");
                                            }
                                        }
                                        break;

                                    case "globalalert":
                                        if (RankManager.containsRight(_Rank, "global_alert"))
                                        {
                                            MessagePacket GlobalAlertMessage = new MessagePacket();

                                            GlobalAlertMessage.T = "";
                                            GlobalAlertMessage.M = ChatMessage.M.Substring(13);

                                            string GlobalAlertMessageString = JsonConvert.SerializeObject(GlobalAlertMessage);

                                            UserManager.sendData("013" + GlobalAlertMessageString + "#");
                                        }
                                        break;

                                    case "alertuser":
                                        if (RankManager.containsRight(_Rank, "alert_user") && args.Length > 1)
                                        {
                                            if (UserManager.containsUser(args[1]))
                                            {
                                                MessagePacket UserAlertMessage = new MessagePacket();

                                                UserAlertMessage.T = "";
                                                UserAlertMessage.M = ChatMessage.M.Substring(10 + args[1].Length + 1);

                                                string UserAlertMessageString = JsonConvert.SerializeObject(UserAlertMessage);

                                                UserManager.sendToUser(args[1], "013" + UserAlertMessageString + "#");
                                            }
                                        }
                                        break;

                                    case "ban":
                                        if (RankManager.containsRight(_Rank, "ban_user") && args.Length > 1)
                                        {
                                            if (UserManager.containsUser(args[1]))
                                            {
                                                MySQL.runQuery("UPDATE members SET ban = 'yes' WHERE username = '******'");
                                                UserManager.getUser(args[1]).Disconnect();
                                            }
                                        }
                                        break;

                                    case "online":
                                        StringBuilder onlineUsers = new StringBuilder();
                                        onlineUsers.Append("Peak online: "+UserManager.peakUserCount+"<br>Bots online: "+RoomManager.countBots()+"<br>Users online: <br><br>");
                                        foreach (ConnectedUser User in UserManager._Users.Values)
                                        {
                                            onlineUsers.Append(User._Username + "<br>");
                                        }
                                        sendData(notify(onlineUsers.ToString(), "Users online"));
                                        break;

                                    case "kick":
                                        if (RankManager.containsRight(_Rank, "kick_user") && args.Length > 1)
                                        {
                                            try
                                            {
                                                MessagePacket KickAlertMessage = new MessagePacket();

                                                KickAlertMessage.T = "kick";
                                                KickAlertMessage.M = "gekicked";

                                                string KickAlertMessageString = JsonConvert.SerializeObject(KickAlertMessage);

                                                UserManager.sendToUser(args[1], "045#" + "013" + KickAlertMessageString + "#");
                                                _Room.removeUser(UserManager.getUser(UserManager.getUserID(args[1])));
                                            }
                                            catch
                                            {
                                            }
                                        }
                                        break;
                                    case "bots":
                                        if (RankManager.containsRight(_Rank, "spawn_bots"))
                                        {
                                            _Room.loadBots(int.Parse(args[1]));
                                        }
                                        break;
                                    case "kickbots":
                                        if (RankManager.containsRight(_Rank, "kick_all_bots"))
                                        {
                                            _Room.kickAllBots();
                                        }
                                        break;
                                    case "pickallup":
                                        // pick up all furniture
                                        if (_Room != null)
                                        {
                                           _Room.pickAllUp(this);
                                        }
                                        break;

                                    default:
                                        break;
                                }
                            }
                        }
                        else
                        {
                            sendData("053" + "#");
                        }
                        break;
                    #endregion

                    #region Avatar
                    case 59: // move avatar
                        MoveAvatarClientPacket movepacket = (MoveAvatarClientPacket)JsonConvert.DeserializeObject(packetBody, typeof(MoveAvatarClientPacket));
                        if (movepacket.X != _Room_X || movepacket.Y != _Room_Y)
                        {
                            if (_Room.checkWalk(_Room_X, _Room_Y, movepacket.X, movepacket.Y))
                            {
                                _Room_X_Target = movepacket.X;
                                _Room_Y_Target = movepacket.Y;
                            }
                        }
                        break;
                    case 73: // get drink
                        GetDrinkPacket drinkPacket = (GetDrinkPacket)JsonConvert.DeserializeObject(packetBody, typeof(GetDrinkPacket));
                        if (_Room != null)
                        {
                            _Room.getDrink(drinkPacket.D, this);
                        }
                        break;
                    #endregion

                    #region Kick Bot
                    case 61:
                        if (RankManager.containsRight(_Rank, "kick_bot"))
                        {
                            KickBotPacket kickBotPacket = (KickBotPacket)JsonConvert.DeserializeObject(packetBody, typeof(KickBotPacket));
                            if (_Room != null)
                            {
                                _Room.removeBot(kickBotPacket.I);
                            }
                        }
                        break;
                    #endregion

                    #region Vote
                    case 65:
                        RoomVotePacket roomVote = (RoomVotePacket)JsonConvert.DeserializeObject(packetBody, typeof(RoomVotePacket));
                        if (_Room != null)
                        {
                            _Room.vote(roomVote.V, this);
                        }
                        break;
                    #endregion

                    #region Rights
                    case 77:
                        // give rights
                        RoomRightsPacket roomGiveRights = (RoomRightsPacket)JsonConvert.DeserializeObject(packetBody, typeof(RoomRightsPacket));
                        if (_Room != null)
                        {
                            if (_Room.RoomOwner == _UserID && _Room.containsUser(roomGiveRights.I))
                            {
                                ConnectedUser targetUser = UserManager.getUser(roomGiveRights.I);
                                if (!RankManager.containsRight(targetUser._Rank, "always_rights"))
                                {
                                    if (!targetUser._HasRights)
                                    {
                                        MySQL.runQuery("INSERT INTO room_rights SET roomid='" + _Room.RoomID + "', userid='" + roomGiveRights.I + "';");
                                        targetUser._HasRights = true;

                                        foreach (ConnectedUser usr in _Room._Users.Values)
                                        {
                                            RoomSendRightsPacket sendRightsPacket = new RoomSendRightsPacket();

                                            sendRightsPacket.I = roomGiveRights.I;
                                            sendRightsPacket.R = true;

                                            string sendString = JsonConvert.SerializeObject(sendRightsPacket);

                                            usr.sendData("079" + sendString + "#");
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    case 78:
                        // take rights
                        RoomRightsPacket roomTakeRights = (RoomRightsPacket)JsonConvert.DeserializeObject(packetBody, typeof(RoomRightsPacket));
                        if (_Room != null)
                        {
                            if (_Room.RoomOwner == _UserID && _Room.containsUser(roomTakeRights.I))
                            {
                                ConnectedUser targetUser = UserManager.getUser(roomTakeRights.I);
                                if (!RankManager.containsRight(targetUser._Rank, "always_rights"))
                                {
                                    if (targetUser._HasRights)
                                    {
                                        MySQL.runQuery("DELETE FROM room_rights WHERE roomid = '" + _Room.RoomID + "' AND userid = '" + roomTakeRights.I + "';");
                                        targetUser._HasRights = false;

                                        foreach (ConnectedUser usr in _Room._Users.Values)
                                        {
                                            RoomSendRightsPacket sendRightsPacket = new RoomSendRightsPacket();

                                            sendRightsPacket.I = roomTakeRights.I;
                                            sendRightsPacket.R = false;

                                            string sendString = JsonConvert.SerializeObject(sendRightsPacket);

                                            usr.sendData("079" + sendString + "#");
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    #endregion

                    #region Furniture
                    case 49:
                        // turn
                        if (_Room != null)
                        {
                            FurnitureTurnPacket furni = (FurnitureTurnPacket)JsonConvert.DeserializeObject(packetBody, typeof(FurnitureTurnPacket));
                            _Room.turnFurni(this, furni.I);
                        }
                        break;
                    case 69:
                        // action
                        if (_Room != null)
                        {
                            FurnitureActionPacket furni = (FurnitureActionPacket)JsonConvert.DeserializeObject(packetBody, typeof(FurnitureActionPacket));
                            _Room.actionFurni(this, furni.I);
                        }
                        break;
                    case 50:
                        // move
                        if (_Room != null)
                        {
                            FurnitureMoveClientPacket furni = (FurnitureMoveClientPacket)JsonConvert.DeserializeObject(packetBody, typeof(FurnitureMoveClientPacket));
                            _Room.doFurni(this, furni.I, furni.T);
                        }
                        break;
                    case 75:
                        // client asks picture info
                        if (_Room != null)
                        {
                            PictureAskPacket ask = (PictureAskPacket)JsonConvert.DeserializeObject(packetBody, typeof(PictureAskPacket));
                            string[] pictureData = MySQL.runReadRow("SELECT code, caption FROM camera WHERE id = '" + ask.I + "'");
                            PictureShowPacket showString = new PictureShowPacket();
                            showString.C = pictureData[0];
                            showString.CA = pictureData[1];
                            sendData("076" + JsonConvert.SerializeObject(showString) + "#");

                        }
                        break;
                    #endregion

                    #endregion

                    #region Navigator
                    case 39:
                        sendData("040" + NavigatorManager.dataPacket(this) + "#");
                        break;
                    case 67: // Navigator - perform guestroom search on name/owner with a given criticeria
                            SearchClientPacket searchClientPacket = (SearchClientPacket)JsonConvert.DeserializeObject(packetBody, typeof(SearchClientPacket));
                            string searchString = MySQL.Stripslash(searchClientPacket.S);
                            int ownerID = MySQL.runRead("SELECT id FROM members WHERE username = '******'", null);
                            string[] roomIDsDB = MySQL.runReadColumn("SELECT id FROM rooms WHERE type='private' AND (owner = '" + ownerID + "' OR name LIKE '%" + searchString + "%') ORDER BY score ASC", 0);

                            List<int> roomIDs = new List<int>();
                            for (int i = 0; i < roomIDsDB.Length; i++)
                            {
                                int furniCount = int.Parse(MySQL.runRead("SELECT count(id) FROM items WHERE room='" + roomIDsDB[i] + "'"));
                                if (furniCount > 0) {
                                    roomIDs.Add(int.Parse(roomIDsDB[i]));
                                }
                            }
                            roomIDs.ToArray();
                            RoomDataPacket[] searchRooms = new RoomDataPacket[roomIDs.Count];
                            for (int i = 0; i < roomIDs.Count; i++)
                            {
                                string[] roomData = MySQL.runReadRow("SELECT name, descr, owner, max, safe FROM rooms WHERE id = '" + roomIDs[i] + "'");
                                RoomDataPacket getr = new RoomDataPacket();
                                int roomID = roomIDs[i];
                                getr.I = roomID;
                                getr.N = roomData[0];
                                getr.D = roomData[1];
                                getr.O = NavigatorManager.getUserName(int.Parse(roomData[2]));
                                if (RoomManager.containsRoom(roomID))
                                {
                                    getr.U = RoomManager.getRoom(roomID).countUsers();
                                }
                                else
                                {
                                    getr.U = 0;
                                }
                                getr.M = int.Parse(roomData[3]);
                                getr.T = "private";
                                getr.S = int.Parse(roomData[4]);
                                getr.F = 0; //FAVORIET?

                                searchRooms[i] = getr;
                            }
                            SearchAnswerPacket searchAnswerPacket = new SearchAnswerPacket();
                            searchAnswerPacket.R = searchRooms;
                            string searchPacketString = JsonConvert.SerializeObject(searchAnswerPacket);
                            sendData("068" + searchPacketString + "#");
                            break;
                    case 70:
                        // Create Room

                        string[] holes = new string[6];
                        string[] doors = new string[6];
                        string[] lang = new string[6];
                        string[] breed = new string[6];
                        holes[0] = "";
                        holes[1] = "1_1;2_1;3_1;4_1;1_2;2_2;3_2;4_2;1_3;2_3;3_3;4_3;1_4;2_4;3_4;4_4";
                        holes[2] = "";
                        holes[3] = "";
                        holes[4] = "";
                        holes[5] = "1_1;2_1;3_1;4_1;5_1;6_1;1_2;2_2;3_2;4_2;5_2;6_2;1_3;2_3;1_4;2_4;1_5;2_5;1_6;2_6";
                        doors[0] = "5_0";
                        doors[1] = "5_0";
                        doors[2] = "3_0";
                        doors[3] = "7_0";
                        doors[4] = "3_0";
                        doors[5] = "5_2";
                        lang[0] = "8";
                        lang[1] = "11";
                        lang[2] = "6";
                        lang[3] = "6";
                        lang[4] = "10";
                        lang[5] = "10";
                        breed[0] = "13";
                        breed[1] = "10";
                        breed[2] = "6";
                        breed[3] = "14";
                        breed[4] = "8";
                        breed[5] = "10";

                        CreateRoomPacket CreateRoomPacket = (CreateRoomPacket)JsonConvert.DeserializeObject(packetBody, typeof(CreateRoomPacket));
                        if (CreateRoomPacket.T > 0 && CreateRoomPacket.T < 7)
                        {
                            int arr_type = CreateRoomPacket.T - 1;
                            int room_ID = MySQL.insertGetLast("INSERT INTO rooms SET name='" + MySQL.Stripslash(Regex.Replace(CreateRoomPacket.N, "<(.|\n)*?>", "")) + "', descr='" + MySQL.Stripslash(Regex.Replace(CreateRoomPacket.D, "<(.|\n)*?>", "")) + "', owner='" + _UserID + "', type='private', lang='" + lang[arr_type] + "', breed='" + breed[arr_type] + "', door='" + doors[arr_type] + "', holes='" + holes[arr_type] + "' ");
                            sendData("040" + NavigatorManager.dataPacket(this) + "#");

                            CreateRoomAnswerPacket createRoomAnswer = new CreateRoomAnswerPacket();
                            createRoomAnswer.A = room_ID.ToString();
                            string createRoomAnswerString = JsonConvert.SerializeObject(createRoomAnswer);
                            sendData("071" + createRoomAnswerString + "#");
                        }
                        else
                        {
                            CreateRoomAnswerPacket createRoomAnswer = new CreateRoomAnswerPacket();
                            createRoomAnswer.A = "error";
                            string createRoomAnswerString = JsonConvert.SerializeObject(createRoomAnswer);
                            sendData("071" + createRoomAnswerString + "#");
                        }
                        break;

                    #endregion

                    #region Help Request
                   case 54:
                         HelpRequestPacket data = (HelpRequestPacket)JsonConvert.DeserializeObject(packetBody, typeof(HelpRequestPacket));

                            HelpRequestReplyPacket tosend = new HelpRequestReplyPacket();

                            DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
                            TimeSpan span = (DateTime.Now.ToLocalTime() - epoch);

                            tosend.ID = _UserID;
                            tosend.TI = (int)span.TotalSeconds;
                            tosend.U = _Username;
                            tosend.M = Regex.Replace(data.M, "<(.|\n)*?>", "");

                            UserManager.sendToRank(4, "055" + JsonConvert.SerializeObject(tosend) + "#");

                        break;
                   #endregion

                    #region Credit Codes
                    case 36:
                        RedeemCouponPacket coupondata = (RedeemCouponPacket)JsonConvert.DeserializeObject(packetBody, typeof(RedeemCouponPacket));

                        int code_check = int.Parse(MySQL.runRead("SELECT count(*) FROM credit_codes WHERE code='" + coupondata.C + "'"));
                        if (code_check == 1)
                        {
                            string[] code_data = MySQL.runReadRow("SELECT type, value FROM credit_codes WHERE code = '" + coupondata.C + "'");
                            string type = code_data[0];

                            if (type == "credits")
                            {
                                int value = int.Parse(code_data[1]);
                                if (value != 0)
                                {
                                    _Money += value;

                                    UserNotificationPacket toupdate = new UserNotificationPacket();
                                    toupdate.Cr = _Money;
                                    toupdate.M = _Mission;
                                    toupdate.C = _Figure;
                                    toupdate.B = _Badge;
                                    string toupdatestring = JsonConvert.SerializeObject(toupdate);
                                    sendData("008" + toupdatestring + "#");
                                    sendData("037#"); //coupon code accepted

                                    string cr_text;
                                    if (value == 1)
                                    {
                                        cr_text = TextsManager.get("money1");
                                    }
                                    else
                                    {
                                        cr_text = TextsManager.get("money2");
                                    }
                                    sendData(notify(TextsManager.get("voucher_success1")+" "+value+" "+cr_text+" "+TextsManager.get("voucher_success2"), ""));

                                    MySQL.runQuery("DELETE FROM credit_codes WHERE code = '" + coupondata.C + "'");
                                    MySQL.runQuery("UPDATE members SET money = '" + _Money + "' WHERE id = '" + _UserID + "'");
                                }
                                else
                                {
                                    CouponFailedPacket failmessage = new CouponFailedPacket();
                                    failmessage.E = TextsManager.get("voucher_novalue");
                                    string packettosend = JsonConvert.SerializeObject(failmessage);
                                    sendData("038" + packettosend + "#");
                                    MySQL.runQuery("DELETE FROM credit_codes WHERE code = '" + coupondata.C + "'");
                                }
                            }
                            else if (type == "furni")
                            {
                                CouponFailedPacket failmessage = new CouponFailedPacket();
                                failmessage.E = "Het spijt ons, meubels kunnen nog niet ontvangen<br>worden met Credit Codes. Uw Code blijft bewaard.";
                                string packettosend = JsonConvert.SerializeObject(failmessage);
                                sendData("038" + packettosend + "#");
                            }
                            else
                            {
                                CouponFailedPacket failmessage = new CouponFailedPacket();
                                failmessage.E = TextsManager.get("voucher_error");
                                string packettosend = JsonConvert.SerializeObject(failmessage);
                                sendData("038" + packettosend + "#");
                            }
                        }
                        else
                        {
                            CouponFailedPacket failmessage = new CouponFailedPacket();
                            failmessage.E = TextsManager.get("voucher_incorrect");
                            string packettosend = JsonConvert.SerializeObject(failmessage);
                            sendData("038" + packettosend + "#");
                        }
                        break;
                    #endregion

                    #region Buy Furniture
                    case 34:
                        BuyFurniPacket buyfurni = (BuyFurniPacket)JsonConvert.DeserializeObject(packetBody, typeof(BuyFurniPacket));
                        string answer = "error";
                        string newFurniPacketString = "";
                        if (CatalogueManager.catalogueCheckAccess(buyfurni.C, _Rank) && CatalogueManager.containsFurni(buyfurni.C, buyfurni.F) && buyfurni.A > 0)
                        {
                            CatalogueManager.categoryFurniTemplate catFurniData = CatalogueManager.getFurni(buyfurni.C, buyfurni.F);
                            int amount = buyfurni.A;
                            if (buyfurni.M == "present")
                            {
                                amount = 1;
                            }
                            int price = catFurniData.price * amount;
                            if (_Money >= price || RankManager.containsRight(_Rank, "dont_pay"))
                            {
                                answer = "ok";
                                bool pay = true;
                                bool tradeable = catFurniData.tradeable;
                                if (RankManager.containsRight(_Rank, "dont_pay"))
                                {
                                    pay = false;
                                    if (!RankManager.containsRight(_Rank, "dont_pay_tradeable")) // staff kan spullen die gekocht zijn met te weinig geld niet ruilen
                                    {
                                        tradeable = false;
                                    }
                                }
                                string tradeable_text = "0";
                                if (tradeable)
                                {
                                    tradeable_text = "1";
                                }
                                for (int i = 0; i < amount; i++)
                                {
                                    if (buyfurni.M == "self")
                                    {
                                        int newFurniID = MySQL.insertGetLast("INSERT INTO items SET owner='" + _UserID + "', furni='" + buyfurni.F + "', tradeable='" + tradeable_text + "'");
                                        MySQL.runQuery("INSERT INTO furni_history SET id='" + newFurniID + "', `date`='" + timestamp.get + "', `type`='cata', `from`='0', `to`='" + _UserID + "', credits='" + catFurniData.price + "';");

                                        FurniturePacket newFurni = new FurniturePacket();
                                        newFurni.I = newFurniID;
                                        newFurni.T = "inv";
                                        newFurni.S = 1;
                                        newFurni.SH = 0;
                                        newFurni.H = 1;
                                        newFurni.A = 0;
                                        newFurni.F = buyfurni.F;

                                        newFurniPacketString += "047"+JsonConvert.SerializeObject(newFurni)+"#";
                                    }
                                }
                                if (pay)
                                {
                                    _Money = int.Parse(MySQL.runRead("SELECT money FROM members WHERE id = '" + _UserID + "'"));
                                    _Money = _Money - price;
                                    MySQL.runQuery("UPDATE members SET money = '" + _Money + "' WHERE id = '" + _UserID + "'");
                                    UpdateMoneyPacket UpdateMoney = new UpdateMoneyPacket();
                                    UpdateMoney.M = _Money;
                                    UpdateMoney.S = _SessionEarned;
                                    string UpdateMoneyString = JsonConvert.SerializeObject(UpdateMoney);
                                    sendData("033" + UpdateMoneyString + "#");
                                }
                             }
                             else
                             {
                                answer = "price";
                             }
                        }
                        BuyAnswerPacket buyFurniAnswer = new BuyAnswerPacket();
                        buyFurniAnswer.A = answer;
                        string buyFurniAnswerString = JsonConvert.SerializeObject(buyFurniAnswer);
                        sendData(newFurniPacketString+"035" + buyFurniAnswerString + "#");
                        break;
                    #endregion

                    default:
                        sendData("003#");
                        Disconnect(2000);
                        break;
                }
            }
        }