Esempio n. 1
0
        private void Application_OnPlayfieldLoaded(IPlayfield playfield)
        {
            PlayfieldScriptData data = null;

            InitGameDependedData(ModApi.Application.Mode == ApplicationMode.SinglePlayer);

            PlayfieldData.TryAdd(playfield.Name, data = new PlayfieldScriptData(this)
            {
                PlayfieldName = playfield.Name,
                Playfield     = playfield,
            });

            UpdateScriptingModInfoData();

            ModApi.Log($"StartScripts for {playfield.Name} pending");
            TaskTools.Delay(Configuration.Current.DelayStartForNSecondsOnPlayfieldLoad, () => {
                ModApi.Log($"StartScripts for {playfield.Name}");
                data.PauseScripts = false;

                if (ModApi.Application.Mode == ApplicationMode.SinglePlayer)
                {
                    ModApi.Log(playfield.Entities?.Aggregate($"Player:{playfield.Players.FirstOrDefault().Value?.Name} PlayerDriving:{playfield.Players.FirstOrDefault().Value?.DrivingEntity?.Name}", (L, E) => L + $" {E.Key}:{E.Value.Name}"));

                    data.AddEntity(playfield.Players.FirstOrDefault().Value?.DrivingEntity);
                    playfield.Entities?.ForEach(E => data.AddEntity(E.Value));
                }
            });

            data.Playfield.OnEntityLoaded   += data.Playfield_OnEntityLoaded;
            data.Playfield.OnEntityUnloaded += data.Playfield_OnEntityUnloaded;
        }
        private void cboPlayfield_SelectedIndexChanged(object sender, EventArgs e)
        {
            IPlayfield playfield   = this.cboPlayfield.SelectedItem as IPlayfield;
            bool       isSimulator = (playfield is PlayfieldSimulator);

            txtPlayfieldType.ReadOnly  = !isSimulator;
            txtPlanetType.ReadOnly     = !isSimulator;
            txtPlanetClass.ReadOnly    = !isSimulator;
            nudSizeClass.ReadOnly      = !isSimulator;
            nudTerrainSeed.ReadOnly    = !isSimulator;
            btnGenerateTerrain.Enabled = !isSimulator;
            pbTerrain.Enabled          = !isSimulator;

            txtPlayfieldType.Text = playfield?.PlayfieldType;
            txtPlanetType.Text    = playfield?.PlanetType;
            txtPlanetClass.Text   = playfield?.PlanetClass;

            if (isSimulator)
            {
                PlayfieldSimulator simulator = playfield as PlayfieldSimulator;
                nudSizeClass.Value   = simulator?.SizeClass ?? 1;
                nudTerrainSeed.Value = simulator?.Terrain?.Seed ?? DateTime.Now.Ticks % 100000;
                if ((simulator?.Terrain != null) && (simulator?.Terrain?.Bitmap == null))
                {
                    simulator.Terrain.Raster();
                }
                pbTerrain.Image = simulator?.Terrain?.Bitmap;
            }
            else
            {
                nudSizeClass.Value = 1;
                pbTerrain.Image    = null;
            }
        }
