public LocalConfigServerTests()
        {
            var configurationCollection = new ConfigurationRegistry();

            configurationCollection.AddRegistration(ConfigurationRegistration.Build <SimpleConfig>());
            repository = new InMemoryRepository();
        }
Beispiel #2
0
 public Item(string itemConfigKey)
 {
     ItemConfigKey = itemConfigKey;
     Configuration = ConfigurationRegistry.GetInstance().GetItemConfiguration(itemConfigKey);
     TileTarget    = new TileTarget();
     _stackSize    = 1;
 }
        private static NhibConfigData GetOrCreateConfigData(String configFileName)
        {
            NhibConfigData retvalue = factories.SafeGet(configFileName);

            if (null == retvalue)
            {
                //This is the first time we ask for this configuration
                global::NHibernate.Cfg.Configuration config = new global::NHibernate.Cfg.Configuration();
                XDocument doc = XDocument.Load(configFileName);
                XElement  connStringElement = (from e in doc.Descendants()
                                               where e.Attribute("name") != null && e.Attribute("name").Value == "connection.connection_string"
                                               select e).Single();
                String cnName = connStringElement.Value;
                connStringElement.Value = ConfigurationRegistry.ConnectionString(connStringElement.Value).ConnectionString;
                using (XmlReader reader = doc.CreateReader())
                {
                    config.Configure(reader);
                }
                ISessionFactory factory = config.BuildSessionFactory();
                retvalue = new NhibConfigData()
                {
                    Configuration = config, SessionFactory = factory, ConnectionName = cnName
                };
                factories.Add(configFileName, retvalue);
            }
            return(retvalue);
        }
        /// <summary>
        /// Gets the format of the parameter, to avoid query the schema the parameter
        /// format is cached with the type of the parameter
        /// </summary>
        /// <param name="command"></param>
        /// <param name="connectionStringName">Connection String name is needed because if
        /// we did not already get the format of the parameter we need the connection to
        /// retrieve the format from the schema.</param>
        /// <returns></returns>
        private static String GetParameterFormat(DbCommand command, String connectionStringName)
        {
            String typeName = command.GetType().FullName;

            if (!mParametersFormat.ContainsKey(typeName))
            {
                ConnectionStringSettings cn;
                if (String.IsNullOrEmpty(connectionStringName))
                {
                    cn = ConfigurationRegistry.MainConnectionString;
                }
                else
                {
                    cn = ConfigurationRegistry.ConnectionString(connectionStringName);
                }
                DbProviderFactory Factory = DbProviderFactories.GetFactory(cn.ProviderName);
                using (DbConnection conn = Factory.CreateConnection())
                {
                    conn.ConnectionString = cn.ConnectionString;
                    conn.Open();
                    mParametersFormat.Add(
                        typeName,
                        conn.GetSchema("DataSourceInformation")
                        .Rows[0]["ParameterMarkerFormat"].ToString());
                }
            }
            return(mParametersFormat[typeName]);
        }
		public override void FixtureSetUp(IBaseTestFixture fixture)
		{
			InMemoryConfigurationRegistry configurationRegistry = new InMemoryConfigurationRegistry();
			fixture.DisposeAtTheEndOfFixture(ConfigurationRegistry.Override(configurationRegistry));
			fixture.SetIntoTestContext(RegistryTestContextKey, configurationRegistry);
			
			base.FixtureSetUp(fixture);
		}
        /// <summary>
        /// Adds Local ConfigServer client to specified ServiceCollection
        /// </summary>
        /// <param name="source">The IServiceCollection to add local ConfigServer client to</param>
        /// <param name="applicationId">Identifier for application requesting the configuration</param>
        /// <returns>ConfigServer client builder for further configuration of client</returns>
        public static ConfigServerClientBuilder UseLocalConfigServerClient(this ConfigServerBuilder source, string applicationId)
        {
            var configurationCollection = new ConfigurationRegistry();
            var builder = new ConfigServerClientBuilder(source.ServiceCollection, configurationCollection);

            source.ServiceCollection.Add(ServiceDescriptor.Transient <IConfigServer>(r => new LocalConfigServerClient(r.GetService <IConfigProvider>(), applicationId)));
            return(builder);
        }
 public SimpleContainer(ConfigurationRegistry configurationRegistry, ContainerContext containerContext,
                        LogError errorLogger)
 {
     Configuration           = configurationRegistry;
     implementationSelectors = configurationRegistry.GetImplementationSelectors();
     dependenciesInjector    = new DependenciesInjector(this);
     this.containerContext   = containerContext;
     this.errorLogger        = errorLogger;
 }
