Example #1
0
 void SpawnObject(RandomObject obj)
 {
     if (obj.spawnAmount < 0)
     {
         GameObject newObj = Instantiate(obj.prefab, transform);
         RotateObject(newObj, obj.rotateRandomly, obj.straightAnglesOnly);
         PlaceObject(newObj);
     }
     else if (obj.spawnAmount > 0)
     {
         obj.spawnAmount--;
         GameObject newObj = Instantiate(obj.prefab, transform);
         RotateObject(newObj, obj.rotateRandomly, obj.straightAnglesOnly);
         PlaceObject(newObj, true, true);
     }
     else
     {
         if (SpawnedObjectCount() < spawnObjectsMin)
         {
             spawnCounter++;
         }
         ;
         // Debug.Log ("Did not spawn, already reached max spawnAmount: " + obj);
     }
 }
        private void Reset()
        {
            int totalEnabled = 0;

            for (int i = 0; i < randomObjects.Count(); i++)
            {
                randomObjects.ElementAt(i).Count = 0;
                if (randomObjects.ElementAt(i).IsEnable)
                {
                    totalEnabled++;
                }
            }
            RandomObject.SetTotalEnabled(totalEnabled);
            RandomObject.Reset();

            if (File.Exists(OutFileName))
            {
                try
                {
                    File.Delete(OutFileName);
                }
                catch
                {
                }
            }
        }
Example #3
0
        /// <summary>
        /// Finds the software asynchronous.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="deepness">if set to <c>true</c> [with children].</param>
        /// <returns></returns>
        public override async Task <int> GetObjectStringCount(RandomObject rObj)
        {
            var obj = await new ServiceClient <ITestService>()
                      .ExecuteAsync(d => d.GetObjectStringCount(rObj));

            return(obj);
        }
Example #4
0
        public async void Put_valid_request_returns_response_not_cached_should_add_to_cache()
        {
            // arrange
            var responseObj = _fixture.Create <RandomObject>();
            var requestObj  = _fixture.Create <RandomObject>();

            _cachedObject = null;

            _httpCachingService.Setup(x => x.CheckCache(_baseAddress, _uri, _headers, CheckCache))
            .Returns(Task.FromResult((RandomObject)null));


            _httpService.Setup(
                x =>
                x.CallHttpMethod <RandomObject, RandomObject>(_baseAddress, _uri, requestObj, _headers, HttpMethods.PUT))
            .Returns(Task.FromResult(responseObj));

            // act
            var response = await _sut.Put(_baseAddress, _uri, requestObj, _headers, CheckCache);

            // assert
            _httpCachingService.Verify(
                x =>
                x.AddToCache(It.IsAny <RandomObject>(), _baseAddress,
                             _uri, _headers, null), Times.Once);
        }
Example #5
0
 public IActionResult InsertLesson(string id, string name, string year, string audioURLOnline, string audioURLDowload,
                                   string imageURL, string transcript, string actor, string summary, string vocabulary, string createdDate)
 {
     try
     {
         var lesson = dataContext.Lessons.FirstOrDefault();
         if (lesson != null)
         {
             lesson.ID             = RandomObject.RandomString(20);
             lesson.Name           = name;
             lesson.IDTP           = TempData["topicID"].ToString();
             lesson.Year           = Int32.Parse(year);
             lesson.FileURLOnline  = audioURLOnline;
             lesson.FileURLDowload = audioURLDowload;
             lesson.ImageURL       = imageURL;
             lesson.Transcript     = transcript;
             lesson.Actor          = actor;
             lesson.Sumary         = summary;
             lesson.Vocabulary     = vocabulary;
             lesson.CreatedDate    = (DateTime.Now).ToString();
             lesson.UpdatedDate    = null;
         }
         dataContext.Lessons.Add(lesson);
         dataContext.SaveChangesAsync();
         return(RedirectToAction("HomePage"));
     }
     catch (Exception ex)
     { }
     return(RedirectToAction("ToCreateLessonPage"));
 }