Esempio n. 3
0
        /// <summary>
        /// </summary>
        /// <param name="charId">
        /// </param>
        /// <exception cref="Exception">
        /// </exception>
        public void CreateCharacter(int charId)
        {
            this.character = new Character(new Identity {
                Type = IdentityType.CanbeAffected, Instance = charId
            }, this);
            IEnumerable <DBCharacter> daochar = CharacterDao.GetById(charId);

            if (daochar.Count() == 0)
            {
                throw new Exception("Character " + charId.ToString() + " not found.");
            }

            if (daochar.Count() > 1)
            {
                throw new Exception(
                          daochar.Count().ToString() + " Characters with id " + charId.ToString()
                          + " found??? Check Database setup!");
            }

            DBCharacter character = daochar.First();

            this.character.Name        = character.Name;
            this.character.LastName    = character.LastName;
            this.character.FirstName   = character.FirstName;
            this.character.Coordinates = new AOCoord(character.X, character.Y, character.Z);
            this.character.Heading     = new Quaternion(
                character.HeadingX, character.HeadingY, character.HeadingZ, character.HeadingW);
            this.character.Playfield = this.server.PlayfieldById(character.Playfield);
            this.Playfield           = this.character.Playfield;
            this.Playfield.Entities.Add(this.character);
            this.character.Stats.Read();
            this.character.BaseInventory.Read();
        }
        public static ICharacter InstantiateMobSpawn(
            DBMobSpawn mob,
            DBMobSpawnStat[] stats,
            IController npccontroller,
            IPlayfield playfield)
        {
            if (playfield != null)
            {
                Identity mobId = new Identity()
                {
                    Type = IdentityType.CanbeAffected, Instance = mob.Id
                };
                if (Pool.Instance.GetObject(playfield.Identity, mobId) != null)
                {
                    throw new Exception("Object " + mobId.ToString() + " already exists!!");
                }
                Character cmob = new Character(playfield.Identity, mobId, npccontroller);
                cmob.Read();
                cmob.Playfield = playfield;
                cmob.Coordinates(new Coordinate()
                {
                    x = mob.X, y = mob.Y, z = mob.Z
                });
                cmob.RawHeading = new Quaternion(mob.HeadingX, mob.HeadingY, mob.HeadingZ, mob.HeadingW);
                cmob.Name       = mob.Name;
                cmob.FirstName  = "";
                cmob.LastName   = "";
                foreach (DBMobSpawnStat stat in stats)
                {
                    cmob.Stats.SetBaseValueWithoutTriggering(stat.Stat, (uint)stat.Value);
                }

                cmob.Stats.SetBaseValueWithoutTriggering((int)StatIds.visualprofession, cmob.Stats[StatIds.profession].BaseValue);
                // initiate affected stats calculation
                int temp = cmob.Stats[StatIds.level].Value;
                temp = cmob.Stats[StatIds.agility].Value;
                temp = cmob.Stats[StatIds.headmesh].Value;
                cmob.MeshLayer.AddMesh(0, cmob.Stats[StatIds.headmesh].Value, 0, 4);
                cmob.SocialMeshLayer.AddMesh(0, cmob.Stats[StatIds.headmesh].Value, 0, 4);
                List <MobSpawnWaypoint> waypoints =
                    MessagePackZip.DeserializeData <MobSpawnWaypoint>(mob.Waypoints.ToArray());
                foreach (MobSpawnWaypoint wp in waypoints)
                {
                    Waypoint mobwp = new Waypoint();
                    mobwp.Position.x = wp.X;
                    mobwp.Position.y = wp.Y;
                    mobwp.Position.z = wp.Z;
                    mobwp.Running    = wp.WalkMode == 1;
                    cmob.Waypoints.Add(mobwp);
                }
                npccontroller.Character = cmob;
                if (cmob.Waypoints.Count > 2)
                {
                    cmob.Controller.State = CharacterState.Patrolling;
                }
                cmob.DoNotDoTimers = false;
                return(cmob);
            }
            return(null);
        }
        public static void SpawnEmptyVendorFromTemplate(StatelData statelData, IPlayfield playfield, int instance)
        {
            Identity pfIdentity = new Identity()
            {
                Type = IdentityType.Playfield, Instance = statelData.PlayfieldId
            };
            Identity freeIdentity = new Identity()
            {
                Type     = IdentityType.VendingMachine,
                Instance =
                    Pool.Instance.GetFreeInstance <Vendor>(
                        0x70000000,
                        IdentityType.VendingMachine)
            };
            Vendor v = new Vendor(pfIdentity, freeIdentity, statelData.TemplateId);

            v.OriginalIdentity = statelData.Identity;
            v.RawCoordinates   = new Vector3(statelData.X, statelData.Y, statelData.Z);
            v.Heading          = new Quaternion(
                statelData.HeadingX,
                statelData.HeadingY,
                statelData.HeadingZ,
                statelData.HeadingW);
            v.Playfield = playfield;
        }
Esempio n. 6
0
        private void Application_OnPlayfieldUnloading(IPlayfield playfield)
        {
            ScriptingModScriptsInfoData.TryRemove(playfield.Name, out _);

            if (!PlayfieldData.TryRemove(playfield.Name, out var data))
            {
                return;
            }

            data.Playfield.OnEntityLoaded   -= data.Playfield_OnEntityLoaded;
            data.Playfield.OnEntityUnloaded -= data.Playfield_OnEntityUnloaded;

            ModApi.Log($"PauseScripts for {playfield.Name} {(data.PauseScripts ? "always stopped" : "scripts running")}");
            data.PauseScripts = true;

            DisplayScriptInfos();
            data.ScriptExecQueue?.Clear();
            data.LcdCompileCache?.Clear();
            data.PersistendData?.Clear();

            var stores = data.EventStore?.Values.ToArray();

            data.EventStore?.Clear();
            stores?.ForEach(S => ((EventStore)S).Dispose());
        }
Esempio n. 7
0
 public ScriptRootData(IEntity[] currentEntities, IPlayfield playfield, IEntity entity, bool deviceLockAllowed, ConcurrentDictionary <string, object> persistendData) : this()
 {
     DeviceLockAllowed   = deviceLockAllowed;
     _PersistendData     = persistendData;
     this.currentEntites = currentEntities;
     this.playfield      = playfield;
     this.entity         = entity;
 }