Beispiel #8
0
        /// <summary>
        /// Adds ConfigServer client to specified ServiceCollection
        /// </summary>
        /// <param name="source">The IServiceCollection to add ConfigServer client to</param>
        /// <param name="options">Options for ConfigServer client</param>
        /// <returns>ConfigServer client builder for further configuration</returns>
        public static ConfigServerClientBuilder AddConfigServerClient(this IServiceCollection source, ConfigServerClientOptions options)
        {
            var configurationCollection = new ConfigurationRegistry();
            var builder = new ConfigServerClientBuilder(source, configurationCollection);

            source.Add(ServiceDescriptor.Transient <IHttpClientWrapper>(r => new HttpClientWrapper(options.Authenticator)));
            source.Add(ServiceDescriptor.Transient <IConfigServerClient>(r => new ConfigServerClient(r.GetService <IHttpClientWrapper>(), r.GetService <IMemoryCache>(), r.GetService <ConfigurationRegistry>(), options)));
            return(builder);
        }
Beispiel #9
0
        public InMemoryRespositoryTests()
        {
            configurationCollection = new ConfigurationRegistry();
            configurationCollection.BuildAndAddRegistration <SimpleConfig>();
            var repo = new InMemoryRepository();

            target       = repo;
            clientTarget = repo;
        }
Beispiel #10
0
 private IContainer CreateContainer(TypesContext currentTypesContext, ConfigurationRegistry configuration)
 {
     return(new Implementation.SimpleContainer(configuration, new ContainerContext
     {
         infoLogger = infoLogger,
         genericsAutoCloser = currentTypesContext.genericsAutoCloser,
         typesList = currentTypesContext.typesList,
         valueFormatters = valueFormatters
     }, errorLogger));
 }
Beispiel #11
0
 public ConfigServerClient(IHttpClientWrapper client, IMemoryCache memorycache, ConfigurationRegistry collection, ConfigServerClientOptions options)
 {
     this.client     = client;
     this.collection = collection;
     this.options    = options;
     if (memorycache == null && !options.CacheOptions.IsDisabled)
     {
         throw new ArgumentNullException(nameof(memorycache), "Caching is enabled, but IMemoryCache is not registered in service collection. Try adding \"services.AddMemoryCache()\" to startup file");
     }
     this.cache = memorycache;
 }
Beispiel #12
0
 public ConfigServerClientTest()
 {
     collection = new ConfigurationRegistry();
     collection.AddRegistration(ConfigurationRegistration.Build <SimpleConfig>());
     options                         = new ConfigServerClientOptions();
     options.ClientId                = "1234-5678-1234";
     options.ConfigServer            = "https://test.com/Config";
     options.CacheOptions.IsDisabled = true;
     clientWrapper                   = new Mock <IHttpClientWrapper>();
     cache  = new Mock <IMemoryCache>();
     target = new ConfigServerClient(clientWrapper.Object, cache.Object, collection, options);
 }
Beispiel #13
0
        public void UseItemRightClick(Simulation.Simulation simulation, SimulationEntity entity)
        {
            if (Configuration.RightClickComponents.Count == 0)
            {
                return;
            }

            foreach (string componentKey in Configuration.RightClickComponents)
            {
                ConfigurationRegistry.GetInstance().GetItemComponent(componentKey).Use(simulation, entity, this);
            }
        }
