コード例 #1
0
    // Start is called before the first frame update
    void Start()
    {
        rend       = GetComponent <Renderer>();
        startColor = rend.material.color;

        buildmanager = Singletons.Instance;
    }
コード例 #2
0
        private AI_DFS_Decision MakeDecision_Using_Hand(AI_DFS_Decision previousState)
        {
            AI_DFS_Decision bestDecisiion = previousState;

            for (int i = 0; i < previousState.GetBoard().GetPlayer(playerNr).GetValidHandOptions().Count; i++)
            {
                BoardState       newBoard       = previousState.GetBoard().Copy();
                PlayerBoardState newPlayerState = newBoard.GetPlayer(playerNr);
                List <ICard>     options        = newPlayerState.GetValidHandOptions();

                ICard actionCard = options[i];

                Singletons.GetPrinter().AI_PlayCard(newPlayerState.playerSetup, actionCard, newPlayerState.GetManaLeft(), actionCard.GetCost());
                newPlayerState.SpendMana(actionCard);

                actionCard.PlayCard();
                AI_DFS_Decision exhaustedDecision = MakeDecision(new AI_DFS_Decision(newBoard, GetBoardStateAsValue(newBoard)));

                if (bestDecisiion.GetValue() < exhaustedDecision.GetValue())
                {
                    bestDecisiion = exhaustedDecision;
                }
            }

            return(bestDecisiion);
            //BATTLECRY NOT IMPLEMENTED YET!
            //if (actionCard.BattlecryRequiresTarget())
            //{
            //    List<ICard> possibleTargets = actionCard.GetBattlecryTargets();
            //    actionCard.SetBattlecryTarget(possibleTargets[random.Next(0, possibleTargets.Count)]);
            //}
        }
コード例 #3
0
 public static void Main()
 {
     HybridLocks.Go();
     Singletons.Go();
     WriterGateDemo.Go();
     BlockingCollectionDemo.Go();
 }
コード例 #4
0
        public T Get <T>() where T : class
        {
            if (!IsInitilized)
            {
                Init();
            }

            Type instanceType = typeof(T);

            if (Singletons.ContainsKey(instanceType))
            {
                return((T)Singletons[instanceType]);
            }

            if (Factories.ContainsKey(instanceType))
            {
                return((T)Factories[instanceType].Invoke());
            }

            if (AsyncFactories.ContainsKey(instanceType))
            {
                return((T)AsyncFactories[instanceType].Invoke().Result);
            }
            return(null);
        }
コード例 #5
0
    // Use this for initialization
    protected override void Setup()
    {
        triggerDown += () =>
        {
            if (behindPlayer())
            {
                currHeldObject = Instantiate(Singletons.GunHand().getCurrGun().MagazinePrefab).GetComponent <HoldableObject>();
                currHeldObject.transform.SetParent(transform);
                currHeldObject.transform.localPosition    = new Vector3();
                currHeldObject.transform.localEulerAngles = Vector3.zero;
                currHeldObject.PickupObject();
            }
            else if (currHeldObject == null && hoveredObjects.Count > 0)
            {
                hoveredObjects[0].PickupObject();
                currHeldObject = hoveredObjects[0];
                hoveredObjects.RemoveAt(0);
            }
        };

        triggerUp += () =>
        {
            if (currHeldObject != null)
            {
                currHeldObject.DropObject();
                if (currHeldObject.GetComponent <Rigidbody>())
                {
                    currHeldObject.GetComponent <Rigidbody>().AddForce(currForceVector);
                }
                currHeldObject = null;
            }
        };
    }