Esempio n. 8
0
        public DeviceLock(IPlayfield playfield, IStructure structure, VectorInt3 position)
        {
            var witherror = false;

            try
            {
                if (ScriptExecQueue.Iteration % EmpyrionScripting.Configuration.Current.DeviceLockOnlyAllowedEveryXCycles != 0)
                {
                    return;
                }

                if (playfield.IsStructureDeviceLocked(structure.Id, position))
                {
                    return;
                }

                var lockkey = $"{structure.Id}#{position.x}#{position.y}#{position.z}";

                var e = new AutoResetEvent(false);
                playfield.LockStructureDevice(structure.Id, position, true, (s) =>
                {
                    if (witherror)
                    {
                        Log($"Lock:Callback:Error {playfield.Name} {structure.Id} {position}", LogLevel.Debug);
                        playfield.LockStructureDevice(structure.Id, position, false, null);
                    }
                    else
                    {
                        Success = s;
                        e.Set();
                    }
                });
                witherror = !e.WaitOne(10000);
                if (witherror)
                {
                    Log($"Lock:WaitOne:Error {playfield.Name} {structure.Id} {position}", LogLevel.Debug);
                }

                if (Success)
                {
                    unlockAction = () =>
                    {
                        e.Reset();
                        playfield.LockStructureDevice(structure.Id, position, false, (s) => e.Set());
                        if (!e.WaitOne(10000))
                        {
                            Log($"Unlock:Timeout {playfield.Name} {structure.Id} {position}", LogLevel.Debug);
                        }
                    }
                }
                ;
            }
            catch (Exception error)
            {
                witherror = true;
                throw new Exception($"DeviceLock:failed on Playfield:{playfield?.Name} at Id:{structure.Id} on {position} with: {error}");
            }
        }
 public TestObjectsFactory()
 {
     this.factory    = new LabyrinthFactory();
     this.playfield  = this.factory.CreatePlayfield();
     this.player     = this.factory.CreatePlayer();
     this.dialogs    = this.factory.CreateDialogs();
     this.scoreboard = this.factory.CreateScoreboard();
     this.save       = new SaveSystem();
 }
 public Memento(ILabyrinthFactory factory, IPlayfield playfield, IPlayer player, IGameDialog dialogs, IScoreboard scoreboard, int numberOfMoves)
 {
     this.Factory = factory;
     this.Playfield = playfield;
     this.Player = player;
     this.Dialogs = dialogs;
     this.Scoreboard = scoreboard;
     this.NumberOfMoves = numberOfMoves;
 }
 private LabyrinthEngine()
 {
     this.factory    = new LabyrinthFactory();
     this.playfield  = this.factory.CreatePlayfield();
     this.player     = this.factory.CreatePlayer();
     this.dialogs    = this.factory.CreateDialogs();
     this.scoreboard = this.factory.CreateScoreboard();
     this.save       = new SaveSystem();
 }
 public Memento(ILabyrinthFactory factory, IPlayfield playfield, IPlayer player, IGameDialog dialogs, IScoreboard scoreboard, int numberOfMoves)
 {
     this.Factory       = factory;
     this.Playfield     = playfield;
     this.Player        = player;
     this.Dialogs       = dialogs;
     this.Scoreboard    = scoreboard;
     this.NumberOfMoves = numberOfMoves;
 }
 private LabyrinthEngine()
 {
     this.factory = new LabyrinthFactory();
     this.playfield = this.factory.CreatePlayfield();
     this.player = this.factory.CreatePlayer();
     this.dialogs = this.factory.CreateDialogs();
     this.scoreboard = this.factory.CreateScoreboard();
     this.save = new SaveSystem();
 }
 public void LoadMemento(Memento restore)
 {
     Console.WriteLine("\nRestoring state --\n");
     this.factory = restore.Factory;
     this.playfield = restore.Playfield;
     this.player = restore.Player;
     this.dialogs = restore.Dialogs;
     this.scoreboard = restore.Scoreboard;
     this.numberOfMoves = restore.NumberOfMoves;
 }
Esempio n. 15
0
 public ScriptSaveGameRootData(
     PlayfieldScriptData playfieldScriptData,
     IEntity[] allEntities,
     IEntity[] currentEntities,
     IPlayfield playfield,
     IEntity entity,
     ConcurrentDictionary <string, object> persistendData,
     EventStore eventStore) : base(playfieldScriptData, allEntities, currentEntities, playfield, entity, persistendData, eventStore)
 {
 }
 public void TestMemento()
 {
     ILabyrinthFactory factory    = new LabyrinthFactory();
     IPlayfield        playfield  = factory.CreatePlayfield();
     IPlayer           player     = factory.CreatePlayer();
     IGameDialog       dialogs    = factory.CreateDialogs();
     IScoreboard       scoreboard = factory.CreateScoreboard();
     int     numberOfMoves        = 5;
     Memento testMemento          = new Memento(factory, playfield, player, dialogs, scoreboard, numberOfMoves);
 }
 public void LoadMemento(Memento restore)
 {
     Console.WriteLine("\nRestoring state --\n");
     this.factory       = restore.Factory;
     this.playfield     = restore.Playfield;
     this.player        = restore.Player;
     this.dialogs       = restore.Dialogs;
     this.scoreboard    = restore.Scoreboard;
     this.numberOfMoves = restore.NumberOfMoves;
 }
Esempio n. 18
0
        private bool MoveEmptyFrame(IPlayfield playfield, Direction direction)
        {
            bool  isMoveValid        = false;
            Point emptyFrameLocation = FindEmptyFrame(playfield);

            Frame[,] board = playfield.Board;
            switch (direction)
            {
            case Direction.Up:
                if (emptyFrameLocation.Y < 1)
                {
                    break;
                }
                var temp = board[emptyFrameLocation.Y - 1, emptyFrameLocation.X];     // frame above the empty frame
                board[emptyFrameLocation.Y - 1, emptyFrameLocation.X] = null;
                board[emptyFrameLocation.Y, emptyFrameLocation.X]     = temp;
                isMoveValid = true;
                break;

            case Direction.Right:
                if (emptyFrameLocation.X == board.GetLength(0) - 1)
                {
                    break;
                }
                var temp1 = board[emptyFrameLocation.Y, emptyFrameLocation.X + 1];     // frame right to the empty frame
                board[emptyFrameLocation.Y, emptyFrameLocation.X + 1] = null;
                board[emptyFrameLocation.Y, emptyFrameLocation.X]     = temp1;
                isMoveValid = true;
                break;

            case Direction.Down:
                if (emptyFrameLocation.Y == board.GetLength(1) - 1)
                {
                    break;
                }
                var temp2 = board[emptyFrameLocation.Y + 1, emptyFrameLocation.X];     // frame under the empty frame
                board[emptyFrameLocation.Y + 1, emptyFrameLocation.X] = null;
                board[emptyFrameLocation.Y, emptyFrameLocation.X]     = temp2;
                isMoveValid = true;
                break;

            case Direction.Left:
                if (emptyFrameLocation.X < 1)
                {
                    break;
                }
                var temp3 = board[emptyFrameLocation.Y, emptyFrameLocation.X - 1];     // frame left to the empty frame
                board[emptyFrameLocation.Y, emptyFrameLocation.X - 1] = null;
                board[emptyFrameLocation.Y, emptyFrameLocation.X]     = temp3;
                isMoveValid = true;
                break;
            }

            return(isMoveValid);
        }