Example #6
0
 void SpawnObjectRandom(RandomObject obj)    // Used for after-the-fact spawning, to add more randomness to their placement
 {
     if (obj.spawnAmount < 0)
     {
         GameObject newObj = Instantiate(obj.prefab, transform);
         RotateObject(newObj, obj.rotateRandomly, obj.straightAnglesOnly);
         ReplaceRandomInfiniteObjectWithForceSpawnedObject(newObj);
     }
     else if (obj.spawnAmount > 0)
     {
         obj.spawnAmount--;
         GameObject newObj = Instantiate(obj.prefab, transform);
         RotateObject(newObj, obj.rotateRandomly, obj.straightAnglesOnly);
         ReplaceRandomInfiniteObjectWithForceSpawnedObject(newObj);
     }
     else
     {
         if (SpawnedObjectCount() < spawnObjectsMin)
         {
             spawnCounter++;
         }
         ;
     };
     Debug.Log("Did not spawn, already reached max spawnAmount: " + obj);
 }
Example #7
0
        static MapInitSystem()
        {
            PlayerPrototypes = Resources.LoadAll <PlayerObject>("SO/Players")
                               .ToDictionary(po => Regex.Match(po.name,
                                                               "^([A-Z][a-z]+)") // Первая часть до следующей большой буквы
                                             .Value.ToLower());

            Skins = Resources.LoadAll <SkinInfo>("SO/Skins")
                    .ToDictionary(po => Regex.Match(po.name,
                                                    "^([A-Z][a-z]+)") // Первая часть до следующей большой буквы
                                  .Value);

            if (PlayerPrototypes.Any(p => p.Value == null))
            {
                throw new Exception($"В {nameof(MapInitSystem)} playerPrototype был null.");
            }

            if (Skins.Any(p => p.Value == null))
            {
                throw new Exception($"В {nameof(MapInitSystem)} skin был null.");
            }

            FlameCircle = Resources.Load <FlameCircleObject>("SO/BaseObjects/FlameCircle");
            if (FlameCircle == null)
            {
                throw new Exception($"В {nameof(MapInitSystem)} flameCircle был null.");
            }
            mapIntRadius = Mathf.CeilToInt(((CircleColliderInfo)FlameCircle.colliderInfo).radius);

            RandomAsteroid = Resources.Load <RandomObject>("SO/BaseObjects/RandomAsteroid");
            if (RandomAsteroid == null)
            {
                throw new Exception($"В {nameof(MapInitSystem)} asteroid был null.");
            }

            SpaceStation = Resources.Load <BaseWithHealthObject>("SO/BaseObjects/SpaceStation");
            if (SpaceStation == null)
            {
                throw new Exception($"В {nameof(MapInitSystem)} spaceStation был null.");
            }

            RandomBonus = Resources.Load <RandomObject>("SO/Bonuses/PickableObjects/RandomSmallBonus");
            if (RandomBonus == null)
            {
                throw new Exception($"В {nameof(MapInitSystem)} bonus был null.");
            }

            UpgradeBonus = Resources.Load <UpgradeBonusObject>("SO/Bonuses/PickableObjects/SmallUpgradeBonus");
            if (UpgradeBonus == null)
            {
                throw new Exception($"В {nameof(MapInitSystem)} upgrade bonus был null.");
            }

            Boss = Resources.Load <FighterObject>("SO/BaseObjects/ScarabBoss");
            if (Boss == null)
            {
                throw new Exception($"В {nameof(MapInitSystem)} boss был null.");
            }
        }
        /// <summary>
        /// Inserts data with EntityFramework
        /// </summary>
        /// <param name="seed">Randomnumber generators seed</param>
        public static void InsertData(int seedID, int rows)
        {
            try
            {
                var sw = new Stopwatch();

                Console.WriteLine("--Inserting data!");

                sw.Start();

                var i      = 0;
                var result = false;
                var seed   = 0;

                using (var db = new ThesisEntities())
                {
                    seed = (from sd in db.Seed
                            where sd.SeedID == seedID
                            select sd.SeedValue).FirstOrDefault();

                    Console.WriteLine("--Seed is : " + seed);

                    var gen = new Random(seed);

                    while (i < rows)
                    {
                        var row = new RandomObject()
                        {
                            RandomObjectID       = i,
                            RandomString         = RandomStringGenerator.RandomString(gen, 15),
                            RandomDateTimeOffset = RandomDateTimeOffsetGenerator.RandomDateTimeOffset(gen),
                            RandomInt            = gen.Next(),
                            SeedId = seedID
                        };

                        db.RandomObject.Add(row);

                        i++;
                    }

                    db.SaveChanges();

                    result = true;

                    sw.Stop();
                }

                Console.WriteLine("--Result was: " + result);
                Console.WriteLine("--Time Elapsed: " + sw.Elapsed + "\n");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occured: " + ex);
                Console.WriteLine("Press any key to continue.");
                Console.ReadKey();
            }
        }
 public void PreferredPercentageChanged(RandomObject ro, Microsoft.AspNetCore.Components.ChangeEventArgs eventArgs)
 {
     totalPercentage        = 0;
     ro.PreferredPercentage = Int32.Parse((string)eventArgs.Value);
     for (int i = 0; i < randomObjects.Count(); i++)
     {
         totalPercentage += randomObjects.ElementAt(i).PreferredPercentage;
     }
 }
    public void SelectObject(RandomObject highlightObject)
    {
        if (this.highlightObject != null)
        {
            this.highlightObject.StopHighlight();
        }

        this.highlightObject = highlightObject;
        this.highlightObject.StartHighlight();
    }
 /// <summary>
 /// Unwrap the data from inside the result and random fields
 /// </summary>
 /// <returns>The JSON object with the data</returns>
 private JArray UnwrapJSONResponse()
 {
     if (!mJSONResponse.GetValue("result").HasValues)
     {
         throw new RandomJSONRPCException("Code: 9999" + ". Message: Request is valid but Response result payload is null");
     }
     // allows later interrogation for signed methods
     ResultObject = (JObject)mJSONResponse.GetValue(RESULT);
     RandomObject = (JObject)ResultObject.GetValue(RANDOM);
     return((JArray)RandomObject.GetValue("data"));
 }
