コード例 #1
0
        public static List <MyTreeElement> GenerateRandomTree(int numTotalElements)
        {
            // 这里是随机创建树
            // numRootChildren: 在根节点上调用几次AddChildrenRecursive
            int numRootChildren = numTotalElements / 4;

            IDCounter = 0;
            var treeElements = new List <MyTreeElement>(numTotalElements);

            // name, depth, id
            var root = new MyTreeElement("Root", -1, IDCounter);

            treeElements.Add(root);
            for (int i = 0; i < numRootChildren; ++i)
            {
                int allowedDepth = 6;
                AddChildrenRecursive(root, Random.Range(minNumChildren, maxNumChildren), true, numTotalElements, ref allowedDepth, treeElements);
            }

            return(treeElements);
        }
コード例 #2
0
ファイル: RoomParser.cs プロジェクト: Weava/U_SatanicPanic
        public static void ClaimRooms(this Region region)
        {
            //Elevation cells are grouped into their own room to prevent complications
            while (region.GetCells().Where(x => x.type == CellType.Elevation).Any(x => !x.claimedByRoom))
            {
                var elevationGroups = region.GetCells().Where(x => x.type == CellType.Elevation)
                                      .GroupBy(g => new Vector2(g.position.x, g.position.y));

                foreach (var elevationGroup in elevationGroups)
                {
                    var room = new Room();
                    if (!ClaimRoom(elevationGroup.ToList(), ref room))
                    {
                        continue;
                    }
                    room.regionId = region.id;
                    RoomCollection.Add(room);
                }
            }

            //Until all cells are claimed by a room
            while (region.GetCells().Any(x => !x.claimedByRoom))
            {
                var cellsLeftToClaim = region.GetCells().Where(x => !x.claimedByRoom).ToList();
                var rootCell         = cellsLeftToClaim[Random.Range(0, cellsLeftToClaim.Count)];
                var claimSize        = region.greedyClaiming ? region.maximumRoomSize : Random.Range(1, region.maximumRoomSize + 1);

                var projection = ProjectRoom(rootCell, ref cellsLeftToClaim, Random.Range(1, region.maximumRoomSize + 1), region.claimChance, region.roomClaimingStrategy);
                if (projection.Any())
                {
                    var room = new Room();
                    if (!ClaimRoom(projection, ref room))
                    {
                        continue;
                    }
                    room.regionId = region.id;
                    RoomCollection.Add(room);
                }
            }
        }
コード例 #3
0
ファイル: TimeLine.cs プロジェクト: yuto1492/mon_rogelike
        public void Initialize()
        {
            _timelineSchedule = new List <int>();
            _timelineData     = new List <TimelineSerializableData>();
            MemberDataModel memberData = MemberDataModel.Instance;
            ActorDataModel  actorData  = ActorDataModel.Instance;

            memberData.Data.ForEach(x =>
            {
                BattlerSerializable battler = actorData.ByIndex(x.index);
                _timelineData.Add(new TimelineSerializableData
                {
                    id          = _timelineData.Count,
                    uniqId      = battler.uniqId,
                    battlerType = BattlerEnum.BattlerType.Actor,
                    timeLine    = Random.Range(battler.parameter.spd / 2,
                                               battler.parameter.spd)
                });
            });
            EnemyDataModel enemyData = EnemyDataModel.Instance;

            enemyData.Data.ForEach(x =>
            {
                _timelineData.Add(new TimelineSerializableData
                {
                    id          = _timelineData.Count,
                    uniqId      = x.uniqId,
                    battlerType = BattlerEnum.BattlerType.Enemy,
                    timeLine    = Random.Range(x.parameter.spd / 2, x.parameter.spd)
                });
            });
            TimelineCalc();
            for (int i = 0; i < SCHEDULE_SIZE; i++)
            {
                TimeLineForward();
            }

            _timelineView = new TimelineView();
            _timelineView.Initialize(this);
        }
