Example #1
0
    void Start()
    {
        objects.ForEach(o => o.SetActive(false));

        currentActivated = objects.GetRandomItem();
        currentActivated.SetActive(true);
    }
Example #2
0
 private static void GenerateDemoUsers()
 {
     for (int i = 0; i < generateUserCount; i++)
     {
         users.Add(new UserEntity()
         {
             Name           = (Random.Next(0, 2) == 0 ? MaleFirstNames.GetRandomItem(Random) : FemaleFirstNames.GetRandomItem(Random)) + " " + LastNames.GetRandomItem(Random),
             UserId         = Guid.NewGuid(),
             ProfileImageId = ImageIds.GetRandomItem(Random)
         });
     }
 }
Example #3
0
 private void CheckSpeechPlayback()
 {
     if (textAudioType == TextAudioType.Mumbling)
     {
         if (audioSource != null)
         {
             if (!audioSource.isPlaying)
             {
                 audioSource.PlayRandomVolumePitch(typeClips.GetRandomItem());
             }
         }
     }
 }
Example #4
0
        private async Task PraiseUser(SocketGuildUser user)
        {
            if (user == null)
            {
                return;
            }
            switch (user.Id)
            {
            case 255453041531158538:
                await PraiseDKay();

                return;

            case 235587420777611265:
                await PraiseDemanicus();

                return;

            case 283233504156975105:
                await PraiseJim();

                return;

            default:
                var msg = string.Format(_soloMessages.GetRandomItem(), user.Mention);
                await ReplyAsync(msg);

                return;
            }
        }
Example #5
0
    public GameObject CreatePickup(MazeCell cell)
    {
        if (numOfPickupsToSpawn > 0)
        {
            GameObject prefabSelected;

            // Create one of each pickup at least once, afterwards randomly select a pickup to spawn
            if (numOfPickups < pickupPrefabList.Count)
            {
                prefabSelected = pickupPrefabList[numOfPickups].gameObject;
            }
            else
            {
                prefabSelected = pickupPrefabList.GetRandomItem().gameObject;
            }

            numOfPickupsToSpawn--;
            numOfPickups++;
            GameObject product = OrderPickupFromFactory(prefabSelected, cell.transform);
            return(product);
            //return Instantiate (prefabSelected, cell.transform.position, Quaternion.identity, cell.transform);
        }
        else
        {
            return(null);
        }
    }
Example #6
0
        private static void GenerateDemoPosts()
        {
            foreach (UserEntity item in users)
            {
                int generatePosts = Random.Next(generatePostPerUserCountMin, generatePostPerUserCountMax + 1);

                for (int i = 0; i < generatePosts; i++)
                {
                    DateTime randomDate = DateTime.Now
                                          .AddYears(Random.Next(-6, 0))
                                          .AddMonths(Random.Next(0, 12))
                                          .AddDays(Random.Next(0, 30));

                    posts.Add(new PostEntity()
                    {
                        Date                  = randomDate,
                        ImageId               = ImageIds.GetRandomItem(Random),
                        HubtasticCount        = Random.Next(0, 500),
                        IsHubbedByCurrentUser = Random.Next(0, 5) == 0,
                        PostDescription       = PostDescriptions.GetRandomItem(Random),
                        PosterId              = item.UserId,
                        PosterName            = item.Name,
                        PosterProfileIconId   = "thisdoggo.jpg",//item.ProfileImageId,
                        PostId                = Guid.NewGuid()
                    });
                }
            }
        }
Example #7
0
        public static Result <List <Track> > TryInsertingVehicleToRandomTrack(List <Track> tracks, Vehicle vehicle, Action <string> logger)
        {
            var newTrackList = new List <Track>(tracks);

            while (true) // should there exist a limit ?
            {
                var maybeRandomTrackInfo = newTrackList.GetRandomItem();
                if (maybeRandomTrackInfo.HasNoValue)
                {
                    return(Result.Fail <List <Track> >("There are no Tracks in this Road yet"));
                }
                var newTrackResult = maybeRandomTrackInfo.Value.chosenObject.AddVehicle(vehicle);
                if (newTrackResult.IsSuccess)
                {
                    return(Result.Ok(newTrackList.ReplaceAt(maybeRandomTrackInfo.Value.objectPosition, newTrackResult.Value)));
                }
                if (!newTrackResult.Error.StartsWith("Cannot add more vehicles to this Track. Current limit is"))
                {
                    return(Result.Fail <List <Track> >(newTrackResult.Error));
                }

                if (logger != null)
                {
                    logger("Retrying ....");
                }
            }
        }