Example #12
0
        public virtual async Task <List <RandomObject> > GetListOfRandomObjects()
        {
            List <RandomObject> randomList = new List <RandomObject>();

            for (int i = 0; i < 1000; i++)
            {
                RandomObject randomObj = new RandomObject()
                {
                    Id = i, RandomObjectInstance = "Instance -" + i
                };
                randomList.Add(randomObj);
            }
            return(randomList);
        }
        public void StartGenerating()
        {
            if (!AtLeastOneEnabled || TotalPercentage != 100)
            {
                return;
            }

            Reset();

            Task.Run(async() =>
            {
                Generate             = true;
                long currentFileSize = 0;
                try
                {
                    using (StreamWriter outFile = File.AppendText(OutFileName))
                    {
                        bool first = true;
                        while (Generate && currentFileSize < FileSizeInKB * 1024)
                        {
                            int rindex      = new Random().Next(RandomObjectCount);
                            RandomObject ro = randomObjects.ElementAt(rindex);
                            if (!ro.IsEnable)
                            {
                                continue;
                            }
                            await InvokeAsync(() =>
                            {
                                if (ro.GenerateNext())
                                {
                                    outFile.Write((first ? "" : ",") + ro.LastGeneratedObject);
                                    currentFileSize += 4;
                                    StateHasChanged();
                                    currentFileSize = new FileInfo(OutFileName).Length;
                                    first           = false;
                                }
                            });

                            //Thread.Sleep(100);
                        }
                    }
                }
                catch
                {
                }

                Generate = false;
            });
        }
        public void CheckBoxClicked(RandomObject ro)
        {
            ro.IsEnable = !ro.IsEnable;
            if (!ro.IsEnable)
            {
                ro.PreferredPercentage = 0;
            }

            AtLeastOneEnabled = false;
            for (int i = 0; i < RandomObjectCount; i++)
            {
                AtLeastOneEnabled = AtLeastOneEnabled || randomObjects.ElementAt(i).IsEnable;
            }
            //StateHasChanged();
            ReCalculatePercentage();
        }