コード例 #4
0
        /**
         *      Returns a random sample from the list.
         */
        public static IEnumerable <T> SampleRandom <T>(this IEnumerable <T> source, int sampleCount)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            if (sampleCount < 0)
            {
                throw new ArgumentOutOfRangeException("sampleCount");
            }

            /* Reservoir sampling. */
            var samples = new List <T>();

            //Must be 1, otherwise we have to use Range(0, i + 1)
            var i = 1;

            foreach (var item in source)
            {
                if (i <= sampleCount)
                {
                    samples.Add(item);
                }
                else
                {
                    // Randomly replace elements in the reservoir with a decreasing probability.
                    var r = Random.Range(0, i);

                    if (r < sampleCount)
                    {
                        samples[r] = item;
                    }
                }

                i++;
            }

            return(samples);
        }
コード例 #5
0
        public static void InitPairs(int minIndex, int maxIndex, int count, NativeArray <ulong> pairs)
        {
            Random.InitState(1234);

            for (var i = 0; i < pairs.Length; ++i)
            {
                ulong indexA = (ulong)Random.Range(minIndex, maxIndex);
                ulong indexB = (ulong)Random.Range(minIndex, maxIndex);

                if (indexB == indexA)
                {
                    if (indexB < (ulong)maxIndex)
                    {
                        indexB++;
                    }
                }

                pairs[i] =
                    indexA << DispatchPairSequencer.DispatchPair.k_BodyAIndexShift |
                        indexB << DispatchPairSequencer.DispatchPair.k_BodyBIndexShift;
            }
        }
コード例 #6
0
        public void CalculateResult()
        {
            for (int i = 0; i < randomNumbers.Length; i++)
            {
                for (int j = 0; j < randomNumbers[i].Length; j++)
                {
                    randomNumbers[i][j] = Random.Range(0, MaxValue);
                }
            }
            for (int i = 0; i < valueNumbers.Length; i++)
            {
                for (int j = 0; j < valueNumbers[i].Length; j++)
                {
                    valueNumbers[i][j] = Random.Range(0, MaxValue);
                }
            }
            for (int i = 0; i < lights.Length; i++)
            {
                lights[i] = Random.Range(0, LightMaxValue);
            }
            for (int i = 0; i < exchangeEnums.Length; i++)
            {
                exchangeEnums[i] = (ExchangeEnum)Random.Range(0, 16);
            }

            exChangedDictionary.Clear();
            for (int i = 0; i < 4; i++)
            {
                int index = 0;
                for (int j = 0; j < 4; j++)
                {
                    if (j != lights[i])
                    {
                        exChangedDictionary.Add(j + i * 4, exchangeEnums[i * 3 + index]);
                        index += 1;
                    }
                }
            }
        }
コード例 #7
0
        private void StartInitializeGame()
        {
            GetController <PlayerController>().InitializePlayer();

            if (_matchManager.MatchType == Enumerators.MatchType.LOCAL)
            {
                GetController <AIController>().InitializePlayer();
            }

            GetController <SkillsController>().InitializeSkills();
            GetController <BattlegroundController>().InitializeBattleground();

            if (IsTutorial)
            {
                IsSpecificGameplayBattleground = true;

                CurrentTurnPlayer = _tutorialManager.CurrentTutorial.PlayerTurnFirst ? CurrentPlayer : OpponentPlayer;

                GetController <PlayerController>().SetHand();
                GetController <CardsController>().StartCardDistribution();
            }
            else
            {
                IsSpecificGameplayBattleground = false;

                CurrentTurnPlayer = Random.Range(0, 100) > 50 ? CurrentPlayer : OpponentPlayer;

                OpponentPlayer.SetFirstHand(false);

                _uiManager.DrawPopup <PlayerOrderPopup>(new object[]
                {
                    CurrentPlayer.SelfHero, OpponentPlayer.SelfHero
                });
            }

            IsGameEnded = false;

            GameInitialized?.Invoke();
        }
        private void RemoveRandom(out int newSize)
        {
            var count = 0;

            for (var i = 0; i < _keySize; i++)
            {
                if (Random.Range(0, 2) == 1)
                {
                    _nativeMultiHashMap.Remove(_keyData[i]);
                    _checkingResults.Remove(_keyData[i]);
                }
                else
                {
                    count++;
                }
            }

            newSize = count * _valueSize;

            Assert.AreEqual(newSize, _nativeMultiHashMap.Length);
            Assert.AreEqual(newSize, Length(_checkingResults));
        }