Example #8
0
    void SpawnPickups()
    {
        BMazeManager.Instance.SetFactoryScale(factoryScale);

        List <GameObject> prefabList = new List <GameObject> ();

        prefabList.AddRange(BMazeManager.Instance.GetFactoryList());
        int listCount = prefabList.Count;

        if (numOfPickupsToSpawn < listCount)
        {
            listCount = numOfPickupsToSpawn;
        }

        for (int i = 0; i < listCount; i++)
        {
            BMazeManager.Instance.OrderPickupFromFactory(prefabList.RemoveRandom(), pointList.RemoveRandom());
            numOfPickupsToSpawn--;
        }

        prefabList.AddRange(BMazeManager.Instance.GetFactoryList());

        for (int i = 0; i < numOfPickupsToSpawn; i++)
        {
            BMazeManager.Instance.OrderPickupFromFactory(prefabList.GetRandomItem(), pointList.RemoveRandom());
        }
    }
Example #9
0
        private static void GenerateDemoComments()
        {
            foreach (PostEntity item in posts)
            {
                int generateComments = Random.Next(generateCommentPerPostCountMin, generateCommentPerPostCountMax + 1);

                for (int i = 0; i < generateComments; i++)
                {
                    DateTime randomDate = item.Date
                                          .AddHours(Random.Next(0, 3))
                                          .AddMinutes(Random.Next(0, 60))
                                          .AddSeconds(Random.Next(0, 60));

                    UserEntity commenter = users.GetRandomItem(Random);
                    comments.Add(new CommentEntity()
                    {
                        PostId                 = item.PostId,
                        CommenterId            = commenter.UserId,
                        CommenterName          = commenter.Name,
                        CommenterProfileIconId = commenter.ProfileImageId,
                        Date = randomDate,
                        Text = CommentTexts.GetRandomItem(Random)
                    });
                }
            }
        }
        /// <summary>
        ///     Spawns a single room and its walls
        /// </summary>
        /// <param name="position">The position of the room on the grid</param>
        /// <param name="roomType">The type of the room</param>
        /// <returns>The new room</returns>
        private GameObject SpawnRoom(Vector2Int position, RoomType roomType)
        {
            GameObject newRoom = MonoBehaviour.Instantiate(this.typeToPrefabs[roomType].GetRandomItem(), this.roomParent);

            // Set room position
            newRoom.transform.position = new Vector3(
                position.x * this.roomSize.x,
                0.0f,
                position.y * this.roomSize.y);

            List <GameObject> walls = this.AddWalls(newRoom, position);

            // Define the floor transition position
            if (roomType == RoomType.Boss)
            {
                this.floorTransitionBlockingWall = walls.GetRandomItem();

                // Unparent it, so it doesn't cause any trouble later on
                this.floorTransitionBlockingWall.transform.parent = this.roomParent;
            }

            ActivityHandler.Add(newRoom.GetComponentsInChildren <Light>());

            return(newRoom);
        }
        /// <summary>
        ///     Adds a given special room to the layout
        /// </summary>
        /// <param name="validSpecialLocations">A list of valid locations for special rooms</param>
        /// <param name="roomType">The room type</param>
        private void AddSpecialRoomToLayout(List <Vector2Int> validSpecialLocations, RoomType roomType)
        {
            Vector2Int roomPosition = validSpecialLocations.GetRandomItem();

            validSpecialLocations.Remove(roomPosition);

            this.floorLayout[roomPosition] = roomType;
        }
        public void GetRandomItemTest()
        {
            Random r     = new Random(987);
            var    items = new List <int>();

            for (int i = 0; i < 1000; i++)
            {
                items.Add(i);
            }

            int v1, v2;

            v1 = v2 = -1;
            for (int i = 0; i < 20; i++)
            {
                v1 = items.GetRandomItem(r);
                Assert.AreNotEqual(v1, v2);
                v2 = v1;
            }


            // Test distribution: We expect a more or less uniform distribution
            int distributionItemToTest = 10;
            int totalTests             = 1000;

            items = items.GetRange(0, distributionItemToTest);
            var distribution = new List <int>();

            for (int i = 0; i < distributionItemToTest; i++)
            {
                distribution.Add(0);
            }

            for (int i = 0; i < totalTests; i++)
            {
                var item = items.GetRandomItem(r);
                distribution[item] = distribution[item] + 1;
            }

            int minimumCount = (totalTests / distributionItemToTest) / 2;

            for (int i = 0; i < 10; i++)
            {
                Assert.IsTrue(distribution[i] >= minimumCount, i.ToString());
            }
        }