Example #15
0
    public RandomSequence(JSONNode node)
    {
        _randomObjects = new List<RandomObject>();
        int size = node.AsArray.Count;

        for (int i = 0; i < size; i++)
        {
            var ro = new RandomObject
            {
                Index = node[i]["index"].AsInt,
                Probability = node[i]["probability"].AsFloat
            };

            _randomObjects.Add(ro);
        }
    }
 private void ReCalculatePercentage()
 {
     if (RandomObject.GetTotalEnabled() != 0)
     {
         int  averageDistribution = 100 / RandomObject.GetTotalEnabled();
         bool first    = true;
         int  leftOver = 100 - averageDistribution * RandomObject.GetTotalEnabled();
         for (int i = 0; i < randomObjects.Count(); i++)
         {
             if (randomObjects.ElementAt(i).IsEnable)
             {
                 randomObjects.ElementAt(i).PreferredPercentage = averageDistribution + (first?leftOver:0);
                 first = false;
             }
         }
     }
     totalPercentage = 100;
 }
Example #17
0
        public virtual async Task <RandomObject> FindRandomStringObjectAsync(int id)
        {
            List <RandomObject> random = new List <RandomObject>();

            for (int i = 0; i < 1000; i++)
            {
                RandomObject randomObj = new RandomObject()
                {
                    Id = i, RandomObjectInstance = "Instance -" + i
                };
                await randomObj.GetObjectStringCount();

                random.Add(randomObj);
            }

            var result = random.Where(x => x.Id == id).ToList().FirstOrDefault();

            return(result);
        }
Example #18
0
        public async void Put_valid_request_cached_should_return_cache_not_hit_CallHttpMethod()
        {
            // arrange
            var responseObj = _fixture.Create <RandomObject>();
            var requestObj  = _fixture.Create <RandomObject>();

            _cachedObject = responseObj;

            _httpCachingService.Setup(
                x =>
                x.CheckCache(_baseAddress, _uri, _headers, It.IsAny <Func <string, Task <RandomObject> > >()))
            .Returns(Task.FromResult(_cachedObject));

            // act
            var response = await _sut.Put(_baseAddress, _uri, requestObj, _headers, CheckCache);

            // assert
            _httpService.Verify(x => x.CallHttpMethod <RandomObject, RandomObject>(_baseAddress, _uri, requestObj, _headers, HttpMethods.PUT), Times.Never);
            response.BackInTime.Should().Be(_cachedObject.BackInTime);
        }
Example #19
0
        public async void Put_valid_request_returns_response_not_cached()
        {
            // arrange
            var responseObj = _fixture.Create <RandomObject>();
            var requestObj  = _fixture.Create <RandomObject>();

            _httpCachingService.Setup(x => x.CheckCache <RandomObject>(_baseAddress, _uri, _headers, null))
            .Returns(Task.FromResult((RandomObject)null));

            _httpService.Setup(
                x =>
                x.CallHttpMethod <RandomObject, RandomObject>(_baseAddress, _uri, requestObj, _headers, HttpMethods.PUT))
            .Returns(Task.FromResult(responseObj));

            // act
            RandomObject response = await _sut.Put <RandomObject, RandomObject>(_baseAddress, _uri, requestObj, _headers);

            // assert
            response.PointlessProperty.Should().Be(responseObj.PointlessProperty);
            response.BackInTime.Should().Be(responseObj.BackInTime);
        }
Example #20
0
    protected override bool ChooseSkill()
    {
        List <AbilityBase> availableSkills = new List <AbilityBase>();

        foreach (AbilityBase skill in m_abilities)
        {
            if (skill.IsValid())
            {
                availableSkills.Add(skill);
            }
        }

        if (availableSkills.Count > 0)
        {
            List <RandomObject> objs = new List <RandomObject>();
            foreach (AbilityBase ab in availableSkills)
            {
                if (ab != null)
                {
                    RandomObject ro = new RandomObject();
                    ro.ItemId = ab.SkillData.id;
                    ro.Weight = ab.SkillData.weight;
                    objs.Add(ro);
                }
            }

            if (objs.Count > 0)
            {
                List <RandomObject> retObjs = ProjectHelper.GetRandomList <RandomObject>(objs, 1);
                AbilityBase         abb     = m_abilities.Where(ability => ability.SkillData.id == retObjs[0].ItemId).FirstOrDefault();
                if (abb != null)
                {
                    abb.onSelect();
                    return(true);
                }
            }
        }

        return(false);
    }
