Exemplo n.º 1
0
        public Player(Client client) : base(client.Character.ObjectType, client.Random)
        {
            try
            {
                if (client.Account.Admin == true)
                {
                    Admin = 1;
                }
                AccountType     = client.Account.AccountType;
                AccountPerks    = new AccountTypePerks(AccountType);
                AccountLifetime = client.Account.AccountLifetime;
                IsVip           = AccountLifetime != DateTime.MinValue;
                Client          = client;
                StatsManager    = new StatsManager(this, client.Random.CurrentSeed);
                Name            = client.Account.Name;
                AccountId       = client.Account.AccountId;
                FameCounter     = new FameCounter(this);
                //TaskManager = new TaskManager(this); // pending addition for future versions
                Tokens         = client.Account.FortuneTokens;
                HpPotionPrice  = 5;
                MpPotionPrice  = 5;
                Level          = client.Character.Level == 0 ? 1 : client.Character.Level;
                Experience     = client.Character.Experience;
                ExperienceGoal = GetExpGoal(Level);
                Stars          = AccountType >= (int)Core.config.AccountType.LEGENDS_OF_LOE_ACCOUNT ? 70 : GetStars();
                Texture1       = client.Character.Tex1;
                Texture2       = client.Character.Tex2;
                Credits        = client.Account.Credits;
                NameChosen     = client.Account.NameChosen;
                CurrentFame    = client.Account.Fame;
                Fame           = client.Character.Fame;
                PetHealing     = null;
                PetAttack      = null;
                if (client.Character.Pet != 0)
                {
                    PetHealing = new List <List <int> >();
                    PetAttack  = new List <int>();
                    PetID      = client.Character.Pet;
                    Tuple <int, int, double> HPData = PetHPHealing.MinMaxBonus(Resolve((ushort)PetID).ObjectDesc.HPTier, Stars);
                    Tuple <int, int, double> MPData = PetMPHealing.MinMaxBonus(Resolve((ushort)PetID).ObjectDesc.MPTier, Stars);
                    PetHealing.Add(new List <int> {
                        HPData.Item1, HPData.Item2, (int)((HPData.Item3 - 1) * 100)
                    });
                    PetHealing.Add(new List <int> {
                        MPData.Item1, MPData.Item2, (int)((MPData.Item3 - 1) * 100)
                    });
                    PetAttack.Add(7750 - Stars * 100);
                    PetAttack.Add(30 + Stars);
                    PetAttack.Add(Resolve((ushort)PetID).ObjectDesc.Projectiles[0].MinDamage);
                    PetAttack.Add(Resolve((ushort)PetID).ObjectDesc.Projectiles[0].MaxDamage);
                }
                LootDropBoostTimeLeft  = client.Character.LootDropTimer;
                lootDropBoostFreeTimer = LootDropBoost;
                LootTierBoostTimeLeft  = client.Character.LootTierTimer;
                lootTierBoostFreeTimer = LootTierBoost;
                FameGoal = (AccountType >= (int)Core.config.AccountType.LEGENDS_OF_LOE_ACCOUNT) ? 0 : GetFameGoal(FameCounter.ClassStats[ObjectType].BestFame);
                Glowing  = false;
                DbGuild guild = GameServer.Manager.Database.GetGuild(client.Account.GuildId);
                if (guild != null)
                {
                    Guild     = GameServer.Manager.Database.GetGuild(client.Account.GuildId).Name;
                    GuildRank = client.Account.GuildRank;
                }
                else
                {
                    Guild     = "";
                    GuildRank = -1;
                }
                HP = client.Character.HP <= 0 ? (int)ObjectDesc.MaxHP : client.Character.HP;
                MP = client.Character.MP;
                ConditionEffects = 0;
                OxygenBar        = 100;
                HasBackpack      = client.Character.HasBackpack == true;
                PlayerSkin       = Client.Account.OwnedSkins.Contains(Client.Character.Skin) ? Client.Character.Skin : 0;
                HealthPotions    = client.Character.HealthPotions < 0 ? 0 : client.Character.HealthPotions;
                MagicPotions     = client.Character.MagicPotions < 0 ? 0 : client.Character.MagicPotions;

                try
                {
                    Locked  = client.Account.Database.GetLockeds(client.Account);
                    Ignored = client.Account.Database.GetIgnoreds(client.Account);
                    Muted   = client.Account.Muted;
                }
                catch (Exception) { }

                if (HasBackpack)
                {
                    Item[] inv =
                        client.Character.Items.Select(
                            _ =>
                            _ == -1
                                    ? null
                                    : (GameServer.Manager.GameData.Items.ContainsKey((ushort)_) ? GameServer.Manager.GameData.Items[(ushort)_] : null))
                        .ToArray();
                    Item[] backpack =
                        client.Character.Backpack.Select(
                            _ =>
                            _ == -1
                                    ? null
                                    : (GameServer.Manager.GameData.Items.ContainsKey((ushort)_) ? GameServer.Manager.GameData.Items[(ushort)_] : null))
                        .ToArray();

                    Inventory = inv.Concat(backpack).ToArray();
                    XElement xElement = GameServer.Manager.GameData.ObjectTypeToElement[ObjectType].Element("SlotTypes");
                    if (xElement != null)
                    {
                        int[] slotTypes =
                            Utils.FromCommaSepString32(
                                xElement.Value);
                        Array.Resize(ref slotTypes, 20);
                        SlotTypes = slotTypes;
                    }
                }
                else
                {
                    Inventory =
                        client.Character.Items.Select(
                            _ =>
                            _ == -1
                                        ? null
                                        : (GameServer.Manager.GameData.Items.ContainsKey((ushort)_) ? GameServer.Manager.GameData.Items[(ushort)_] : null))
                        .ToArray();
                    XElement xElement = GameServer.Manager.GameData.ObjectTypeToElement[ObjectType].Element("SlotTypes");
                    if (xElement != null)
                    {
                        SlotTypes =
                            Utils.FromCommaSepString32(
                                xElement.Value);
                    }
                }
                Stats = (int[])client.Character.Stats.Clone();

                for (var i = 0; i < SlotTypes.Length; i++)
                {
                    if (SlotTypes[i] == 0)
                    {
                        SlotTypes[i] = 10;
                    }
                }

                if (Client.Account.AccountType >= (int)Core.config.AccountType.TUTOR_ACCOUNT)
                {
                    return;
                }

                for (var i = 0; i < 4; i++)
                {
                    if (Inventory[i]?.SlotType != SlotTypes[i])
                    {
                        Inventory[i] = null;
                    }
                }
            }
            catch (Exception) { }
        }
Exemplo n.º 2
0
        public void Teleport(RealmTime time, TELEPORT packet)
        {
            var obj = Client.Player.Owner.GetEntity(packet.ObjectId);

            try
            {
                if (obj == null)
                {
                    return;
                }
                if (!TPCooledDown())
                {
                    SendError("Player.teleportCoolDown");
                    return;
                }
                if (obj.HasConditionEffect(ConditionEffectIndex.Invisible))
                {
                    SendError("server.no_teleport_to_invisible");
                    return;
                }
                if (obj.HasConditionEffect(ConditionEffectIndex.Paused))
                {
                    SendError("server.no_teleport_to_paused");
                    return;
                }
                if (obj is Player player && !player.NameChosen)
                {
                    SendError("server.teleport_needs_name");
                    return;
                }
                if (obj.Id == Id)
                {
                    SendError("server.teleport_to_self");
                    return;
                }
                if (!Owner.AllowTeleport)
                {
                    SendError(GetLanguageString("server.no_teleport_in_realm", new KeyValuePair <string, object>("realm", Owner.Name)));
                    return;
                }

                SetTPDisabledPeriod();
                Move(obj.X, obj.Y);
                FameCounter.Teleport();
                SetNewbiePeriod();
                UpdateCount++;
            }
            catch (Exception)
            {
                SendError("player.cannotTeleportTo");
                return;
            }

            Owner.BroadcastMessage(new GOTO
            {
                ObjectId = Id,
                Position = new Position
                {
                    X = X,
                    Y = Y
                }
            }, null);
            Owner.BroadcastMessage(new SHOWEFFECT
            {
                EffectType = EffectType.Teleport,
                TargetId   = Id,
                PosA       = new Position
                {
                    X = X,
                    Y = Y
                },
                Color = new ARGB(0xFFFFFFFF)
            }, null);
        }