Example #13
0
    public void Apply()
    {
        if (meshRenderer != null)
        {
            List <Material> newMaterials = new List <Material>(meshRenderer.materials);
            newMaterials[useSpecificIndex ? index : 0] = materials.GetRandomItem();

            meshRenderer.materials = newMaterials.ToArray();
        }
        else
        {
            List <Material> newMaterials = new List <Material>(skinnedMeshRenderer.materials);
            newMaterials[useSpecificIndex ? index : 0] = materials.GetRandomItem();

            skinnedMeshRenderer.materials = newMaterials.ToArray();
        }
    }
Example #14
0
 IEnumerator DoSpawnPowerup()
 {
     while (continueSpawn)
     {
         Spawn(powerupPrefabs.GetRandomItem <GameObject>());
         yield return(new WaitForSeconds(powerupSpawnInterval));
     }
 }
        public void GetRandomItemArgumentNullExceptionTest()
        {
            List <String> list = null;
            // ReSharper disable once AssignNullToNotNullAttribute
            // ReSharper disable once ReturnValueOfPureMethodIsNotUsed
            Action test = () => list.GetRandomItem();

            test.ShouldNotThrow();
        }
Example #16
0
        public void GetRandomItem()
        {
            var testValue = new List <int> {
                1, 2, 4, 5, 7, 8
            };

            var itemA = testValue.GetRandomItem();

            Assert.IsTrue(testValue.Contains(itemA));

            var itemB = testValue.GetRandomItem(DateTime.Now.Millisecond);

            Assert.IsTrue(testValue.Contains(itemB));

            var itemC = testValue.GetRandomItem(new Random());

            Assert.IsTrue(testValue.Contains(itemC));
        }
        public IActionResult GetRandomQuote(ulong guildId, int quoteId)
        {
            List <Quote> quotes = Core.GetAllQuotes(guildId);

            if (!quotes.Any())
            {
                return(new NotFoundResult());
            }
            return(new JsonResult(quotes.GetRandomItem()));
        }
Example #18
0
    int AnotherRandomDistrict(int distIndex)
    {
        List <int> indices = new List <int>()
        {
            0, 1, 2, 3
        };

        indices.Remove(distIndex);
        return(indices.GetRandomItem());
    }
Example #19
0
        public void Auto_ShortestPath()
        {
            Arb.Register <MyGenerators>();
            Prop.ForAll <int>(i =>
            {
                uint j    = (uint)i;
                Dungeon d = new Dungeon(j, 1);

                //get 2 random nodes
                List <Node> nodes = Predicates.reachableNodes(d.startNode);
                Node from         = nodes.GetRandomItem();
                Node to           = nodes.GetRandomItem();

                //check if found path == shortest
                int shortest  = Predicates.find_all_paths_extract_shortest(from, to, d.graph.Count);
                int foundPath = d.shortestpath(from, to).Count;
                return(shortest == foundPath);
            }).QuickCheckThrowOnFailure();
        }
        public void PathingThreadAction(PathingContext context)
        {
            foreach (var colony in ServerManager.ColonyTracker.ColoniesByID.Values)
            {
                List <IPandaZombie> canSpawn = PandaZombies.Where(p => p.MinColonists < colony.FollowerCount).ToList();

                if (canSpawn.Count > 0 && colony.DifficultySetting.ShouldSpawnZombies(colony))
                {
                    var bannerGoal = colony?.Banners?.FirstOrDefault();

                    if (bannerGoal == null)
                    {
                        continue;
                    }

                    var cs = ColonyState.GetColonyState(colony);

                    if (cs.ColonyRef.OwnerIsOnline())
                    {
                        Vector3Int positionFinal;
                        var        max = Math.RoundToInt(colony.FollowerCount / 100) + 1;

                        if (max == 0)
                        {
                            max = 1;
                        }

                        for (int i = 0; i < max; i++)
                        {
                            var zombie = canSpawn.GetRandomItem();

                            switch (((MonsterSpawner)MonsterTracker.MonsterSpawner).TryGetSpawnLocation(context, bannerGoal.Position, bannerGoal.SafeRadius, 200, 500f, out positionFinal))
                            {
                            case MonsterSpawner.ESpawnResult.Success:
                                if (context.Pathing.TryFindPath(ref context, positionFinal, bannerGoal.Position, out var path, 2000000000) == EPathFindingResult.Success)
                                {
                                    _spawnQueue.Enqueue(zombie.GetNewInstance(path, colony));
                                }

                                break;

                            case MonsterSpawner.ESpawnResult.NotLoaded:
                            case MonsterSpawner.ESpawnResult.Impossible:
                                colony.OnZombieSpawn(true);
                                break;

                            case MonsterSpawner.ESpawnResult.Fail:
                                colony.OnZombieSpawn(false);
                                break;
                            }
                        }
                    }
                }
            }
        }