コード例 #6
0
    private IEnumerator ExecuteSloMo()
    {
        float startTime = Time.realtimeSinceStartup;

        while (startTime + affectDuration >= Time.realtimeSinceStartup)
        {
            float percentDone = ((Time.realtimeSinceStartup - startTime) / affectDuration);

            if (percentDone < .75f)
            {
                Time.timeScale = 0.3f;
            }
            else
            {
                Time.timeScale = ((Time.realtimeSinceStartup - startTime) / affectDuration);
            }

            Color c = playerViewColor;
            c.a = 1 - Time.timeScale;
            Singletons.PlayerAffectsVisualizer().playerAffectsOverlay.material.color = c;

            yield return(null);
        }
        Time.timeScale = 1f;
        Destroy(gameObject);
    }
コード例 #7
0
        public static void AddMyEventStoreServices(this IServiceCollection services, IConfiguration config)
        {
            config.ConfigureByOption("eventStore:type", new Options
            {
                ["MongoDb"] = () =>
                {
                    var mongoConfiguration = config.GetRequiredValue("eventStore:mongoDb:configuration");
                    var mongoDatabaseName  = config.GetRequiredValue("eventStore:mongoDb:database");

                    services.AddSingletonAs(c =>
                    {
                        var mongoClient  = Singletons <IMongoClient> .GetOrAdd(mongoConfiguration, s => new MongoClient(s));
                        var mongDatabase = mongoClient.GetDatabase(mongoDatabaseName);

                        return(new MongoEventStore(mongDatabase, c.GetRequiredService <IEventNotifier>()));
                    })
                    .As <IExternalSystem>()
                    .As <IEventStore>();
                },
                ["GetEventStore"] = () =>
                {
                    var eventStoreConfiguration  = config.GetRequiredValue("eventStore:getEventStore:configuration");
                    var eventStoreProjectionHost = config.GetRequiredValue("eventStore:getEventStore:projectionHost");
                    var eventStorePrefix         = config.GetValue <string>("eventStore:getEventStore:prefix");

                    var connection = EventStoreConnection.Create(eventStoreConfiguration);

                    services.AddSingletonAs(c => new GetEventStore(connection, eventStorePrefix, eventStoreProjectionHost))
                    .As <IExternalSystem>()
                    .As <IEventStore>();
                }
            });
        }
コード例 #8
0
    void Update()
    {
        if (Mathf.Approximately(accelerate.value, 0f))
        {
            Brake();
        }
        else
        {
            Acellerate(accelerate.value);
        }

        if (Mathf.Approximately(turn.value, 0))
        {
            Turn(0);
        }
        else
        {
            Turn(turn.value);
        }

        if (heath <= 0)
        {
            Singletons.GetGameManager().LoadScene("tier_1");
        }
    }
コード例 #9
0
ファイル: Server.cs プロジェクト: blockspacer/iCarus
 void Run()
 {
     Singletons.Add <PlayerManager>().Initialize();
     Singletons.Add <SyncManager>().Initialize();
     StartNetwork();
     TSLog.Info("Server Started!");
 }
コード例 #10
0
        /// <summary>
        /// Sets the logger based on the requested logger type.
        /// </summary>
        /// <param name="loggerType">The requested logger type</param>
        public override void SetLoggerByType(LoggerType loggerType)
        {
            //This example shows three different ways to access your singletons
            switch (loggerType)
            {
            case LoggerType.Log:
                //A simple Singletons.Get<TYPE>() works just great!
                SetLogger(Singletons.Get <MessageLogger>());
                break;

            case LoggerType.Warn:
                //If you have the type, but don't know it at compile time, you can pass the type as a paramater
                Type type = typeof(WarnLogger);
                SetLogger((ExampleLogger)Singletons.Get(type));
                break;

            case LoggerType.Error:
                //If you want to make an instanced reference, you can derive from Singleton<T>.
                //An example logger won't fit with the current design, so here's a basic example:
                //      public class ExampleSingleton : Singleton<ExampleSingleton> { }
                //      Allows a reference via ExampleSingleton.Instance
                SetLogger(InstancedErrorLogger.Instance);
                break;
            }

            //Logger type is not the custom logger, so ensure the logger window is empty
            Singletons.Get <ExampleCustomLogger>().EmptyLoggerWindow();
        }