Beispiel #14
0
        /// <summary>
        /// Loads the module into the kernel.
        /// </summary>
        public override void Load()
        {
            //Configuration Registry
            Bind <IConfigurationRegistry>().ToMethod((context) =>
            {
                var registry = new ConfigurationRegistry();

                registry.AddValue("StockTradingAnalysis_MSSQL", ConfigurationManager.ConnectionStrings["StockTradingAnalysis_MSSQL"].ConnectionString);
                registry.AddValue("StockTradingAnalysis_RavenDB", ConfigurationManager.ConnectionStrings["StockTradingAnalysis_RavenDB"].ConnectionString);

                return(registry);
            }).InSingletonScope();
        }
Beispiel #15
0
        /// <summary>
        /// In the test fixture setup I simply ovveride the configuration registry
        /// using an in memory configuration with a fixed connection string.
        /// </summary>
        protected override void OnTestFixtureSetUp()
        {
            sut = new NHibernateRepository <AnEntity>();
            sut.ConfigurationFileName = ConfigFileName;
            repo = new InMemoryConfigurationRegistry();
            repo.ConnStrings.Add(
                "main", new ConnectionStringSettings(
                    "main", "Data Source=DbFile1.db;Version=3", "System.Data.SQLite"));
            DisposeAtTheEndOfFixture(ConfigurationRegistry.Override(repo));
            NHibernateSessionManager.GenerateDbFor(ConfigFileName);

            base.OnTestFixtureSetUp();
        }
Beispiel #16
0
 public ConfigServerClientTest()
 {
     collection = new ConfigurationRegistry();
     collection.AddRegistration(ConfigurationRegistration.Build <SimpleConfig>());
     collection.AddRegistration(ConfigurationRegistration.Build <SampleConfig>(configRegisration));
     options = new ConfigServerClientOptions
     {
         ConfigServer = "https://test.com/Config"
     };
     options.CacheOptions.IsDisabled = true;
     clientWrapper = new Mock <IHttpClientWrapper>();
     target        = new ConfigServerClient(clientWrapper.Object, new NoCachingStrategy(), new SingleClientIdProvider(clientId), collection, options);
 }
Beispiel #17
0
        public void UseItemLeftClick(Simulation.Simulation simulation, SimulationEntity entity)
        {
            if (Configuration.LeftClickComponents.Count == 0)
            {//Do default actions if no specified item components
                ConfigurationRegistry.GetInstance().GetItemComponent("Hit").Use(simulation, entity, this);
                ConfigurationRegistry.GetInstance().GetItemComponent("BreakBlock").Use(simulation, entity, this);
                return;
            }

            foreach (string componentKey in Configuration.LeftClickComponents)
            {
                ConfigurationRegistry.GetInstance().GetItemComponent(componentKey).Use(simulation, entity, this);
            }
        }
Beispiel #18
0
        private void InstantiateInStructureMap()
        {
            StructureMap.ObjectFactory.Configure(x =>
            {
                x.For <ILog>().Use(a => LogManager.GetLogger());
                x.For <IWebPageDownloader>().Use <WebPageDownloader>();
                x.For <IDateTimeHelper>().LifecycleIs(Lifecycles.GetLifecycle(InstanceScope.Singleton)).Use <DateTimeHelper>();

                ConfigurationRegistry.RegisterConfigurationSection(typeof(FileSystemConfiguration), "file-system.config");

                x.For <IFileSystemFactory>().Use <FileSystemFactory>();
                x.For <IFileSystem>().Use <FileSystem>();
                x.For <IWebUtilities>().LifecycleIs(Lifecycles.GetLifecycle(InstanceScope.Singleton)).Use <WebUtilities>();
                x.For <ILockServer>().LifecycleIs(Lifecycles.GetLifecycle(InstanceScope.Singleton)).Use <LockServer.LockServer>();
            });
        }