コード例 #9
0
        public override void Update(float deltaTime)
        {
            // Moves character in a random direction while idle.
            timeSpentIdle += deltaTime;
            if (timeSpentIdle >= totalIdleTime)
            {
                Tile[]      neighbors = character.CurrTile.GetNeighbours();
                Tile        endTile   = neighbors[Random.Range(0, 4)];
                List <Tile> path      = Pathfinder.FindPathToTile(character.CurrTile, endTile);

                if (endTile.MovementCost != 0)
                {
                    // See if the desired tile is walkable, then go there if we can.
                    character.SetState(new MoveState(character, Pathfinder.GoalTileEvaluator(endTile, true), path));
                }
                else
                {
                    // If the tile is unwalkable, just get a new state.
                    character.SetState(null);
                }
            }
        }
コード例 #10
0
        public async Task RandomizeFrom(IList <PreloadMetaData> meta)
        {
            Console.WriteLine(meta.Count);

            if (_lastSelectedRandoms.Count == meta.Count)
            {
                _lastSelectedRandoms.Clear();
            }

            var idx = 1;

            while (_lastSelectedRandoms.Contains(idx))
            {
                idx = (int)(Random.Range(0f, 1f) * meta.Count);
            }

            _lastSelectedRandoms.Add(idx);

            var comp = meta[idx];

            SetModelComposition(await _mainAssetStore.GetCompositionByMeta(comp));
        }
コード例 #11
0
 public override void OnEnter()
 {
     //interestArousal += 0.1f;
     //interestValence += 0.05f;
     morphMouthAction         = true;
     mSmileFullFaceTarget     = -1.0f;
     mSmileOpenFullFaceTarget = 0.0f;
     mHappyTarget             = 0.0f;
     mFlirtingTarget          = 0.0f;
     mVisFTarget             = 0.0f;
     mTongueInOutTarget      = Random.Range(0.5f, 1.0f);
     mTongueSideSideTarget   = 0.0f;
     mTongueBendTipTarget    = 0.0f;
     mMouthOpenTarget        = Random.Range(0.01f, 0.1f);;
     mMouthSideLeftTarget    = 0.0f;
     mMouthSideRightTarget   = 0.0f;
     mSmileSimpleLeftTarget  = Random.Range(0.0f, 0.3f);;
     mSmileSimpleRightTarget = mSmileSimpleLeftTarget;
     mLipsPuckerTarget       = Random.Range(0.0f, 0.3f);;
     mLipsPuckerWideTarget   = 0.0f;
     Duration = Random.Range(1.0f, 3.0f) * lookVariation;
 }
コード例 #12
0
        int[] GenerateZoneCenterCoordinates(int distanceFromAnotherObject, int[,] mapData)
        {
            int errors = 0;

            while (true)
            {
                errors++;
                if (errors > 5000)
                {
                    return(null);
                }

                int  xParent     = Random.Range(0, _mapCountrySize);
                int  yParent     = Random.Range(0, _mapCountrySize);
                bool canGenerate = FindContent(xParent, yParent, distanceFromAnotherObject, mapData);
                if (!canGenerate)
                {
                    continue;
                }
                return(new[] { xParent, yParent });
            }
        }
コード例 #13
0
        /// <summary>
        /// Extension to select and return a random item from any IEnumerable.
        /// NOTE: If the collection does not implement IList, the collection will be iterated through up to twice!
        /// </summary>
        /// <param name="collection">The IEnumerable to iterate over and choose an item from.</param>
        /// <returns>A random item from the provided IEnumerable.</returns>
        public static object ChooseRandom(this IEnumerable collection)
        {
            IList iList = collection as IList;

            if (iList != null)
            {
                if (iList.Count == 0)
                {
                    throw new ArgumentException("Trying to choose random item from an empty list!");
                }

                return(iList[Random.Range(0, iList.Count)]);
            }

            IEnumerator enumerator = collection.GetEnumerator();
            int         count      = 0;

            while (enumerator.MoveNext())
            {
                count++;
            }

            if (count == 0)
            {
                throw new ArgumentException("Trying to choose random item from an empty list!");
            }

            enumerator.Reset();

            int index = Random.Range(0, count);

            for (int i = 0; i < index; i++)
            {
                enumerator.MoveNext();
            }

            return(enumerator.Current);
        }