コード例 #11
0
ファイル: IdentityServices.cs プロジェクト: ifle/squidex
        public static IServiceCollection AddMyDataProtectection(this IServiceCollection services, IConfiguration config)
        {
            var dataProtection = services.AddDataProtection().SetApplicationName("Squidex");

            config.ConfigureByOption("identity:keysStore:type", new Options
            {
                ["Redis"] = () =>
                {
                    var redisConfiguration = config.GetRequiredValue("identity:keysStore:redis:configuration");

                    var connectionMultiplexer = Singletons <ConnectionMultiplexer> .GetOrAdd(redisConfiguration, s => ConnectionMultiplexer.Connect(s));

                    dataProtection.PersistKeysToRedis(connectionMultiplexer);
                },
                ["Folder"] = () =>
                {
                    var folderPath = config.GetRequiredValue("identity:keysStore:folder:path");

                    dataProtection.PersistKeysToFileSystem(new DirectoryInfo(folderPath));
                },
                ["InMemory"] = () => { }
            });

            return(services);
        }
コード例 #12
0
        protected new static TSingleton GetSingleton([NotNull] TKey key)
        {
            TSingleton singleton = Singletons.GetOrAdd(key, k => Constructor(k));

            Debug.Assert(singleton != null);

            // Use optimistic locking to see if we're initialised
            // Most of the time we will be initialised so we won't get a lock.
            if (!singleton.IsInitialised)
            {
                lock (singleton._initialisationLock)
                {
                    // Once we have a lock, we need to re-check, incase a different thread
                    // won the race to initialise.
                    if (!singleton.IsInitialised)
                    {
                        // We're the first thread with a lock so initialise.
                        singleton.Initialise();
                    }

                    // We are now initialised (so long as an exception isn't thrown).
                    singleton.IsInitialised = true;
                }
            }
            return(singleton);
        }
コード例 #13
0
ファイル: Hero.cs プロジェクト: AAstrup/Bachelor
 public void CheckForDeath()
 {
     if (hp <= 0)
     {
         Singletons.GetPrinter().GameOver();
     }
 }
コード例 #14
0
    /// <summary>
    /// Função que o veículo segue o alvo.
    /// </summary>
    void Chasing()
    {
        Vector3 targetPosition = Singletons.GetPlayer().transform.position;
        Vector3 actualPosition = m_transform.position;

        //Checando a direção do alvo.
        Vector3 targetDirection = (targetPosition - actualPosition).normalized;

        //Checando se o alvo está à frente. Se estiver a frente, irá seguir reto.
        if (Vector3.Dot(m_transform.forward, targetDirection) < 0.9)
        {
            //Checando se o alvo está mais a direita ou esquerda.
            if (Vector3.Dot(m_transform.right, targetDirection) > 0)
            {
                Turn(1f);
            }
            else
            {
                Turn(-1f);
            }
        }
        else
        {
            Turn(0f);
        }

        //Acelera o veículo.
        Acellerate(1f);
    }
コード例 #15
0
        /// <summary>
        /// Logs a message using the selected logger
        /// </summary>
        /// <param name="message">The message to be output</param>
        public override void LogMessage(string message)
        {
            //Use the custom logger, or use a predefined logger.
            if (UseCustomLogger)
            {
                Singletons.Get <ExampleCustomLogger>().LogMessage(message);
            }
            else
            {
                //This example shows three different ways to access your singletons
                switch (SelectedLogger)
                {
                case LoggerType.Log:
                    //A simple Singletons.Get<TYPE>() works just great!
                    Singletons.Get <MessageLogger>().LogMessage(message);
                    break;

                case LoggerType.Warn:
                    //If you have the type, but don't know it at compile time, you can pass the type as a paramater
                    Type loggerType = typeof(WarnLogger);
                    ((ExampleLogger)Singletons.Get(loggerType)).LogMessage(message);
                    break;

                case LoggerType.Error:
                    //If you want to make an instanced reference, you can derive from Singleton<T>.
                    //An example of this type won't fit with the logger's design, so here's a basic example:
                    //      public class ExampleSingleton : Singleton<ExampleSingleton> { }
                    //      Allows a reference via ExampleSingleton.Instance
                    InstancedErrorLogger.Instance.LogMessage(message);
                    break;
                }
            }
        }