Exemplo n.º 3
0
        public override void Tick(RealmTime time)
        {
            try
            {
                if (Manager.Clients.Count(_ => _.Value.Id == Client.Id) == 0)
                {
                    if (Owner != null)
                    {
                        Owner.LeaveWorld(this);
                    }
                    else
                    {
                        WorldInstance.LeaveWorld(this);
                    }
                    Manager.Database.DoActionAsync(db => db.UnlockAccount(Client.Account));
                    return;
                }
                if (Client.Stage == ProtocalStage.Disconnected || (!Client.Account.VerifiedEmail && Program.Verify))
                {
                    if (Owner != null)
                    {
                        Owner.LeaveWorld(this);
                    }
                    else
                    {
                        WorldInstance.LeaveWorld(this);
                    }
                    Manager.Database.DoActionAsync(db => db.UnlockAccount(Client.Account));
                    return;
                }
            }
            catch (Exception e)
            {
                log.Error(e);
            }

            if (Stats != null && Boost != null)
            {
                MaxHp = Stats[0] + Boost[0];
                MaxMp = Stats[1] + Boost[1];
            }



            if (CheckHalfMPAImmune() && Mp >= MaxMp / 2)
            {
                ApplyConditionEffect(new ConditionEffect
                {
                    Effect     = ConditionEffectIndex.ArmorBreakImmune,
                    DurationMS = -1
                });
            }
            else
            {
                ApplyConditionEffect(new ConditionEffect
                {
                    Effect     = ConditionEffectIndex.ArmorBreakImmune,
                    DurationMS = 0
                });
            }

            if (!KeepAlive(time))
            {
                return;
            }

            if (Boost == null)
            {
                CalcBoost();
            }

            TradeHandler?.Tick(time);
            HandleRegen(time);
            HandleQuest(time);
            HandleEffects(time);
            HandleGround(time);
            HandleBoosts();

            FameCounter.Tick(time);

            //if(pingSerial > 5)
            //    if (!Enumerable.Range(UpdatesSend, 5000).Contains(UpdatesReceived))
            //        Client.Disconnect();

            if (Mp < 0)
            {
                Mp = 0;
            }

            /* try
             * {
             *     psr.Database.SaveCharacter(psr.Account, psr.Character);
             *     UpdateCount++;
             * }
             * catch (ex)
             * {
             * }
             */

            try
            {
                if (Owner != null)
                {
                    SendUpdate(time);
                    if (!Owner.IsPassable((int)X, (int)Y) && Client.Account.Rank < 2)
                    {
                        log.Fatal($"Player {Name} No-Cliped at position: {X}, {Y}");
                    }
                }
            }
            catch (Exception e)
            {
                log.Error(e);
            }
            try
            {
                SendNewTick(time);
            }
            catch (Exception e)
            {
                log.Error(e);
            }

            if (HP < 0 && !dying)
            {
                Death("Unknown");
                return;
            }

            base.Tick(time);
        }
Exemplo n.º 4
0
        public Player(RealmManager manager, Client psr)
            : base(manager, (ushort)psr.Character.ObjectType, psr.Random)
        {
            try
            {
                Client        = psr;
                Manager       = psr.Manager;
                StatsManager  = new StatsManager(this, psr.Random.CurrentSeed);
                Name          = psr.Account.Name;
                AccountId     = psr.Account.AccountId;
                FameCounter   = new FameCounter(this);
                Tokens        = psr.Account.FortuneTokens;
                HpPotionPrice = 5;
                MpPotionPrice = 5;

                Level                  = psr.Character.Level == 0 ? 1 : psr.Character.Level;
                Experience             = psr.Character.Exp;
                ExperienceGoal         = GetExpGoal(Level);
                Stars                  = GetStars();
                Texture1               = psr.Character.Tex1;
                Texture2               = psr.Character.Tex2;
                Credits                = psr.Account.Credits;
                NameChosen             = psr.Account.NameChosen;
                CurrentFame            = psr.Account.Stats.Fame;
                Fame                   = psr.Character.CurrentFame;
                XpBoosted              = psr.Character.XpBoosted;
                XpBoostTimeLeft        = psr.Character.XpTimer;
                xpFreeTimer            = XpBoostTimeLeft != -1.0;
                LootDropBoostTimeLeft  = psr.Character.LDTimer;
                lootDropBoostFreeTimer = LootDropBoost;
                LootTierBoostTimeLeft  = psr.Character.LTTimer;
                lootTierBoostFreeTimer = LootTierBoost;
                var state =
                    psr.Account.Stats.ClassStates.SingleOrDefault(_ => Utils.FromString(_.ObjectType) == ObjectType);
                FameGoal         = GetFameGoal(state?.BestFame ?? 0);
                Glowing          = IsUserInLegends();
                Guild            = GuildManager.Add(this, psr.Account.Guild);
                HP               = psr.Character.HitPoints <= 0 ? psr.Character.MaxHitPoints : psr.Character.HitPoints;
                Mp               = psr.Character.MagicPoints;
                ConditionEffects = 0;
                OxygenBar        = 100;
                HasBackpack      = psr.Character.HasBackpack == 1;
                PlayerSkin       = Client.Account.OwnedSkins.Contains(Client.Character.Skin) ? Client.Character.Skin : 0;
                HealthPotions    = psr.Character.HealthStackCount < 0 ? 0 : psr.Character.HealthStackCount;
                MagicPotions     = psr.Character.MagicStackCount < 0 ? 0 : psr.Character.MagicStackCount;

                Locked  = psr.Account.Locked ?? new List <string>();
                Ignored = psr.Account.Ignored ?? new List <string>();
                try
                {
                    Manager.Database.DoActionAsync(db =>
                    {
                        Locked     = db.GetLockeds(AccountId);
                        Ignored    = db.GetIgnoreds(AccountId);
                        Muted      = db.IsMuted(AccountId);
                        DailyQuest = psr.Account.DailyQuest;
                    });
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }



                if (HasBackpack)
                {
                    var inv =
                        psr.Character.Equipment.Select(
                            _ =>
                            _ == -1
                                    ? null
                                    : (Manager.GameData.Items.ContainsKey((ushort)_) ? Manager.GameData.Items[(ushort)_] : null))
                        .ToArray();
                    var backpack =
                        psr.Character.Backpack.Select(
                            _ =>
                            _ == -1
                                    ? null
                                    : (Manager.GameData.Items.ContainsKey((ushort)_) ? Manager.GameData.Items[(ushort)_] : null))
                        .ToArray();

                    Inventory = inv.Concat(backpack).ToArray();
                    var xElement = Manager.GameData.ObjectTypeToElement[ObjectType].Element("SlotTypes");
                    if (xElement != null)
                    {
                        var slotTypes =
                            Utils.FromCommaSepString32(
                                xElement.Value);
                        Array.Resize(ref slotTypes, 20);
                        SlotTypes = slotTypes;
                    }
                }
                else
                {
                    Inventory =
                        psr.Character.Equipment.Select(
                            _ =>
                            _ == -1
                                    ? null
                                    : (Manager.GameData.Items.ContainsKey((ushort)_) ? Manager.GameData.Items[(ushort)_] : null))
                        .ToArray();
                    var xElement = Manager.GameData.ObjectTypeToElement[ObjectType].Element("SlotTypes");
                    if (xElement != null)
                    {
                        SlotTypes =
                            Utils.FromCommaSepString32(
                                xElement.Value);
                    }
                }
                Stats = new[]
                {
                    psr.Character.MaxHitPoints,
                    psr.Character.MaxMagicPoints,
                    psr.Character.Attack,
                    psr.Character.Defense,
                    psr.Character.Speed,
                    psr.Character.HpRegen,
                    psr.Character.MpRegen,
                    psr.Character.Dexterity
                };

                Pet = null;

                for (var i = 0; i < SlotTypes.Length; i++)
                {
                    if (SlotTypes[i] == 0)
                    {
                        SlotTypes[i] = 10;
                    }
                }

                if (Client.Account.Rank >= 3)
                {
                    return;
                }
                for (var i = 0; i < 4; i++)
                {
                    if (Inventory[i]?.SlotType != SlotTypes[i])
                    {
                        Inventory[i] = null;
                    }
                }
            }
            catch (Exception e)
            {
                log.Error(e);
            }
        }