コード例 #14
0
        /// <summary>
        /// Gets a random item from the list using the weights at a certain time
        /// </summary>
        /// <param name="time">The time on the animation curve to get the weight from</param>
        /// <returns>A random item, if all weights are 0, selects a random with equal weighting</returns>
        /// <exception cref="NullReferenceException">The list is empty</exception>
        public T GetRandomItem(float time)
        {
            if (list.Count == 0)
            {
                throw new NullReferenceException("WeightedList is empty");
            }

            float total = list.Sum(t => t.weight.Evaluate(time));

            total = Random.Range(0f, total);

            if (total == 0)
            {
                return(list[Random.Range(0, list.Count)].item);
            }

            var i = 0;

            while (total >= 0 && i < list.Count)
            {
                float iWeight = list[i].weight.Evaluate(time);
                if (total < iWeight && iWeight != 0)
                {
                    return(list[i].item);
                }

                total -= iWeight;
                i++;
            }

            // It's not perfect, but it's better than nothing
            if (total == 0)
            {
                return(list[Random.Range(0, list.Count)].item);
            }

            throw new NullReferenceException("Cannot return a random item from the WeightedList");
        }
        /// <summary>
        /// Generates unique number according specified letter
        /// </summary>
        /// <param name="letter"></param>
        /// <returns></returns>
        public int GenerateUniqueNumberForLetter(BingoLetter letter)
        {
            if (!CanGenerateNumberForLetter(letter))
            {
                throw new Exception("All numbers for letter " + letter + " were already generated");
            }
            var letterIndex = BingoLetterCaster.BingoLetterToInt(letter);
            var numbersList = _bingoNumberListsArray[letterIndex];

            var randomIndexForPickNumber = Random.Range(0, numbersList.Count);

            // Pick number by random index in numbersList
            var randomNumber = numbersList[randomIndexForPickNumber];


            while (true)
            {
                randomNumber = Random.Range(0, 25);
                if (indexValues[randomNumber] != -1)
                {
                    indexValues[randomNumber] = -1;
                    break;
                }
                else
                {
                    continue;
                }
            }


            // Remove picked number from list (we don't want generate this number again in further calls
            // to GenerateUniqueNumberForLetter() method)
            //indexValues.RemoveAt(randomIndexForPickNumber);

            //randomNumber = Random.Range(0, 25);

            return(randomNumber);
        }
コード例 #16
0
        private IEnumerator Tick()
        {
            while (true)
            {
                var tankMovementSoundEntityViews = entityViewsDB.QueryEntityViews <TankMovementSoundEntityView>();

                if (tankMovementSoundEntityViews.Count > 0)
                {
                    for (int i = 0; i < tankMovementSoundEntityViews.Count; i++)
                    {
                        IAudioSourceComponent        audioSourceComponent = tankMovementSoundEntityViews[i].AudioSourceComponent;
                        ITankMovementSoundsComponent soundComponent       = tankMovementSoundEntityViews[i].TankMovementSoundsComponent;
                        ITankInputComponent          inputComponent       = tankMovementSoundEntityViews[i].TankInputComponent;
                        if (Mathf.Abs(inputComponent.Input.z) < 0.1f && Mathf.Abs(inputComponent.Input.x) < 0.1f)
                        {
                            if (audioSourceComponent.Clip == soundComponent.EngineDrivingAudioClip)
                            {
                                audioSourceComponent.Clip  = soundComponent.IdleAudioClip;
                                audioSourceComponent.Pitch = Random.Range(1 - 0.1f, 1 + 0.1f);
                                audioSourceComponent.Play();
                            }
                        }
                        else
                        {
                            if (audioSourceComponent.Clip == soundComponent.IdleAudioClip)
                            {
                                // ... change the clip to driving and play.
                                audioSourceComponent.Clip  = soundComponent.EngineDrivingAudioClip;
                                audioSourceComponent.Pitch = Random.Range(1 - 0.1f, 1 + 0.1f);
                                audioSourceComponent.Play();
                            }
                        }
                    }
                }

                yield return(null);
            }
        }