Example #21
0
    /// <summary>
    /// 产生随机的房间类型
    /// </summary>
    /// <returns></returns>
    private CommonDefine.RoomType RandomRoomType()
    {
        List <RandomObject> objs = new List <RandomObject>();

        foreach (KeyValuePair <int, RoomData> kv in RoomData.dataMap)
        {
            RandomObject ro = new RandomObject();
            ro.ItemId = kv.Key;
            ro.Weight = kv.Value.weight;
            objs.Add(ro);
        }

        List <RandomObject> retObjs = ProjectHelper.GetRandomList <RandomObject>(objs, 1);

        if (retObjs == null)
        {
            Debug.logger.LogError("DungeonPoint", "random objet occurs error");
        }

        CommonDefine.RoomType rt = (CommonDefine.RoomType)retObjs[0].ItemId;

        return(rt);
    }
Example #22
0
    public override void ToAttackPerson()
    {
        if (ChooseSkill())
        {
            GameData.Instance.BattleSceneActionFlag.RemoveFlag((long)StateDef.BattleActionFlag.OnChoosingSkill);
            GameData.Instance.BattleSceneActionFlag.AddFlag((long)StateDef.BattleActionFlag.OnAttacking);

            List <RandomObject> ros = new List <RandomObject>();

            foreach (RoleBase play in RoleManager.Instance.RolesInBattle())
            {
                if (CurrentAbility.SkillData.affectpositions.Contains(play.m_playerPosition))
                {
                    RandomObject ro = new RandomObject();
                    ro.ItemId = play.m_playerPosition;
                    ro.Weight = 1;
                    if (play.OverlayItemModel.IsTaged)
                    {
                        ro.Weight += 1;
                    }
                    ros.Add(ro);
                }
            }

            List <RandomObject> retObjs = ProjectHelper.GetRandomList <RandomObject>(ros, 1);
            RoleBase            toWho   = RoleManager.Instance.RolesInBattle().Where(role => role.m_playerPosition == retObjs[0].ItemId).FirstOrDefault();
            if (toWho != null)
            {
                RoleManager.Instance.AffectRole(toWho);
            }
        }
        else
        {
            //TODO:移动位置。。。。
            Debug.logger.Log("bad luck..............");
        }
    }
Example #23
0
    // Use this for initialization
    void Start()
    {
        scenario       = new Scenario();
        objectif       = scenario.getObjectif();
        Time.timeScale = 1;

        scriptIntroControl         = this.GetComponent <IntroControl> ();
        scriptIntroControl.enabled = true;
        scriptIntroState           = plane.GetComponent <IntroState> ();
        scriptIntroState.enabled   = true;
        //intro script activation
        state = State.INTRO;
        scriptPlanePhysics         = plane.GetComponent <PlanePhysics> ();
        scriptPlanePhysics.enabled = false;
        scriptSlidingBackground    = backgrounds.GetComponent <SlidingBackground>();
        scriptRandomObject         = this.GetComponent <RandomObject> ();
        scriptRandomObject.enabled = false;
        scriptFuelControl          = GetComponent <FuelControl>();
        scriptFuelControl.enabled  = true;

        prevY              = scriptPlanePhysics.transform.position.y;
        isPause            = false;
        guiBestScore.value = PlayerPrefs.GetInt(Constants.MAIN_GAME_HIGH_SCORE);

        tutoScript = tutoPref.GetComponent <GenericTutoScript>();
        if (PlayerPrefs.GetInt(Constants.MAIN_GAME_ALREADY_PLAYED) == 0)
        {
            bouttonPause.GetComponent <Image> ().enabled = false;
            firstPlayTuto();

            PlayerPrefs.SetInt(Constants.MAIN_GAME_ALREADY_PLAYED, 1);
        }
        else if (!scenario.isFinished())
        {
            displayObjectif();
        }
    }