Beispiel #19
0
        public LocalConfigServerTests()
        {
            var configurationCollection = new ConfigurationRegistry();

            configurationCollection.AddRegistration(ConfigurationRegistration.Build <SimpleConfig>());
            var repo = new InMemoryRepository();

            repository    = repo;
            clientservice = new Mock <IConfigurationClientService>();
            clientservice.Setup(service => service.GetClientOrDefault(configIdentity.Client.ClientId))
            .ReturnsAsync(configIdentity.Client);
            registry = new Mock <IConfigurationModelRegistry>();
            registry.Setup(s => s.GetVersion())
            .Returns(() => configIdentity.ServerVersion);
            resourceStore = new Mock <IResourceStore>();
        }
Beispiel #20
0
        public void UseItemRightHold(Simulation.Simulation simulation, SimulationEntity entity, int holdTicks)
        {
            if (holdTicks % Configuration.CoolDown != 0)
            {
                return;
            }

            if (Configuration.RightHoldComponents.Count == 0)
            {
                return;
            }

            foreach (string componentKey in Configuration.RightHoldComponents)
            {
                ConfigurationRegistry.GetInstance().GetItemComponent(componentKey).Use(simulation, entity, this);
            }
        }
Beispiel #21
0
        /// <summary>
        /// Loads the binding configuration.
        /// </summary>
        /// <param name="serviceCollection">The service collection.</param>
        public void Load(IServiceCollection serviceCollection)
        {
            //Configuration Registry
            serviceCollection.AddSingleton <IConfigurationRegistry>(context =>
            {
                var registry = new ConfigurationRegistry();

                registry.AddValue("StockTradingAnalysis_MSSQL",
                                  DependencyResolver.Current.GetService <IConfiguration>()
                                  .GetConnectionString("StockTradingAnalysis_MSSQL"));

                registry.AddValue("StockTradingAnalysis_RavenDB",
                                  DependencyResolver.Current.GetService <IConfiguration>()
                                  .GetConnectionString("StockTradingAnalysis_RavenDB"));

                return(registry);
            });
        }
Beispiel #22
0
            /// <summary>
            /// In the constructor we creates all the object we need to access the database.
            /// </summary>
            /// <param name="connectionName"></param>
            public ConnectionData(String connectionName)
            {
                ConnectionStringSettings cn;

                if (String.IsNullOrEmpty(connectionName))
                {
                    cn = ConfigurationRegistry.MainConnectionString;
                }
                else
                {
                    cn = ConfigurationRegistry.ConnectionString(connectionName);
                }

                Factory    = DbProviderFactories.GetFactory(cn.ProviderName);
                Connection = Factory.CreateConnection();
                Connection.ConnectionString = cn.ConnectionString;
                Connection.Open();
                TransactionStack.Push(Connection.BeginTransaction());
            }
        public void TestFixtureSetUp()
        {
            overrideContext        = new TestContext();
            OverrideContextCleanUp = CurrentContext.Override(overrideContext);
            repo = new InMemoryConfigurationRegistry();
            repo.ConnStrings.Add(
                "main", new ConnectionStringSettings(
                    "main", "Data Source=DbFile1.db;Version=3", "System.Data.SQLite"));
            repo.ConnStrings.Add(
                "NhConfig1", new ConnectionStringSettings(
                    "NhConfig1", "Data Source=:memory:;Version=3;New=True;", "System.Data.SQLite"));
            repo.ConnStrings.Add(
                "NhConfig2", new ConnectionStringSettings(
                    "NhConfig2", "Data Source=:memory:;Version=3;New=True;", "System.Data.SQLite"));

            OverrideSettings = ConfigurationRegistry.Override(repo);

            NHibernateSessionManager.GenerateDbFor("files//NhConfigFile1.cfg.xml");
        }
        /// <summary>
        /// No bean resolve in this stage.
        /// Except for bean definition.
        /// </summary>
        /// <param name="count"></param>
        public void PostRegistry(int?count = null)
        {
            if (count == null)
            {
                count = 0;
            }

            var newCount = ApplicationSP.UnityContainer.Registrations.Count();

            if (count == newCount)
            {
                return;
            }

            count = newCount;
            ConfigurationRegistry.Refresh();
            BeanDefinitionRegistry.Refresh();
            ImportRegistry.Refresh();
            PostRegistry(count);
        }