コード例 #16
0
        public async Task DeleteTokenAsync()
        {
            // we cannot delete a code which has not yet been created
            if (_id == null)
            {
                return;
            }

            if (_redisClient == null)
            {
                _redisClient = await Singletons.GetRedisClientAsync();
            }

            int RESULT_KEY_CONFLICT = -1;

            // generate Lua script (which we will use to commit all changes--or the new record--in an atomic transaction)
            StringBuilder luaBuilder = new StringBuilder();
            List <string> arguments  = new List <string>();

            //int iArgument = 1;
            // if the code has already been deleted, return success
            luaBuilder.Append(
                "if redis.call(\"EXISTS\", KEYS[1]) == 0 then\n" +
                "  return 1\n" +
                "end\n");
            //
            luaBuilder.Append(
                "redis.call(\"DEL\", KEYS[1])\n");
            //
            luaBuilder.Append("return 1\n");

            long          luaResult = 0;
            List <string> keys      = new List <string>();

            keys.Add(REDIS_PREFIX_OAUTH2CODE + REDIS_PREFIX_SEPARATOR + _id);
            luaResult = await _redisClient.EvalAsync <string, string, long>(luaBuilder.ToString(), keys.ToArray(), arguments.ToArray()).ConfigureAwait(false);

            // NOTE: the result will contain a negative integer (error) or positive one (success)
            if (luaResult == 1)
            {
                // reset our server-assigned values
                _id = null;
            }
            else if (luaResult == RESULT_KEY_CONFLICT)
            {
                // key name conflict; abort
                return;
            }
            else
            {
                // unknown error
                throw new Exception("Critical Redis error!");
            }

            if (luaResult < 0)
            {
                throw new Exception("Critical Redis error!");
            }
        }
コード例 #17
0
        /// <summary>
        /// Sets the logger based on the requested logger type.
        /// </summary>
        /// <param name="loggerType">The requested logger type</param>
        public override void SetLoggerByType(LoggerType loggerType)
        {
            SelectedLogger  = loggerType;
            UseCustomLogger = false;

            //Logger type is not the custom logger, so ensure the logger window is empty
            Singletons.Get <ExampleCustomLogger>().EmptyLoggerWindow();
        }
コード例 #18
0
 public T Single <T>()
 {
     if (Singletons.ContainsKey(typeof(T)))
     {
         return((T)Singletons[typeof(T)]);
     }
     return(default(T));
 }
 public static void Main()
 {
     HybridLocks.Go();
     Singletons.Go();
     AsyncSynchronization.Go();
     BlockingCollectionDemo.Go();
     Console.ReadLine();
 }
コード例 #20
0
    private void Awake()
    {
        Instance = this;

        //Start the Game Theme
        AudioScript.GameThemeAS.clip = AudioScript.GameThemeAC;
        AudioScript.GameThemeAS.Play();
    }
コード例 #21
0
        static void Main(string[] args)
        {
            SimulationResults results = RunSimulation(SetupData.GetTestJakob());

            //Print results
            Singletons.GetPrinter().AddEmptySpaces(2);
            PrintResults(results);
        }