Example #21
0
        public override void Run()
        {
            // TODO: Modify messages by placeholders like {PlayersOnlineCount}
            if (_api.World.AllOnlinePlayers.Length < _minPlayersCountToPost)
            {
                return;
            }
            var message = _messages.GetRandomItem();

            _api.BroadcastMessageToAllGroups($"{_prefix}{message}", EnumChatType.AllGroups);
        }
Example #22
0
        public void GetRandomItemFromCollectionTest()
        {
            Protein protein1       = new Protein("protein1");
            Protein protein2       = new Protein("protein2");
            var     listOfProteins = new List <Protein> {
                protein1, protein2
            };
            Protein protein = listOfProteins.GetRandomItem();

            CollectionAssert.Contains(listOfProteins, protein);
        }
Example #23
0
        private RecipeGroupSplit GetRanodmNotInvlolvedRecipe(List <Recipe> includedRecipes)
        {
            var recipeGroupSplit = new RecipeGroupSplit(_personalData.Count);

            do
            {
                recipeGroupSplit.Recipe = _recipes.GetRandomItem();
            } while (includedRecipes.Contains(recipeGroupSplit.Recipe));

            return(recipeGroupSplit);
        }
        public void GetRandomItemTest()
        {
            var list = new List <String> {
                "a", "b", "c", "d"
            };
            var actual = list.GetRandomItem();

            actual.Should()
            .NotBeNull();
            list.Should()
            .Contain(actual);
        }
Example #25
0
        /* Execute a fight between the player and the packs in this node.
         * Such a fight can take multiple rounds as describe in the Project Document.
         * A fight terminates when either the node has no more monster-pack, or when
         * the player's HP is reduced to 0.
         */
        public void fight(Player player, Dungeon dungeon)
        {
            //select pack
            Pack randomPack = packs.GetRandomItem();
            //calc pack HP
            int currentHP = 0;

            foreach (Monster member in randomPack.members.ToList())
            {
                currentHP += member.HP;
            }

            float fleeProbability = (1 - (float)currentHP / (float)randomPack.startingHP) / 2 * 100;

            //Console.WriteLine(fleeProbability);

            //%%%%%%%%%%% Pack Turn %%%%%%%%%%%
            if (fleeProbability > (float)RandomGenerator.rnd.Next(0, 100))
            {
                //the pack flees
                Node randomNeighbor = randomPack.getRandomValidNeighbour(dungeon);
                if (randomNeighbor != null)
                {
                    Console.WriteLine("Pack {0} flees.", randomPack.id);
                    randomPack.move(randomNeighbor, player.location);
                    if (this.packs.Count == 0)
                    {
                        contested = false;
                        return;
                    }

                    randomPack = packs.GetRandomItem();
                }
            }

            //pack attack
            randomPack.Attack(player);

            player.location.contested = player.location.packs.Count > 0 && player.HP > 0;
        }
Example #26
0
        public void FetchRandomFile()
        {
            string _filePath = testJsonFilePaths.GetRandomItem();

            loadedData   = FetchDataFromFile(_filePath, out string _md5, out bool _changed);
            lastFileMD5  = _md5;
            lastFileName = _filePath;

            if (_changed)
            {
                Build();
            }
        }