Esempio n. 19
0
 public void UnloadPlayfield(IPlayfield playfield)
 {
     if (this.Playfields.Contains(playfield))
     {
         if (this.OnPlayfieldUnloading != null)
         {
             this.OnPlayfieldUnloading(playfield);
         }
         this.Playfields.Remove(playfield);
     }
 }
        public static ICharacter InstantiateMobSpawn(
            DBMobSpawn mob,
            DBMobSpawnStat[] stats,
            IController npccontroller,
            IPlayfield playfield)
        {
            if (playfield != null)
            {
                Identity mobId = new Identity() { Type = IdentityType.CanbeAffected, Instance = mob.Id };
                if (Pool.Instance.GetObject(playfield.Identity, mobId) != null)
                {
                    throw new Exception("Object " + mobId.ToString(true) + " already exists!!");
                }
                Character cmob = new Character(playfield.Identity, mobId, npccontroller);
                cmob.Read();
                cmob.Playfield = playfield;
                cmob.Coordinates(new Coordinate() { x = mob.X, y = mob.Y, z = mob.Z });
                cmob.RawHeading = new Quaternion(mob.HeadingX, mob.HeadingY, mob.HeadingZ, mob.HeadingW);
                cmob.Name = mob.Name;
                cmob.FirstName = "";
                cmob.LastName = "";
                foreach (DBMobSpawnStat stat in stats)
                {
                    cmob.Stats.SetBaseValueWithoutTriggering(stat.Stat, (uint)stat.Value);
                }

                cmob.Stats.SetBaseValueWithoutTriggering((int)StatIds.visualprofession, cmob.Stats[StatIds.profession].BaseValue);
                // initiate affected stats calculation
                int temp = cmob.Stats[StatIds.level].Value;
                temp = cmob.Stats[StatIds.agility].Value;
                temp = cmob.Stats[StatIds.headmesh].Value;
                cmob.MeshLayer.AddMesh(0, cmob.Stats[StatIds.headmesh].Value, 0, 4);
                cmob.SocialMeshLayer.AddMesh(0, cmob.Stats[StatIds.headmesh].Value, 0, 4);
                List<MobSpawnWaypoint> waypoints =
                    MessagePackZip.DeserializeData<MobSpawnWaypoint>(mob.Waypoints.ToArray());
                foreach (MobSpawnWaypoint wp in waypoints)
                {
                    Waypoint mobwp = new Waypoint();
                    mobwp.Position.x = wp.X;
                    mobwp.Position.y = wp.Y;
                    mobwp.Position.z = wp.Z;
                    mobwp.Running = wp.WalkMode == 1;
                    cmob.Waypoints.Add(mobwp);
                }
                npccontroller.Character = cmob;
                if (cmob.Waypoints.Count > 2)
                {
                    cmob.Controller.State = CharacterState.Patrolling;
                }
                cmob.DoNotDoTimers = false;
                return cmob;
            }
            return null;
        }
        private void Application_OnPlayfieldLoaded(IPlayfield playfield)
        {
            _nlog.Trace($"Application_OnPlayfieldLoaded Raised => PlayfieldLoad := \"{playfield.Name}\"");
            foreach (var p in playfield.Players)
            {
                var player        = p.Value;
                var vessel        = player.Structure;
                var dockedVessels = vessel?.GetDockedVessels() ?? new List <IStructure>();

                _nlog.Trace("Player {0} is Piloting {1} and has {2} vessels docked", player.Name, vessel?.Entity.Name ?? "Nothing", dockedVessels.Count());
            }
        }
        public void TestLoadMememntoMethod()
        {
            ILabyrinthFactory factory    = new LabyrinthFactory();
            IPlayfield        playfield  = factory.CreatePlayfield();
            IPlayer           player     = factory.CreatePlayer();
            IGameDialog       dialogs    = factory.CreateDialogs();
            IScoreboard       scoreboard = factory.CreateScoreboard();
            int     numberOfMoves        = 5;
            Memento testMemento          = new Memento(factory, playfield, player, dialogs, scoreboard, numberOfMoves);

            Labyrinth.Engine.LabyrinthEngine.Instance.LoadMemento(testMemento);
        }
Esempio n. 23
0
        /// <summary>
        /// </summary>
        /// <param name="charId">
        /// </param>
        /// <exception cref="Exception">
        /// </exception>
        public void CreateCharacter(int charId)
        {
            DBCharacter character = CharacterDao.Instance.Get(charId);

            if (character == null)
            {
                throw new Exception("Character " + charId + " not found.");
            }

            // TODO: Save playfield type into Character table and use it accordingly
            IPlayfield pf =
                this.server.PlayfieldById(
                    new Identity()
            {
                Type = IdentityType.Playfield, Instance = character.Playfield
            });

            if (
                Pool.Instance.GetObject <Character>(
                    new Identity()
            {
                Type = IdentityType.CanbeAffected, Instance = charId
            }) == null)
            {
                this.Controller.Character = new Character(
                    pf.Identity,
                    new Identity {
                    Type = IdentityType.CanbeAffected, Instance = charId
                },
                    this.Controller);
                this.controller.Character.Read();
            }
            else
            {
                this.Controller.Character =
                    Pool.Instance.GetObject <Character>(
                        new Identity()
                {
                    Type = IdentityType.CanbeAffected, Instance = charId
                });
                this.Controller.Character.Reconnect(this);
                LogUtil.Debug(DebugInfoDetail.Engine, "Reconnected to Character " + charId);
            }

            // Stop pending logouts
            this.Controller.Character.StopLogoutTimer();

            this.Controller.Character.Playfield = pf;
            this.Playfield = pf;
            this.Controller.Character.Stats.Read();
            this.controller.Character.Stats[StatIds.visualprofession].BaseValue = (uint)this.controller.Character.Stats[StatIds.profession].Value;
        }
