Ejemplo n.º 1
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Initialize Data
            ISeedStore seedStore = null;

            if (Properties.Settings.Default.UseDatabaseStore)
            {
                if (!TestConnection(Properties.Settings.Default.SeedStoreConnectionString))
                {
                    MessageBox.Show($"Failed to connect to database.  Using in-memory cache instead.  Seed results won't be saved if you close the program: \n\n{Properties.Settings.Default.SeedStoreConnectionString}", "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    seedStore = new SeedMemoryStore();
                }
                else
                {
                    seedStore = new SeedDatabaseStore(Properties.Settings.Default.SeedStoreConnectionString);
                }
            }
            else
            {
                seedStore = new SeedMemoryStore();
            }

            var seedManager = new SeedManager(seedStore);

            Application.Run(new RustCrossbreederForm(seedManager));
        }
Ejemplo n.º 2
0
        public static void Main(string[] args)
        {
            Console.WriteLine("START");

            try
            {
                var arguments = new Arguments().Parse(args);

                Console.WriteLine("Datasource: {0}", arguments.Datasource);
                Console.WriteLine("Catalog: {0}", arguments.Catalog);

                if (arguments.ForceReseeding)
                {
                    Console.WriteLine("Forcing the reseeding of the system accounts");
                }

                using (var dbContext = new DatabaseContextFactory().Create(arguments.Datasource, arguments.Catalog))
                {
                    Console.WriteLine("Seeding the database with data...");
                    var seedManager = new SeedManager(dbContext, arguments.ForceReseeding);
                    seedManager.Seed();
                }

                Console.WriteLine("Database seeded.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToDetail());
            }
            finally
            {
                Console.WriteLine("END");
            }
        }
Ejemplo n.º 3
0
    public static async Task <IHost> MigrateDataBaseAsync(this IHost host)
    {
        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            try
            {
                var dbContext = services.GetRequiredService <StoreContext>();
                await dbContext.Database.MigrateAsync();

                await SeedManager.SeedDataBaseAsync(dbContext, services.GetRequiredService <ILogger <SeedManager> >());

                var userDbContext = services.GetRequiredService <AppUserDbContext>();
                await userDbContext.Database.MigrateAsync();

                await AppUserDbContextSeed.SeedUserDataAsync(services.GetRequiredService <UserManager <AppUser> >());
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService <ILogger <Program> >();
                logger.LogError(ex, "An error occured while applying migrations");
            }
        }
        return(host);
    }
Ejemplo n.º 4
0
        public void InstallConfigure(IApplicationBuilder app)
        {
            var context = app.ApplicationServices.GetService <YeditepeContext>();

            context.Database.Migrate();
            SeedManager.SeedData(context);
        }
        /// <summary>
        /// Create a new Form
        /// </summary>
        public RustCrossbreederForm(SeedManager seedManager)
        {
            InitializeComponent();

            // Set DataGridViews to DoubleBuffer to reduce redraw lag
            this.dgvInputSeeds.DoubleBuffered(true);
            this.dgvOutputSeeds.DoubleBuffered(true);
            this.dgvCrossbreedInput.DoubleBuffered(true);

            // Configure DataGridView column sorting
            dgvInputSeeds.AutoGenerateColumns      = false;
            dgvOutputSeeds.AutoGenerateColumns     = false;
            dgvCrossbreedInput.AutoGenerateColumns = false;

            // Hook SeedManager events
            this._seedManager = seedManager;
            this._seedManager.ActiveCatalogUpdated    += HandleActiveCatalogUpdated;
            this._seedManager.ActiveSeedTypeUpdated   += HandleActiveSeedTypeUpdated;
            this._seedManager.AutoCrossBreedCompleted += HandleAutoCrossBreedCompleted;
            this._seedManager.DisplayError            += HandleDisplayError;
            this._seedManager.CreateCatalog(cmbCatalog.Text);

            // Set Combo box data sources
            this.cmbSeedType.DataSource   = Enum.GetNames(typeof(Seed.SeedTypes));
            this.cmbCatalog.DataSource    = this._seedManager.GetCatalogs().ToList();
            this.cmbCatalog.DisplayMember = nameof(KeyValuePair <int, string> .Value);           // Set display member to the Category string name
        }