Exemplo n.º 5
0
        public void SendUpdate(RealmTime time)
        {
            mapWidth  = Owner.Map.Width;
            mapHeight = Owner.Map.Height;
            var map   = Owner.Map;
            var xBase = (int)X;
            var yBase = (int)Y;

            var sendEntities = new HashSet <Entity>(GetNewEntities());

            var list = new List <UpdatePacket.TileData>(APPOX_AREA_OF_SIGHT);
            var sent = 0;

            foreach (var i in Sight.GetSightCircle(SIGHTRADIUS))
            {
                var x = i.X + xBase;
                var y = i.Y + yBase;

                WmapTile tile;
                if (x < 0 || x >= mapWidth ||
                    y < 0 || y >= mapHeight ||
                    tiles[x, y] >= (tile = map[x, y]).UpdateCount)
                {
                    continue;
                }

                var world = Manager.GetWorld(Owner.Id);
                if (world.Dungeon)
                {
                    //Todo add blocksight
                }

                list.Add(new UpdatePacket.TileData()
                {
                    X    = (short)x,
                    Y    = (short)y,
                    Tile = tile.TileId
                });
                tiles[x, y] = tile.UpdateCount;
                sent++;
            }
            FameCounter.TileSent(sent);

            var dropEntities = GetRemovedEntities().Distinct().ToArray();

            clientEntities.RemoveWhere(_ => Array.IndexOf(dropEntities, _.Id) != -1);

            var toRemove = lastUpdate.Keys.Where(i => !clientEntities.Contains(i)).ToList();

            toRemove.ForEach(i => lastUpdate.Remove(i));

            foreach (var i in sendEntities)
            {
                lastUpdate[i] = i.UpdateCount;
            }

            var newStatics    = GetNewStatics(xBase, yBase).ToArray();
            var removeStatics = GetRemovedStatics(xBase, yBase).ToArray();
            var removedIds    = new List <int>();

            foreach (var i in removeStatics)
            {
                removedIds.Add(Owner.Map[i.X, i.Y].ObjId);
                clientStatic.Remove(i);
            }

            if (sendEntities.Count <= 0 && list.Count <= 0 && dropEntities.Length <= 0 && newStatics.Length <= 0 &&
                removedIds.Count <= 0)
            {
                return;
            }
            var packet = new UpdatePacket()
            {
                Tiles            = list.ToArray(),
                NewObjects       = sendEntities.Select(_ => _.ToDefinition()).Concat(newStatics).ToArray(),
                RemovedObjectIds = dropEntities.Concat(removedIds).ToArray()
            };

            Client.SendPacket(packet);
            UpdatesSend++;
        }
Exemplo n.º 6
0
        public void Teleport(RealmTime time, TeleportPacket packet)
        {
            var obj = Client.Player.Owner.GetEntity(packet.ObjectId);

            try
            {
                if (obj == null)
                {
                    return;
                }
                if (!TPCooledDown())
                {
                    SendError("Player.teleportCoolDown");
                    return;
                }
                if (obj.HasConditionEffect(ConditionEffectIndex.Paused))
                {
                    SendError("server.no_teleport_to_paused");
                    return;
                }
                var player = obj as Player;
                if (player != null && !player.NameChosen)
                {
                    SendError("server.teleport_needs_name");
                    return;
                }
                if (obj.Id == Id)
                {
                    SendError("server.teleport_to_self");
                    return;
                }
                if (!Owner.AllowTeleport)
                {
                    SendError(GetLanguageString("server.no_teleport_in_realm", new KeyValuePair <string, object>("realm", Owner.Name)));
                    return;
                }

                if (CheckTeleportLowHp() && HP <= MaxHp / 2)
                {
                    ApplyConditionEffect(new ConditionEffect
                    {
                        Effect     = ConditionEffectIndex.Damaging,
                        DurationMS = 5000
                    });
                }
                else
                {
                    ApplyConditionEffect(new ConditionEffect
                    {
                        Effect     = ConditionEffectIndex.Damaging,
                        DurationMS = 0
                    });
                }


                SetTPDisabledPeriod();
                Move(obj.X, obj.Y);
                Pet?.Move(obj.X, obj.X);
                FameCounter.Teleport();
                SetNewbiePeriod();
                UpdateCount++;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                SendError("player.cannotTeleportTo");
                return;
            }
            Owner.BroadcastPacket(new GotoPacket
            {
                ObjectId = Id,
                Position = new Position
                {
                    X = X,
                    Y = Y
                }
            }, null);
            if (!isNotVisible)
            {
                Owner.BroadcastPacket(new ShowEffectPacket
                {
                    EffectType = EffectType.Teleport,
                    TargetId   = Id,
                    PosA       = new Position
                    {
                        X = X,
                        Y = Y
                    },
                    Color = new ARGB(0xFFFFFFFF)
                }, null);
            }
        }
Exemplo n.º 7
0
        public void UseItem(RealmTime time, int objId, int slot, Position pos)
        {
            using (TimedLock.Lock(_useLock))
            {
                //Log.Debug(objId + ":" + slot);
                var entity = Owner.GetEntity(objId);
                if (entity == null)
                {
                    Client.SendPacket(new InvResult()
                    {
                        Result = 1
                    });
                    return;
                }

                if (entity is Player && objId != Id)
                {
                    Client.SendPacket(new InvResult()
                    {
                        Result = 1
                    });
                    return;
                }

                var container = entity as IContainer;

                // eheh no more clearing BBQ loot bags
                if (this.Dist(entity) > 3)
                {
                    Client.SendPacket(new InvResult()
                    {
                        Result = 1
                    });
                    return;
                }

                var cInv = container?.Inventory.CreateTransaction();

                // get item
                Item item = null;
                foreach (var stack in Stacks.Where(stack => stack.Slot == slot))
                {
                    item = stack.Pull();

                    if (item == null)
                    {
                        return;
                    }

                    break;
                }
                if (item == null)
                {
                    if (container == null)
                    {
                        return;
                    }

                    item = cInv[slot];
                }

                if (item == null)
                {
                    return;
                }

                // make sure not trading and trying to cunsume item
                if (tradeTarget != null && item.Consumable)
                {
                    return;
                }

                if (MP < item.MpCost)
                {
                    Client.SendPacket(new InvResult()
                    {
                        Result = 1
                    });
                    return;
                }


                // use item
                var slotType = 10;
                if (slot < cInv.Length)
                {
                    slotType = container.SlotTypes[slot];

                    if (item.TypeOfConsumable)
                    {
                        var gameData = Manager.Resources.GameData;
                        var db       = Manager.Database;

                        if (item.Consumable)
                        {
                            Item successor = null;
                            if (item.SuccessorId != null)
                            {
                                successor = gameData.Items[gameData.IdToObjectType[item.SuccessorId]];
                            }
                            cInv[slot] = successor;
                        }

                        var trans = db.Conn.CreateTransaction();
                        if (container is GiftChest)
                        {
                            if (successor != null)
                            {
                                db.SwapGift(Client.Account, item.ObjectType, successor.ObjectType, trans);
                            }
                            else
                            {
                                db.RemoveGift(Client.Account, item.ObjectType, trans);
                            }
                        }
                        var task = trans.ExecuteAsync();
                        task.ContinueWith(t =>
                        {
                            var success = !t.IsCanceled && t.Result;
                            if (!success || !Inventory.Execute(cInv)) // can result in the loss of an item if inv trans fails...
                            {
                                entity.ForceUpdate(slot);
                                return;
                            }

                            if (slotType > 0)
                            {
                                FameCounter.UseAbility();
                            }
                            else
                            {
                                if (item.ActivateEffects.Any(eff => eff.Effect == ActivateEffects.Heal ||
                                                             eff.Effect == ActivateEffects.HealNova ||
                                                             eff.Effect == ActivateEffects.Magic ||
                                                             eff.Effect == ActivateEffects.MagicNova))
                                {
                                    FameCounter.DrinkPot();
                                }
                            }

                            Activate(time, item, pos);
                        });
                        task.ContinueWith(e =>
                                          Log.Error(e.Exception.InnerException.ToString()),
                                          TaskContinuationOptions.OnlyOnFaulted);
                        return;
                    }

                    if (slotType > 0)
                    {
                        FameCounter.UseAbility();
                    }
                }
                else
                {
                    FameCounter.DrinkPot();
                }

                //Log.Debug(item.SlotType + ":" + slotType);
                if (item.Consumable || item.SlotType == slotType)
                {
                    //Log.Debug("HUH");
                    Activate(time, item, pos);
                }
                else
                {
                    Client.SendPacket(new InvResult()
                    {
                        Result = 1
                    });
                }
            }
        }