Esempio n. 24
0
        /// <summary>
        /// </summary>
        /// <param name="charId">
        /// </param>
        /// <exception cref="Exception">
        /// </exception>
        public void CreateCharacter(int charId)
        {
            IEnumerable <DBCharacter> daochar = CharacterDao.GetById(charId);

            if (daochar.Count() == 0)
            {
                throw new Exception("Character " + charId + " not found.");
            }

            if (daochar.Count() > 1)
            {
                throw new Exception(
                          daochar.Count() + " Characters with id " + charId + " found??? Check Database setup!");
            }

            DBCharacter character = daochar.First();
            IPlayfield  pf        = this.server.PlayfieldById(character.Playfield);

            if (pf.Entities.GetObject <Character>(
                    new Identity()
            {
                Type = IdentityType.CanbeAffected, Instance = charId
            }) == null)
            {
                this.character = new Character(
                    pf.Entities,
                    new Identity {
                    Type = IdentityType.CanbeAffected, Instance = charId
                },
                    this);
            }
            else
            {
                this.character =
                    pf.Entities.GetObject <Character>(
                        new Identity()
                {
                    Type = IdentityType.CanbeAffected, Instance = charId
                });
                this.character.Reconnect(this);
                LogUtil.Debug("Reconnected to Character " + charId);
            }

            // Stop pending logouts
            this.character.StopLogoutTimer();

            this.character.Playfield = pf;
            this.Playfield           = pf;
            this.character.Stats.Read();
        }
Esempio n. 25
0
 /// <summary>
 /// Handles the OnPlayfieldUnloading event from the IApplication instance. Shuts down the PlayfieldProcessor that was handling the IPlayfield instance.
 /// </summary>
 /// <param name="playfield">The IPlayfield instance that is about to be unloaded.</param>
 private void Application_OnPlayfieldUnloading(IPlayfield playfield)
 {
     try
     {
         if (this.PlayfieldProcessors.ContainsKey(playfield.Name))
         {
             this.PlayfieldProcessors[playfield.Name].Stop();
             this.PlayfieldProcessors.Remove(playfield.Name);
         }
     } catch (Exception ex)
     {
         Log.Warn($"Unexpected error when unloading processor for playfield {playfield.Name}. {ex.Message}");
     }
 }
Esempio n. 26
0
        /// <summary>
        /// Handles the OnPlayfieldLoaded event from the game IApplication instance. Passes off the new IPlayfield instance to a PlayfieldProcessor.
        /// </summary>
        /// <param name="playfield">The newly loaded IPlayfield instance.</param>
        private void Application_OnPlayfieldLoaded(IPlayfield playfield)
        {
            try
            {
                if (this.PlayfieldProcessors.ContainsKey(playfield.Name))
                {
                    this.PlayfieldProcessors[playfield.Name].Stop();
                }

                this.PlayfieldProcessors[playfield.Name] = new PlayfieldProcessor(playfield);
            } catch (Exception ex)
            {
                Log.Warn($"Failed to create a processor for {playfield.Name}. {ex.Message}");
            }
        }
Esempio n. 27
0
        public bool MakeMove(IPlayfield playfield, Direction direction, bool withRandomMoves)
        {
            bool isMoveValid = MoveEmptyFrame(playfield, direction);

            if (isMoveValid)
            {
                if (withRandomMoves)
                {
                    Random random = new Random();
                    MakeRandomMoves(playfield, random.Next(1, 6)); // [1;6)
                }
                NotifyOnPlayfieldChange?.Invoke(playfield.Board);
            }
            return(isMoveValid);
        }
Esempio n. 28
0
        private void MakeRandomMoves(IPlayfield playfield, int numberOfMoves)
        {
            Random random = new Random();
            var    values = Enum.GetValues(typeof(Direction));

            for (int i = 0; i < numberOfMoves; i++)
            {
                int       index           = random.Next(values.Length);
                Direction randomDirection = (Direction)values.GetValue(index);
                bool      isMoveValid     = MoveEmptyFrame(playfield, randomDirection);
                if (isMoveValid == false)
                {
                    i--;
                }
            }
        }
 public void Update(IPlayer player, IPlayfield playfield, int numberOfMoves, IScoreboard scoreboard, IGameDialog dialogs)
 {
     if (playfield.IsPlayerWinning(player))
     {
         Console.Write(dialogs.WinnerMessage(numberOfMoves));
         string name = Console.ReadLine();
         try
         {
             scoreboard.AddTopScoreToScoreboard(name, numberOfMoves);
         }
         finally
         {
         }
         Console.WriteLine();
         LabyrinthEngine.Instance.StartNewGame();
     }
 }