コード例 #17
0
 public override void OnEnter()
 {
     //interestArousal += 0.25f;
     //interestValence += 0.1f;
     morphMouthAction         = true;
     mSmileFullFaceTarget     = 0.0f;
     mSmileOpenFullFaceTarget = 0.0f;
     mGlareTarget             = 0.0f;
     mHappyTarget             = Random.Range(0.1f, 0.3f);
     //mTongueInOutTarget = Random.Range(-0.15f,0.5f);
     //mTongueSideSideTarget = 0.5f;
     mTongueBendTipTarget = 0.0f;
     ///mVisFTarget = Random.Range(0.5f,1.0f);
     mMouthOpenTarget        = -1.0f;
     mMouthSideLeftTarget    = 0.0f;
     mMouthSideRightTarget   = 0.0f;
     mSmileSimpleLeftTarget  = -1.0f;
     mSmileSimpleRightTarget = -1.0f;
     mLipsPuckerTarget       = Random.Range(0.0f, 0.3f);
     mLipsPuckerWideTarget   = 0.0f;
     mExcitementTarget       = 0.0f;
     Duration = Random.Range(2.0f, 4.5f) * lookVariation;
 }
コード例 #18
0
        private IDictionary <string, NodeType> FindSubgraphAndMarkNodes(GraphType otherGraph)
        {
            IDictionary <string, IList <NodeType> > candidateMarkedNodes = new Dictionary <string, IList <NodeType> >();

            bool isSupergraphOfSourceGraph = SubgraphSearch(otherGraph, candidateMarkedNodes);

            if (!isSupergraphOfSourceGraph)
            {
                throw new InvalidOperationException($"No subgraph found in graph {id} matching source graph" +
                                                    $" {otherGraph.id}, so cannot carry out find and replace operation");
            }

            IDictionary <string, NodeType> markedNodes = new Dictionary <string, NodeType>(candidateMarkedNodes.Count);

            foreach (KeyValuePair <string, IList <NodeType> > keyValuePair in candidateMarkedNodes)
            {
                IList <NodeType> nodes     = keyValuePair.Value;
                NodeType         nodeToUse = nodes[nodes.Count == 1 ? 0 : Random.Range(0, nodes.Count)];
                markedNodes[keyValuePair.Key] = nodeToUse;
            }

            return(markedNodes);
        }
コード例 #19
0
            public override IEnumerable <string> GetAnswers(SouvenirModule module)
            {
                if (MaxSteps >= 10)
                {
                    while (true)
                    {
                        yield return((Random.Range(0, MaxSteps) * Step + Min).ToString(Format));
                    }
                }
                // With no more than 6 possible values, the above case may go into an infinite loop trying to generate 5 distinct values.
                // In this case, we will return all possible values in a random order and then halt.
                var values = new int[MaxSteps];

                for (int i = MaxSteps - 1; i >= 0; --i)
                {
                    values[i] = i * Step + Min;
                }
                values.Shuffle();
                foreach (var i in values)
                {
                    yield return(i.ToString(Format));
                }
            }
コード例 #20
0
        public void PlaySfx(SfxId sfxId)
        {
            var sfxInfo = _sfxSettings.GetSfxInfo(sfxId);

            switch (sfxId)
            {
            case SfxId.Shot:
                _audioViewFactory.Create(sfxInfo.AudioClip, sfxInfo.MixerGroup, Random.Range(0.8f, 1.1f), 0f);
                break;

            case SfxId.Pop:
                _audioViewFactory.Create(sfxInfo.AudioClip, sfxInfo.MixerGroup, Random.Range(0.9f, 1.1f),
                                         Random.Range(0f, 0.2f));
                break;

            case SfxId.Explosion:
                _audioViewFactory.Create(sfxInfo.AudioClip, sfxInfo.MixerGroup, 1f, 0f);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(sfxId), sfxId, null);
            }
        }