Example #24
0
    public static DungeonPoint CreateCheckPoint()
    {
        List <RandomObject> objs = new List <RandomObject>();

        foreach (KeyValuePair <int, CheckPointData> kv in CheckPointData.dataMap)
        {
            RandomObject ro = new RandomObject();
            ro.ItemId = kv.Key;
            ro.Weight = kv.Value.weight;
            objs.Add(ro);
        }

        List <RandomObject> retObjs = ProjectHelper.GetRandomList <RandomObject>(objs, 1);

        if (retObjs == null)
        {
            Debug.logger.LogError("DungeonPoint", "random objet occurs error");
        }

        CommonDefine.CheckPointType cp = (CommonDefine.CheckPointType)retObjs[0].ItemId;
        switch (cp)
        {
        case CommonDefine.CheckPointType.bag:
            return(new DungeonBagPoint());

        case CommonDefine.CheckPointType.bucket:
            return(new DungeonBucketPoint());

        case CommonDefine.CheckPointType.coffin:
            return(new DungeonCoffinPoint());

        case CommonDefine.CheckPointType.None:
            return(new DungeonPoint());
        }

        return(new DungeonPoint());
    }
Example #25
0
    // Use this for initialization
    void Start()
    {
        Random.seed = (int)Time.time;

        dragon = new RandomObject();
        spartan = new RandomObject();

        dragon.freq = 1;
        dragon.maxLife = 3;
        dragon.aliveTime = 0;
        dragon.deadTime = 0;
        dragon.resurectTime = dragon.freq + 5*Random.value;
        dragon.gameObject = GameObject.Find("TheDragon");

        spartan.freq = 4;
        spartan.maxLife = 20;
        spartan.aliveTime = 0;
        spartan.deadTime = 0;
        spartan.resurectTime = spartan.freq + 5*Random.value;
        spartan.gameObject = GameObject.Find("EnemySpartan");

        dragon.gameObject.SetActiveRecursively(false);
        spartan.gameObject.SetActiveRecursively(false);
    }
Example #26
0
    public static string CreateDefaultSkills(CommonDefine.RoleType roleType)
    {
        List <RandomObject> objs = new List <RandomObject>();
        RoleData            role = RoleData.GetRoleDataByID((int)roleType);
        RandomObject        ro1  = new RandomObject();

        ro1.ItemId = role.skill1;
        ro1.Weight = SkillData.GetSkillDataByID(role.skill1).weight;
        objs.Add(ro1);

        RandomObject ro2 = new RandomObject();

        ro2.ItemId = role.skill2;
        ro2.Weight = SkillData.GetSkillDataByID(role.skill2).weight;
        objs.Add(ro2);

        RandomObject ro3 = new RandomObject();

        ro3.ItemId = role.skill3;
        ro3.Weight = SkillData.GetSkillDataByID(role.skill3).weight;
        objs.Add(ro3);

        RandomObject ro4 = new RandomObject();

        ro4.ItemId = role.skill4;
        ro4.Weight = SkillData.GetSkillDataByID(role.skill4).weight;
        objs.Add(ro4);

        RandomObject ro5 = new RandomObject();

        ro5.ItemId = role.skill5;
        ro5.Weight = SkillData.GetSkillDataByID(role.skill5).weight;
        objs.Add(ro5);

        RandomObject ro6 = new RandomObject();

        ro6.ItemId = role.skill6;
        ro6.Weight = SkillData.GetSkillDataByID(role.skill6).weight;
        objs.Add(ro6);

        RandomObject ro7 = new RandomObject();

        ro7.ItemId = role.skill7;
        ro7.Weight = SkillData.GetSkillDataByID(role.skill7).weight;
        objs.Add(ro7);

        List <RandomObject> retObjs = ProjectHelper.GetRandomList <RandomObject>(objs, 4);

        if (retObjs == null)
        {
            Debug.logger.LogError("DungeonPoint", "random objet occurs error");
        }

        string ret = string.Empty;

        foreach (RandomObject obj in retObjs)
        {
            if (!string.IsNullOrEmpty(ret))
            {
                ret += ":";
            }
            ret += (obj.ItemId % (int)roleType).ToString();
        }

        return(ret);
    }
 /// <summary>
 /// Finds the software asynchronous.
 /// </summary>
 /// <param name="id">The identifier.</param>
 /// <param name="deepness">if set to <c>true</c> [with children].</param>
 /// <returns></returns>
 public virtual async Task <int> GetObjectStringCount(RandomObject obj)
 {
     return(await new ServiceClient <ITestService>()
            .ExecuteAsync(d => d.GetObjectStringCount(obj)));
 }