Esempio n. 30
0
        protected virtual void HandleRequestPacket(Connection connection, RequestPacket packet)
        {
            switch (packet.Specification)
            {
            case RequestSpecification.GameState:
                connection.Send(EmpyrionExtension.Instance.GameStateProcessor.GetCurrentState());
                break;

            case RequestSpecification.ClientPlayfieldName:
                string name = EmpyrionExtension.EmpyrionApi?.ClientPlayfield?.Name;
                if (!string.IsNullOrWhiteSpace(name))
                {
                    connection.Send(new RequestPacket(RequestSpecification.ClientPlayfieldName, name));
                }
                break;

            case RequestSpecification.PlayfieldData:
                if (EmpyrionExtension.Instance?.PlayfieldProcessors?.ContainsKey(packet.Specifier) ?? false)
                {
                    IPlayfield playfield = EmpyrionExtension.Instance?.PlayfieldProcessors?[packet.Specifier]?.Playfield;
                    if (playfield != null)
                    {
                        connection.Send(new PlayfieldDataPacket(DataFactory.PlayfieldData(playfield)));
                    }
                }
                break;

            case RequestSpecification.PlayfieldMap:
                if (EmpyrionExtension.Instance?.PlayfieldProcessors?.ContainsKey(packet.Specifier) ?? false)
                {
                    PlayfieldProcessor processor = EmpyrionExtension.Instance?.PlayfieldProcessors?[packet.Specifier];
                    if (processor != null)
                    {
                        if (processor.PlayfieldMap == null)
                        {
                            processor.WhenMapReady(map => connection.Send(new PlayfieldMapPacket(map)));
                        }
                        else
                        {
                            connection.Send(new PlayfieldMapPacket(processor.PlayfieldMap));
                        }
                    }
                }
                break;
            }
        }
        /// <summary>
        /// </summary>
        /// <param name="sender">
        /// </param>
        /// <param name="message">
        /// </param>
        public void Handle(object sender, Message message)
        {
            if (((TextMessage)message.Body).Message.Text.StartsWith("."))
            {
                // It is a chat command in vicinity chat, lets process it
                ChatCommandHandler.Read(((TextMessage)message.Body).Message.Text.TrimStart('.'), (ZoneClient)sender);
                return;
            }

            ICharacter character = ((IZoneClient)sender).Character;
            IPlayfield playfield = character.Playfield;

            float range = 0.0f;

            switch ((int)((TextMessage)message.Body).Message.Type)
            {
            case 0x01:
                range = 1.5f;
                break;

            case 0x00:
                range = 10.0f;
                break;

            case 0x02:
                range = 60.0f;
                break;
            }

            List <Character> charsInRange = playfield.FindInRange(character, range);

            VicinityChatMessage vicinityChat = new VicinityChatMessage
            {
                CharacterIds =
                    charsInRange.Select(
                        x => x.Identity.Instance).ToList(),
                MessageType =
                    (byte)
                    ((TextMessage)message.Body).Message.Type,
                Text =
                    ((TextMessage)message.Body).Message.Text,
                SenderId = character.Identity.Instance
            };

            Program.ISComClient.Send(vicinityChat);
        }
Esempio n. 32
0
        public static void SpawnVendorFromDatabaseTemplate(DBVendor vendor, IPlayfield playfield)
        {
            Identity pfIdentity = new Identity() { Type = IdentityType.Playfield, Instance = vendor.Playfield };
            Identity freeIdentity = new Identity()
                                    {
                                        Type = IdentityType.VendingMachine,
                                        Instance =
                                            Pool.Instance.GetFreeInstance<Vendor>(
                                                0x70000000,
                                                IdentityType.VendingMachine)
                                    };

            Vendor v = new Vendor(pfIdentity, freeIdentity, vendor.Hash);

            v.RawCoordinates = new Vector3(vendor.X, vendor.Y, vendor.Z);
            v.Heading = new Quaternion(vendor.HeadingX, vendor.HeadingY, vendor.HeadingZ, vendor.HeadingW);
            v.Playfield = playfield;
        }
Esempio n. 33
0
        public void ShuffleBoard(IPlayfield playfield, Level level)
        {
            switch (level)
            {
            case Level.Easy:
                MakeRandomMoves(playfield, 5);
                break;

            case Level.Medium:
                MakeRandomMoves(playfield, 20);
                break;

            case  Level.Hard:
                MakeRandomMoves(playfield, 100);
                break;
            }
            NotifyOnPlayfieldChange?.Invoke(playfield.Board);
        }
Esempio n. 34
0
        private Point FindEmptyFrame(IPlayfield playfield)
        {
            Point emptyFrame = new Point();

            for (int i = 0; i < playfield.Board.GetLength(0); i++)
            {
                for (int j = 0; j < playfield.Board.GetLength(1); j++)
                {
                    if (playfield.Board[i, j] == null)
                    {
                        emptyFrame.X = j;
                        emptyFrame.Y = i;
                    }
                }
            }

            return(emptyFrame);
        }