コード例 #21
0
        /// <summary>
        /// Returns a random element from an <c>IEnumerable</c>. Special case for 'int' type.
        /// Note: RandomOrDefault is much faster when used on a collection of 'int' or 'float'.
        /// Count &lt; 100 optimised from https://nickstrips.wordpress.com/2010/08/28/c-optimized-extension-method-get-a-random-element-from-a-collection/
        /// </summary>
        public static float RandomOrDefault(this IEnumerable <float> self)
        {
            IEnumerable <float> enumerable = self as float[] ?? self.ToArray();
            int count = enumerable.Count();
            int index = Random.Range(0, count);

            // When the collection has 100 elements or less, get the random element.
            // by traversing the collection one element at a time.
            if (count > 100)
            {
                return(enumerable.ElementAt(index));
            }

            using (IEnumerator <float> enumerator = enumerable.GetEnumerator())
            {
                while (index >= 0 && enumerator.MoveNext())
                {
                    index--;
                }

                return(enumerator.Current);
            }
        }
コード例 #22
0
ファイル: MapGenerator.cs プロジェクト: aluspl/RogueLikeDSP
        public void GetVerticalWall(MapElement[,] map, ref int posX, int posY, int xSize, int ySize)
        {
            //Debug.Log(string.Format("X: {0} Y: {1} PosX: {2} PosY: {3} PosY+Y={4}", xSize,ySize,posX,posY,posY+ySize));
            posX += xSize;

            var door = Random.Range(posY + 1, (posY + ySize) - 1);

            for (var y = posY; y < posY + ySize; y++)
            {
                if (y >= MapSizeY - 1 || posX >= MapSizeX - 1)
                {
                    continue;
                }
                if (y == door)
                {
                    map[posX, y] = MapElement.Door;
                }
                else
                {
                    map[posX, y] = MapElement.Wall;
                }
            }
        }
コード例 #23
0
 public override void OnEnter()
 {
     currentEye = "Wink";
     //interestArousal += 0.5f;
     //interestValence += 0.1f;
     morphEyeAction = true;
     if (Random.Range(0.0f, 100.0f) > 50.0f)
     {
         mEyesClosedLeftTarget   = 0.95f;
         mEyesClosedRightTarget  = 0.0f;
         mSmileSimpleLeftTarget  = 0.4f;
         mSmileSimpleRightTarget = 0.0f;
     }
     else
     {
         mEyesClosedLeftTarget   = 0.0f;
         mEyesClosedRightTarget  = 0.95f;
         mSmileSimpleLeftTarget  = 0.0f;
         mSmileSimpleRightTarget = 0.4f;
     }
     mEyesSquintTarget = 0.0f;
     Duration          = Random.Range(0.25f, 0.3f);
 }
コード例 #24
0
 public override void OnEnter()
 {
     //interestArousal += 5.0f;
     //interestValence += 1.0f;
     morphMouthAction         = true;
     mSmileFullFaceTarget     = 0.0f;
     mSmileOpenFullFaceTarget = 0.0f;
     mGlareTarget             = 0.0f;
     sexActionNeckX           = -5.0f;
     mTongueInOutTarget       = Random.Range(-0.6f, 0.3f);
     mTongueSideSideTarget    = Random.Range(-0.2f, 0.2f);
     mTongueBendTipTarget     = 0.0f;
     mHappyTarget             = 0.0f;
     mFlirtingTarget          = 0.0f;
     mMouthOpenTarget         = Random.Range(0.4f, 0.8f);
     mMouthSideLeftTarget     = 0.0f;
     mMouthSideRightTarget    = 0.0f;
     mSmileSimpleLeftTarget   = 0.0f;
     mSmileSimpleRightTarget  = 0.0f;
     mLipsPuckerTarget        = Random.Range(0.4f, 1.1f);
     mLipsPuckerWideTarget    = 0.0f;
     Duration = Random.Range(1.5f, 3.0f) * lookVariation;
 }