Ejemplo n.º 6
0
        public static Particle Create(EParticles particleType, Vector3 location, Vector3 force)
        {
            Particle particle = EntityFactory.Create <Particle>(string.Format("{0}Particle", particleType.ToString()));

            particle.AddComponent <TransformComponent>().Init(location);

            PhysicsComponent physics = particle.AddComponent <PhysicsComponent>();

            physics.Init(BodyType.Dynamic, 0.94f, 0.5f);
            physics.ApplyForce(force, true);

            SpriteComponent   sprite  = particle.AddComponent <SpriteComponent>();
            LightingComponent light   = particle.AddComponent <LightingComponent>();
            DespawnComponent  despawn = particle.AddComponent <DespawnComponent>();

            switch (particleType)
            {
            case EParticles.Spark:
                float lifeTime = SeedManager.Get().NextRandF(2.0f, 5.0f);

                sprite.Init(CollisionManager.Get().PointTexture);
                sprite.Scale = new Vector2(SeedManager.Get().NextRandF(5, 15), SeedManager.Get().NextRandF(5, 15));
                sprite.AddColorFunction(x => { return(Color.Lerp(new Color(0.99f, 1.0f, 0.78f), new Color(1.0f, 0.0f, 0.0f), x)); });
                sprite.AddOpacityFunction(x => { return(1.0f - x / lifeTime); });

                light.Init(AssetManager.Get().Find <Texture2D>(ELightAssets.CircleLight), Vector2.Zero, new Vector2(0.4f, 0.4f));
                light.AddColorFunction(x => { return(Color.Lerp(new Color(0.99f, 1.0f, 0.78f), new Color(1.0f, 0.0f, 0.0f), x)); });
                light.AddBrightnessFunction(x => { return(1.0f - x / lifeTime); });

                despawn.AddTimeTrigger(x => x > lifeTime);
                break;
            }

            return(particle);
        }
Ejemplo n.º 7
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseAnalytics();
            app.UseRouting();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            ModelContext modelContext = new ModelContext();

            modelContext.Database.EnsureCreated();
#if DEBUG
            SeedManager seedManager = new SeedManager(modelContext);
            seedManager.Execute();
#endif
        }
Ejemplo n.º 8
0
        public static ApplicationContext Create(bool performSeed = true)
        {
            var context = new ApplicationContext();

            SeedManager.Initialize(context);
            return(context);
        }
Ejemplo n.º 9
0
        public void SetupSeedFilters()
        {
            // Set up the score filter.
            // TODO: Better way of doing this.
            SeedGeneration tomatoSeeds = SeedManager.GetLatestGenerationOfCropType("Tomato");

            tomatoSeeds.ScoreFilter.Add("DistanceFromGoal", -1);
            tomatoSeeds.ScoreFilter.Add("AliveTime", 0.5f);
            tomatoSeeds.ScoreFilter.Add("MaxConcurrentSeenCreatures", 0.1f);
            tomatoSeeds.ScoreFilter.Add("EnemyDamageDealt", 1.5f);
            tomatoSeeds.ScoreFilter.Add("EnemyKills", 2);

            SeedGeneration asparagusSeeds = SeedManager.GetLatestGenerationOfCropType("Asparagus");

            asparagusSeeds.ScoreFilter.Add("DistanceFromGoal", -1);
            asparagusSeeds.ScoreFilter.Add("AliveTime", 2f);
            asparagusSeeds.ScoreFilter.Add("MaxConcurrentSeenCreatures", 0.1f);
            asparagusSeeds.ScoreFilter.Add("EnemyDamageDealt", 1.5f);
            asparagusSeeds.ScoreFilter.Add("FriendlyDamageDealt", -2f);
            asparagusSeeds.ScoreFilter.Add("EnemyKills", 2);
            asparagusSeeds.ScoreFilter.Add("FriendlyKills", -3);
            asparagusSeeds.ScoreFilter.Add("ClosestHit", -4.5f);
            asparagusSeeds.ScoreFilter.Add("BestAngle", 3);
            asparagusSeeds.ScoreFilter.Add("OffMap", -1.5f);
        }
Ejemplo n.º 10
0
        //---------------------------------------------------------------------------

        public ItemPool(EItemPool type)
        {
            Type = type;

            Types  = new Dictionary <EItemType, float>();
            m_Rand = new Random(SeedManager.Get().NextSeed());
        }
    private void Awake()
    {
        _grid = transform.GetChild(0);

        // init singleton SeedManager with system time
        SeedManager.Init((int)DateTime.Now.Ticks);
    }