Example #28
0
        //ak自動派彩
        public void akAutoPay(H5Games h5)
        {
            string url = "https://api.random.org/json-rpc/2/invoke";
            Random r   = new Random();
            int    id  = r.Next(0, 100);


            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.ContentType = "application/json";
            request.Method      = "POST";
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                string json = "{\"jsonrpc\":\"2.0\"," +
                              "\"method\":\"generateIntegers\"," +
                              "\"params\":{" +
                              "\"apiKey\":\"3d80c333-78f2-4ed1-b4e1-80e07eb9f041\"," +
                              "\"n\":1," +
                              "\"min\":1," +
                              "\"max\":13," +
                              "\"replacement\":true}," +
                              "\"id\":" + id + "}"

                ;

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }
            var httpResponse = (HttpWebResponse)request.GetResponse();

            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var          result = streamReader.ReadToEnd();
                RandomObject ro     = JsonConvert.DeserializeObject <RandomObject>(result);

                //1:A-K 2:樂透
                GameNumberRecord gnr = new GameNumberRecord
                {
                    gameSn  = h5.id,
                    number  = ro.result.random.data[0],
                    inpdate = DateTime.Now,
                };
                //寫入牌記錄
                this.GNCreate(gnr);
                //派彩
                var player = this.PlayerGetAll(h5.id);
                foreach (var p in player)
                {
                    var number = this.NumberGetAll(p.id);
                    foreach (var n in number)
                    {
                        //確認正解
                        p.valid = 2;
                        this.betsUpdate(p);

                        if (gnr.number == n.Number)
                        {
                            //派彩記錄
                            H5payouts h5p = new H5payouts
                            {
                                gameSn     = h5.id,
                                userId     = p.userId,
                                betSn      = p.id,
                                Odds       = p.Odds,
                                money      = p.money,
                                readlMoney = p.money * p.Odds * (100 - h5.rake) / 100,
                                createDate = DateTime.Now,
                                modiDate   = DateTime.Now,
                                rake       = h5.rake
                            };
                            this.Payouts(h5p);
                            //玩家加錢和記錄
                            AssetsRecord assr = new AssetsRecord {
                                UserId     = h5p.userId,
                                unitSn     = 1,
                                gameSn     = h5.id,
                                assets     = (double)h5p.readlMoney,
                                type       = 15,
                                h5forValue = h5.gameModel
                            };

                            new AssetsRepository().Addh5gameByAssets(assr);
                        }
                    }
                }


                //開盤資料更新
                h5.gameStatus = 0;
                h5.payDate    = DateTime.Now;
                this.H5GameUpdate(h5);
            }
        }