Example #27
0
        /// <summary>
        /// 增殖单元格
        /// </summary>
        /// <param name="cell">需要增殖的单元格</param>
        /// <param name="Size">单元格增值的数量</param>
        /// <param name="math">增殖单元格选择范围断言</param>
        /// <returns>增殖过项的列表</returns>
        private List <HexCell> ProliferationHexCell(HexCell cell, int Size, Predicate <HexCell> math)
        {
            //增殖过的列表
            List <HexCell> ProliferationList = new List <HexCell>();
            //增殖备选列表
            List <HexCell> AddCell = new List <HexCell>
            {
                cell
            };

            if (Size > MapSize)
            {
                Size = MapSize;
            }
            //增殖的单元格的地图类型 即核心单元格的地图类型
            Terrain thisTerrain = cell.TerrainTypeIndex;
            int     i           = 0;

            while (i < Size && AddCell.Count > 0)
            {
                HexCell selectedCell = AddCell.GetRandomItem(random);
                //相邻可更改的单元格的备选列表
                List <HexCell> alternative = new List <HexCell>();

                //向备选列表添加所有的可以返回条件的相邻单元格
                foreach (HexCell item in selectedCell.neighbors)
                {
                    if (item != null && item.TerrainTypeIndex != thisTerrain && math(item))
                    {
                        alternative.Add(item);
                    }
                }

                //如果没有可改变的单元格则将这个单元格从增殖单元格备选列表中移除
                //然后重新选择一个备选列表中的单元格
                if (alternative.Count == 0)
                {
                    AddCell.Remove(selectedCell);
                    continue;
                }

                //随机从邻近备选列表中选一个单元格改变地貌,并加它添加到备选列表中
                HexCell neighbor = alternative.GetRandomItem(random);
                neighbor.TerrainTypeIndex = thisTerrain;
                ProliferationList.Add(neighbor);
                AddCell.Add(neighbor);
                i++;
            }
            return(ProliferationList);
        }
Example #28
0
        public string GenerateSentence()
        {
            string     sentence    = StartingWords.GetRandomItem();;
            MarkovNode currentNode = Nodes.Find(n => n.Word == sentence);

            while (true)
            {
                string currentWord = currentNode.GetNextWord();
                if (currentWord == "__END__")
                {
                    break;
                }

                sentence   += " " + currentWord;
                currentNode = Nodes.Find(n => n.Word == currentWord);
            }

            return(sentence);
        }
    public void StartReview(DataType.Minigame minigame)
    {
        // Check if there is at least 1 review game in the pool, otherwise terminate review
        print("*CHECKING REVIEW CONDITIONS*");

        if (reviewGamesList.Count > 0)
        {
            DataType.Minigame selectedReview = reviewGamesList.GetRandomItem();

            // If the same type of game matches review, don't review
            if (minigame != selectedReview)
            {
                SpawnReview(GameManager.Instance.GetMinigameData(selectedReview).reviewPrefab);
                return;
            }
        }

        TerminateReview();
    }
Example #30
0
        public Node getRandomValidNeighbour(Dungeon d)
        {
            List <Node> candidates = new List <Node>();

            foreach (Node n in this.location.neighbors.ToList())
            {
                if (n.CountCreatures() + this.members.Count < n.Capacity(d) && d.level(n) == d.level(this.location) && n != dungeon.exitNode)
                {
                    candidates.Add(n);
                }
            }
            if (candidates.Count() == 0)
            {
                return(this.location);
            }
            else
            {
                return(candidates.GetRandomItem());
            }
        }