Ejemplo n.º 12
0
 public void Awake()
 {
     if (instance == null)
     {
         instance = this;
     }
     else if (instance != this)
     {
         Destroy(gameObject);
     }
 }
Ejemplo n.º 13
0
        //---------------------------------------------------------------------------

        public void Spawn(EItemType item)
        {
            TransformComponent transform = GetComponent <TransformComponent>();

            if (transform != null)
            {
                float   rot   = (SeedManager.Get().NextRandF() * (float)Math.PI * 2.0f);
                float   dist  = (SeedManager.Get().NextRandF() * 120.0f + 400.0f);
                Vector3 force = new Vector3((float)Math.Sin(rot) * dist, (float)Math.Cos(rot) * dist, SeedManager.Get().NextRandF(20, 40));
                PickupFactory.Create(item, transform.Location, force);
            }
        }
Ejemplo n.º 14
0
 private void plantCrops()
 {
     for (int x = 0; x < WorldMap.Width; x++)
     {
         if (cropTilemap.IsTileEmpty(x, tomatoZ))
         {
             cropTilemap.PlantSeed(x, tomatoZ, SeedManager.GetLatestGenerationOfCropType("Tomato").GetBestSeed());
         }
         if (cropTilemap.IsTileEmpty(x, asparagusZ))
         {
             cropTilemap.PlantSeed(x, asparagusZ, SeedManager.GetLatestGenerationOfCropType("Asparagus").GetBestSeed());
         }
     }
 }
Ejemplo n.º 15
0
        public static void RegisterPersistence(this IServiceCollection services, string connectionString)
        {
            services.AddSingleton <IDataBaseServiceOptions>(provider => new DataBaseServiceOptions()
            {
                ConnectionString = connectionString, Provider = services.BuildServiceProvider()
            });

            services.AddDbContext <DatabaseService>();
            services.AddScoped <IDatabaseService, DatabaseService>();
            services.AddTransient <SeedManager, SeedManager>();
            services.AddScoped(typeof(IRepository <>), typeof(Repository <>));

            // ======================================Seed Management==========================
            SeedManager seedManager = services.BuildServiceProvider().GetService <SeedManager>();

            seedManager.Seed();
        }
Ejemplo n.º 16
0
        private static void SeedDatabase(IHost host)
        {
            using var scope = host.Services.CreateScope();
            var services = scope.ServiceProvider;

            try
            {
                var hashService = services.GetRequiredService <IHashService>();
                var context     = services.GetRequiredService <EFContext>();
                var seedManager = new SeedManager(context, hashService);
                seedManager.SeedDatabaseAsync().GetAwaiter().GetResult();
            }
            catch (Exception exception)
            {
                Log.Fatal(exception, "An error occurred while seeding the database.");
            }
        }
Ejemplo n.º 17
0
    private void SetVariables()
    {
        blocksDatabase = blockDB.database;
        biomesDatabase = biomeDB.database;
        xBound         = xChunkSize * chunkCountX;
        yBound         = yChunkSize * chunkCountY;

        if (useSeed)
        {
            SeedManager.setSeed(seed);
        }
        else
        {
            SeedManager.setSeed();
        }
        rng            = SeedManager.rng;
        biomeGenerator = new BiomeGenerator(xBound, yBound, rng, xSamples, ySamples, tranzitionTreshhold);
    }
Ejemplo n.º 18
0
        //---------------------------------------------------------------------------

        public byte[,] CreateMap(int size = 1)
        {
            byte[,] map = new byte[Bounds.Width / size, Bounds.Height / size];

            for (int x = 0; x < Bounds.Width / size; x++)
            {
                for (int y = 0; y < Bounds.Height / size; y++)
                {
                    map[x, y] = SeedManager.Get().NextRand(0, 2) == 0 ? (byte)0 : (byte)2;
                }
            }

            foreach (Room room in Rooms)
            {
                for (int x = room.Bounds.X; x < room.Bounds.X + room.Bounds.Width; x++)
                {
                    for (int y = room.Bounds.Y; y < room.Bounds.Y + room.Bounds.Height; y++)
                    {
                        map[x / size, y / size] = 255;
                    }
                }
            }
            foreach (Corridor corridor in Corridors)
            {
                foreach (CorridorSegment segment in corridor.Segments)
                {
                    int thickness = (segment.Thickness - 1) / 2;
                    for (int x = Math.Min(segment.Start.X, segment.End.X) - thickness; x <= Math.Max(segment.Start.X, segment.End.X) + thickness; x++)
                    {
                        for (int y = Math.Min(segment.Start.Y, segment.End.Y) - thickness; y <= Math.Max(segment.Start.Y, segment.End.Y) + thickness; y++)
                        {
                            if (x >= 0 && x < map.GetLength(0) && y >= 0 && y < map.GetLength(1))
                            {
                                map[x, y] = 255;
                            }
                        }
                    }
                }
            }
            return(map);
        }