Example #29
0
        //樂透自動派彩
        public double ballAutoPay(H5Games h5)
        {
            string url = "https://api.random.org/json-rpc/2/invoke";
            Random r   = new Random();
            int    id  = r.Next(0, 100);


            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.ContentType = "application/json";
            request.Method      = "POST";
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                string json = "{\"jsonrpc\":\"2.0\"," +
                              "\"method\":\"generateIntegers\"," +
                              "\"params\":{" +
                              "\"apiKey\":\"3d80c333-78f2-4ed1-b4e1-80e07eb9f041\"," +
                              "\"n\":5," +
                              "\"min\":0," +
                              "\"max\":35," +
                              "\"replacement\":false}," +
                              "\"id\":" + id + "}"

                ;

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }
            var httpResponse = (HttpWebResponse)request.GetResponse();

            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var          result = streamReader.ReadToEnd();
                RandomObject ro     = JsonConvert.DeserializeObject <RandomObject>(result);

                //1:A-K 2:樂透
                foreach (var rd in ro.result.random.data)
                {
                    GameNumberRecord gnr = new GameNumberRecord
                    {
                        gameSn  = h5.id,
                        number  = rd,
                        inpdate = DateTime.Now,
                    };
                    //寫入牌記錄
                    this.GNCreate(gnr);
                }

                //派彩
                var   player = this.PlayerGetAll(h5.id);
                int[] ary    = new int[] { 0, 0, 0, 0 };
                var   ucm    = new List <BallGameModel>();
                //確認多少中獎
                foreach (var p in player)
                {
                    var number = this.NumberGetAll(p.id);
                    int count  = 0;
                    var uc     = new BallGameModel();

                    foreach (var n in number)
                    {
                        foreach (var rd in ro.result.random.data)
                        {
                            if (rd == n.Number)
                            {
                                count += 1;
                            }
                        }
                    }
                    if (count >= 2)
                    {
                        ary[count - 2] += 1;
                        uc.gamebets     = p;
                        uc.count        = count;
                        ucm.Add(uc);
                    }
                    //確認正解
                    p.valid = 2;
                    this.betsUpdate(p);
                }
                double total     = (h5.totallottery != null) ? (double)h5.totallottery:0;
                double ball      = 500000 + total;
                double totalbets = this.PlayerGetAll(h5.id).Sum(x => (double)x.money);

                double deduction = 0;

                foreach (var c in ucm)
                {
                    double?rm = (c.count != 5)?(totalbets * 25 / 100) / ary[c.count - 2]: ball + (totalbets * 25 / 100) / ary[c.count - 2];


                    if (c.count == 5)
                    {
                        h5.bingo   = 1;
                        deduction += total + (totalbets * 25 / 100) / ary[c.count - 2];
                    }
                    else
                    {
                        deduction += (double)rm;
                    }


                    //派彩記錄
                    H5payouts h5p = new H5payouts
                    {
                        gameSn     = h5.id,
                        userId     = c.gamebets.userId,
                        betSn      = c.gamebets.id,
                        Odds       = c.gamebets.Odds,
                        money      = c.gamebets.money,
                        readlMoney = rm * (100 - h5.rake) / 100,
                        createDate = DateTime.Now,
                        modiDate   = DateTime.Now,
                        rake       = h5.rake
                    };

                    this.Payouts(h5p);
                    //玩家加錢和記錄
                    AssetsRecord assr = new AssetsRecord
                    {
                        UserId     = h5p.userId,
                        unitSn     = 1,
                        gameSn     = h5.id,
                        assets     = (double)h5p.readlMoney,
                        type       = 15,
                        h5forValue = h5.gameModel
                    };

                    new AssetsRepository().Addh5gameByAssets(assr);
                }



                //開盤資料更新
                h5.gameStatus = 0;
                h5.payDate    = DateTime.Now;
                this.H5GameUpdate(h5);


                return(totalbets + total - deduction);
            }
        }
Example #30
0
    // Use this for initialization
    void Start()
    {
        scenario = new Scenario ();
        objectif = scenario.getObjectif();
        Time.timeScale = 1;

        scriptIntroControl = this.GetComponent<IntroControl> ();
        scriptIntroControl.enabled = true;
        scriptIntroState = plane.GetComponent<IntroState> ();
        scriptIntroState.enabled = true;
        //intro script activation
        state = State.INTRO;
        scriptPlanePhysics = plane.GetComponent<PlanePhysics> ();
        scriptPlanePhysics.enabled = false;
        scriptSlidingBackground = backgrounds.GetComponent<SlidingBackground>();
        scriptRandomObject = this.GetComponent<RandomObject> ();
        scriptRandomObject.enabled = false;
        scriptFuelControl = GetComponent<FuelControl>();
        scriptFuelControl.enabled = true;

        prevY = scriptPlanePhysics.transform.position.y;
        isPause = false;
        guiBestScore.value = PlayerPrefs.GetInt (Constants.MAIN_GAME_HIGH_SCORE);

        tutoScript = tutoPref.GetComponent<GenericTutoScript>();
        if (PlayerPrefs.GetInt (Constants.MAIN_GAME_ALREADY_PLAYED) == 0) {
            bouttonPause.GetComponent<Image> ().enabled = false;
            firstPlayTuto ();

            PlayerPrefs.SetInt (Constants.MAIN_GAME_ALREADY_PLAYED, 1);
        } else if (! scenario.isFinished()){
            displayObjectif();
        }
    }
Example #31
0
 private async Task SetCache(RandomObject obj, string key)
 {
     _cache.Add(key, obj);
 }
Example #32
0
        public virtual async Task <int> GetObjectStringCount(RandomObject obj)
        {
            await Task.Delay(10);

            return(obj.RandomObjectInstance.Length);
        }