Esempio n. 35
0
        /// <summary>
        /// </summary>
        /// <param name="playfieldNumber">
        /// </param>
        public void CreatePlayfield(int playfieldNumber)
        {
            foreach (PlayfieldInfo playfieldInfo in Playfields.Instance.playfields)
            {
                if (playfieldInfo.id != playfieldNumber)
                {
                    continue;
                }

                Identity identity = new Identity();
                identity.Type     = IdentityType.Playfield;
                identity.Instance = playfieldNumber;
                IPlayfield playfield = this.CreatePlayfield(identity);

                foreach (DistrictInfo districtInfo in playfieldInfo.districts)
                {
                    PlayfieldDistrict playfieldDistrict = new PlayfieldDistrict();
                    playfieldDistrict.Name           = districtInfo.districtName;
                    playfieldDistrict.MinLevel       = districtInfo.minLevel;
                    playfieldDistrict.MaxLevel       = districtInfo.maxLevel;
                    playfieldDistrict.SuppressionGas = districtInfo.suppressionGas;
                    playfield.Districts.Add(playfieldDistrict);
                }

                playfield.X         = playfieldInfo.x;
                playfield.Z         = playfieldInfo.z;
                playfield.XScale    = playfieldInfo.xscale;
                playfield.ZScale    = playfieldInfo.zscale;
                playfield.Expansion = (Expansions)playfieldInfo.expansion;
                this.playfields.Add(playfield);
                PlayfieldWorkerHolder playfieldWorkerHolder = new PlayfieldWorkerHolder();
                playfieldWorkerHolder.PlayfieldWorker.SetPlayfield(playfield);
                Thread thread = new Thread(playfieldWorkerHolder.PlayfieldWorker.DoWork);
                playfieldWorkerHolder.thread = thread;
                thread.Start();
                this.workers.Add(playfieldWorkerHolder);
                while (!thread.IsAlive)
                {
                    ;
                }

                break;
            }
        }
Esempio n. 36
0
 public static void SpawnEmptyVendorFromTemplate(StatelData statelData, IPlayfield playfield, int instance)
 {
     Identity pfIdentity = new Identity() { Type = IdentityType.Playfield, Instance = statelData.PlayfieldId };
     Identity freeIdentity = new Identity()
                             {
                                 Type = IdentityType.VendingMachine,
                                 Instance =
                                     Pool.Instance.GetFreeInstance<Vendor>(
                                         0x70000000,
                                         IdentityType.VendingMachine)
                             };
     Vendor v = new Vendor(pfIdentity, freeIdentity, statelData.TemplateId);
     v.OriginalIdentity = statelData.Identity;
     v.RawCoordinates = new Vector3(statelData.X, statelData.Y, statelData.Z);
     v.Heading = new Quaternion(
         statelData.HeadingX,
         statelData.HeadingY,
         statelData.HeadingZ,
         statelData.HeadingW);
     v.Playfield = playfield;
 }
Esempio n. 37
0
        public static void SpawnVendorsForPlayfield(IPlayfield playfield, StatelData[] rdbVendors)
        {
            IEnumerable<DBVendor> vendors = VendorDao.Instance.GetWhere(new { Playfield = playfield.Identity.Instance });

            foreach (StatelData sd in rdbVendors)
            {
                int id = (((sd.Identity.Instance) >> 16) & 0xff | (playfield.Identity.Instance << 16));

                DBVendor vendor = vendors.FirstOrDefault(x => x.Id == id);
                if (vendor != null)
                {
                    LogUtil.Debug(DebugInfoDetail.Statel, sd.Identity.ToString(true) + " - DB " + vendor.TemplateId);
                    SpawnVendorFromDatabaseTemplate(vendor, playfield);
                }
                else
                {
                    LogUtil.Debug(DebugInfoDetail.Statel, sd.Identity.ToString(true) + " -    " + sd.TemplateId);
                    SpawnEmptyVendorFromTemplate(sd, playfield, id);
                }
            }
        }
        /// <summary>
        /// Render playfield classes on Console
        /// </summary>
        /// <param name="playfield">The playfield that will be draw on Console</param>
        public void RenderPlayfield(IPlayfield playfield)
        {
            for (int row = 0; row < playfield.Size + GlobalConstants.BorderSize; row++)
            {
                for (int col = 0; col < playfield.Size + GlobalConstants.BorderSize; col++)
                {
                    if (row == 0)
                    {
                        if (col == 0)
                        {
                            this.RenderSingleSymbol(" ");
                        }

                        if (col == 1)
                        {
                            this.RenderSingleSymbol(" ");
                        }

                        if (col > 1)
                        {
                            this.RenderSingleSymbol((col - GlobalConstants.BorderSize).ToString());
                        }
                    }

                    if (row == 1)
                    {
                        if (col == 0)
                        {
                            this.RenderSingleSymbol(" ");
                        }

                        if (col == 1)
                        {
                            this.RenderSingleSymbol(" ");
                        }

                        if (col > 1)
                        {
                            this.RenderSingleSymbol("_");
                        }
                    }

                    if (row > 1)
                    {
                        if (col == 0)
                        {
                            this.RenderSingleSymbol((row - GlobalConstants.BorderSize).ToString());
                        }

                        if (col == 1)
                        {
                            this.RenderSingleSymbol("|");
                        }

                        if (col > 1)
                        {
                            Console.Write("{0, 2}", playfield.GetCell(row - GlobalConstants.BorderSize, col - GlobalConstants.BorderSize));
                        }
                    }
                }

                Console.WriteLine();
            }
        }