コード例 #22
0
        // 处理外部调用
        private static async Task <string> _process_method_call(string _module_name, string _method_name, string _content)
        {
            string _resp = "";

            // 确认是否能直接调用
            foreach (var(_key, _obj) in Singletons.CallerMap)
            {
                if (!_key.Item1.StartsWith(_module_name))
                {
                    continue;
                }

                // 获取参数内容
                var _method = _key.Item2.GetMethod(_method_name);
                if (_method == null)
                {
                    throw new MissingMethodException($"未在模块 {_module_name} 中找到");
                }
                var       _param_infos = _method.GetParameters();
                object [] _params      = new object [_param_infos?.Length ?? 0];
                if (_content?.Length > 0 && _params.Length > 0)
                {
                    JObject _param_obj = JObject.Parse(_content);
                    for (int i = 0; i < _params.Length; ++i)
                    {
                        _params [i] = _param_obj [_param_infos [i].Name].ToObject(_param_infos [i].ParameterType);
                    }
                }

                // 调用
                try {
                    var _ret = _method.Invoke(_obj, _params);
                    if (_method.ReturnType == typeof(Task))
                    {
                        await(Task) _ret;
                        _resp = JsonConvert.SerializeObject(new { result = "success" });
                    }
                    else
                    {
                        await(Task) _ret;
                        _ret  = _ret.GetType().InvokeMember("Result", BindingFlags.GetProperty, null, _ret, Array.Empty <object> ());
                        _resp = JsonConvert.SerializeObject(new { result = "success", content = _ret });
                    }
                } catch (Exception ex) {
                    _resp = JsonConvert.SerializeObject(new { result = "failure", reason = ex.Message });
                }
                return(_resp);
            }

            // 转发调用
            try {
                return(await Singletons.InvokeRemoteService(_module_name, _method_name, _content));
            } catch (Exception ex) {
                _resp = JsonConvert.SerializeObject(new { result = "failure", reason = ex.Message });
            }
            return(_resp);
        }
コード例 #23
0
        public static void AddMyAssetServices(this IServiceCollection services, IConfiguration config)
        {
            config.ConfigureByOption("assetStore:type", new Alternatives
            {
                ["Default"] = () =>
                {
                    services.AddSingletonAs <NoopAssetStore>()
                    .AsOptional <IAssetStore>();
                },
                ["Folder"] = () =>
                {
                    var path = config.GetRequiredValue("assetStore:folder:path");

                    services.AddSingletonAs(c => new FolderAssetStore(path, c.GetRequiredService <ISemanticLog>()))
                    .As <IAssetStore>();
                },
                ["GoogleCloud"] = () =>
                {
                    var bucketName = config.GetRequiredValue("assetStore:googleCloud:bucket");

                    services.AddSingletonAs(c => new GoogleCloudAssetStore(bucketName))
                    .As <IAssetStore>();
                },
                ["AzureBlob"] = () =>
                {
                    var connectionString = config.GetRequiredValue("assetStore:azureBlob:connectionString");
                    var containerName    = config.GetRequiredValue("assetStore:azureBlob:containerName");

                    services.AddSingletonAs(c => new AzureBlobAssetStore(connectionString, containerName))
                    .As <IAssetStore>();
                },
                ["MongoDb"] = () =>
                {
                    var mongoConfiguration    = config.GetRequiredValue("assetStore:mongoDb:configuration");
                    var mongoDatabaseName     = config.GetRequiredValue("assetStore:mongoDb:database");
                    var mongoGridFsBucketName = config.GetRequiredValue("assetStore:mongoDb:bucket");

                    services.AddSingletonAs(c =>
                    {
                        var mongoClient   = Singletons <IMongoClient> .GetOrAdd(mongoConfiguration, s => new MongoClient(s));
                        var mongoDatabase = mongoClient.GetDatabase(mongoDatabaseName);

                        var gridFsbucket = new GridFSBucket <string>(mongoDatabase, new GridFSBucketOptions
                        {
                            BucketName = mongoGridFsBucketName
                        });

                        return(new MongoGridFsAssetStore(gridFsbucket));
                    })
                    .As <IAssetStore>();
                }
            });

            services.AddSingletonAs <ImageSharpAssetThumbnailGenerator>()
            .As <IAssetThumbnailGenerator>();
        }