Beispiel #25
0
        public ExpandedUnions?TryExpandUnions(ConfigurationRegistry configuration)
        {
            ExpandedUnions?result     = null;
            var            startIndex = 0;

            for (var i = 0; i < contracts.Count; i++)
            {
                var contract = contracts[i];
                var union    = configuration.GetContractsUnionOrNull(contract);
                if (union == null)
                {
                    if (result != null)
                    {
                        result.Value.contracts[i - startIndex] = new[] { contract }
                    }
                    ;
                }
                else
                {
                    if (result == null)
                    {
                        startIndex = i;

                        result = new ExpandedUnions
                        {
                            contracts        = new string[contracts.Count - startIndex][],
                            unionedContracts = new List <UnionedContact>(1)
                        };
                    }
                    result.Value.unionedContracts.Add(new UnionedContact {
                        children = union, parent = contract
                    });
                    result.Value.contracts[i - startIndex] = union.ToArray();
                }
            }
            return(result);
        }
    }
Beispiel #26
0
        public static SimulationEntity SimulationEntityFactory(string entityKey, ClientSocket socket = null)
        {
            Random rand = new Random();

            ConfigurationRegistry registry = ConfigurationRegistry.GetInstance();
            EntityConfiguration   config   = registry.GetEntityConfiguration(entityKey);

            config.EntityKey = entityKey;

            //create new entity
            SimulationEntity newEntity = new SimulationEntity(socket?.ClientId ?? Guid.NewGuid().ToString(),
                                                              new EntityOptions
            {
                TextureKey = config.TextureKey,
                Dimensions = config.DimensionRange == null  ? config.Dimensions  : new BfbVector(
                    rand.Next((int)config.DimensionRange.X, (int)config.DimensionRange.Y),
                    rand.Next((int)config.DimensionRange.X, (int)config.DimensionRange.Y)),
                Origin     = config.Origin,
                EntityType = config.EntityType
            }, socket)
            {
                CollideFilter      = config.CollideFilter,
                CollideWithFilters = config.CollideWithFilters,
                Meta = new EntityMeta
                {
                    Health    = config.Health,
                    Mana      = config.Mana,
                    MaxHealth = config.Health,
                    MaxMana   = config.Mana
                },
                EntityConfiguration = config
            };

            //Required components
            newEntity.EntityComponents.Add(new EntityFacing());

            //Add a lifetime component if needed
            if (config.Lifetime > 0)
            {
                newEntity.EntityComponents.Add(new LifetimeComponent(config.Lifetime));
            }

            //Add components
            foreach (string configComponent in config.Components)
            {
                newEntity.EntityComponents.Add(registry.GetEntityComponent(configComponent));
            }

            if (newEntity.EntityType == EntityType.Mob || newEntity.EntityType == EntityType.Player)
            {
                newEntity.EntityComponents.Add(new ManaRegen());
            }


            if (socket == null)//We can assume if a socket is supplied then its a player
            {
                return(newEntity);
            }

            newEntity.EntityType = EntityType.Player;
            newEntity.EntityComponents.Add(new InputRemote());
            newEntity.EntityComponents.Add(new InventoryComponent());
            newEntity.EntityComponents.Add(new InventoryConnection());
            newEntity.EntityComponents.Add(new AnimatedHolding());

            return(newEntity);
        }