Ejemplo n.º 19
0
    // Update is called once per frame
    void Update()
    {
        timeCounter += Time.deltaTime;

        if (timeCounter >= 2.5)
        {
            Destroy(gameObject);
        }
        else if (timeCounter >= 1.3)
        {
            if (done == false)
            {
                SeedManager newSeed = Instantiate(seed, transform.position + new Vector3(0, 0.7f, 0), Quaternion.identity);
                newSeed.setTarget(target);
                done = true;
            }
        }
        else if (timeCounter >= 0.6)
        {
            animator.SetBool("hasSpawn", true);
        }
    }
Ejemplo n.º 20
0
        //---------------------------------------------------------------------------

        public SpawnerComponent(Guid entity) : base(entity)
        {
            m_Rand = new Random(SeedManager.Get().NextSeed());
        }
Ejemplo n.º 21
0
    public int[,] GenerateBiomsFromRarity(Biome[] toSpawn)
    {
        resetMap();
        this.biomeAvailability = new bool[xSamples, ySamples];
        int raritySum = 0;

        foreach (Biome n in toSpawn)
        {
            raritySum += n.rarity;
            //Debug.Log(n.biomaName+ " rarity: "+ n.rarity);
        }
        float biomeParcel = (float)(xSamples * ySamples) / raritySum;

        int[] biomeCount = new int[toSpawn.Length];


        int highestRarity       = 0;
        int highestRarityI      = 0;
        int sumOfReservedChunks = 0;

        for (int i = 0; i < biomeCount.Length; i++)
        {
            if (toSpawn[i].rarity > highestRarity)
            {
                highestRarity  = toSpawn[i].rarity;
                highestRarityI = i;
            }
            biomeCount[i]        = (int)(toSpawn[i].rarity * biomeParcel);
            sumOfReservedChunks += biomeCount[i];
        }
        biomeCount[highestRarityI] += ((xSamples * ySamples) - sumOfReservedChunks); //mozna by zrobic ranodomowo to

        List <int> biomeSpawnOrder = new List <int>();

        for (int i = 0; i < biomeCount.Length; i++)
        {
            for (int j = 0; j < biomeCount[i]; j++)
            {
                biomeSpawnOrder.Add(toSpawn[i].ID);
            }
        }

        SeedManager.Shuffle <int>(biomeSpawnOrder);

        //string s = "";
        //foreach (int t in biomeSpawnOrder)
        //    s += t.ToString();
        //Debug.Log(s);


        int[,] biomeCenterMap = ListToBiomeCenters(biomeSpawnOrder);


        int xSampleSizeInBlocks = xBound / xSamples;
        int ySampleSizeInBlocks = yBound / ySamples;

        Vector2Int[,] centers = new Vector2Int[xSamples, ySamples];

        Vector2Int randomizedPos;

        for (int y = 0; y < ySamples; y++)
        {
            for (int x = 0; x < xSamples; x++)
            {
                randomizedPos = new Vector2Int(
                    rng.Next(x * xSampleSizeInBlocks, x * xSampleSizeInBlocks + xSampleSizeInBlocks),
                    rng.Next(y * ySampleSizeInBlocks, y * ySampleSizeInBlocks + ySampleSizeInBlocks));
                centers[x, y] = randomizedPos;
                //GameObject o = new GameObject();
                //o.transform.position = new Vector3(randomizedPos.x, randomizedPos.y, 0);
                //o.transform.name = biomeCenterMap[x, y].ToString();
            }
        }
        MapToVoronoiDiagram(centers, biomeCenterMap);
        //GenerateOneBiome();
        return(biomeMap);
    }