コード例 #24
0
ファイル: MainGame.cs プロジェクト: Straskal/MonoReaper
        protected override void Draw(GameTime gameTime)
        {
            _renderer.BeginDraw();
            CurrentLayout.Draw(_renderer, _isDebugging);
            Singletons.Draw(_renderer, _isDebugging);
            Singletons.DrawGUI(_renderer);
            _renderer.EndDraw();

            base.Draw(gameTime);
        }
コード例 #25
0
        public static object GetSingleton(string name)
        {
            var candidates = Singletons.Where(x => x.GetType().Name.Contains(name));

            if (candidates.Count() == 1)
            {
                return(candidates.FirstOrDefault());
            }

            return(null);
        }
コード例 #26
0
ファイル: IoC.cs プロジェクト: JunaidAK/MvvmCore
 private static void SetSingleton(Type service)
 {
     try
     {
         if (Get(service) == null)
         {
             Singletons.Add(service, Activator.CreateInstance(service));
         }
     }
     catch { }
 }
コード例 #27
0
ファイル: IoC.cs プロジェクト: JunaidAK/MvvmCore
 private static void SetSingleton <Service>()
 {
     try
     {
         if (Get <Service>() == null)
         {
             Singletons.Add(typeof(Service), Activator.CreateInstance(typeof(Service)));
         }
     }
     catch { }
 }
コード例 #28
0
        public static void AddMyEventStoreServices(this IServiceCollection services, IConfiguration config)
        {
            config.ConfigureByOption("eventStore:type", new Options
            {
                ["MongoDb"] = () =>
                {
                    var mongoConfiguration = config.GetRequiredValue("eventStore:mongoDb:configuration");
                    var mongoDatabaseName  = config.GetRequiredValue("eventStore:mongoDb:database");

                    services.AddSingletonAs(c =>
                    {
                        var mongoClient  = Singletons <IMongoClient> .GetOrAdd(mongoConfiguration, s => new MongoClient(s));
                        var mongDatabase = mongoClient.GetDatabase(mongoDatabaseName);

                        return(new MongoEventStore(mongDatabase, c.GetRequiredService <IEventNotifier>()));
                    })
                    .As <IInitializable>()
                    .As <IEventStore>();
                },
                ["GetEventStore"] = () =>
                {
                    var eventStoreConfiguration  = config.GetRequiredValue("eventStore:getEventStore:configuration");
                    var eventStoreProjectionHost = config.GetRequiredValue("eventStore:getEventStore:projectionHost");
                    var eventStorePrefix         = config.GetValue <string>("eventStore:getEventStore:prefix");

                    var connection = EventStoreConnection.Create(eventStoreConfiguration);

                    services.AddSingletonAs(connection)
                    .As <IEventStoreConnection>();

                    services.AddSingletonAs(c => new GetEventStore(connection, c.GetRequiredService <IJsonSerializer>(), eventStorePrefix, eventStoreProjectionHost))
                    .As <IEventStore>();

                    services.AddHealthChecks()
                    .AddCheck <GetEventStoreHealthCheck>("EventStore", tags: new[] { "node" });
                }
            });

            services.AddSingletonAs <OrleansEventNotifier>()
            .As <IEventNotifier>();

            services.AddSingletonAs <DefaultStreamNameResolver>()
            .As <IStreamNameResolver>();

            services.AddSingletonAs <DefaultEventDataFormatter>()
            .As <IEventDataFormatter>();

            services.AddSingletonAs(c =>
            {
                var allEventConsumers = c.GetServices <IEventConsumer>();

                return(new EventConsumerFactory(n => allEventConsumers.FirstOrDefault(x => x.Name == n)));
            });
        }
コード例 #29
0
 // Use this for initialization
 void Start()
 {
     if (instance != null)
     {
         GameObject.Destroy(gameObject);
     }
     else
     {
         GameObject.DontDestroyOnLoad(gameObject);
         instance = this;
     }
 }
コード例 #30
0
 private void Awake()
 {
     if (!Instance)
     {
         Instance = this;
         DontDestroyOnLoad(gameObject);
     }
     else
     {
         Destroy(gameObject);
     }
 }