Beispiel #27
0
        private void Init()
        {
            ConfigurationRegistry.InitializeRegistry();

            #region Server Callbacks

            #region Terminal Header

            //Terminal Header format
            _server.SetTerminalHeader(() =>
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write($"[BFB-Server|{DateTime.Now:h:mm:ss tt}|T:{Process.GetCurrentProcess().Threads.Count}] ");
                Console.ResetColor();
            });

            #endregion

            #region Handle Client Connection

            _server.OnClientConnect = socket =>
            {
                _server.PrintMessage($"Client {socket.ClientId} Connected");
            };

            #endregion

            #region Handle Client Authentication

            _server.OnClientAuthentication = m =>
            {
                _server.PrintMessage($"Client {m.ClientId} Authenticated.");
                return(true);
            };

            #endregion

            #region OnClientPrepare

            _server.OnClientPrepare = socket =>
            {
                socket.Emit("prepare", _simulation.World.GetInitWorldData());
            };

            #endregion

            #region Handle Client Ready

            _server.OnClientReady = socket =>
            {
                SimulationEntity player = SimulationEntity.SimulationEntityFactory("Human", socket: socket);
                _simulation.AddEntity(player);
                _simulation.ConnectedClients += 1;

                _server.PrintMessage($"Client {socket.ClientId} Ready and added to Simulation");
            };

            #endregion

            #region Handle Client Disconnect

            _server.OnClientDisconnect = id =>
            {
                _simulation.RemoveEntity(id, EntityRemovalReason.Disconnect);
                _simulation.ConnectedClients -= 1;
                _server.PrintMessage($"Client {id} Disconnected");
            };

            #endregion

            #region OnServerStart/Generate World

            //probably should just be triggered to generate the first time the simulation starts
            _server.OnServerStart = () =>
            {
                Console.WriteLine("Generating World...");
                Console.Write("[");
                _cursorPositionStart = Console.CursorLeft;
                Console.CursorLeft   = _cursorPositionStart + 101;
                Console.Write("]");
                Console.CursorLeft      = _cursorPositionStart;
                Console.BackgroundColor = ConsoleColor.Blue;
                Console.CursorVisible   = false;
                _simulation.GenerateWorld();
                Console.ResetColor();
                Console.CursorVisible = true;
                Console.WriteLine();
                _server.PrintMessage();
            };

            #endregion

            #endregion

            #region Simulation Callbacks

            #region OnSimulationStart

            _simulation.OnSimulationStart = () => _server.PrintMessage("Simulation exiting Hibernation");

            #endregion

            #region OnSimulationStop

            _simulation.OnSimulationStop = () => _server.PrintMessage("Simulation entering Hibernation");

            #endregion

            #region OnSimulationTick

            _simulation.OnSimulationTick = () =>
            {
                _server.Emit("HeartBeat");
            };

            #endregion

            #region OnWorldGenerationProgress

            _simulation.OnWorldGenerationProgress = progress =>
            {
                Console.Write("=");
                int previous = Console.CursorLeft;
                Console.CursorLeft = _cursorPositionStart + 50;
                Console.Write(progress);
                Console.CursorLeft = previous;
            };

            #endregion

            #region OnEntityAdd

            _simulation.OnEntityAdd = (entityKey, isPlayer) =>
            {
                if (isPlayer)
                {
                    _server.GetClient(entityKey).On("UISelect", (m) =>
                    {
                        SimulationEntity player = SimulationEntity.SimulationEntityFactory(m.Message, socket: _server.GetClient(m.ClientId));
                        player.Position.X       = 100;
                        player.Position.Y       = 100;
                        _simulation.AddEntity(player);
                    });
                }
            };

            #endregion

            #region OnEntityRemove

            _simulation.OnEntityRemove = (entityKey, isPlayer) =>
            {
                _server.Emit("/player/disconnect", new DataMessage {
                    Message = entityKey
                });
            };

            #endregion

            #region OnEntityUpdates

            _simulation.OnEntityUpdates = (entityKey, updates) =>
            {
                _server.GetClient(entityKey)?.Emit("/players/updates", updates);
            };

            #endregion

            #region OnInventoryUpdates

            _simulation.OnInventoryUpdate = (entityKey, updates) =>
            {
                _server.GetClient(entityKey)?.Emit("/players/inventoryUpdates", updates);
            };

            #endregion

            #region OnChunkUpdates

            _simulation.OnChunkUpdates = (entityKey, updates) =>
            {
                _server.GetClient(entityKey)?.Emit("/players/chunkUpdates", updates);
            };

            #endregion

            #region OnSimulationOverload

            _simulation.OnSimulationOverLoad = ticksBehind => _server.PrintMessage($"SERVER IS OVERLOADED. ({ticksBehind}).");

            #endregion

            #endregion

            #region Terminal Prep

            Console.Clear();
            Console.Title = "BFB Server";
            _server.PrintMessage();

            #endregion
        }