Ejemplo n.º 22
0
        //---------------------------------------------------------------------------

        protected override void Initialize()
        {
            base.Initialize();
            Window.AllowUserResizing = true;
            GameWindowSettings.SetWindowSettings(graphics, Window, 1680, 1050);

            oldKeyboardState = Keyboard.GetState();

            int width  = GraphicsDevice.PresentationParameters.BackBufferWidth;
            int height = GraphicsDevice.PresentationParameters.BackBufferHeight;

            GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp;

            LightingManager.Get().Device = GraphicsDevice;

            SeedManager.Get().ResetBaseSeed(1234);

            /*--------------------------------------------------------------------------
            *          Items
            *  --------------------------------------------------------------------------*/

            ItemManager.Get().LoadItems();
            ItemManager.Get().LoadItemPools();

            /*--------------------------------------------------------------------------
            *          Stage
            *  --------------------------------------------------------------------------*/

            Stage stage = new Stage(SeedManager.Get().NextSeed());

            StageManager.Get().Create(stage.CreateMap());
            StageManager.Get().Stage = stage;

            foreach (Room room in stage.Rooms)
            {
                int max = SeedManager.Get().NextSeed(3, 7);
                for (int i = 0; i < max; i++)
                {
                    Vector2 position = new Vector2(room.Bounds.Center.X * 64 + (float)Math.Sin((i / (max / 2.0f)) * Math.PI) * 360, room.Bounds.Center.Y * 64 + (float)Math.Cos((i / (max / 2.0f)) * Math.PI) * 360);
                    EntityFactory.Create <Chest>("Chest").Init(position);
                }
                EntityFactory.Create <SimpleTestEnemy>("Enemy").Init(new Vector2(room.Bounds.Center.X * 64, room.Bounds.Center.Y * 64));

                for (int x = 0; x < room.Bounds.Width; x += 3)
                {
                    IEntity torch = EntityFactory.Create <Entity>("Torch");
                    torch.AddComponent <TransformComponent>().Init(new Vector3(room.Bounds.X * 64 + x * 64 + 32, room.Bounds.Y * 64 + 32, 110));
                    torch.AddComponent <ParticleSpawnerComponent>().Emitter.Description = ParticleDesc.Fire;
                    torch.AddComponent <LightingComponent>().Init(AssetManager.Get().Find <Texture2D>(ELightAssets.CircleLight), new Vector2(0, 6), new Vector2(1, 1), Color.Orange, 0.6f);
                }
            }

            stage.SaveStageAsImage(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Map.png"));

            /*--------------------------------------------------------------------------
            *          Player 1
            *  --------------------------------------------------------------------------*/

            Player player = EntityFactory.Create <Player>("Player1");

            /*--------------------------------------------------------------------------
            *           Player 2
            *  --------------------------------------------------------------------------*/

            Player player2 = EntityFactory.Create <Player>("Player2");

            /*--------------------------------------------------------------------------
            *           Camera
            *  --------------------------------------------------------------------------*/

            CameraManager.Get().Init(width, height);

            Camera cam1 = EntityFactory.Create <Camera>("Cam1");

            cam1.Properties.Init(GraphicsDevice, width / 2, height, AssetManager.Get().Find <Texture2D>(ESpriteAssets.CameraBackground1), AssetManager.Get().Find <Effect>(EEffectAssets.DeferredLighting));
            cam1.Properties.Viewport           = new Rectangle(0, 0, width / 2, height);
            cam1.Properties.BloomExtractEffect = AssetManager.Get().Find <Effect>(EEffectAssets.BloomExtract);
            cam1.Properties.BloomCombineEffect = AssetManager.Get().Find <Effect>(EEffectAssets.BloomCombine);
            cam1.Properties.BlurEffect         = AssetManager.Get().Find <Effect>(EEffectAssets.Blur);
            cam1.Properties.Tileset            = AssetManager.Get().Find <Texture2D>(ETilesetAssets.DungeonTileset2);
            cam1.Properties.AddTarget(player);
            //cam1.Properties.IsAmbientOcclusionEnabled = true;

            Camera cam2 = EntityFactory.Create <Camera>("Cam2");

            cam2.Properties.Init(GraphicsDevice, width / 2, height, AssetManager.Get().Find <Texture2D>(ESpriteAssets.CameraBackground1), AssetManager.Get().Find <Effect>(EEffectAssets.DeferredLighting));
            cam2.Properties.Viewport           = new Rectangle(width / 2, 0, width / 2, height);
            cam2.Properties.BloomExtractEffect = AssetManager.Get().Find <Effect>(EEffectAssets.BloomExtract);
            cam2.Properties.BloomCombineEffect = AssetManager.Get().Find <Effect>(EEffectAssets.BloomCombine);
            cam2.Properties.BlurEffect         = AssetManager.Get().Find <Effect>(EEffectAssets.Blur);
            cam2.Properties.Tileset            = AssetManager.Get().Find <Texture2D>(ETilesetAssets.DungeonTileset2);
            cam2.Properties.AddTarget(player2);
            //cam2.Properties.IsAmbientOcclusionEnabled = true;

            CameraManager.Get().FuseCameras(cam1, cam2, width / 2);


            /*--------------------------------------------------------------------------
            *           UI
            *  --------------------------------------------------------------------------*/

            UIManager.Get().Init(GraphicsDevice, width, height);
            SpriteFont debug_font = AssetManager.Get().Find <SpriteFont>(EFontAssets.DebugFont);

            UIEntity           healthbar1          = EntityFactory.CreateUI <UIEntity>("HealthbarPlayer1");
            HealthbarComponent healthbarcomponent1 = healthbar1.AddComponent <HealthbarComponent>();

            healthbar1.VerticalAlignment   = EVerticalAlignment.Top;
            healthbar1.HorizontalAlignment = EHorizontalAlignment.Left;
            healthbar1.Margin = new Rectangle(15, 25, 0, 0);
            healthbarcomponent1.BindPlayer(player, EHorizontalAlignment.Left);

            UIEntity           healthbar2          = EntityFactory.CreateUI <UIEntity>("HealthbarPlayer2");
            HealthbarComponent healthbarcomponent2 = healthbar2.AddComponent <HealthbarComponent>();

            healthbar2.VerticalAlignment   = EVerticalAlignment.Top;
            healthbar2.HorizontalAlignment = EHorizontalAlignment.Right;
            healthbar2.Margin = new Rectangle(0, 25, 15, 0);
            healthbarcomponent2.BindPlayer(player2, EHorizontalAlignment.Right);

            UIEntity coins = EntityFactory.CreateUI <UIEntity>("CollectedCoins");
            CoinCollectionComponent coincollectioncomponent = coins.AddComponent <CoinCollectionComponent>();

            coins.VerticalAlignment   = EVerticalAlignment.Top;
            coins.HorizontalAlignment = EHorizontalAlignment.Center;
            coins.Margin = new Rectangle(0, 25, 0, 0);
            coincollectioncomponent.Bind(player, player2);

#if DEBUG
            ConsoleManager.Get().RegisterCommand("SpawnChestAtPosition", null, (Func <int, int, string>)Chest.SpawnChest);
            ConsoleManager.Get().RegisterCommand("SpawnChestAtCamera", null, (Func <int, string>)Chest.SpawnChest);
            ConsoleManager.Get().RegisterCommand("SpawnPickup", null, (Func <string, int, Pickup>)PickupFactory.Create);
#endif
        }
Ejemplo n.º 23
0
        public void BlankStateDatabase()
        {
            SampleVehicleRepository  seedVehicles  = new SampleVehicleRepository();
            SampleSpecialRepository  seedSpecials  = new SampleSpecialRepository();
            SamplePurchaseRepository seedPurchases = new SamplePurchaseRepository();
            SampleContactRepository  seedContact   = new SampleContactRepository();

            var mSeed = seedVehicles.GetMakes();
            var nSeed = seedVehicles.GetModels();
            var sSeed = seedSpecials.GetSpecials();
            var pSeed = seedPurchases.GetAllPurchases();
            var cSeed = seedContact.GetAll();

            List <Vehicle> vSeed = new List <Vehicle>();
            SeedManager    sMgr  = new SeedManager();

            for (int i = 0; i < 500; i++)
            {
                var v = sMgr.PlantACar(nSeed.Max(n => n.NameplateId));
                v.Model = nSeed.FirstOrDefault(n => n.NameplateId == v.NameplateId);
                vSeed.Add(v);
            }

            VehicleRepository  vRepo = new VehicleRepository();
            SpecialRepository  sRepo = new SpecialRepository();
            PurchaseRepository pRepo = new PurchaseRepository();
            ContactRepository  cRepo = new ContactRepository();

            foreach (var m in mSeed)
            {
                vRepo.AddMake(m);
            }
            foreach (var n in nSeed)
            {
                n.ManufacturerId = n.Manufacturer.ManufacturerId;
                vRepo.AddModel(n);
            }
            foreach (var v in vSeed)
            {
                if (v.ImageFileName == null || v.ImageFileName.Length < 4)
                {
                    switch (v.Model.BodyStyle)
                    {
                    case BodyStyle.Car:
                        v.ImageFileName = "Car.png";
                        break;

                    case BodyStyle.SUV:
                        v.ImageFileName = "SUV.png";
                        break;

                    case BodyStyle.Truck:
                        v.ImageFileName = "Truck.png";
                        break;

                    case BodyStyle.Van:
                        v.ImageFileName = "Van.png";
                        break;

                    default:
                        throw new Exception("A vehicle's model's body style data was corrupt.");
                    }
                }
                v.NameplateId = v.Model.NameplateId;
                vRepo.AddVehicle(v);
            }
            foreach (var s in sSeed)
            {
                sRepo.AddSpecial(s);
            }
            foreach (var p in pSeed)
            {
                pRepo.AddPurchase(p);
            }
            foreach (var c in cSeed)
            {
                cRepo.Add(c);
            }
        }
Ejemplo n.º 24
0
 public static SeedManager Init(int seed) => _instance ?? (_instance = new SeedManager(seed));
Ejemplo n.º 25
0
 private void Start()
 {
     _seedManager    = GetComponent <SeedManager>();
     _chickenManager = GetComponent <ChickenManager>();
     timer           = 0;
 }
Ejemplo n.º 26
0
        public void Configure(IApplicationBuilder app,
                              IHostingEnvironment env,
                              ILoggerFactory loggerFactory,
                              SeedManager seedManager,
                              MigrationManager migrationManager)
        {
            var stopwatch = Stopwatch.StartNew();

            try
            {
                loggerFactory.AddSerilog();
                Log.Logger().Information("Application is starting...");
                Log.Logger().Information("Configuration:");

                ConfigurationProvider.GetType().GetProperties().ToList().ForEach(prop =>
                {
                    Log.Logger().Information("[{name}] = '{value}'", prop.Name, prop.GetValue(ConfigurationProvider));
                });

                DateTimeContext.Initialize(ConfigurationProvider.TimeZone);

                Log.Logger().Information("Configure EF Mappings...");
                MappingConfig.RegisterMappings();

                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseDatabaseErrorPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error"); //todo IS incorrect page diesnt exist yet!!
                    app.UseHsts();
                    app.UseHttpsRedirection();
                }

                app.UseStaticFiles(new StaticFileOptions {
                    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot"))
                });
                app.UseSession();
                app.UseAuthentication();

                app.UseMvc(routes =>
                {
                    routes.MapRoute(name: "Area", template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                    routes.MapRoute(name: "Area2", template: "{area:exists}/{controller=Home}/{action=Index}/{isReadonly?}");

                    routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
                    routes.MapRoute(name: "default2", template: "{controller=Home}/{action=Index}/{isReadonly?}");
                });

                //migrationManager.EnsureCreated(ConfigurationProvider);
                //migrationManager.ApplyMigrations(ConfigurationProvider);
                seedManager.Seed(ConfigurationProvider);
            }
            catch (Exception e)
            {
                Log.Logger().Error(e, "Application failed to start");

                throw;
            }
            finally
            {
                stopwatch.Stop();
                Log.Logger().Information("Startup time: {Seconds}s", stopwatch.Elapsed.Seconds);
            }
        }
 // Use this for initialization
 void Start()
 {
     SM = GetComponent <SeedManager>();
 }
Ejemplo n.º 28
0
        /// <inheritdoc />
        protected override void Load(ContainerBuilder builder)
        {
            var iotaRepository = new RestIotaRepository(
                new FallbackIotaClient(new List <string> {
                "https://nodes.devnet.thetangle.org:443"
            }, 5000),
                new PoWService(new CpuPearlDiver()));

            var channelFactory      = new MamChannelFactory(CurlMamFactory.Default, CurlMerkleTreeFactory.Default, iotaRepository);
            var subscriptionFactory = new MamChannelSubscriptionFactory(iotaRepository, CurlMamParser.Default, CurlMask.Default);

            var encryption      = new RijndaelEncryption("somenicekey", "somenicesalt");
            var resourceTracker = new ResourceTracker(
                channelFactory,
                subscriptionFactory,
                encryption,
                $"{DependencyResolver.LocalStoragePath}\\resources.sqlite");

            var seedManager = new SeedManager(
                resourceTracker,
                new IssSigningHelper(new Curl(), new Curl(), new Curl()),
                new AddressGenerator(),
                iotaRepository,
                encryption,
                $"{DependencyResolver.LocalStoragePath}\\seedmanager.sqlite");

            var fhirRepository   = new IotaFhirRepository(iotaRepository, new FhirJsonTryteSerializer(), resourceTracker, seedManager);
            var fhirParser       = new FhirJsonParser();
            var searchRepository = new SearchRepository($"{DependencyResolver.LocalStoragePath}\\search.sqlite");

            var createInteractor     = new CreateResourceInteractor(fhirRepository, fhirParser, searchRepository);
            var readInteractor       = new ReadResourceInteractor(fhirRepository, searchRepository);
            var validationInteractor = new ValidateResourceInteractor(fhirRepository, fhirParser);
            var searchInteractor     = new SearchResourcesInteractor(fhirRepository, searchRepository);

            var resourceImporter = new ResourceImporter(searchRepository, fhirRepository, seedManager);

            builder.RegisterInstance(searchRepository).As <ISearchRepository>();
            builder.RegisterInstance(resourceTracker).As <IResourceTracker>();

            builder.RegisterInstance(createInteractor);
            builder.RegisterInstance(readInteractor);
            builder.RegisterInstance(validationInteractor);
            builder.RegisterInstance(searchInteractor);
            builder.RegisterInstance(resourceImporter);
            builder.RegisterInstance(seedManager).As <ISeedManager>();
            builder.RegisterInstance(subscriptionFactory);
            builder.RegisterInstance(fhirRepository).As <IFhirRepository>();
            builder.RegisterInstance(new AndroidLogout()).As <ILogout>();

            var backgroundWorker = new BackgroundWorkerService();

            var glucoseService = new FhirGlucoseService(
                new CreateResourceInteractor(fhirRepository, fhirParser, searchRepository),
                new UpdateResourceInteractor(fhirRepository, fhirParser),
                new ReadResourceInteractor(fhirRepository, searchRepository),
                searchRepository);
            var glucoseRepository = new DexcomGlucoseManagementRepository(new RestClient("https://sandbox-api.dexcom.com"));

            //backgoundWorker.RegisterTaskWorker(new ContinuousGlucoseTaskWorker(glucoseService, glucoseRepository));
            backgroundWorker.RegisterTaskWorker(new AggregateGlucoseTaskWorker(glucoseService, glucoseRepository));
        }
    // Wrapper function for level generation
    private void Process()
    {
        SeedManager.Refresh();

        // initialization of two lists which will be used in union–find data structure
        _parent = new List <int>(mapSize.x * mapSize.y);
        _weight = new List <int>(mapSize.x * mapSize.y);

        for (var i = 0; i < mapSize.x * mapSize.y; ++i)
        {
            _parent.Add(i);
            _weight.Add(1);
        }

        // arrangement of rooms
        foreach (var y in Enumerable.Range(0, mapSize.y))
        {
            foreach (var x in Enumerable.Range(0, mapSize.x))
            {
                var roomPosition =
                    new Vector2Int(x * (roomSize.x + roomMargin.x), y * (roomSize.y + roomMargin.y));
                AddRoom(roomPrefabs[Random.Range(0, roomPrefabs.Capacity)], roomPosition);
            }
        }

        // building a minimal connected graph
        while (_weight[ParentOf(0, 0)] != mapSize.x * mapSize.y)
        {
            int x = Random.Range(0, mapSize.x), y = Random.Range(0, mapSize.y);

            if (x > 0 && ParentOf(x, y) != ParentOf(x - 1, y))
            {
                ConnectRooms(new Vector2Int(x, y), new Vector2Int(x - 1, y));
            }

            if (y > 0 && ParentOf(x, y) != ParentOf(x, y - 1))
            {
                ConnectRooms(new Vector2Int(x, y), new Vector2Int(x, y - 1));
            }
        }

        // adding random connectors between rooms
        foreach (var y in Enumerable.Range(0, mapSize.y))
        {
            foreach (var x in Enumerable.Range(0, mapSize.x))
            {
                if (x > 0 && Random.Range(0, 5) == 0)
                {
                    ConnectRooms(new Vector2Int(x, y), new Vector2Int(x - 1, y));
                }

                if (y > 0 && Random.Range(0, 5) == 0)
                {
                    ConnectRooms(new Vector2Int(x, y), new Vector2Int(x, y - 1));
                }
            }
        }

        Instantiate(aStarPrefab, new Vector2(
                        mapSize.x * (roomSize.x + roomMargin.x) / 2,
                        mapSize.y * (roomSize.y + roomMargin.y) / 2),
                    Quaternion.identity);

        StartCoroutine(ScanWithDelay());
    }