Esempio n. 39
0
        /// <summary>
        /// </summary>
        /// <param name="charId">
        /// </param>
        /// <exception cref="Exception">
        /// </exception>
        public void CreateCharacter(int charId)
        {
            DBCharacter character = CharacterDao.Instance.Get(charId);
            if (character == null)
            {
                throw new Exception("Character " + charId + " not found.");
            }

            // TODO: Save playfield type into Character table and use it accordingly
            IPlayfield pf =
                this.server.PlayfieldById(
                    new Identity() { Type = IdentityType.Playfield, Instance = character.Playfield });

            if (
                Pool.Instance.GetObject<Character>(
                    new Identity() { Type = IdentityType.CanbeAffected, Instance = charId }) == null)
            {
                this.Controller.Character = new Character(
                    pf.Identity,
                    new Identity { Type = IdentityType.CanbeAffected, Instance = charId },
                    this.Controller);
                this.controller.Character.Read();
            }
            else
            {
                this.Controller.Character =
                    Pool.Instance.GetObject<Character>(
                        new Identity() { Type = IdentityType.CanbeAffected, Instance = charId });
                this.Controller.Character.Reconnect(this);
                LogUtil.Debug(DebugInfoDetail.Engine, "Reconnected to Character " + charId);
            }

            // Stop pending logouts
            this.Controller.Character.StopLogoutTimer();

            this.Controller.Character.Playfield = pf;
            this.Playfield = pf;
            this.Controller.Character.Stats.Read();
            this.controller.Character.Stats[StatIds.visualprofession].BaseValue = (uint)this.controller.Character.Stats[StatIds.profession].Value;
        }
        public void Update(IPlayer player, IPlayfield playfield, int numberOfMoves, IScoreboard scoreboard, IGameDialog dialogs)
        {
            if (playfield.IsPlayerWinning(player))
            {
                Console.Write(dialogs.WinnerMessage(numberOfMoves));
                string name = Console.ReadLine();
                try
                {
                    scoreboard.AddTopScoreToScoreboard(name, numberOfMoves);
                }
                finally
                {

                }
                Console.WriteLine();
                LabyrinthEngine.Instance.StartNewGame();
            }
        }
 public TestObjectsFactory()
 {
     this.factory = new LabyrinthFactory();
     this.playfield = this.factory.CreatePlayfield();
     this.player = this.factory.CreatePlayer();
     this.dialogs = this.factory.CreateDialogs();
     this.scoreboard = this.factory.CreateScoreboard();
     this.save = new SaveSystem();
 }
Esempio n. 42
0
        /// <summary>
        /// </summary>
        /// <param name="charId">
        /// </param>
        /// <exception cref="Exception">
        /// </exception>
        public void CreateCharacter(int charId)
        {
            IEnumerable<DBCharacter> daochar = CharacterDao.GetById(charId);
            if (daochar.Count() == 0)
            {
                throw new Exception("Character " + charId + " not found.");
            }

            if (daochar.Count() > 1)
            {
                throw new Exception(
                    daochar.Count() + " Characters with id " + charId + " found??? Check Database setup!");
            }

            DBCharacter character = daochar.First();
            IPlayfield pf = this.server.PlayfieldById(character.Playfield);

            if (pf.Entities.GetObject<Character>(
                new Identity() { Type = IdentityType.CanbeAffected, Instance = charId }) == null)
            {
                this.character = new Character(
                    pf.Entities,
                    new Identity { Type = IdentityType.CanbeAffected, Instance = charId },
                    this);
            }
            else
            {
                this.character =
                    pf.Entities.GetObject<Character>(
                        new Identity() { Type = IdentityType.CanbeAffected, Instance = charId });
                this.character.Reconnect(this);
                LogUtil.Debug("Reconnected to Character " + charId);
            }

            // Stop pending logouts
            this.character.StopLogoutTimer();

            this.character.Playfield = pf;
            this.Playfield = pf;
            this.character.Stats.Read();
        }
Esempio n. 43
0
 /// <summary>
 /// </summary>
 /// <param name="playfield">
 /// </param>
 public void SetPlayfield(IPlayfield playfield)
 {
     this.playfield = playfield;
 }
        private string GetSymbolFromField(IPlayfield playfield)
        {
            Console.WriteLine(GlobalConstants.EnterCoordinates);

            int[] coordinates = this.reader.ReadCoordinates();

            while (!(coordinates[0] >= 0 && coordinates[0] < playfield.Size
                    && coordinates[1] >= 0 && coordinates[1] < playfield.Size))
            {
                coordinates = this.reader.ReadCoordinates();
            }

            int row = coordinates[0];
            int col = coordinates[1];

            this.currentHit.Row = row;
            this.currentHit.Col = col;

            return playfield.GetCell(row, col);
        }
Esempio n. 45
0
        /// <summary>
        /// </summary>
        /// <param name="charId">
        /// </param>
        /// <exception cref="Exception">
        /// </exception>
        public void CreateCharacter(int charId)
        {
            this.character = new Character(new Identity { Type = IdentityType.CanbeAffected, Instance = charId }, this);
            IEnumerable<DBCharacter> daochar = CharacterDao.GetById(charId);
            if (daochar.Count() == 0)
            {
                throw new Exception("Character " + charId.ToString() + " not found.");
            }

            if (daochar.Count() > 1)
            {
                throw new Exception(
                    daochar.Count().ToString() + " Characters with id " + charId.ToString()
                    + " found??? Check Database setup!");
            }

            DBCharacter character = daochar.First();
            this.character.Name = character.Name;
            this.character.LastName = character.LastName;
            this.character.FirstName = character.FirstName;
            this.character.Coordinates = new AOCoord(character.X, character.Y, character.Z);
            this.character.Heading = new Quaternion(
                character.HeadingX, character.HeadingY, character.HeadingZ, character.HeadingW);
            this.character.Playfield = this.server.PlayfieldById(character.Playfield);
            this.Playfield = this.character.Playfield;
            this.Playfield.Entities.Add(this.character);
            this.character.Stats.Read();
            this.character.BaseInventory.Read();
        }