Beispiel #28
0
        public void Use(Simulation simulation, SimulationEntity entity, IItem item)
        {
            if (entity.ControlState == null)
            {
                return;
            }

            int mouseX = (int)entity.ControlState.Mouse.X;
            int mouseY = (int)entity.ControlState.Mouse.Y;

            Tuple <int, int, int, int> chunkInformation = simulation.World.TranslatePixelPosition(mouseX, mouseY);

            //If we are inside map
            if (chunkInformation == null)
            {
                return;
            }

            Chunk targetChunk = simulation.World.ChunkFromChunkLocation(chunkInformation.Item1, chunkInformation.Item2);

            //If the chunk exist
            if (targetChunk == null)
            {
                return;
            }

            int xSelection = chunkInformation.Item3;
            int ySelection = chunkInformation.Item4;

            if (item.TileTarget.X != xSelection || item.TileTarget.Y != ySelection)
            {
                item.TileTarget.X             = xSelection;
                item.TileTarget.Y             = ySelection;
                item.TileTarget.Progress      = 0;
                item.TileTarget.ProgressTotal = ConfigurationRegistry.GetInstance()?
                                                .GetWallConfiguration((WorldTile)targetChunk.Wall[xSelection, ySelection])?.BreakSpeed ?? 0;
                return;
            }
            item.TileTarget.Progress++;

            WorldTile             tileType;
            ConfigurationRegistry config = ConfigurationRegistry.GetInstance();

            if (targetChunk.Block[xSelection, ySelection] == 0 && (tileType = (WorldTile)targetChunk.Wall[xSelection, ySelection]) != 0)
            {//Is block
                if (item.TileTarget.Progress < config.GetBlockConfiguration(tileType).BreakSpeed)
                {
                    return;//Not ready yet
                }
            }
            else
            {//is wall or air
                item.TileTarget.Progress = 0;
                return;
            }

            //If we made it here then we are ready to break a block
            targetChunk.ApplyBlockUpdate(new TileUpdate
            {
                X         = (byte)xSelection,
                Y         = (byte)ySelection,
                Mode      = false,
                TileValue = (ushort)WorldTile.Air
            });

            item.TileTarget.Progress = 0;

            int blockX = (simulation.World.WorldOptions.ChunkSize * chunkInformation.Item1 + xSelection) * simulation.World.WorldOptions.WorldScale;
            int blockY = (simulation.World.WorldOptions.ChunkSize * chunkInformation.Item2 + ySelection) * simulation.World.WorldOptions.WorldScale;

            InventoryManager inventory = new InventoryManager();
            Item             newItem   = new Item(config.GetWallConfiguration(tileType).ItemKey);

            inventory.Insert(newItem);

            SimulationEntity itemEntity = SimulationEntity.SimulationEntityFactory("Item");

            itemEntity.TextureKey = config.GetWallConfiguration(tileType).TextureKey;
            itemEntity.Position   = new BfbVector(blockX, blockY);
            itemEntity.Inventory  = inventory;
            simulation.AddEntity(itemEntity);
        }