コード例 #25
0
        public EffectBase MakeEffect(EffectSet effectSet, EffectDuration durationType = EffectDuration.Undefined)
        {
            if (durationType == EffectDuration.Undefined)
            {
                durationType = Random.Range(0, 2) > 0 ? EffectDuration.Timed : EffectDuration.Permanent;
            }

            EffectBase effect;
            var        statType = effectSet.GameStatType;
            var        amount   = Random.Range(effectSet.MinAmount, effectSet.MaxAmount);

            if (effectSet.GameEffectType == EffectType.Negative)
            {
                amount *= -1;
            }
            var duration = 0f;

            if (durationType == EffectDuration.Timed)
            {
                duration = Random.Range(effectSet.MinDuration, effectSet.MaxDuration);
            }
            else
            {
                amount *= _permanentEffectsModifier;
            }

            if (effectSet.AffectRegen)
            {
                effect = new StatRegenerationChangingEffect(statType, amount, duration, durationType, effectSet.GameEffectType, effectSet.Icon);
            }
            else
            {
                effect = new StatValueChangingEffect(statType, amount, duration, durationType, effectSet.GameEffectType, effectSet.Icon);
            }

            return(effect);
        }
コード例 #26
0
        /// <summary>
        /// Generate new random level chunk graph
        /// </summary>
        /// <param name="width"></param>
        /// <param name="length"></param>
        /// <param name="prevGraph"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static LevelGraph Generate(int width, int length, LevelGraph prevGraph = null)
        {
            if (length < MinLength)
            {
                throw new Exception("Length must be >= 2");
            }
            if (width < MinWidth)
            {
                throw new Exception("Width must be >= 1");
            }
            if (prevGraph != null && prevGraph.width != width)
            {
                throw new Exception("Prev graph width not equal");
            }

            var nodes = new Grid <LevelGraphNode>(width, length);

            // todo handle prevGraph

            // Fill graph by connected nodes
            for (var y = 0; y < length; y++)
            {
                for (var x = 0; x < width; x++)
                {
                    nodes.Set(x, y, new LevelGraphNode(x, y, width));
                }
            }

            // Close one random node on each grid row
            for (var y = 1; y < length; y++)
            {
                CloseNode(Random.Range(0, width), y, nodes);
            }

            return(new LevelGraph(nodes));
        }
コード例 #27
0
ファイル: DropTable.cs プロジェクト: gormel/has
        public static Item GenerateLoot(int level)
        {
            if (Random.value > 0.3)
            {
                return(null);
            }

            var possibles = new List <Item>();

            foreach (var record in mTable)
            {
                if (Random.value < record.Possibility)
                {
                    possibles.Add(record.CreateLoot(level));
                }
            }

            if (possibles.Count == 0)
            {
                return(null);
            }

            return(possibles[Random.Range(0, possibles.Count)]);
        }
コード例 #28
0
                public char Pick()
                {
                    var n = Chars != null ? Chars.Length : 0;

                    if (Ranges != null)
                    {
                        for (int i = 0; i < Ranges.Length; i += 2)
                        {
                            n += Ranges[i + 1] + 1 - Ranges[i];
                        }
                    }
                    n = Random.Range(0, n);
                    if (Chars != null)
                    {
                        if (n < Chars.Length)
                        {
                            return(Chars[n]);
                        }
                        n -= Chars.Length;
                    }
                    if (Ranges != null)
                    {
                        for (int i = 0; i < Ranges.Length; i += 2)
                        {
                            if (n < Ranges[i + 1] + 1 - Ranges[i])
                            {
                                return((char)(Ranges[i] + n));
                            }
                            n -= Ranges[i + 1] + 1 - Ranges[i];
                        }
                        // We shouldn't reach here.
                        return(Ranges[0]);
                    }
                    // We shouldn't reach here either.
                    return(Chars[0]);
                }
コード例 #29
0
 public static T Sample <T>(this IEnumerable <T> self)
 {
     return(self.ElementAt(Random.Range(0, self.Count())));
 }
コード例 #30
0
 public int Compare(T a, T b)
 {
     return(1 - 2 * Random.Range(0, 1));
 }