Example #31
0
        //Connect any number of points on the level grid.
        void ConnectPoints(LevelBlockRequirements[,] basicGrid, List<Point> points)
        {
            if (points.Count == 0)
                return;

            //Choose a random point and connect that to each other point.
            //This automatically guarantees that each point is connected to each other point, as
            //you can always travel to the first point and then to the target point.
            Point point = points.GetRandomItem();

            for (int i = 0; i < points.Count; i++)
            {
                Point otherPoint = points[i];
                if (point == otherPoint)
                    continue;

                //Check how far we have to travel
                Point distanceDifference = new Point(otherPoint.X - point.X, otherPoint.Y - point.Y);

                //And store the directions we have to take into a RandomCollection of directions
                RandomCollection<Direction> directionsToTravel = new RandomCollection<Direction>();

                if (distanceDifference.X < 0)
                    directionsToTravel.Add(Direction.Left, -distanceDifference.X);
                if (distanceDifference.X > 0)
                    directionsToTravel.Add(Direction.Right, distanceDifference.X);
                if (distanceDifference.Y < 0)
                    directionsToTravel.Add(Direction.Up, -distanceDifference.Y);
                if (distanceDifference.Y > 0)
                    directionsToTravel.Add(Direction.Down, distanceDifference.Y);

                //Then actually travel from the first point to the second one.
                Point position = point;
                while (directionsToTravel.Count != 0)
                {
                    switch (directionsToTravel.Take())
                    {
                        case Direction.Left:
                            basicGrid[position.X, position.Y].LeftSideType = SideType.Exit;
                            position.X -= 1;
                            basicGrid[position.X, position.Y].RightSideType = SideType.Exit;
                            break;
                        case Direction.Right:
                            basicGrid[position.X, position.Y].RightSideType = SideType.Exit;
                            position.X += 1;
                            basicGrid[position.X, position.Y].LeftSideType = SideType.Exit;
                            break;
                        case Direction.Up:
                            basicGrid[position.X, position.Y].TopSideType = SideType.Exit;
                            position.Y -= 1;
                            basicGrid[position.X, position.Y].BottomSideType = SideType.Exit;
                            break;
                        case Direction.Down:
                            basicGrid[position.X, position.Y].BottomSideType = SideType.Exit;
                            position.Y += 1;
                            basicGrid[position.X, position.Y].TopSideType = SideType.Exit;
                            break;
                    }
                }
            }
        }
Example #32
0
        //Connect all completely unconnected points to a connected point, making sure all cells are reachable.
        void ConnectUnconnectedPoints(LevelBlockRequirements[,] basicGrid)
        {
            int hBlocks = Width / BlockWidth, vBlocks = Height / BlockHeight;

            //Store which blocks weren't connected.
            bool[,] isConnected = new bool[hBlocks, vBlocks];
            List<Point> unconnectedPoints = new List<Point>();
            for (int i = 0; i < hBlocks; i++)
            {
                for (int j = 0; j < vBlocks; j++)
                {
                    isConnected[i, j] = ! basicGrid[i, j].IsOnlyWalls();
                    if (! isConnected[i, j])
                        unconnectedPoints.Add(new Point(i, j));
                }
            }

            bool connectedAnythingThisRound;

            while (unconnectedPoints.Count > 0)
            {
                connectedAnythingThisRound = false;

                List<Point> removedUnconnectedPoints = new List<Point>(); //A list to store points we remove as changing a list during foreach is impossible

                unconnectedPoints.Shuffle(); //Shuffle the points so that they connect in a more random way.

                foreach (Point point in unconnectedPoints)
                {
                    int i = point.X, j = point.Y; //Temporary store the x and y of this point.

                    List<Point> possiblePoints = new List<Point>(); //Points to connect to.
                    if (i > 0 && isConnected[i - 1, j])
                        possiblePoints.Add(new Point(i - 1, j));
                    if (i < hBlocks - 1 && isConnected[i + 1, j])
                        possiblePoints.Add(new Point(i + 1, j));
                    if (j > 0 && isConnected[i, j - 1])
                        possiblePoints.Add(new Point(i, j - 1));
                    if (j < vBlocks - 1 && isConnected[i, j + 1])
                        possiblePoints.Add(new Point(i, j + 1));

                    if (possiblePoints.Count != 0)
                    {
                        //Connect this point to a random other one.
                        ConnectPoints(basicGrid, new List<Point>() { point, possiblePoints.GetRandomItem() });
                        isConnected[i, j] = true; //Mark this point as connected.
                        connectedAnythingThisRound = true;
                        removedUnconnectedPoints.Add(point);
                    }
                }

                foreach (Point point in removedUnconnectedPoints)
                    unconnectedPoints.Remove(point);

                //Give up if we couldn't connect anything at all.
                if (! connectedAnythingThisRound)
                    break;
            }
        }