Beispiel #29
0
 public void TestFixtureSetUp()
 {
     repo             = new InMemoryConfigurationRegistry();
     OverrideSettings = ConfigurationRegistry.Override(repo);
     InitDatabase();
 }
Beispiel #30
0
        public void Use(Simulation simulation, SimulationEntity entity, IItem item)
        {
            if (entity.ControlState == null)
            {
                return;
            }

            int mouseX = (int)entity.ControlState.Mouse.X;
            int mouseY = (int)entity.ControlState.Mouse.Y;

            Tuple <int, int, int, int> chunkInformation = simulation.World.TranslatePixelPosition(mouseX, mouseY);

            //If we are inside map
            if (chunkInformation == null)
            {
                return;
            }

            Chunk targetChunk = simulation.World.ChunkFromChunkLocation(chunkInformation.Item1, chunkInformation.Item2);

            //If the chunk exist
            if (targetChunk == null)
            {
                return;
            }

            int xSelection = chunkInformation.Item3;
            int ySelection = chunkInformation.Item4;

            if (item.TileTarget.X != xSelection || item.TileTarget.Y != ySelection)
            {
                item.TileTarget.X             = xSelection;
                item.TileTarget.Y             = ySelection;
                item.TileTarget.Progress      = 0;
                item.TileTarget.ProgressTotal = ConfigurationRegistry.GetInstance()?
                                                .GetBlockConfiguration((WorldTile)targetChunk.Block[xSelection, ySelection])?.BreakSpeed ?? 0;
                return;
            }
            item.TileTarget.Progress++;

            WorldTile             tileType;
            ConfigurationRegistry config = ConfigurationRegistry.GetInstance();

            if ((tileType = (WorldTile)targetChunk.Block[xSelection, ySelection]) != 0)
            {//Is block
                if (item.TileTarget.Progress < config.GetBlockConfiguration(tileType).BreakSpeed)
                {
                    return;//Not ready yet
                }
            }
            else
            {//is wall or air
                return;
            }

            //If we made it here then we are ready to break a block
            targetChunk.ApplyBlockUpdate(new TileUpdate
            {
                X         = (byte)xSelection,
                Y         = (byte)ySelection,
                Mode      = true,
                TileValue = (ushort)WorldTile.Air
            });

            item.TileTarget.Progress = 0;

            int blockX = (simulation.World.WorldOptions.ChunkSize * chunkInformation.Item1 + xSelection) * simulation.World.WorldOptions.WorldScale;
            int blockY = (simulation.World.WorldOptions.ChunkSize * chunkInformation.Item2 + ySelection) * simulation.World.WorldOptions.WorldScale;

            InventoryManager inventory = new InventoryManager();
            Item             newItem   = new Item(config.GetBlockConfiguration(tileType).ItemKey);

            inventory.Insert(newItem);

            SimulationEntity itemEntity = SimulationEntity.SimulationEntityFactory("Item");

            itemEntity.TextureKey = config.GetBlockConfiguration(tileType).TextureKey;
            itemEntity.Position   = new BfbVector(blockX, blockY);
            itemEntity.Inventory  = inventory;
            simulation.AddEntity(itemEntity);

//            simulation.AddEntity(new SimulationEntity(
//                Guid.NewGuid().ToString(),
//                new EntityOptions
//                {
//                    TextureKey = config.GetBlockConfiguration(tileType).TextureKey,
//                    Position = new BfbVector(blockX, blockY),
//                    Dimensions = new BfbVector(1 * simulation.World.WorldOptions.WorldScale,
//                        1 * simulation.World.WorldOptions.WorldScale),
//                    Rotation = 0,
//                    Origin = new BfbVector(0, 0),
//                    EntityType = EntityType.Item
//                }, new List<EntityComponent>
//                {
//                    new LifetimeComponent(2000),
//                    new TilePhysics()
//                })
//            {
//                CollideFilter = "item",
//                CollideWithFilters = new List<string>{ "tile" },
//                Inventory = inventory
//            });
        }