Exemplo n.º 8
0
        public override void Tick(RealmTime time)
        {
            try
            {
                if (Client.State == ProtocolState.Disconnected)
                {
                    if (Owner != null)
                    {
                        Owner.LeaveWorld(this);
                    }
                    else
                    {
                        WorldInstance.LeaveWorld(this);
                    }
                    return;
                }
            }
            catch (Exception e)
            {
                log.Error(e);
            }
            if (Stats != null && Boost != null)
            {
                MaxHp = Stats[0] + Boost[0];
                MaxMp = Stats[1] + Boost[1];
            }

            if (!KeepAlive(time))
            {
                return;
            }

            if (Boost == null)
            {
                CalcBoost();
            }

            if (!HasConditionEffect(ConditionEffects.Paused))
            {
                HandleRegen(time);
                HandleGround(time);
                FameCounter.Tick(time);
            }

            TradeHandler?.Tick(time);
            HandleQuest(time);
            HandleEffects(time);
            HandleBoosts();

            if (Mp < 0)
            {
                Mp = 0;
            }

            if (Owner != null)
            {
                SendNewTick(time);
                SendUpdate(time);
            }

            if (HP < 0 && !dying)
            {
                Death("Unknown");
                return;
            }

            base.Tick(time);
        }
Exemplo n.º 9
0
        private void SendUpdate(RealmTime time)
        {
            // init sight circle
            var sCircle = Sight.GetSightCircle(Owner.Blocking);

            // get list of tiles for update
            var tilesUpdate = new List <Update.TileData>(AppoxAreaOfSight);

            foreach (var point in sCircle)
            {
                var x    = point.X;
                var y    = point.Y;
                var tile = Owner.Map[x, y];

                if (tile.TileId == 255 ||
                    tiles[x, y] >= tile.UpdateCount)
                {
                    continue;
                }

                tilesUpdate.Add(new Update.TileData()
                {
                    X    = (short)x,
                    Y    = (short)y,
                    Tile = (Tile)tile.TileId
                });
                tiles[x, y] = tile.UpdateCount;
            }
            FameCounter.TileSent(tilesUpdate.Count);

            // get list of new static objects to add
            var staticsUpdate = GetNewStatics(sCircle).ToArray();

            // get dropped entities list
            var entitiesRemove = new HashSet <int>(GetRemovedEntities(sCircle));

            // removed stale entities
            _clientEntities.RemoveWhere(e => entitiesRemove.Contains(e.Id));

            // get list of added entities
            var entitiesAdd = GetNewEntities(sCircle).ToArray();

            // get dropped statics list
            var staticsRemove = new HashSet <IntPoint>(GetRemovedStatics(sCircle));

            _clientStatic.ExceptWith(staticsRemove);

            if (tilesUpdate.Count > 0 || entitiesRemove.Count > 0 || staticsRemove.Count > 0 ||
                entitiesAdd.Length > 0 || staticsUpdate.Length > 0)
            {
                entitiesRemove.UnionWith(
                    staticsRemove.Select(s => Owner.Map[s.X, s.Y].ObjId));

                _tiles          = tilesUpdate.ToArray();
                _newObjects     = entitiesAdd.Select(_ => _.ToDefinition()).Concat(staticsUpdate).ToArray();
                _removedObjects = entitiesRemove.ToArray();
                _client.SendPacket(new Update
                {
                    Tiles   = _tiles,
                    NewObjs = _newObjects,
                    Drops   = _removedObjects
                });
                AwaitUpdateAck(time.TotalElapsedMs);
            }
        }
        public override void Tick(RealmTime time)
        {
            try
            {
                if (Manager.Clients.Count(_ => _.Value.Id == Client.Id) == 0)
                {
                    if (Owner != null)
                    {
                        Owner.LeaveWorld(this);
                    }
                    else
                    {
                        WorldInstance.LeaveWorld(this);
                    }
                    return;
                }
                if (Client.Stage == ProtocalStage.Disconnected || !Client.Account.VerifiedEmail)
                {
                    if (Owner != null)
                    {
                        Owner.LeaveWorld(this);
                    }
                    else
                    {
                        WorldInstance.LeaveWorld(this);
                    }
                    return;
                }
            }
            catch (Exception e)
            {
                log.Error(e);
            }

            if (Stats != null && Boost != null)
            {
                MaxHp = Stats[0] + Boost[0];
                MaxMp = Stats[1] + Boost[1];
            }

            if (!KeepAlive(time))
            {
                return;
            }

            if (Boost == null)
            {
                CalcBoost();
            }

            TradeHandler?.Tick(time);
            HandleRegen(time);
            HandleQuest(time);
            HandleEffects(time);
            HandleBoosts();

            FameCounter.Tick(time);

            //if(pingSerial > 5)
            //    if (!Enumerable.Range(UpdatesSend, 5000).Contains(UpdatesReceived))
            //        Client.Disconnect();

            if (Mp < 0)
            {
                Mp = 0;
            }

            /* try
             * {
             *     psr.Database.SaveCharacter(psr.Account, psr.Character);
             *     UpdateCount++;
             * }
             * catch (ex)
             * {
             * }
             */

            try
            {
                if (Owner != null)
                {
                    SendUpdate(time);
                    if (!Owner.IsPassable((int)X, (int)Y) && !Client.Account.Admin)
                    {
                        log.Fatal($"Player {Name} No-Cliped at position: {X}, {Y}");
                        Client.Disconnect();
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                log.Error(e);
            }

            try
            {
                SendNewTick(time);
            }
            catch (Exception e)
            {
                log.Error(e);
            }

            if (HP < 0 && !dying)
            {
                Death("Unknown");
                return;
            }

            CheckCurrencyAmounts();

            base.Tick(time);
        }
Exemplo n.º 11
0
        private void Activate(RealmTime time, Item item, Position target)
        {
            MP -= item.MpCost;
            foreach (var eff in item.ActivateEffects)
            {
                switch (eff.Effect)
                {
                case ActivateEffects.BulletNova:
                {
                    var      prjDesc = item.Projectiles[0];    //Assume only one
                    Packet[] batch   = new Packet[21];
                    uint     s       = Random.CurrentSeed;
                    Random.CurrentSeed = (uint)(s * time.tickTimes);
                    for (int i = 0; i < 20; i++)
                    {
                        Projectile proj = CreateProjectile(prjDesc, item.ObjectType,
                                                           (int)StatsManager.GetAttackDamage(prjDesc.MinDamage, prjDesc.MaxDamage),
                                                           time.tickTimes, target, (float)(i * (Math.PI * 2) / 20));
                        Owner.EnterWorld(proj);
                        FameCounter.Shoot(proj);
                        batch[i] = new Shoot2Packet
                        {
                            BulletId      = proj.ProjectileId,
                            OwnerId       = Id,
                            ContainerType = item.ObjectType,
                            StartingPos   = target,
                            Angle         = proj.Angle,
                            Damage        = (short)proj.Damage
                        };
                    }
                    Random.CurrentSeed = s;
                    batch[20]          = new ShowEffectPacket()
                    {
                        EffectType = EffectType.Trail,
                        PosA       = target,
                        TargetId   = Id,
                        Color      = new ARGB(0xFFFF00AA)
                    };
                    BroadcastSync(batch, p => this.Dist(p) < 25);
                }
                break;

                case ActivateEffects.Shoot:
                {
                    ActivateShoot(time, item, target);
                }
                break;

                case ActivateEffects.StatBoostSelf:
                {
                    int idx = -1;
                    switch ((StatsType)eff.Stats)
                    {
                    case StatsType.MaximumHP: idx = 0; break;

                    case StatsType.MaximumMP: idx = 1; break;

                    case StatsType.Attack: idx = 2; break;

                    case StatsType.Defense: idx = 3; break;

                    case StatsType.Speed: idx = 4; break;

                    case StatsType.Vitality: idx = 5; break;

                    case StatsType.Wisdom: idx = 6; break;

                    case StatsType.Dexterity: idx = 7; break;
                    }
                    int s = eff.Amount;
                    Boost[idx] += s;
                    UpdateCount++;
                    Owner.Timers.Add(new WorldTimer(eff.DurationMS, (world, t) =>
                        {
                            Boost[idx] -= s;
                            UpdateCount++;
                        }));
                    BroadcastSync(new ShowEffectPacket()
                        {
                            EffectType = EffectType.Potion,
                            TargetId   = Id,
                            Color      = new ARGB(0xffffffff)
                        }, null);
                }
                break;

                case ActivateEffects.StatBoostAura:
                {
                    int idx = -1;
                    switch ((StatsType)eff.Stats)
                    {
                    case StatsType.MaximumHP: idx = 0; break;

                    case StatsType.MaximumMP: idx = 1; break;

                    case StatsType.Attack: idx = 2; break;

                    case StatsType.Defense: idx = 3; break;

                    case StatsType.Speed: idx = 4; break;

                    case StatsType.Vitality: idx = 5; break;

                    case StatsType.Wisdom: idx = 6; break;

                    case StatsType.Dexterity: idx = 7; break;
                    }
                    int s = eff.Amount;
                    this.AOE(eff.Range / 2, true, player =>
                        {
                            (player as Player).Boost[idx] += s;
                            player.UpdateCount++;
                            Owner.Timers.Add(new WorldTimer(eff.DurationMS, (world, t) =>
                            {
                                (player as Player).Boost[idx] -= s;
                                player.UpdateCount++;
                            }));
                        });
                    BroadcastSync(new ShowEffectPacket()
                        {
                            EffectType = EffectType.AreaBlast,
                            TargetId   = Id,
                            Color      = new ARGB(0xffffffff),
                            PosA       = new Position()
                            {
                                X = eff.Range / 2
                            }
                        }, p => this.Dist(p) < 25);
                }
                break;

                case ActivateEffects.ConditionEffectSelf:
                {
                    ApplyConditionEffect(new ConditionEffect()
                        {
                            Effect     = eff.ConditionEffect.Value,
                            DurationMS = eff.DurationMS
                        });
                    BroadcastSync(new ShowEffectPacket()
                        {
                            EffectType = EffectType.AreaBlast,
                            TargetId   = Id,
                            Color      = new ARGB(0xffffffff),
                            PosA       = new Position()
                            {
                                X = 1
                            }
                        }, p => this.Dist(p) < 25);
                }
                break;

                case ActivateEffects.ConditionEffectAura:
                {
                    this.AOE(eff.Range / 2, true, player =>
                        {
                            player.ApplyConditionEffect(new ConditionEffect()
                            {
                                Effect     = eff.ConditionEffect.Value,
                                DurationMS = eff.DurationMS
                            });
                        });
                    uint color = 0xffffffff;
                    if (eff.ConditionEffect.Value == ConditionEffectIndex.Damaging)
                    {
                        color = 0xffff0000;
                    }
                    BroadcastSync(new ShowEffectPacket()
                        {
                            EffectType = EffectType.AreaBlast,
                            TargetId   = Id,
                            Color      = new ARGB(color),
                            PosA       = new Position()
                            {
                                X = eff.Range / 2
                            }
                        }, p => this.Dist(p) < 25);
                }
                break;

                case ActivateEffects.Heal:
                {
                    List <Packet> pkts = new List <Packet>();
                    ActivateHealHp(this, eff.Amount, pkts);
                    BroadcastSync(pkts, p => this.Dist(p) < 25);
                }
                break;

                case ActivateEffects.HealNova:
                {
                    List <Packet> pkts = new List <Packet>();
                    this.AOE(eff.Range / 2, true, player =>
                        {
                            ActivateHealHp(player as Player, eff.Amount, pkts);
                        });
                    pkts.Add(new ShowEffectPacket()
                        {
                            EffectType = EffectType.AreaBlast,
                            TargetId   = Id,
                            Color      = new ARGB(0xffffffff),
                            PosA       = new Position()
                            {
                                X = eff.Range / 2
                            }
                        });
                    BroadcastSync(pkts, p => this.Dist(p) < 25);
                }
                break;

                case ActivateEffects.Magic:
                {
                    List <Packet> pkts = new List <Packet>();
                    ActivateHealMp(this, eff.Amount, pkts);
                    BroadcastSync(pkts, p => this.Dist(p) < 25);
                }
                break;

                case ActivateEffects.MagicNova:
                {
                    List <Packet> pkts = new List <Packet>();
                    this.AOE(eff.Range / 2, true, player =>
                        {
                            ActivateHealMp(player as Player, eff.Amount, pkts);
                        });
                    pkts.Add(new ShowEffectPacket()
                        {
                            EffectType = EffectType.AreaBlast,
                            TargetId   = Id,
                            Color      = new ARGB(0xffffffff),
                            PosA       = new Position()
                            {
                                X = eff.Range / 2
                            }
                        });
                    BroadcastSync(pkts, p => this.Dist(p) < 25);
                }
                break;

                case ActivateEffects.Teleport:
                {
                    Move(target.X, target.Y);
                    UpdateCount++;
                    Owner.BroadcastPackets(new Packet[]
                        {
                            new GotoPacket()
                            {
                                ObjectId = Id,
                                Position = new Position()
                                {
                                    X = X,
                                    Y = Y
                                }
                            },
                            new ShowEffectPacket()
                            {
                                EffectType = EffectType.Teleport,
                                TargetId   = Id,
                                PosA       = new Position()
                                {
                                    X = X,
                                    Y = Y
                                },
                                Color = new ARGB(0xFFFFFFFF)
                            }
                        }, null);
                }
                break;

                case ActivateEffects.VampireBlast:
                {
                    List <Packet> pkts = new List <Packet>();
                    pkts.Add(new ShowEffectPacket()
                        {
                            EffectType = EffectType.Trail,
                            TargetId   = Id,
                            PosA       = target,
                            Color      = new ARGB(0xFFFF0000)
                        });
                    pkts.Add(new AOEPacket()
                        {
                            Position       = target,
                            Radius         = eff.Radius,
                            Damage         = (ushort)eff.TotalDamage,
                            EffectDuration = 0,
                            Effects        = 0,
                            OriginType     = (short)item.ObjectType
                        });

                    int totalDmg = 0;
                    var enemies  = new List <Enemy>();
                    Owner.AOE(target, eff.Radius, false, enemy =>
                        {
                            enemies.Add(enemy as Enemy);
                            totalDmg += (enemy as Enemy).Damage(this, time, eff.TotalDamage, false);
                        });
                    var players = new List <Player>();
                    this.AOE(eff.Radius, true, player =>
                        {
                            players.Add(player as Player);
                            ActivateHealHp(player as Player, totalDmg, pkts);
                        });

                    Random rand = new Random();
                    for (int i = 0; i < 5; i++)
                    {
                        Enemy  a = enemies[rand.Next(0, enemies.Count)];
                        Player b = players[rand.Next(0, players.Count)];
                        pkts.Add(new ShowEffectPacket()
                            {
                                EffectType = EffectType.Flow,
                                TargetId   = b.Id,
                                PosA       = new Position()
                                {
                                    X = a.X, Y = a.Y
                                },
                                Color = new ARGB(0xffffffff)
                            });
                    }

                    BroadcastSync(pkts, p => this.Dist(p) < 25);
                }
                break;

                case ActivateEffects.Trap:
                {
                    BroadcastSync(new ShowEffectPacket()
                        {
                            EffectType = EffectType.Throw,
                            Color      = new ARGB(0xff9000ff),
                            TargetId   = Id,
                            PosA       = target
                        }, p => this.Dist(p) < 25);
                    Owner.Timers.Add(new WorldTimer(1500, (world, t) =>
                        {
                            Trap trap = new Trap(
                                this,
                                eff.Radius,
                                eff.TotalDamage,
                                eff.ConditionEffect ?? ConditionEffectIndex.Slowed,
                                eff.EffectDuration);
                            trap.Move(target.X, target.Y);
                            world.EnterWorld(trap);
                        }));
                }
                break;

                case ActivateEffects.StasisBlast:
                {
                    List <Packet> pkts = new List <Packet>();

                    pkts.Add(new ShowEffectPacket()
                        {
                            EffectType = EffectType.Concentrate,
                            TargetId   = Id,
                            PosA       = target,
                            PosB       = new Position()
                            {
                                X = target.X + 3, Y = target.Y
                            },
                            Color = new ARGB(0xffffffff)
                        });
                    Owner.AOE(target, 3, false, enemy =>
                        {
                            if (enemy.HasConditionEffect(ConditionEffects.StasisImmune))
                            {
                                pkts.Add(new NotificationPacket()
                                {
                                    ObjectId = enemy.Id,
                                    Color    = new ARGB(0xff00ff00),
                                    Text     = "{\"key\":\"blank\",\"tokens\":{\"data\":\"Immune\"}}"
                                });
                            }
                            else if (!enemy.HasConditionEffect(ConditionEffects.Stasis))
                            {
                                enemy.ApplyConditionEffect(
                                    new ConditionEffect()
                                {
                                    Effect     = ConditionEffectIndex.Stasis,
                                    DurationMS = eff.DurationMS
                                },
                                    new ConditionEffect()
                                {
                                    Effect     = ConditionEffectIndex.Confused,
                                    DurationMS = eff.DurationMS
                                }
                                    );
                                Owner.Timers.Add(new WorldTimer(eff.DurationMS, (world, t) =>
                                {
                                    enemy.ApplyConditionEffect(new ConditionEffect()
                                    {
                                        Effect     = ConditionEffectIndex.StasisImmune,
                                        DurationMS = 3000
                                    }
                                                               );
                                }
                                                                ));
                                pkts.Add(new NotificationPacket()
                                {
                                    ObjectId = enemy.Id,
                                    Color    = new ARGB(0xffff0000),
                                    Text     = "{\"key\":\"blank\",\"tokens\":{\"data\":\"Stasis\"}}"
                                });
                            }
                        });
                    BroadcastSync(pkts, p => this.Dist(p) < 25);
                }
                break;

                case ActivateEffects.Decoy:
                {
                    var decoy = new Decoy(this, eff.DurationMS, StatsManager.GetSpeed());
                    decoy.Move(X, Y);
                    Owner.EnterWorld(decoy);
                }
                break;

                case ActivateEffects.Lightning:
                {
                    Enemy  start = null;
                    double angle = Math.Atan2(target.Y - Y, target.X - X);
                    double diff  = Math.PI / 3;
                    Owner.AOE(target, 6, false, enemy =>
                        {
                            if (!(enemy is Enemy))
                            {
                                return;
                            }
                            var x = Math.Atan2(enemy.Y - Y, enemy.X - X);
                            if (Math.Abs(angle - x) < diff)
                            {
                                start = enemy as Enemy;
                                diff  = Math.Abs(angle - x);
                            }
                        });
                    if (start == null)
                    {
                        break;
                    }

                    Enemy   current = start;
                    Enemy[] targets = new Enemy[eff.MaxTargets];
                    for (int i = 0; i < targets.Length; i++)
                    {
                        targets[i] = current;
                        Enemy next = current.GetNearestEntity(8, false,
                                                              enemy =>
                                                              enemy is Enemy &&
                                                              Array.IndexOf(targets, enemy) == -1 &&
                                                              this.Dist(enemy) <= 6) as Enemy;

                        if (next == null)
                        {
                            break;
                        }
                        else
                        {
                            current = next;
                        }
                    }

                    List <Packet> pkts = new List <Packet>();
                    for (int i = 0; i < targets.Length; i++)
                    {
                        if (targets[i] == null)
                        {
                            break;
                        }
                        Entity prev = i == 0 ? (Entity)this : targets[i - 1];
                        targets[i].Damage(this, time, eff.TotalDamage, false);
                        if (eff.ConditionEffect != null)
                        {
                            targets[i].ApplyConditionEffect(new ConditionEffect()
                                {
                                    Effect     = eff.ConditionEffect.Value,
                                    DurationMS = (int)(eff.EffectDuration * 1000)
                                });
                        }
                        pkts.Add(new ShowEffectPacket()
                            {
                                EffectType = EffectType.Lightning,
                                TargetId   = prev.Id,
                                Color      = new ARGB(0xffff0088),
                                PosA       = new Position()
                                {
                                    X = targets[i].X,
                                    Y = targets[i].Y
                                },
                                PosB = new Position()
                                {
                                    X = 350
                                }
                            });
                    }
                    BroadcastSync(pkts, p => this.Dist(p) < 25);
                }
                break;

                case ActivateEffects.PoisonGrenade:
                {
                    BroadcastSync(new ShowEffectPacket()
                        {
                            EffectType = EffectType.Throw,
                            Color      = new ARGB(0xffddff00),
                            TargetId   = Id,
                            PosA       = target
                        }, p => this.Dist(p) < 25);
                    Placeholder x = new Placeholder(Manager, 1500);
                    x.Move(target.X, target.Y);
                    Owner.EnterWorld(x);
                    Owner.Timers.Add(new WorldTimer(1500, (world, t) =>
                        {
                            Owner.BroadcastPacket(new ShowEffectPacket()
                            {
                                EffectType = EffectType.AreaBlast,
                                Color      = new ARGB(0xffddff00),
                                TargetId   = x.Id,
                                PosA       = new Position()
                                {
                                    X = eff.Radius
                                }
                            }, null);
                            List <Enemy> enemies = new List <Enemy>();
                            Owner.AOE(target, eff.Radius, false,
                                      enemy => PoisonEnemy(enemy as Enemy, eff));
                        }));
                }
                break;

                case ActivateEffects.RemoveNegativeConditions:
                {
                    this.AOE(eff.Range / 2, true, player =>
                        {
                            ApplyConditionEffect(NegativeEffs);
                        });
                    BroadcastSync(new ShowEffectPacket()
                        {
                            EffectType = EffectType.AreaBlast,
                            TargetId   = Id,
                            Color      = new ARGB(0xffffffff),
                            PosA       = new Position()
                            {
                                X = eff.Range / 2
                            }
                        }, p => this.Dist(p) < 25);
                }
                break;

                case ActivateEffects.RemoveNegativeConditionsSelf:
                {
                    ApplyConditionEffect(NegativeEffs);
                    BroadcastSync(new ShowEffectPacket()
                        {
                            EffectType = EffectType.AreaBlast,
                            TargetId   = Id,
                            Color      = new ARGB(0xffffffff),
                            PosA       = new Position()
                            {
                                X = 1
                            }
                        }, p => this.Dist(p) < 25);
                }
                break;

                case ActivateEffects.IncrementStat:
                {
                    int idx = -1;
                    switch ((StatsType)eff.Stats)
                    {
                    case StatsType.MaximumHP: idx = 0; break;

                    case StatsType.MaximumMP: idx = 1; break;

                    case StatsType.Attack: idx = 2; break;

                    case StatsType.Defense: idx = 3; break;

                    case StatsType.Speed: idx = 4; break;

                    case StatsType.Vitality: idx = 5; break;

                    case StatsType.Wisdom: idx = 6; break;

                    case StatsType.Dexterity: idx = 7; break;
                    }
                    Stats[idx] += eff.Amount;
                    int limit = int.Parse(Manager.GameData.ObjectTypeToElement[ObjectType].Element(StatsManager.StatsIndexToName(idx)).Attribute("max").Value);
                    if (Stats[idx] > limit)
                    {
                        Stats[idx] = limit;
                    }
                    UpdateCount++;
                }
                break;

                case ActivateEffects.Create:     //this is a portal
                {
                    ushort objType;
                    if (!Manager.GameData.IdToObjectType.TryGetValue(eff.Id, out objType) ||
                        !Manager.GameData.Portals.ContainsKey(objType))
                    {
                        break;        // object not found, ignore
                    }
                    var    entity      = Resolve(Manager, objType);
                    var    w           = Manager.GetWorld(Owner.Id); //can't use Owner here, as it goes out of scope
                    int    TimeoutTime = Manager.GameData.Portals[objType].TimeoutTime;
                    string DungName    = Manager.GameData.Portals[objType].DungeonName;

                    var color = new ARGB(0x00FF00);

                    entity.Move(X, Y);
                    w.EnterWorld(entity);

                    w.BroadcastPacket(new NotificationPacket
                        {
                            Color = color,
                            Text  =
                                "{\"key\":\"blank\",\"tokens\":{\"data\":\"" + DungName + " opened by " +
                                Client.Account.Name + "\"}}",
                            ObjectId = Client.Player.Id
                        }, null);

                    w.BroadcastPacket(new TextPacket
                        {
                            BubbleTime = 0,
                            Stars      = -1,
                            Name       = "",
                            Text       = DungName + " opened by " + Client.Account.Name
                        }, null);

                    w.Timers.Add(new WorldTimer(TimeoutTime * 1000, (world, t) =>         //default portal close time * 1000
                        {
                            try
                            {
                                w.LeaveWorld(entity);
                            }
                            catch     //couldn't remove portal, Owner became null. Should be fixed with RealmManager implementation
                            {
                                Console.WriteLine("Couldn't despawn portal.");
                            }
                        }));
                }
                break;

                case ActivateEffects.Dye:
                    if (item.Texture1 != 0)
                    {
                        Texture1 = item.Texture1;
                    }
                    if (item.Texture2 != 0)
                    {
                        Texture2 = item.Texture2;
                    }
                    SaveToCharacter();
                    break;

                case ActivateEffects.Pet:
                case ActivateEffects.UnlockPortal:
                    break;
                }
            }
            UpdateCount++;
        }
Exemplo n.º 12
0
        public override void Init(World owner)
        {
            var x            = 0;
            var y            = 0;
            var spawnRegions = owner.GetSpawnPoints();

            if (spawnRegions.Any())
            {
                var rand    = new System.Random();
                var sRegion = spawnRegions.ElementAt(rand.Next(0, spawnRegions.Length));
                x = sRegion.Key.X;
                y = sRegion.Key.Y;
            }
            Move(x + 0.5f, y + 0.5f);
            tiles = new byte[owner.Map.Width, owner.Map.Height];

            // spawn pet if player has one attached
            var petId = _client.Character.PetId;

            if (petId > 0 && Manager.Config.serverSettings.enablePets)
            {
                var dbPet = new DbPet(Client.Account, petId);
                if (dbPet.ObjectType != 0)
                {
                    var pet = new Pet(Manager, this, dbPet);
                    pet.Move(X, Y);
                    owner.EnterWorld(pet);
                    Pet = pet;
                }
            }

            FameCounter    = new FameCounter(this);
            FameGoal       = GetFameGoal(FameCounter.ClassStats[ObjectType].BestFame);
            ExperienceGoal = GetExpGoal(_client.Character.Level);
            Stars          = GetStars();

            if (owner.Name.Equals("OceanTrench"))
            {
                OxygenBar = 100;
            }

            SetNewbiePeriod();

            if (owner.IsNotCombatMapArea)
            {
                Client.SendPacket(new GlobalNotification
                {
                    Text = Client.Account.Gifts.Length > 0 ? "giftChestOccupied" : "giftChestEmpty"
                });

                if (DeathArena.Instance?.CurrentState != DeathArena.ArenaState.NotStarted && DeathArena.Instance?.CurrentState != DeathArena.ArenaState.Ended)
                {
                    Client.SendPacket(new GlobalNotification
                    {
                        Type = GlobalNotification.ADD_ARENA,
                        Text = $"{{\"name\":\"Oryx Arena\",\"open\":{DeathArena.Instance?.CurrentState == DeathArena.ArenaState.CountDown}}}"
                    });
                }

                if (worlds.logic.Arena.Instance?.CurrentState != worlds.logic.Arena.ArenaState.NotStarted)
                {
                    Client.SendPacket(new GlobalNotification
                    {
                        Type = GlobalNotification.ADD_ARENA,
                        Text = $"{{\"name\":\"Public Arena\",\"open\":{worlds.logic.Arena.Instance?.CurrentState == worlds.logic.Arena.ArenaState.CountDown}}}"
                    });
                }
            }

            base.Init(owner);
        }
        public override void Tick(RealmTime time)
        {
            try
            {
                if (Manager.Clients.Count(_ => _.Value.Id == Client.Id) == 0)
                {
                    if (Owner != null)
                    {
                        Owner.LeaveWorld(this);
                    }
                    else
                    {
                        WorldInstance.LeaveWorld(this);
                    }
                    Manager.Database.DoActionAsync(db => db.UnlockAccount(Client.Account));
                    return;
                }
                if (Client.Stage == ProtocalStage.Disconnected || (!Client.Account.VerifiedEmail && Program.Verify))
                {
                    if (Owner != null)
                    {
                        Owner.LeaveWorld(this);
                    }
                    else
                    {
                        WorldInstance.LeaveWorld(this);
                    }
                    Manager.Database.DoActionAsync(db => db.UnlockAccount(Client.Account));
                    return;
                }
            }
            catch (Exception e)
            {
                logger.Error(e);
            }

            if (Stats != null && Boost != null)
            {
                MaxHp = Stats[0] + Boost[0];
                MaxMp = Stats[1] + Boost[1];
            }

            if (!KeepAlive(time))
            {
                return;
            }

            if (Boost == null)
            {
                CalcBoost();
            }

            TradeHandler?.Tick(time);
            HandleRegen(time);
            HandleQuest(time);
            HandleEffects(time);
            HandleGround(time);
            HandleBoosts();

            FameCounter.Tick(time);

            if (Mp < 0)
            {
                Mp = 0;
            }

            try
            {
                if (Owner != null)
                {
                    SendUpdate(time);
                    if (!Owner.IsPassable((int)X, (int)Y) && Client.Account.Rank < 2)
                    {
                        logger.Fatal($"Player {Name} No-Cliped at position: {X}, {Y}");
                        Client.Disconnect();
                    }
                }
            }
            catch (Exception e)
            {
                logger.Error(e);
            }
            try
            {
                SendNewTick(time);
            }
            catch (Exception e)
            {
                logger.Error(e);
            }

            if (HP < 0 && !dying)
            {
                Death("Unknown");
                return;
            }

            #region Ban manager
            if (Client?.Account.Credits >= Program.MaxAllowedCredit && Client.Account.Rank != 3)
            {
                Client?.Disconnect();
                logger.Info($"{Name} has been kicked.");
                Manager.Database.DoActionAsync(db =>
                {
                    var cmd         = db.CreateQuery();
                    cmd.CommandText = "update accounts set warnings = warnings + 1 where id=@AccountId";
                    cmd.Parameters.AddWithValue("@AccountId", AccountId);
                    cmd.ExecuteNonQuery();
                });
                Manager.Database.DoActionAsync(db =>
                {
                    var cmd         = db.CreateQuery();
                    cmd.CommandText = "insert into warnings (accId, warning) values (@AccountId, @Warning)";
                    cmd.Parameters.AddWithValue("@AccountId", AccountId);
                    cmd.Parameters.AddWithValue("@Warning", $"Credits was greater then {Program.MaxAllowedCredit}");
                    cmd.ExecuteNonQuery();
                });
                Manager.Database.DoActionAsync(db =>
                {
                    var cmd         = db.CreateQuery();
                    cmd.CommandText = "update stats set credits = -1 where accId=@AccountId";
                    cmd.Parameters.AddWithValue("@AccountId", AccountId);
                    cmd.ExecuteNonQuery();
                });
            }
            if (Client?.Account.Stats.Fame >= Program.MaxAllowedFame && Client.Account.Rank != 3)
            {
                Client?.Disconnect();
                logger.Info($"{Name} has been kicked.");
                Manager.Database.DoActionAsync(db =>
                {
                    var cmd         = db.CreateQuery();
                    cmd.CommandText = "update accounts set warnings = warnings + 1 where id=@AccountId";
                    cmd.Parameters.AddWithValue("@AccountId", AccountId);
                    cmd.ExecuteNonQuery();
                });
                Manager.Database.DoActionAsync(db =>
                {
                    var cmd         = db.CreateQuery();
                    cmd.CommandText = "insert into warnings (accId, warning) values (@AccountId, @Warning)";
                    cmd.Parameters.AddWithValue("@AccountId", AccountId);
                    cmd.Parameters.AddWithValue("@Warning", $"Fame was greater then {Program.MaxAllowedFame}");
                    cmd.ExecuteNonQuery();
                });
                Manager.Database.DoActionAsync(db =>
                {
                    var cmd         = db.CreateQuery();
                    cmd.CommandText = "update stats set fame = -1 where accId=@AccountId";
                    cmd.Parameters.AddWithValue("@AccountId", AccountId);
                    cmd.ExecuteNonQuery();
                });
            }

            if (Client?.Account.Warnings >= 3)
            {
                BanManager_Ban();
            }
            #endregion

            base.Tick(time);
        }
Exemplo n.º 14
0
        public override void Tick(RealmTime time)
        {
            if (Client == null)
            {
                return;
            }

            if (!KeepAlive(time) || Client.State == ProtocolState.Disconnected)
            {
                if (Owner != null)
                {
                    Owner.LeaveWorld(this);
                }
                else
                {
                    WorldInstance.LeaveWorld(this);
                }

                return;
            }

            if (Stats != null && Boost != null)
            {
                MaxHp = Stats[0] + Boost[0];
                MaxMp = Stats[1] + Boost[1];
            }

            if (Boost == null)
            {
                CalculateBoost();
            }

            if (!HasConditionEffect(ConditionEffects.Paused))
            {
                HandleRegen(time);

                HandleGround(time);

                FameCounter.Tick(time);
            }

            HandleTrade?.Tick(time);

            try
            {
                HandleQuest(time);
            }
            catch (NullReferenceException) { }

            HandleEffects(time);

            HandleBoosts();

            if (MP < 0)
            {
                MP = 0;
            }

            if (Owner != null)
            {
                HandleNewTick(time);

                HandleUpdate(time);
            }

            if (HP < 0 && !dying)
            {
                Death("Unknown");
                return;
            }

            base.Tick(time);
        }
Exemplo n.º 15
0
        public override void Tick(RealmTime time)
        {
            try
            {
                if (Manager.Clients.Count(_ => _.Value.Id == Client.Id) == 0)
                {
                    if (Owner != null)
                    {
                        Owner.LeaveWorld(this);
                    }
                    else
                    {
                        WorldInstance.LeaveWorld(this);
                    }
                    Manager.Database.DoActionAsync(db => db.UnlockAccount(Client.Account));
                    return;
                }
                if (Client.Stage == ProtocalStage.Disconnected || (!Client.Account.VerifiedEmail && Program.Verify))
                {
                    if (Owner != null)
                    {
                        Owner.LeaveWorld(this);
                    }
                    else
                    {
                        WorldInstance.LeaveWorld(this);
                    }
                    Manager.Database.DoActionAsync(db => db.UnlockAccount(Client.Account));
                    return;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            if (Stats != null && Boost != null)
            {
                MaxHp = Stats[0] + Boost[0];
                MaxMp = Stats[1] + Boost[1];
            }

            if (!KeepAlive(time))
            {
                return;
            }

            if (HP > MaxHp / 2)
            {
                _pendantReady = 1;
            }

            if (Boost == null)
            {
                CalcBoost();
            }

            TradeHandler?.Tick(time);
            HandleRegen(time);
            HandleQuest(time);
            HandleEffects(time);
            HandleGround(time);
            HandleBoosts();

            FameCounter.Tick(time);

            if (Mp < 0)
            {
                Mp = 0;
            }

            try
            {
                if (Owner != null)
                {
                    SendUpdate(time);
                    if (!Owner.IsPassable((int)X, (int)Y))
                    {
                        Console.WriteLine($"Player {Name} No-Clipped at position: {X}, {Y}");
                        Client.Player.SendError("Uhhh, No. Don't Noclip");
                        Client.Reconnect(new ReconnectPacket
                        {
                            Host   = "",
                            Port   = Program.Settings.GetValue <int>("port"),
                            GameId = World.NEXUS_ID,
                            Name   = "Nexus",
                            Key    = Empty <byte> .Array
                        });
                    }
                }
            }

            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            try
            {
                SendNewTick(time);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            if (HP < 0 && !_dying)
            {
                Client.Player.SendError("Woooooah there cowboy! you almost died to 'Unknown' Luckily thats a dumb way to die so I'm not gonna let that happen!");
                Client.Reconnect(new ReconnectPacket
                {
                    Host   = "",
                    Port   = Program.Settings.GetValue <int>("port"),
                    GameId = World.NEXUS_ID,
                    Name   = "Nexus",
                    Key    = Empty <byte> .Array
                });
                return;
            }
            if (HP >= MaxHp / 2)
            {
                AshCooldown = 0;
            }

            base.Tick(time);
        }
Exemplo n.º 16
0
 public override void Init(World owner)
 {
     Random rand = new System.Random();
     int x, y;
     do
     {
         x = rand.Next(0, owner.Map.Width);
         y = rand.Next(0, owner.Map.Height);
     } while (owner.Map[x, y].Region != TileRegion.Spawn);
     Move(x + 0.5f, y + 0.5f);
     tiles = new byte[owner.Map.Width, owner.Map.Height];
     fames = new FameCounter(this);
     if (!psr.CheckAccountInUse(AccountId))
         base.Init(owner);
     else
         psr.Disconnect();
 }
Exemplo n.º 17
0
        public Player(RealmManager manager, Client client) : base(manager, client.Character.ObjectType, client.Random)
        {
            try
            {
                if (client.Account.Admin == true)
                {
                    Admin = 1;
                }
                AccountType            = ComparableExtension.RankToAccountType(client.Account.Rank);
                Client                 = client;
                Manager                = client.Manager;
                StatsManager           = new StatsManager(this, client.Random.CurrentSeed);
                Name                   = client.Account.Name;
                AccountId              = client.Account.AccountId;
                FameCounter            = new FameCounter(this);
                Tokens                 = client.Account.FortuneTokens;
                HpPotionPrice          = 5;
                MpPotionPrice          = 5;
                Level                  = client.Character.Level == 0 ? 1 : client.Character.Level;
                Experience             = client.Character.Experience;
                ExperienceGoal         = GetExpGoal(Level);
                Stars                  = GetStars();
                Texture1               = client.Character.Tex1;
                Texture2               = client.Character.Tex2;
                Credits                = client.Account.Credits;
                NameChosen             = client.Account.NameChosen;
                CurrentFame            = client.Account.Fame;
                Fame                   = client.Character.Fame;
                LootDropBoostTimeLeft  = client.Character.LootDropTimer;
                lootDropBoostFreeTimer = LootDropBoost;
                LootTierBoostTimeLeft  = client.Character.LootTierTimer;
                lootTierBoostFreeTimer = LootTierBoost;
                FameGoal               = GetFameGoal(FameCounter.ClassStats[ObjectType].BestFame);
                Glowing                = false;
                Guild                  = "";
                GuildRank              = -1;
                HP = client.Character.HP <= 0 ? (int)ObjectDesc.MaxHP : client.Character.HP;
                Mp = client.Character.MP;
                ConditionEffects = 0;
                OxygenBar        = 100;
                HasBackpack      = client.Character.HasBackpack == true;
                PlayerSkin       = Client.Account.OwnedSkins.Contains(Client.Character.Skin) ? Client.Character.Skin : 0;
                HealthPotions    = client.Character.HealthPotions < 0 ? 0 : client.Character.HealthPotions;
                MagicPotions     = client.Character.MagicPotions < 0 ? 0 : client.Character.MagicPotions;

                try
                {
                    Locked  = client.Account.Database.GetLockeds(client.Account);
                    Ignored = client.Account.Database.GetIgnoreds(client.Account);
                    Muted   = client.Account.Muted;
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
                if (HasBackpack)
                {
                    Item[] inv =
                        client.Character.Items.Select(
                            _ =>
                            _ == -1
                                    ? null
                                    : (Manager.GameData.Items.ContainsKey((ushort)_) ? Manager.GameData.Items[(ushort)_] : null))
                        .ToArray();
                    Item[] backpack =
                        client.Character.Backpack.Select(
                            _ =>
                            _ == -1
                                    ? null
                                    : (Manager.GameData.Items.ContainsKey((ushort)_) ? Manager.GameData.Items[(ushort)_] : null))
                        .ToArray();

                    Inventory = inv.Concat(backpack).ToArray();
                    XElement xElement = Manager.GameData.ObjectTypeToElement[ObjectType].Element("SlotTypes");
                    if (xElement != null)
                    {
                        int[] slotTypes =
                            Utils.FromCommaSepString32(
                                xElement.Value);
                        Array.Resize(ref slotTypes, 20);
                        SlotTypes = slotTypes;
                    }
                }
                else
                {
                    Inventory =
                        client.Character.Items.Select(
                            _ =>
                            _ == -1
                                        ? null
                                        : (Manager.GameData.Items.ContainsKey((ushort)_) ? Manager.GameData.Items[(ushort)_] : null))
                        .ToArray();
                    XElement xElement = Manager.GameData.ObjectTypeToElement[ObjectType].Element("SlotTypes");
                    if (xElement != null)
                    {
                        SlotTypes =
                            Utils.FromCommaSepString32(
                                xElement.Value);
                    }
                }
                Stats = (int[])client.Character.Stats.Clone();

                for (var i = 0; i < SlotTypes.Length; i++)
                {
                    if (SlotTypes[i] == 0)
                    {
                        SlotTypes[i] = 10;
                    }
                }

                if (Client.Account.Rank >= 3)
                {
                    return;
                }
                for (var i = 0; i < 4; i++)
                {
                    if (Inventory[i]?.SlotType != SlotTypes[i])
                    {
                        Inventory[i] = null;
                    }
                }
            }
            catch (Exception e)
            {
                log.Error(e);
            }
        }