public static SuggestedTournamentRound CreateRandomRound(List<Player> players)
        {
            players.Shuffle();
            var round = new SuggestedTournamentRound();

            var playersSittingOut = CalculatePlayersSittingOutNext(players);
            round.AddPlayersSittingOut(playersSittingOut);
            var playingPlayers = players.Except(playersSittingOut).ToList();
            List<Player> remainingPlayers;
            var match = SuggestedMatch.CreateMatchFromFirstFirstFourPlayers(playingPlayers, out remainingPlayers);
            while (match != null)
            {
                round.AddMatch(match);
                playingPlayers = remainingPlayers;
                match = SuggestedMatch.CreateMatchFromFirstFirstFourPlayers(playingPlayers, out remainingPlayers);

            }

            if (remainingPlayers.Count != 0)
            {
                throw new Exception("Was not expecting any remainig players!");
            }

            return round;
        }
        public void AddWords(params string[] words)
        {
            //var placers = new List<WordPlacers.WordPlacer>{new WordPlacers.Diagonal(),
            //                                               new WordPlacers.Vertical(),
            //                                               new WordPlacers.Horizontal(),
            //                                               new WordPlacers.Reversed(new WordPlacers.Diagonal()),
            //                                               new WordPlacers.Reversed(new WordPlacers.Vertical()),
            //                                               new WordPlacers.Reversed(new WordPlacers.Horizontal()),
            //                                               };

            var placers = new List<WordPlacers.WordPlacer> { new WordPlacers.Horizontal() };

            foreach (var currentWord in words)
            {
                placers.Shuffle();

                foreach (var placer in placers)
                {
                    var result = placer.TryPlaceWord(currentWord, this);
                    if(result!=null)
                    {
                        Console.WriteLine("placed $result->word with {$result->direction} at X:{$result->x} Y:{$result->y}<br/>");
                        break;
                    }
                }
            }
        }
Example #3
0
        /// <summary>Partition dataset user- and item-wise for parallel processing</summary>
        /// <remarks>
        /// Literature:
        /// <list type="bullet">
        ///   <item><description>
        ///     Rainer Gemulla, Peter J. Haas, Erik Nijkamp, Yannis Sismanis:
        ///     Large-Scale Matrix Factorization with Distributed Stochastic Gradient Descent.
        ///     KDD 2011.
        ///     http://www.mpi-inf.mpg.de/~rgemulla/publications/gemulla11dsgd.pdf
        ///   </description></item>
        /// </list>
        /// </remarks>
        /// <returns>a two-dimensional array of index lists, each entry corresponds to one block entry</returns>
        /// <param name='dataset'>a feedback dataset</param>
        /// <param name='num_groups'>the number of groups both users and items are partitioned into</param>
        public static IList<int>[,] PartitionUsersAndItems(this IDataSet dataset, int num_groups)
        {
            // divide rating matrix into blocks
            var user_permutation = new List<int>(Enumerable.Range(0, dataset.MaxUserID + 1));
            var item_permutation = new List<int>(Enumerable.Range(0, dataset.MaxItemID + 1));
            user_permutation.Shuffle();
            item_permutation.Shuffle();

            var blocks = new IList<int>[num_groups, num_groups];
            for (int i = 0; i < num_groups; i++)
                for (int j = 0; j < num_groups; j++)
                    blocks[i, j] = new List<int>();

            for (int index = 0; index < dataset.Count; index++)
            {
                int u = dataset.Users[index];
                int i = dataset.Items[index];

                blocks[user_permutation[u] % num_groups, item_permutation[i] % num_groups].Add(index);
            }

            // randomize index sequences inside the blocks
            for (int i = 0; i < num_groups; i++)
                for (int j = 0; j < num_groups; j++)
                    blocks[i, j].Shuffle();

            return blocks;
        }
Example #4
0
        public void Randomize(Patch patch, Random r)
        {
            // Create list of default teleporter position values
            List<byte[]> coords = new List<byte[]>
            {
                new byte[]{ 0x20, 0x3B }, // Teleporter X, Y (top-left)
                new byte[]{ 0x20, 0x7B },
                new byte[]{ 0x20, 0xBB },
                new byte[]{ 0x70, 0xBB },
                new byte[]{ 0x90, 0xBB },
                new byte[]{ 0xE0, 0x3B },
                new byte[]{ 0xE0, 0x7B },
                new byte[]{ 0xE0, 0xBB }
            };

            // Randomize them
            coords.Shuffle(r);

            // Write the new x-coordinates
            for (int i = 0; i < coords.Count; i++)
            {
                byte[] location = coords[i];
                patch.Add((int)(EMiscAddresses.WarpXCoordinateStartAddress + i), location[0], String.Format("Teleporter {0} X-Pos", i));
            }

            // Write the new y-coordinates
            for (int i = 0; i < coords.Count; i++)
            {
                byte[] location = coords[i];
                patch.Add((int)(EMiscAddresses.WarpYCoordinateStartAddress + i), location[1], String.Format("Teleporter {0} Y-Pos", i));
            }

            // These values will be copied over to $04b0 (y) and $0470 (x), which will be checked
            // for in real time to determine where Mega will teleport to
        }
Example #5
0
        public DataHolder()
        {
            phrases = new List<Phrase> ();

            phrases.Add (new Phrase ("USP", false));
            phrases.Add (new Phrase ("Micro services", false));
            phrases.Add (new Phrase ("Win-Win", false));
            phrases.Add (new Phrase ("Time to market", false));
            phrases.Add (new Phrase ("Perfor-mance", false));
            phrases.Add (new Phrase ("Scalable", false));
            phrases.Add (new Phrase ("Portfolio", false));
            phrases.Add (new Phrase ("24/7", false));
            phrases.Add (new Phrase ("New econo-my", false));
            phrases.Add (new Phrase ("Niche", false));
            phrases.Add (new Phrase ("Upside", false));
            phrases.Add (new Phrase ("Revenue", false));
            phrases.Add (new Phrase ("Supply chain", false));
            phrases.Add (new Phrase ("Call", false));
            phrases.Add (new Phrase ("Web 2.0", false));
            phrases.Add (new Phrase ("The new Face-book", false));
            phrases.Add (new Phrase ("Market share", false));
            phrases.Add (new Phrase ("Stake-holder", false));
            phrases.Add (new Phrase ("Inves-tors", false));
            phrases.Add (new Phrase ("VC", false));
            phrases.Add (new Phrase ("Burn rate", false));
            phrases.Add (new Phrase ("Work group", false));
            phrases.Add (new Phrase ("Market leader", false));
            phrases.Add (new Phrase ("Work load", false));
            phrases.Add (new Phrase ("Work-Life balance", false));

            phrases.Shuffle ();

            Current = this;
        }
        /// <summary>
        /// Gets available hint strings
        /// </summary>
        /// <remarks>Adapted from vimium to give a consistent experience, see https://github.com/philc/vimium/blob/master/content_scripts/link_hints.coffee </remarks>
        /// <param name="hintCount">The number of hints</param>
        /// <returns>A list of hint strings</returns>
        public IList<string> GetHintStrings(int hintCount)
        {
            var hintCharacters = new[] { 's', 'a', 'd', 'f', 'j', 'k', 'l', 'e', 'w', 'c', 'm', 'p', 'g', 'h' };
            var digitsNeeded = (int)Math.Ceiling(Math.Log(hintCount) / Math.Log(hintCharacters.Length));

            var shortHintCount = Math.Floor((Math.Pow(hintCharacters.Length, digitsNeeded) - hintCount) / hintCharacters.Length);
            var longHintCount = hintCount - shortHintCount;

            var hintStrings = new List<string>();

            if (digitsNeeded > 1)
            {
                for (var i = 0; i < shortHintCount; ++i)
                {
                    hintStrings.Add(NumberToHintString(i, hintCharacters, digitsNeeded - 1));
                }
            }

            var start = (int)(shortHintCount * hintCharacters.Length);
            for (var i = start; i < (start + longHintCount); ++i)
            {
                hintStrings.Add(NumberToHintString(i, hintCharacters, digitsNeeded));
            }

            // Note that shuffle is lazy evaluated. Sigh.
            return hintStrings.Shuffle().ToList();
        }
Example #7
0
        private static List<Card> GenerateStartDeck()
        {
            List<Card> startDeck = new List<Card>();
            startDeck.AddRange(GetCardsOfType(54, CardType.Hero, true));
            startDeck.AddRange(GetCardsOfType(15, CardType.ElementalAura, true));
            startDeck.AddRange(GetCardsOfType(15, CardType.PowerAura, true));
            startDeck.AddRange(GetCardsOfType(15, CardType.ShadowAura, true));
            startDeck.AddRange(GetCardsOfType(15, CardType.LightAura, true));
            startDeck.AddRange(GetCardsOfType(15, CardType.TimeAura, true));
            startDeck.AddRange(GetCardsOfType(15, CardType.SkillAura, true));
            startDeck.AddRange(GetCardsOfType(171, CardType.Action, false));
            startDeck.AddRange(GetCardsOfType(108, CardType.Item, true));
            startDeck.AddRange(GetCardsOfType(100, CardType.Spell, true));
            startDeck.AddRange(GetCardsOfType(60, CardType.Quest, false));
            startDeck.AddRange(GetCardsOfType(8, CardType.Boss, false));
            startDeck.AddRange(GetCardsOfType(15, CardType.Mercenary, false));
            startDeck.AddRange(GetCardsOfType(15, CardType.Mercenary, false));
            startDeck.Add(new Slime());
            startDeck.Add(new Slime());
            startDeck.Add(new Slime());
            startDeck.Add(new Slime());
            startDeck.Add(new CaptainFalcon());

            startDeck.Shuffle();

            return startDeck;
        }
        private List<Chromosom> GetListOfChromosomsUsinRuletteMethod(List<Chromosom> population)
        {
            double sumOfAllChromosomsFitnessValues = population.Sum(x => x.SurivatePoints);
            double meanOfChromosomsFitnessValues = sumOfAllChromosomsFitnessValues / population.Count;

            List<Chromosom> tmpPopulation = new List<Chromosom>(population.Count);

            foreach (var chromosom in population)
            {
                int numberOfChromosomsInNewGeneration = (int)Math.Round(chromosom.SurivatePoints / meanOfChromosomsFitnessValues);
                Console.WriteLine("Chomosom: {0} is going to be add {1}-times to new generation", chromosom, numberOfChromosomsInNewGeneration);
                for (int i = 0; i < numberOfChromosomsInNewGeneration; i++)
                {
                    tmpPopulation.Add(chromosom);
                }
            }

            int countDiffence = tmpPopulation.Count - population.Count;
            
            if (countDiffence < 0 )
            {
                var sortedPopulation = population.OrderByDescending(chromosom => chromosom.SurivatePoints);
                tmpPopulation.AddRange(sortedPopulation.Take(Math.Abs(countDiffence)));
            }
            else if (tmpPopulation.Count - population.Count > 0)
            {
                tmpPopulation = tmpPopulation.Shuffle().Take(population.Count).ToList();
            }

            return tmpPopulation;
            // do cross
        }
        public Level Build(int dimension)
        {
            if (dimension == 0)
                return _Level;
            var mapCells = LevelGenerator._BuildMaze(dimension);
            var rooms = new List<MazeCell>();
            var aisles = new List<MazeCell>();
            foreach (var cell in mapCells)
            {
                var walls = cell.Walls;
                var center = cell.GetPosition(_Width, _Height);
                foreach (var wall in walls)
                {
                    var dir = _WallToDirection(wall);
                    _Level.Add(new LevelUnit(Data.LEVEL_UNIT.WALL , center, dir));
                }

                if (cell.IsRoom())
                {
                    rooms.Add(cell);
                }
                else if (cell.HaveWall())
                {
                    aisles.Add(cell);
                }
            }

            _BuildScene(rooms.Shuffle().ToArray(), aisles.Shuffle().ToArray());

            return _Level;
        }
        public void Mutate(Genotype genotype, MutationResults results)
        {
            var neuronIndexA = Random.Range(0, genotype.NeuronCount);
              var neuronGeneA = genotype.NeuronGenes.ElementAt(neuronIndexA);

              var candidates = new List<NeuronGene>(genotype.NeuronGenes);
              candidates.Shuffle();

              NeuronGene neuronGeneB = default(NeuronGene);
              bool foundNeuron = false;
              for (var i = 0; i < candidates.Count; i++) {
            neuronGeneB = candidates[i];

            var exists = genotype.SynapseGenes.Any(s =>
              neuronGeneA.InnovationId == s.fromNeuronId &&
              neuronGeneB.InnovationId == s.toNeuronId);

            if (!exists) {
              foundNeuron = true;
              break;
            }
              }

              if (foundNeuron) {
            var synapseInnovationId = innovations.GetSynapseInnovationId(neuronGeneA.InnovationId, neuronGeneB.InnovationId);
            var synapseGene = new SynapseGene(synapseInnovationId, neuronGeneA.InnovationId, neuronGeneB.InnovationId, true);

            var synapseGenes = new GeneList<SynapseGene>(genotype.SynapseGenes);
            synapseGenes.Add(synapseGene);
            genotype.SynapseGenes = synapseGenes;

            results.addedSynapses += 1;
              }
        }
Example #11
0
        public List<Square> GetMove(Square square)
        {
            var movesList = new List<Square>();

            var move = HorizontalLeftUp(square);
            if (IsSquareValid(move)) movesList.Add(move);

            move = HorizontalLeftDown(square);
            if (IsSquareValid(move)) movesList.Add(move);

            move = HorizontalRightUp(square);
            if (IsSquareValid(move)) movesList.Add(move);

            move = HorizontalRightDown(square);
            if (IsSquareValid(move)) movesList.Add(move);

            move = VerticalUpLeft(square);
            if (IsSquareValid(move)) movesList.Add(move);

            move = VerticalUpRight(square);
            if (IsSquareValid(move)) movesList.Add(move);

            move = VerticalDownLeft(square);
            if (IsSquareValid(move)) movesList.Add(move);

            move = VerticalDownRight(square);
            if (IsSquareValid(move)) movesList.Add(move);

            movesList.RemoveAll(Visited);

            // randomize the order of a list to provide various detours each time
            movesList.Shuffle();

            return movesList;
        }
        public IList<string> GetDayActivity(IList<string> zoo, string killer)
        {
            if (!zoo.Contains(killer))
            {
                return new List<string>();
            }

            var herring = new List<string>(GameResources.Herrings);
            var goodTraits = new List<string>(GameResources.GoodTraits);
            var badTraits = new List<string>(GameResources.BadTraits);
            herring.Shuffle();
            goodTraits.Shuffle();
            badTraits.Shuffle();

            // good and bad traits
            int badIndex = 0;
            int goodIndex = 0;
            var clues = zoo.Select(x =>
                                {
                                    double chance = x == killer ? ChanceBadKillerTrait : ChanceBadFodderTrait;
                                    string trait = Extensions.RandomGenerator.Next(0, 999)/1000.0 < chance
                                        ? badTraits[badIndex++]
                                        : goodTraits[goodIndex++];
                                    return String.Format(trait, x);
                                }).ToList();

            // herrings
            int herringIndex = 0;
            clues.AddRange(zoo.Select(x => String.Format(herring[herringIndex++], x)));

            clues.Shuffle();

            return clues;
        }
Example #13
0
	public static LGcharacter CharacterGen () 
	{
		LGcharacter Baby = LGcharacter.CreateInstance<LGcharacter>();
		List<int> toGen = new List<int>();
		List<int> lastPass = new List<int> ();
		for (int i = 0; i < (int)TraitType.COUNT; i++) {
			Baby.SetTrait ((TraitType)i, kMinTrait);
			toGen.Add (i);
		}
		toGen.Shuffle ();
		int toSpend = kMaxGenPoints;
		while (toGen.Count > 0) {
			TraitType type = (TraitType)toGen [0];
			lastPass.Add (toGen [0]);
			toGen.RemoveAt (0);
			double gaussRoll = RNGesus.PraiseGauss (kMeanTrait, kTraitDev);
			int newVal = (int)gaussRoll;
			if (newVal > kMaxTrait-1) {
				newVal = kMaxTrait-1;
			}
			if (newVal < kMinTrait) {
				newVal = kMinTrait;
			}
			if (newVal > toSpend) {
				newVal = toSpend;
			}
			if (Baby.AddTrait (type, newVal)) {
				toSpend -= newVal;
			}
		}
		// Do one last pass to spend remaining points randomly.
		// Removing stats that are too full. 
		// TODO: Instead, spend these on specialized traits based on the number of unspent points
		/*
		while (toSpend > 0 && lastPass.Count > 0) {
			int roll = RNGesus.Praise (0, lastPass.Count-1);
			if (Baby.AddTrait ((TraitType)lastPass[roll], 1)) {
				toSpend--;
			} else {
				lastPass.RemoveAt (roll);
			}
		}
		*/
		// Set stats to their default values (max for most, min for Toxicity)
		for (int i = 0; i < (int)StatusType.COUNT; i++) {
			Baby.SetStat ((StatusType)i, kMaxStatus);
		}
		Baby.SetStat (StatusType.TOXICITY, kMinStatus);

		// Roll Random Skills
		Dictionary<uint, LGskill> genSkill = LGskillData.Skills;
		Baby._AttackSkill = genSkill [(uint)RNGesus.Praise (0, genSkill.Count)];
		Baby._ClassSkill = genSkill [(uint)RNGesus.Praise (0, genSkill.Count)];
		Baby._UtilitySkill = genSkill [(uint)RNGesus.Praise (0, genSkill.Count)];
		Baby._AugmentSkill = genSkill [(uint)RNGesus.Praise (0, genSkill.Count)];


		return Baby;
	}
Example #14
0
 public void Shuffle_OrderChanges()
 {
     // In theory we could get back the exact same order- really unlikely, particularly with larger collections
     int[] source = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
     List<int> items = new List<int>(source);
     items.Shuffle();
     items.Should().NotEqual(source);
 }
Example #15
0
        public void Shuffle_ShouldPreserveOriginalList()
        {
            var list = new List<int> {1, 2, 3, 4};
            var expected = new List<int>(list);
            list.Shuffle(RandomProvider.GetRandom(2));

            Assert.Equal(expected, list);
        }
 public OneHotRecordProvider(GPUModule gpuModule, List<OneHotRecordReadOnly> records, string id = "", bool shuffleEveryEpoch = false)
 {
     Id = id;
     _records = records;
     GpuModule = gpuModule;
     _shuffle = shuffleEveryEpoch;
     if (_shuffle) _records.Shuffle();
 }
Example #17
0
        public void ListExtensionShuffle_CommonList_EndWithNoExceptions_Test()
        {
            var list = new List<string> {"4","2","7","5","1"};

            list.Shuffle();

            Assert.NotNull(list);
            Assert.Equal(5,list.Count);
        }
Example #18
0
        public void Shuffle_ShouldShuffle()
        {
            var list = new List<int> { 1, 2, 3, 4 };
            var result = list.Shuffle(RandomProvider.GetRandom(2));

            Assert.NotNull(result);
            Assert.Equal(list, result.OrderBy(i => i).ToList());
            Assert.NotEqual(list, result);
        }
Example #19
0
 /// <summary>
 /// Generates a random route.
 /// </summary>
 /// <param name="problem"></param>
 /// <returns></returns>
 public static IRoute DoSolveStatic(IProblem problem)
 {
     List<int> customers = new List<int>();
     for (int customer = 0; customer < problem.Size; customer++)
     {
         customers.Add(customer);
     }
     customers.Shuffle<int>();
     return DynamicAsymmetricRoute.CreateFrom(customers);
 }
 private IEnumerable<List<int>> GetRandomVectors(int n, FastRandom rand) {
   for (int i = 0; i < n; i++) {
     int length = rand.Next(1, 50);
     List<int> cur = new List<int>(length) { 0 };
     for (int j = 0; j < length - 1; j++) {
       cur.Add(rand.Next(-50, 50));
     }
     yield return cur.Shuffle(rand).ToList();
   }
 }
Example #21
0
 public Answersheet(Question q)
 {
     SelectedQuestion = q;
     Answerkeys = new ObservableCollection<Pair<string, bool>>();
     GivenAnswers = new ObservableCollection<string>();
     List<Pair<string, bool>> tAnswer = new List<Pair<string, bool>>(q.Answers);
     tAnswer.Shuffle();
     foreach (Pair<string, bool> answer in tAnswer)
         Answerkeys.Add(new Pair<string, bool>(answer.First, false));
 }
Example #22
0
		protected override async Task<bool> Main()
		{
			if (startZoneId != WorldManager.ZoneId)
			{
				return isDone = true;
			}

			if (ExProfileBehavior.Me.Distance(Location) <= Distance)
			{
				return isDone = true;
			}

			if (HotSpots != null)
			{
				if (Type == MoveToType.Auto)
				{
					Type = MoveToType.RandomPointWithin;
				}

				var locations = new List<HotSpot>(HotSpots);
				if (Location != Vector3.Zero)
				{
					locations.Add(new HotSpot(Location, Distance) {Name = Name});
				}

				destination = locations.Shuffle().First();

				Logger.Verbose(Localization.Localization.ExMoveTo_Random, Location);
			}
			else
			{
				if (Type == MoveToType.Auto)
				{
					Type = MoveToType.StopWithinRange;
				}

				destination = new HotSpot(Location, Distance) {Name = Name};
			}

			var name = !string.IsNullOrWhiteSpace(destination.Name) ? "[" + destination.Name + "] " : string.Empty;

			StatusText = string.Format(Localization.Localization.ExMoveTo_Move, name, destination, Type);

			switch (Type)
			{
				case MoveToType.StopWithinRange:
					await destination.MoveTo(UseMesh);
					break;
				case MoveToType.RandomPointWithin:
					await destination.MoveToPointWithin();
					break;
			}

			return isDone = true;
		}
        public Meta Load()
        {
            List<string> metaServerList = metaServerLocator.GetMetaServerList();
            if (metaServerList == null || metaServerList.Count == 0)
            {
                throw new Exception("No meta server found.");
            }

            List<String> ipPorts = new List<String>(metaServerList);
            ipPorts.Shuffle();

            foreach (string ipPort in ipPorts)
            {
                log.Debug(string.Format("Loading meta from server: {0}", ipPort));

                try
                {
                    string url = string.Format("http://{0}/meta", ipPort);
                    if (metaCache.ReadFullFence() != null)
                    {
                        url += "?version=" + metaCache.ReadFullFence().Version;
                    }

                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                    req.Timeout = config.MetaServerConnectTimeoutInMills + config.MetaServerReadTimeoutInMills;

                    using (HttpWebResponse res = (HttpWebResponse)req.BetterGetResponse())
                    {
                        HttpStatusCode statusCode = res.StatusCode;
                        if (statusCode == HttpStatusCode.OK)
                        {
                            using (var stream = new StreamReader(res.GetResponseStream(), Encoding.UTF8))
                            {
                                string responseContent = stream.ReadToEnd();
                                JsonSerializerSettings settings = new JsonSerializerSettings();
                                settings.NullValueHandling = NullValueHandling.Ignore;
                                metaCache.WriteFullFence(JsonConvert.DeserializeObject<Meta>(responseContent, settings));
                                return metaCache.ReadFullFence();
                            }
                        }
                        else if (statusCode == HttpStatusCode.NotModified)
                        {
                            return metaCache.ReadFullFence();
                        }
                    }

                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
            }
            throw new Exception(string.Format("Failed to load remote meta from {0}", ipPorts));
        }
Example #24
0
        public static void DoWork(List<User> users, IMailer mailer)
        {
            var secrets = new List<User>();
            secrets.AddRange(users);

            //shuffle secrets:
            secrets = secrets.Shuffle(new Random(DateTime.Now.Millisecond)).ToList();

            //shuffle not perfect: check for mistakes
            while (GetError(secrets, users))
            {
                secrets = secrets.Shuffle(new Random(DateTime.Now.Millisecond)).ToList();
            }

            for (int i = 0; i < users.Count; i++)
            {
                var user = users[i];
                //Debug.WriteLine(string.Format("{0} to {1}", user.Email, secrets[i].Name));
                mailer.SendMail(user.Name, user.Email, secrets[i].Name, secrets[i].Wishes);
            }
        }
 private IEnumerable<int> GenerateDiceCards()
 {
     var cards = new List<int>();
     foreach (var item in GameConstants.DiceRollNumber2Chance)
     {
         for (var i = 0; i < item.Value; ++i)
         {
             cards.Add(item.Key);
         }
     }
     return cards.Shuffle();
 }
        public static double CalculateHandValue(IList<Card> myHand, IList<Card> communityCards)
        {
            if (communityCards.Count == 0)
            {
                if ((int) myHand[0].Type < 5 && (int) myHand[1].Type < 5 && myHand[0].Type != myHand[1].Type)
                {
                    return 0;
                }
            }

            double wins = 0;

            Parallel.For(0, Settings.GameSimulationsCount, i =>
            //for (int i = 0; i < Settings.GameSimulationsCount; i++)
            {
                var player1Hand = new List<Card>(myHand);
                var player2Hand = new List<Card>();

                var remainingCommunityCards = new List<Card>();

                var deck = new List<Card>(Deck.AllCards);
                deck.CustomRemoveRange(myHand);
                deck.CustomRemoveRange(communityCards);
                deck = deck.Shuffle().ToList();

                //generate remaining community cards
                for (int j = 0; j < 5 - communityCards.Count; j++)
                {
                    remainingCommunityCards.Add(deck.Deal());
                }

                //add hole/community cards to the AI
                player1Hand.AddRange(communityCards);
                player1Hand.AddRange(remainingCommunityCards);

                //add cards to player2
                player2Hand.Add(deck.Deal());
                player2Hand.Add(deck.Deal());
                player2Hand.AddRange(communityCards);
                player2Hand.AddRange(remainingCommunityCards);

                //compare hands
                if (Helpers.CompareCards(player1Hand, player2Hand) == 1)
                {
                    lock (locker)
                    {
                        wins++;
                    }
                }
            });

            return wins / Settings.GameSimulationsCount;
        }
Example #27
0
 public static Stack<PlayerColorEnum> GetColors()
 {
     Stack<PlayerColorEnum> colors = new Stack<PlayerColorEnum>();
     List<PlayerColorEnum> shuffleList = new List<PlayerColorEnum>();
     foreach (PlayerColorEnum color in Enum.GetValues(typeof(PlayerColorEnum)))
     {
         shuffleList.Add(color);
     }
     shuffleList.Shuffle();
     shuffleList.ForEach(color => colors.Push(color));
     return colors;
 }
Example #28
0
    public static List<Node> GetRandomNodesInRange(Vector3 position, float range)
    {
        List<Node> nodes = new List<Node>();
        Collider[] colliders = Physics.OverlapSphere(position,range) as Collider[];
        foreach(Collider collider in colliders) {
            if(collider.gameObject.tag == "Node") {
                nodes.Add (collider.gameObject.GetComponent<Node>()) ;

            }
        }
        nodes.Shuffle();
        return nodes;
    }
Example #29
0
    //protected override IEnumerable<int> GenerateTraining() {
    //  var x0 = new List<int>() { 1, 2, 3, 4, 5, 100 };
    //  x0.AddRange(ValueGenerator.SampleRandomWithoutRepetition(numbers, 44, rand));
    //  return x0;
    //}

    //protected override IEnumerable<int> GenerateTest() {
    //  return numbers.Except(GenerateTraining());
    //}

    //protected override Tuple<string[], string[]> GenerateInputOutput(IEnumerable<int> x0) {
    //  var input = x0.Select(x => x.ToString()).ToArray();
    //  var output = x0.Select(x => CalcSumOfSquares(x).ToString()).ToArray();
    //  return new Tuple<string[], string[]>(input, output);
    //}

    protected override Tuple<string[], string[]> GenerateInputOutput() {
      FastRandom rand = new FastRandom();
      var x0 = new List<int>() { 1, 2, 3, 4, 5, 100 };
      x0.AddRange(ValueGenerator.SampleRandomWithoutRepetition(numbers, 44, rand));

      x0 = x0.Shuffle(rand).ToList();

      x0.AddRange(numbers.Except(x0));

      var input = x0.Select(x => x.ToString()).ToArray();
      var output = x0.Select(x => CalcSumOfSquares(x).ToString()).ToArray();
      return new Tuple<string[], string[]>(input, output);
    }
Example #30
0
 private static void BuildDeck() {
     Cards = new List<Card>(52);
     foreach (CardSuit s in GetValues(typeof(CardSuit)).Cast<CardSuit>()) {
         foreach (CardValue v in
             GetValues(typeof(CardValue)).Cast<CardValue>()) {
             Cards.Add(new Card(s,v) {
                 IsInPlay = false,
                 IsVisible = false
             });
         }
     }
     Cards.Shuffle();
 }
Example #31
0
        //private List<Constraint> constraints;

        // Automaticall fill lists with mock data
        public MockData()
        {
            campers = new List <Camper>();
            lodges  = new List <Lodge>();
            rooms   = new List <Room>();
            //constraints = new List<Constraint>();
            // Fill camper list with mock data
            campers.Add(new Camper("001", "John", true, false, false, "Male", "Stewart", "Hal", "Barry", "Bruce"));
            campers.Add(new Camper("002", "Stewart", true, false, false, "M", "John", "Hal", "Barry", "Bruce"));
            campers.Add(new Camper("003", "Hal", true, false, false, "male", "John", "Stewart", "Barry", "Bruce"));
            campers.Add(new Camper("004", "Barry", true, false, false, "m", "John", "Stewart", "Hal", "Bruce"));
            campers.Add(new Camper("005", "Bruce", true, false, false, "Male", "John", "Stewart", "Hal", "Barry"));

            campers.Add(new Camper("006", "Diana", false, true, false, "Female", "Kara", "Barbara", "", ""));
            campers.Add(new Camper("007", "Kara", false, true, false, "F", "Diana", "Barabara", "", ""));
            campers.Add(new Camper("008", "Barbara", false, true, false, "female", "Diana", "Kara", "", ""));

            campers.Add(new Camper("009", "Clark", false, false, true, "Male", "Victor", "", "", ""));
            campers.Add(new Camper("010", "Harley", false, false, true, "Female"));
            campers.Add(new Camper("011", "Victor", false, false, true, "Male", "Clark", "", "", ""));
            campers.Add(new Camper("012", "Pamela", false, false, true, "Female"));

            campers.Add(new Camper("013", "Barda", true, true, false, "Female", "Dinah", "Helena", "Zatanna", "Jennifer"));
            campers.Add(new Camper("014", "Dinah", true, true, false, "Female", "Barda", "Helena", "Zatanna", "Jennifer"));
            campers.Add(new Camper("015", "Helena", true, true, false, "Female", "Barda", "Dinah", "Zatanna", "Jennifer"));
            campers.Add(new Camper("016", "Zatanna", true, true, false, "Female", "Barda", "Dinah", "Helena", "Jennifer"));
            campers.Add(new Camper("017", "Jennifer", true, true, false, "Female", "Barda", "Dinah", "Helena", "Zatanna"));

            campers.Add(new Camper("018", "Jaime", true, false, true, "Male"));
            campers.Add(new Camper("019", "Damian", true, false, true, "Male"));
            campers.Add(new Camper("020", "Billy", true, false, true, "Male"));
            campers.Add(new Camper("021", "Arthur", true, false, true, "Male"));
            campers.Add(new Camper("022", "Mera", true, false, true, "Female", "Zatanna", "", "", ""));
            campers.Add(new Camper("023", "Oliver", true, false, true, "Female"));
            campers.Add(new Camper("024", "Ted", true, false, true, "Female"));

            campers.Add(new Camper("025", "Alan", false, true, true, "Male"));
            campers.Add(new Camper("026", "Jay", false, true, true, "Male"));
            campers.Add(new Camper("027", "Dick", false, true, true, "Male"));

            campers.Add(new Camper("028", "Adrianna", true, true, true, "Female"));
            campers.Add(new Camper("029", "Mary", true, true, true, "Female"));
            campers.Add(new Camper("030", "Nura", true, true, true, "Female"));
            campers.Add(new Camper("031", "Artemis", true, true, true, "Female"));

            campers.Add(new Camper("032", "Travis", false, false, false, "Other"));
            campers.Add(new Camper("033", "Jonah", false, false, false, "Other"));
            campers.Add(new Camper("034", "Kent", false, false, false, "Other"));
            campers.Add(new Camper("035", "Carter", false, false, false, "Other"));

            // Fill lodge list with mock data
            lodges.Add(new Lodge("Alpha", 4));
            lodges.Add(new Lodge("Beta", 4));
            lodges.Add(new Lodge("Gamma", 4));
            lodges.Add(new Lodge("Delta", 4));
            lodges.Add(new Lodge("Epsilon", 4));

            lodges.Add((new Lodge("Zeta", 2)));

            lodges.Add(new Lodge("Eta", 3));
            lodges.Add(new Lodge("Theta", 3));

            lodges.Add(new Lodge("Iota", 5));
            lodges.Add(new Lodge("Kappa", 5));
            lodges.Add(new Lodge("Lambda", 4));
            lodges.Add(new Lodge("Mu", 4));
            lodges.Add(new Lodge("Nu", 4));
            lodges.Add(new Lodge("Xi", 4));
            lodges.Add((new Lodge("Omicron", 4)));

            // Fill constraint list with mock data
            //foreach (Camper camper in campers)
            //{
            //	constraints.Add(camper.Constraints);
            //}

            foreach (Lodge lodge in lodges)
            {
                for (int i = 0; i < lodge.Capacity; i++)
                {
                    rooms.Add(new Room(1));
                }
            }
            campers.Shuffle();
        }
Example #32
0
 public static void Shuffle(BotData data, [Variable] List <string> list)
 {
     list.Shuffle(data.Random);
     data.Logger.LogHeader();
     data.Logger.Log("Shuffled the list", LogColors.YellowGreen);
 }
Example #33
0
    private List <Vector2> Astar(Vector2 start, Vector2 target)
    {
        start = Integerize(start); target = Integerize(target);

        List <Vector2> dirs = new List <Vector2> {
            Vector2.up, Vector2.right, Vector2.down, Vector2.left
        };

        List <Vector2> visited           = new List <Vector2>();
        List <Tuple <float, Vector2> > q = new List <Tuple <float, Vector2> >();

        q.Add(new Tuple <float, Vector2>(0, start));

        Vector2 cur;

        for (int i = 0; i < MAX_ITERS; i++)
        {
            dirs.Shuffle();

            //Find best node to go to
            float lowest = float.MaxValue;
            Tuple <float, Vector2> bestnode = new Tuple <float, Vector2>(0, new Vector2(-1, -1));
            foreach (Tuple <float, Vector2> t in q)
            {
                if (t.Item1 < lowest)
                {
                    lowest   = t.Item1;
                    bestnode = t;
                }
            }
            cur = Integerize(bestnode.Item2);
            q.Remove(bestnode);
            visited.Add(cur);

            //find valid nodes to travel to
            foreach (Vector2 d in dirs)   //check in four directions
            {
                Vector2 targetnode = Integerize(cur + d);

                //check to see if target node is valid
                if (!global.grid.IsValidPosition((int)targetnode.x, (int)targetnode.y))
                {
                    continue;
                }
                if (visited.Contains(targetnode))
                {
                    continue;
                }

                //if it is, append to queue
                q.Add(new Tuple <float, Vector2>(Vector2.Distance(targetnode, target), targetnode));
            }

            if (cur == target)
            {
                break;
            }
            if (q.Count == 0)
            {
                break;
            }
        }
        return(visited);
    }
Example #34
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            stopWatch.Start();
            chosed_butoon.Enabled = true;
            this.timer1.Start();
            package        = new List <Question>();
            m_dbConnection = new SQLiteConnection("Data Source=" + "data\\question\\data_" + current_package_name + ".sqlite;Version=3;");
            m_dbConnection.Open();
            sql     = "select * from data_" + current_package_name + "_table";
            command = new SQLiteCommand(sql, m_dbConnection);
            reader  = command.ExecuteReader();
            while (reader.Read())
            {
                key         = reader["key"].ToString();
                value       = reader["value"].ToString();
                repeat_time = Convert.ToInt32(reader["repeat"]);
                package.Add(new Question(key, value, repeat_time));
            }
            list_question_nondistinct = new List <Question>();
            list_question_nondistinct = LearningAssistantTool.create_list_question_nondistinct(package);

            question_chose      = new Question();
            last_question_chose = new Question();

            total_point          = list_question_nondistinct.Count();
            current_right_answer = 0;

            //Console.Clear();
            //Console.WriteLine("Da lam duoc {0}/{1} cau.", current_right_answer, total_point);
            current_complete_question.Text = current_right_answer.ToString() + "\\" + total_point.ToString();
            while (true)
            {
                list_question_nondistinct.Shuffle();
                question_chose = list_question_nondistinct.ElementAt(0);
                if (list_question_nondistinct.Distinct().Count() == 1)
                {
                    break;
                }
                if (!question_chose.equal_q(last_question_chose))
                {
                    break;
                }
                //kiem tra truong hop list chi con 1 loai cau hoi
            }
            last_question_chose = list_question_nondistinct.ElementAt(0);
            package.Shuffle();
            //create list answer
            answer = new List <string>();
            answer.Add(package.ElementAt(0).answer);
            answer.Add(package.ElementAt(1).answer);
            answer.Add(package.ElementAt(2).answer);
            if (answer.Exists(item => item.Equals(question_chose.answer, StringComparison.Ordinal)))
            {
                answer.Add(package.ElementAt(3).answer);
            }
            else
            {
                answer.Add(question_chose.answer);
            }

            //bool user_res = LearningAssistantTool.ask_user(question_chose, answer);

            answer.Shuffle();
            question_content.Text = question_chose.question;
            ans_A.Text            = answer.ElementAt(0);
            ans_B.Text            = answer.ElementAt(1);
            ans_C.Text            = answer.ElementAt(2);
            ans_D.Text            = answer.ElementAt(3);
        }
Example #35
0
        public static bool GenRandomRoom(World world, float x, float y, Wall theWall)
        {
            try
            {
                Random rand = new Random();
                if (rand.Next(1, 60) != 1)
                {
                    return(false);
                }
                //Console.Out.WriteLine("Generating room...");
                List <string> dirs = new List <string>();
                for (int tx = -1; tx <= 1; tx++)
                {
                    for (int ty = -1; ty <= 1; ty++)
                    {
                        WmapTile targetTile = world.Map[(int)x + tx, (int)y + ty];
                        WmapTile thisTile   = world.Map[(int)x, (int)y];
                        if (targetTile.TileId == 0xff)
                        {
                            if (tx == -1 && ty == 0)
                            {
                                dirs.Add("left");
                            }
                            else if (tx == 1 && ty == 0)
                            {
                                dirs.Add("right");
                            }
                            else if (tx == 0 && ty == 1)
                            {
                                dirs.Add("down");
                            }
                            else if (tx == 0 && ty == -1)
                            {
                                dirs.Add("up");
                            }
                        }
                    }
                }
                if (dirs.Count < 1)
                {
                    return(false);
                }
                dirs.Shuffle();
                //Console.Out.WriteLine("Room direction: " + dirs.First());
                float mainX     = x;
                float mainY     = y;
                float entranceX = x;
                float entranceY = y;
                switch (dirs.First())
                {
                case "up":
                    mainX     = x - 6; mainY = y - 8;
                    entranceY = y - 1; break;

                case "down":
                    mainX     = x - 6; mainY = y + 1;
                    entranceY = y + 1; break;

                case "left":
                    mainX     = x - 12; mainY = y - 3;
                    entranceX = x - 1; break;

                case "right":
                    mainX     = x + 1; mainY = y - 3;
                    entranceX = x + 1; break;
                }
                List <WmapTile> addedTiles = new List <WmapTile>();
                for (int ty = (int)mainY; ty <= mainY + 7; ty++)
                {
                    for (int tx = (int)mainX; tx <= mainX + 11; tx++)
                    {
                        WmapTile tTile = world.Map[tx, ty];
                        if (tTile.TileId != 0xff || tTile.ObjType != 0)
                        {
                            //Console.Out.WriteLine("Found collision while generating room!");
                            return(false);
                        }
                        tTile.TileId = world.Map[(int)x, (int)y].TileId;
                        addedTiles.Add(tTile);
                    }
                }
                //Console.Out.WriteLine("Generated tiles, placing...");
                int tileNum = 0;
                for (int ty = (int)mainY; ty <= mainY + 7; ty++)
                {
                    for (int tx = (int)mainX; tx <= mainX + 11; tx++)
                    {
                        WmapTile ctile = addedTiles[tileNum];
                        if ((tx == (int)mainX || tx == (int)mainX + 11 || ty == (int)mainY || ty == (int)mainY + 7) && !(tx == entranceX && ty == entranceY))
                        {
                            //Console.Out.WriteLine("Placed wall");
                            Wall e = new Wall(theWall.ObjectType, XmlDatas.TypeToElement[theWall.ObjectType]);
                            e.Move(tx, ty);
                            world.EnterWorld(e);
                            ctile.ObjType = theWall.ObjectType;
                        }
                        else
                        {
                            //Console.Out.WriteLine("Placed treasure");
                            if (rand.Next(1, 30) == 1)
                            {
                                Entity e = Entity.Resolve(XmlDatas.IdToType["Coral Gift"]);
                                e.Move(tx + 0.5f, ty + 0.5f);
                                world.EnterWorld(e);
                                ctile.ObjType = XmlDatas.IdToType["Coral Gift"];
                            }
                        }
                        world.Map[tx, ty] = ctile;
                    }
                }
                //Console.Out.WriteLine("Placed tiles!");
                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Example #36
0
 private void ShuffleLists()
 {
     Givers.Shuffle();
     Receivers.Shuffle();
 }
Example #37
0
 public void ShuffleCards()
 {
     deckCards.Shuffle();
 }
        private static void PlaceRandomCacti(Dungeon dungeon, RoomHandler currentRoom)
        {
            PrototypeDungeonRoom.RoomCategory roomCategory = currentRoom.area.PrototypeRoomCategory;

            if (currentRoom == null | roomCategory == PrototypeDungeonRoom.RoomCategory.REWARD | currentRoom.IsMaintenanceRoom() |
                string.IsNullOrEmpty(currentRoom.GetRoomName()) | currentRoom.GetRoomName().StartsWith("Boss Foyer") |
                currentRoom.RoomVisualSubtype != 0 | !currentRoom.HasActiveEnemies(RoomHandler.ActiveEnemyType.RoomClear) |
                currentRoom.PrecludeTilemapDrawing)
            {
                return;
            }


            if (Random.value <= 0.8f | currentRoom.GetRoomName().ToLower().StartsWith("expand_west_entrance"))
            {
                List <IntVector2> m_CachedPositions = new List <IntVector2>();
                int MaxCactiCount = 12;
                int MinCactiCount = 6;
                if (Random.value <= 0.3f)
                {
                    MaxCactiCount = 20;
                }
                else if (roomCategory == PrototypeDungeonRoom.RoomCategory.BOSS)
                {
                    MaxCactiCount = 10;
                }

                int X = currentRoom.area.dimensions.x;
                int Y = currentRoom.area.dimensions.y;

                if (X * Y < 100)
                {
                    MinCactiCount = 3;
                    MaxCactiCount = 6;
                }

                if (!string.IsNullOrEmpty(currentRoom.GetRoomName()) && currentRoom.GetRoomName().ToLower().StartsWith("expand_west_canyon1_tiny"))
                {
                    MinCactiCount = 1;
                    MaxCactiCount = 3;
                }

                int CactusCount = Random.Range(MinCactiCount, MaxCactiCount);

                if (!currentRoom.GetRoomName().ToLower().StartsWith("expand_west_entrance"))
                {
                    for (int i = 0; i < CactusCount; i++)
                    {
                        IntVector2?RandomVector = GetRandomAvailableCell(dungeon, currentRoom, m_CachedPositions, ExitClearence: 3, avoidExits: true);

                        List <GameObject> CactiList = new List <GameObject>()
                        {
                            ExpandPrefabs.Cactus_A, ExpandPrefabs.Cactus_B
                        };
                        CactiList = CactiList.Shuffle();

                        if (RandomVector.HasValue)
                        {
                            GameObject Cactus = Object.Instantiate(BraveUtility.RandomElement(CactiList), RandomVector.Value.ToVector3(), Quaternion.identity);
                            Cactus.transform.parent = currentRoom.hierarchyParent;
                            RandomObjectsPlaced++;
                            if (m_CachedPositions.Count <= 0)
                            {
                                break;
                            }
                        }
                        else
                        {
                            RandomObjectsSkipped++;
                        }
                    }
                }
                else
                {
                    List <GameObject> CactiList = new List <GameObject>()
                    {
                        ExpandPrefabs.Cactus_A, ExpandPrefabs.Cactus_B
                    };
                    CactiList = CactiList.Shuffle();

                    m_CachedPositions = new List <IntVector2>()
                    {
                        new IntVector2(34, 49),
                        new IntVector2(29, 43),
                        new IntVector2(16, 43),
                        new IntVector2(2, 19),
                        new IntVector2(49, 17),
                        new IntVector2(9, 23),
                        new IntVector2(40, 23),
                        new IntVector2(30, 20),
                        new IntVector2(22, 29),
                        new IntVector2(31, 31),
                        new IntVector2(14, 14),
                        new IntVector2(14, 37),
                        new IntVector2(37, 14),
                        new IntVector2(37, 37),
                        new IntVector2(33, 2),
                        new IntVector2(33, 10),
                        new IntVector2(3, 17),
                        new IntVector2(2, 34),
                        new IntVector2(14, 20),
                        new IntVector2(16, 39),
                        new IntVector2(31, 38),
                        new IntVector2(49, 34),
                        new IntVector2(38, 29),
                        new IntVector2(21, 21),
                        new IntVector2(20, 32),
                        new IntVector2(31, 22),
                    };
                    m_CachedPositions = m_CachedPositions.Shuffle();
                    for (int i = 0; i < 14; i++)
                    {
                        IntVector2 selectedPosition = BraveUtility.RandomElement(m_CachedPositions);
                        m_CachedPositions.Remove(selectedPosition);
                        m_CachedPositions = m_CachedPositions.Shuffle();
                        GameObject Cactus = Object.Instantiate(BraveUtility.RandomElement(CactiList), (selectedPosition + currentRoom.area.basePosition).ToVector3(), Quaternion.identity);
                        Cactus.transform.SetParent(currentRoom.hierarchyParent);
                        RandomObjectsPlaced++;
                    }
                }
            }
        }
Example #39
0
    public IEnumerable CalculateSpritePoints()
    {
        if (m_wraps != null)
        {
            foreach (var m in m_wraps)
            {
                m.CalculateSpritePoints();
                if (Util.ShouldYield())
                {
                    yield return(null);
                }
            }
        }

        m_sprite_points = new List <Vector3>();
        var mins         = get_mins();
        var maxs         = get_maxs();
        var cur          = new Vector3(mins.x, mins.y);
        var roads_rivers = m_connections.Where(x => x.Connection.ConnectionType == ConnectionType.ROAD || x.Connection.ConnectionType == ConnectionType.SHALLOWRIVER);
        var set          = ArtManager.s_art_manager.GetMapSpriteSet(m_node.ProvinceData.Terrain);

        while (cur.x < maxs.x)
        {
            while (cur.y < maxs.y)
            {
                var pt = cur;
                pt.z = -900;
                RaycastHit hit;

                if (MeshCollider.Raycast(new Ray(pt, Vector3.forward), out hit, 9000))
                {
                    m_sprite_points.Add(new Vector3(pt.x, pt.y, 0));
                }
                cur.y += UnityEngine.Random.Range(0.04f, 0.06f);
            }

            cur.y  = mins.y + UnityEngine.Random.Range(0.04f, 0.06f);
            cur.x += 0.04f;
            if (Util.ShouldYield())
            {
                yield return(null);
            }
        }

        NativeCullNearby.Invoke(m_sprite_points, GetCullPoints(roads_rivers), set.ProvinceEdgeThreshold);
        for (var i = 0; i < m_sprite_points.Count; ++i)
        {
            m_sprite_points[i] += new Vector3(0, 0, -10);
        }

        m_sprite_points.Shuffle();
        var result = new List <Vector3>();

        var cull      = ArtManager.s_art_manager.CurrentArtConfiguration.GetCullChance(m_node.ProvinceData.Terrain);
        var cullcount = Mathf.RoundToInt((1.0f - cull) * m_sprite_points.Count);

        for (var i = 0; i < cullcount; i++)
        {
            result.Add(m_sprite_points[i]);
        }

        m_sprite_points = result;
    }
Example #40
0
        static void Main(string[] args)
        {
            Time.LogAction      += Console.WriteLine;
            Time.LogAction      += s => Debug.WriteLine(s);
            Time.StartLogAction += Console.WriteLine;
            Time.StartLogAction += s => Debug.WriteLine(s);

            if (!Directory.Exists(@".\Networks"))
            {
                Directory.CreateDirectory(@".\Networks");
            }

            List <GrayscaleImage> trainImages;

            using (Time.Capture("Load_Training_Images"))
            {
                trainImages = new List <GrayscaleImage>(ImageLoader.LoadFromFile("train-images.dat", "train-labels.dat"));
            }

            List <GrayscaleImage> testImages;

            using (Time.Capture("Load_Training_Images"))
            {
                testImages = new List <GrayscaleImage>(ImageLoader.LoadFromFile("test-images.dat", "test-labels.dat"));
            }

            NeuralNetwork network = CreateNetwork();

            var imageCount     = 60000;
            var trainBatchSize = 5000;
            var trainrate      = 2.95;

            var batches = trainImages.Shuffle().Split(trainBatchSize).Select(x => x.ToList()).ToList();

            var tasks = new List <Task <NeuralNetwork> >();


            using (Time.Capture("Batch_Train_Networks"))
            {
                var i = 0;
                foreach (var batch in batches)
                {
                    i++;
                    var index = i;
                    tasks.Add(Task.Run(() =>
                    {
                        var nw = CreateNetwork();
                        nw.TrainImageSet(batch, trainrate);
                        nw.Save(@".\Networks\BatchTrainedNetwork_" + index + ".net");
                        return(nw);
                    }));
                }

                Task.WaitAll(tasks.ToArray());
            }


            var networks = tasks.Select(t => t.Result);

            using (Time.Capture("Test_All_Networks"))
            {
                var i = 0;
                foreach (var neuralNetwork in networks)
                {
                    var result = TestImages(neuralNetwork, testImages);
                    i++;
                    Console.WriteLine($"{i:000}.: " + result.ToString());
                }
            }


            //var trainImages = images.Take(imageCount);
            //using (Time.Capture("Network_Training"))
            //{
            //    TrainImageSet(network, trainImages, 2.95);
            //}

            //network.Save(@".\TrainedNetwork5.net");

            //network = NeuronalExtensions.Load(@".\TrainedNetwork5.net");

            // var testImageCount = 100;

            // var testImages = trainImages.Shuffle().Take(testImageCount);
            // using (Time.Capture("Network_Testing"))
            // {
            //     TestImages(network, testImages);
            // }


            Console.WriteLine("-- finish. Press Enter to exit.");
            Console.ReadLine();
        }
Example #41
0
        static void Main(string[] args)
        {
            bool shuffle = true;

            foreach (var s in args)
            {
                if (s == "--noshuffle")
                {
                    shuffle = false;
                }
            }

            if (!Init())
            {
                Console.WriteLine("Not completed...");
                return;
            }

            if (allTeams.Length % 3 != 0)
            {
                Console.WriteLine("Teams nicht durch 3 Teilbar...");
                return;
            }

            var shuffledTeams = new List <Team>(allTeams);

            if (shuffle)
            {
                shuffledTeams.Shuffle();
            }

            var firstCourseCooks  = new List <Team>();
            var secondCourseCooks = new List <Team>();
            var thirdCourseCooks  = new List <Team>();

            var n = shuffledTeams.Count / 3;

            var i = 0;

            while (i < n)
            {
                firstCourseCooks.Add(shuffledTeams[i]);
                ++i;
            }

            while (i < n * 2)
            {
                secondCourseCooks.Add(shuffledTeams[i]);
                ++i;
            }

            while (i < n * 3)
            {
                thirdCourseCooks.Add(shuffledTeams[i]);
                ++i;
            }

            // Appetizer Courses...
            for (i = 0; i < n; i++)
            {
                var course = new Course
                {
                    Type = CourseType.Appetiser,
                    Cook = firstCourseCooks[i]
                };
                course.Guests.Add(secondCourseCooks[(i + 1) % secondCourseCooks.Count]);
                course.Guests.Add(thirdCourseCooks[(i + 2) % thirdCourseCooks.Count]);
                appetizerCourses.Add(course);
            }

            // Main Courses...
            for (i = 0; i < n; i++)
            {
                var course = new Course
                {
                    Type = CourseType.MainCourse,
                    Cook = secondCourseCooks[i]
                };
                course.Guests.Add(firstCourseCooks[(i + 1) % firstCourseCooks.Count]);
                course.Guests.Add(thirdCourseCooks[(i + 2) % thirdCourseCooks.Count]);
                mainCourses.Add(course);
            }

            // Dessert Courses...
            for (i = 0; i < n; i++)
            {
                var course = new Course
                {
                    Type = CourseType.Dessert,
                    Cook = thirdCourseCooks[i]
                };
                course.Guests.Add(secondCourseCooks[(i + 1) % secondCourseCooks.Count]);
                course.Guests.Add(firstCourseCooks[(i + 2) % firstCourseCooks.Count]);
                dessertCourses.Add(course);
            }

            allCourses.AddRange(appetizerCourses);
            allCourses.AddRange(mainCourses);
            allCourses.AddRange(dessertCourses);

            Directory.CreateDirectory("Plan");

            CreatePlan("Vorspeise", "Plan\\VorspeisePlan.txt", appetizerCourses);
            CreatePlan("Hauptspeise", "Plan\\HauptspeisePlan.txt", mainCourses);
            CreatePlan("Dessert", "Plan\\DessertPlan.txt", dessertCourses);


            Directory.CreateDirectory("Mail");

            foreach (var team in allTeams)
            {
                CreateMail(team);
            }

            Console.WriteLine("Done...");
        }
Example #42
0
 public void Shuffle()
 {
     cards.Shuffle();
 }
Example #43
0
        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            Map map = (Map)parms.target;

            if (parms.points <= 0f)
            {
                Log.Error("AnimalInsanity running without points.", false);
                parms.points = (float)((int)(map.strengthWatcher.StrengthRating * 50f));
            }
            float adjustedPoints = parms.points;

            if (adjustedPoints > 250f)
            {
                adjustedPoints -= 250f;
                adjustedPoints *= 0.5f;
                adjustedPoints += 250f;
            }
            IEnumerable <PawnKindDef> source = from def in DefDatabase <PawnKindDef> .AllDefs
                                               where def.RaceProps.Animal && def.combatPower <= adjustedPoints && (from p in map.mapPawns.AllPawnsSpawned
                                                                                                                   where p.kindDef == def && IncidentWorker_AnimalInsanityMass.AnimalUsable(p)
                                                                                                                   select p).Count <Pawn>() >= 3
                                               select def;
            PawnKindDef animalDef;

            if (!source.TryRandomElement(out animalDef))
            {
                return(false);
            }
            List <Pawn> list = (from p in map.mapPawns.AllPawnsSpawned
                                where p.kindDef == animalDef && IncidentWorker_AnimalInsanityMass.AnimalUsable(p)
                                select p).ToList <Pawn>();
            float combatPower = animalDef.combatPower;
            float num         = 0f;
            int   num2        = 0;
            Pawn  pawn        = null;

            list.Shuffle <Pawn>();
            foreach (Pawn current in list)
            {
                if (num + combatPower > adjustedPoints)
                {
                    break;
                }
                IncidentWorker_AnimalInsanityMass.DriveInsane(current);
                num += combatPower;
                num2++;
                pawn = current;
            }
            if (num == 0f)
            {
                return(false);
            }
            string    label;
            string    text;
            LetterDef textLetterDef;

            if (num2 == 1)
            {
                label = "LetterLabelAnimalInsanitySingle".Translate(new object[]
                {
                    pawn.LabelShort
                });
                text = "AnimalInsanitySingle".Translate(new object[]
                {
                    pawn.LabelShort
                });
                textLetterDef = LetterDefOf.ThreatSmall;
            }
            else
            {
                label = "LetterLabelAnimalInsanityMultiple".Translate(new object[]
                {
                    animalDef.GetLabelPlural(-1)
                });
                text = "AnimalInsanityMultiple".Translate(new object[]
                {
                    animalDef.GetLabelPlural(-1)
                });
                textLetterDef = LetterDefOf.ThreatBig;
            }
            Find.LetterStack.ReceiveLetter(label, text, textLetterDef, pawn, null, null);
            SoundDefOf.PsychicPulseGlobal.PlayOneShotOnCamera(map);
            if (map == Find.CurrentMap)
            {
                Find.CameraDriver.shaker.DoShake(1f);
            }
            return(true);
        }
Example #44
0
        public double Train(List <List <SentenceDetectorToken> > sentences, int trainingSteps = 20)
        {
            Data           = new SentenceDetectorModel();
            Data.Weights   = new Dictionary <int, float[]>();
            AverageWeights = new Dictionary <int, float[]>();

            var sw  = new System.Diagnostics.Stopwatch();
            var rng = new Random();

            double precision = 0;

            for (int step = 0; step < trainingSteps; step++)
            {
                sentences.Shuffle();

                sw.Start();

                double correct = 0, total = 0, totalTokens = 0; bool first = true;
                var    filteredSentences = sentences.Where(s => s.Count > 5 && s.Last().IsPunctuation == true);

                foreach (var tokens in filteredSentences)
                {
                    var paddedTokens  = new List <string>();
                    var isSentenceEnd = new List <bool>();
                    if (rng.NextDouble() > 0.1)
                    {
                        var tmp = Enumerable.Reverse(sentences.RandomItem()).Take(2).Reverse();
                        paddedTokens.AddRange(tmp.Select(st => st.Value));
                        isSentenceEnd.AddRange(tmp.Select(st => st.IsSentenceEnd));
                    }
                    else
                    {
                        paddedTokens.Add(SpecialToken.BOS); paddedTokens.Add(SpecialToken.BOS);
                        isSentenceEnd.Add(false); isSentenceEnd.Add(false);
                    }

                    paddedTokens.AddRange(tokens.Select(st => st.Value));
                    isSentenceEnd.AddRange(tokens.Select(st => st.IsSentenceEnd));

                    if (rng.NextDouble() > 0.1)
                    {
                        var tmp = sentences.RandomItem().Take(2);
                        paddedTokens.AddRange(tmp.Select(st => st.Value));
                        isSentenceEnd.AddRange(tmp.Select(st => st.IsSentenceEnd));
                    }
                    else
                    {
                        paddedTokens.Add(SpecialToken.EOS); paddedTokens.Add(SpecialToken.EOS);
                        isSentenceEnd.Add(false); isSentenceEnd.Add(false);
                    }

                    correct += TrainOnSentence(paddedTokens, isSentenceEnd, ref first);;

                    total += tokens.Count(tk => tk.IsSentenceEnd);;

                    totalTokens += tokens.Count;
                }

                precision = correct / total;
                sw.Stop();
                Logger.LogInformation($"{Languages.EnumToCode(Language)} Step {step + 1}/{trainingSteps}: {Math.Round(100 * correct / total, 2)}% at a rate of {Math.Round(1000 * totalTokens / sw.ElapsedMilliseconds, 0) } tokens/second");
                sw.Restart();

                UpdateAverages();
            }

            UpdateAverages(final: true, trainingSteps: trainingSteps);

            FinishTraining();
            return(precision * 100);
        }
Example #45
0
        public static IntVec3 TradeDropSpot(Map map)
        {
            IEnumerable <Building> collection = from b in map.listerBuildings.allBuildingsColonist
                                                where b.def.IsCommsConsole
                                                select b;
            IEnumerable <Building> enumerable = from b in map.listerBuildings.allBuildingsColonist
                                                where b.def.IsOrbitalTradeBeacon
                                                select b;
            Building building = enumerable.FirstOrDefault((Building b) => !map.roofGrid.Roofed(b.Position) && DropCellFinder.AnyAdjacentGoodDropSpot(b.Position, map, false, false));
            IntVec3  position;

            if (building != null)
            {
                position = building.Position;
                IntVec3 result;
                if (!DropCellFinder.TryFindDropSpotNear(position, map, out result, false, false))
                {
                    Log.Error("Could find no good TradeDropSpot near dropCenter " + position + ". Using a random standable unfogged cell.");
                    result = CellFinderLoose.RandomCellWith((IntVec3 c) => c.Standable(map) && !c.Fogged(map), map, 1000);
                }
                return(result);
            }
            List <Building> list = new List <Building>();

            list.AddRange(enumerable);
            list.AddRange(collection);
            list.RemoveAll(delegate(Building b)
            {
                CompPowerTrader compPowerTrader = b.TryGetComp <CompPowerTrader>();
                return(compPowerTrader != null && !compPowerTrader.PowerOn);
            });
            Predicate <IntVec3> validator = (IntVec3 c) => DropCellFinder.IsGoodDropSpot(c, map, false, false);

            if (!list.Any <Building>())
            {
                list.AddRange(map.listerBuildings.allBuildingsColonist);
                list.Shuffle <Building>();
                if (!list.Any <Building>())
                {
                    return(CellFinderLoose.RandomCellWith(validator, map, 1000));
                }
            }
            int num = 8;

            while (true)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    IntVec3 position2 = list[i].Position;
                    if (CellFinder.TryFindRandomCellNear(position2, map, num, validator, out position))
                    {
                        return(position);
                    }
                }
                num = Mathf.RoundToInt((float)num * 1.1f);
                if (num > map.Size.x)
                {
                    goto Block_9;
                }
            }
            return(position);

Block_9:
            Log.Error("Failed to generate trade drop center. Giving random.");
            return(CellFinderLoose.RandomCellWith(validator, map, 1000));
        }
Example #46
0
 public static List <Card> ShuffleDeck(List <Card> deck)
 {
     return(deck.Shuffle());
 }
Example #47
0
        //------------Private Methods------------------------------//

        private void InitTerrain(int terrainSeed, int numberSeed, bool randomNumbers)
        {
            // generate random board

            // construct pool
            List <Terrain> terrainPool = new List <Terrain>(19);

            for (int i = 0; i < 4; i++)
            {
                if (i < 3)
                {
                    terrainPool.Add(Terrain.Hills);
                }
                if (i < 3)
                {
                    terrainPool.Add(Terrain.Mountains);
                }
                terrainPool.Add(Terrain.Pasture);
                terrainPool.Add(Terrain.Fields);
                terrainPool.Add(Terrain.Forest);
            }
            terrainPool.Add(Terrain.Desert);
            List <int> numberPool = new List <int>(valueOrder);

            List <HarborType> harborPool = new List <HarborType>(9);

            harborPool.Add(HarborType.Brick);
            harborPool.Add(HarborType.Grain);
            harborPool.Add(HarborType.Lumber);
            harborPool.Add(HarborType.Ore);
            harborPool.Add(HarborType.Wool);
            for (int i = 0; i < 4; i++)
            {
                harborPool.Add(HarborType.ThreeForOne);
            }

            // shuffles
            terrainPool.Shuffle(terrainSeed);
            harborPool.Shuffle(terrainSeed);
            if (randomNumbers)
            {
                numberPool.Shuffle(numberSeed);
            }

            // place randomized tiles
            bool desertFound = false;

            for (int i = 0; i < placementOrder.Length; i++)
            {
                Tuple <int, int> coords = GetTerrainCoords(placementOrder[i]);
                if (terrainPool[i] == Terrain.Desert)
                {
                    terrain[coords.Item1][coords.Item2] = new Tile(terrainPool[i], 0);
                    desertFound    = true;
                    robberLocation = placementOrder[i]; // place the robber
                }
                else
                {
                    terrain[coords.Item1][coords.Item2] = new Tile(terrainPool[i], numberPool[i - (desertFound ? 1 : 0)]);
                }
            }

            // place harbors random at positions
            for (int i = 0; i < 9; i++)
            {
                this.harbors[i] = new Harbor(harborPool[i], harborEdges[i]);
            }
        }
        private void ResolveOption(int roomsPerRowX, int pathwayWidthX, int roomsPerRowZ, int pathwayWidthZ, ResolveParams rp)
        {
            Map      map       = BaseGen.globalSettings.map;
            int      roomSize  = GetRoomSize(roomsPerRowX, pathwayWidthX, rp.rect.Width);
            int      roomSize2 = GetRoomSize(roomsPerRowZ, pathwayWidthZ, rp.rect.Height);
            ThingDef thingDef  = null;

            if (pathwayWidthX >= 3)
            {
                thingDef = ((rp.faction != null && (int)rp.faction.def.techLevel < 4) ? ThingDefOf.TorchLamp : ThingDefOf.StandingLamp);
            }
            //TerrainDef floorDef = TerrainDef.Named("BrokenAsphalt");
            int num = roomSize;

            for (int i = 0; i < roomsPerRowX - 1; i++)
            {
                CellRect      rect          = new CellRect(rp.rect.minX + num, rp.rect.minZ, pathwayWidthX, rp.rect.Height);
                ResolveParams resolveParams = rp;
                resolveParams.rect = rect;
                //resolveParams.floorDef = floorDef;
                resolveParams.streetHorizontal = false;
                BaseGen.symbolStack.Push("street", resolveParams);
                num += roomSize + pathwayWidthX;
            }
            int num2 = roomSize2;

            for (int j = 0; j < roomsPerRowZ - 1; j++)
            {
                CellRect      rect2          = new CellRect(rp.rect.minX, rp.rect.minZ + num2, rp.rect.Width, pathwayWidthZ);
                ResolveParams resolveParams2 = rp;
                resolveParams2.rect = rect2;
                //resolveParams2.floorDef = floorDef;
                resolveParams2.streetHorizontal = true;
                BaseGen.symbolStack.Push("street", resolveParams2);
                num2 += roomSize2 + pathwayWidthZ;
            }
            num  = 0;
            num2 = 0;
            children.Clear();
            for (int k = 0; k < roomsPerRowX; k++)
            {
                for (int l = 0; l < roomsPerRowZ; l++)
                {
                    Child child = new Child();
                    child.rect  = new CellRect(rp.rect.minX + num, rp.rect.minZ + num2, roomSize, roomSize2);
                    child.gridX = k;
                    child.gridY = l;
                    children.Add(child);
                    num2 += roomSize2 + pathwayWidthZ;
                }
                num += roomSize + pathwayWidthX;
                num2 = 0;
            }
            MergeRandomChildren();
            children.Shuffle();
            for (int m = 0; m < children.Count; m++)
            {
                if (thingDef != null)
                {
                    IntVec3 c = new IntVec3(children[m].rect.maxX + 1, 0, children[m].rect.maxZ);
                    if (rp.rect.Contains(c) && c.Standable(map))
                    {
                        ResolveParams resolveParams3 = rp;
                        resolveParams3.rect           = CellRect.SingleCell(c);
                        resolveParams3.singleThingDef = thingDef;
                        BaseGen.symbolStack.Push("thing", resolveParams3);
                    }
                }
                ResolveParams resolveParams4 = rp;
                resolveParams4.rect = children[m].rect;
                BaseGen.symbolStack.Push("zombieBasePart_outdoors", resolveParams4);
            }
        }
Example #49
0
        private void chosed_butoon_Click(object sender, EventArgs e)
        {
            total_question_asked++;
            //y
            right_ans = answer.FindIndex(a => a == question_chose.answer);
            if (radio_A.Checked)
            {
                index_choosed = 0;
            }
            if (radio_B.Checked)
            {
                index_choosed = 1;
            }
            if (radio_C.Checked)
            {
                index_choosed = 2;
            }
            if (radio_D.Checked)
            {
                index_choosed = 3;
            }

            if (index_choosed == right_ans)
            {
                MessageBox.Show("Đúng rồi nha!", "Succesfull", MessageBoxButtons.OK, MessageBoxIcon.Information);
                list_question_nondistinct.Remove(question_chose);
                current_right_answer++;
                current_complete_question.Text = current_right_answer.ToString() + "\\" + total_point.ToString();
            }
            else
            {
                MessageBox.Show("Sai mất rồi!", "Succesfull", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            //first_question = false;
            if (list_question_nondistinct.Count == 0)
            {
                MessageBox.Show("You was clean package!", "Succesfull", MessageBoxButtons.OK, MessageBoxIcon.Information);
                result.Visible = true;
                begin.Visible  = false;
                stopWatch.Stop();
                TimeSpan ts = stopWatch.Elapsed;
                result_completion_time.Text = String.Format("{0:00}h:{1:00}m:{2:00}s", ts.Hours, ts.Minutes, ts.Seconds) + result_completion_time.Text;

                TimeSpan ts_per_question = new TimeSpan(ts.Ticks / total_point);
                result_sec_per_question.Text = String.Format("{0:00}h:{1:00}m:{2:00}s", ts_per_question.Hours, ts_per_question.Minutes, ts_per_question.Seconds) + result_sec_per_question.Text;

                double p_res = (total_question_asked - total_point) * 100 / total_question_asked;
                p_wrong.Text         = Math.Round(p_res) + p_wrong.Text;
                total_question_asked = 0;
                return;
            }

            while (true)
            {
                list_question_nondistinct.Shuffle();
                question_chose = list_question_nondistinct.ElementAt(0);
                if (list_question_nondistinct.Distinct().Count() == 1)
                {
                    break;
                }
                if (!question_chose.equal_q(last_question_chose))
                {
                    break;
                }
                //kiem tra truong hop list chi con 1 loai cau hoi
            }
            last_question_chose = list_question_nondistinct.ElementAt(0);
            package.Shuffle();
            //create list answer
            answer = new List <string>();
            answer.Add(package.ElementAt(0).answer);
            answer.Add(package.ElementAt(1).answer);
            answer.Add(package.ElementAt(2).answer);
            if (answer.Exists(item => item.Equals(question_chose.answer, StringComparison.Ordinal)))
            {
                answer.Add(package.ElementAt(3).answer);
            }
            else
            {
                answer.Add(question_chose.answer);
            }

            //bool user_res = LearningAssistantTool.ask_user(question_chose, answer);

            answer.Shuffle();
            question_content.Text = question_chose.question;
            ans_A.Text            = answer.ElementAt(0);
            ans_B.Text            = answer.ElementAt(1);
            ans_C.Text            = answer.ElementAt(2);
            ans_D.Text            = answer.ElementAt(3);
            //check emty list question
            //if (list_question_nondistinct.Count == 0) break;
        }
Example #50
0
        /// <summary>
        /// Threading function that takes care of loading.
        /// </summary>
        private static void LoadContent(object ThreadObject)
        {
            var loadingList = new List <ContentPreload>();

            /** UI Textures **/
            loadingList.AddRange(
                CollectionUtils.Select <FileIDs.UIFileIDs, ContentPreload>(
                    Enum.GetValues(typeof(FileIDs.UIFileIDs)),
                    x => new ContentPreload
            {
                ID   = (ulong)((long)x),
                Type = ContentPreloadType.Other
            }
                    )
                );

            ///** Sim textures for CAS **/
            loadingList.AddRange(
                CollectionUtils.Select <FileIDs.UIFileIDs, ContentPreload>(
                    Enum.GetValues(typeof(FileIDs.OutfitsFileIDs)),
                    x => new ContentPreload
            {
                ID   = (ulong)((long)x),
                Type = ContentPreloadType.Other
            }
                    )
                );
            loadingList.AddRange(
                CollectionUtils.Select <FileIDs.UIFileIDs, ContentPreload>(
                    Enum.GetValues(typeof(FileIDs.AppearancesFileIDs)),
                    x => new ContentPreload
            {
                ID   = (ulong)((long)x),
                Type = ContentPreloadType.Other
            }
                    )
                );
            loadingList.AddRange(
                CollectionUtils.Select <FileIDs.UIFileIDs, ContentPreload>(
                    Enum.GetValues(typeof(FileIDs.PurchasablesFileIDs)),
                    x => new ContentPreload
            {
                ID   = (ulong)((long)x),
                Type = ContentPreloadType.Other
            }
                    )
                );
            loadingList.AddRange(
                CollectionUtils.Select <FileIDs.UIFileIDs, ContentPreload>(
                    Enum.GetValues(typeof(FileIDs.ThumbnailsFileIDs)),
                    x => new ContentPreload
            {
                ID   = (ulong)((long)x),
                Type = ContentPreloadType.Other
            }
                    )
                );

            var startTime = DateTime.Now;

            var totalItems = (float)loadingList.Count;

            loadingList.Shuffle();

            var loadingListLength = loadingList.Count;

            for (var i = 0; i < loadingListLength; i++)
            {
                var item = loadingList[i];
                try
                {
                    ContentResource contentItem = null;
                    contentItem = ContentManager.GetResourceInfo(item.ID);

                    switch (item.Type)
                    {
                    case ContentPreloadType.UITexture:
                        /** Apply alpha channel masking & load into GD **/
                        UIElement.StoreTexture(item.ID, contentItem, true, true);
                        break;

                    case ContentPreloadType.UITexture_NoMask:
                        UIElement.StoreTexture(item.ID, contentItem, false, true);
                        break;

                    case ContentPreloadType.Other:
                        ContentManager.TryToStoreResource(item.ID, contentItem);
                        break;
                    }
                }
                catch (Exception)
                {
                }

                PreloadProgress = i / totalItems;
            }

            var endTime = DateTime.Now;

            System.Diagnostics.Debug.WriteLine("Content took " + new TimeSpan(endTime.Ticks - startTime.Ticks).ToString() + " to load");

            PreloadProgress = 1.0f;
        }
    private void BeginInstanceGeneration(int seed)
    {
        int instanceIterations = Iterations;

        instanceIterations = 100;
        Random.InitState(seed);
        //start room
        GameObject start = (Instantiate(StartRoom_Prefab, DungeonWorldPos, Quaternion.identity));

        start.transform.parent = this.transform;
        //Add the startroom exit marker to list
        List <Transform> availableExits = new List <Transform>
        {
            start.gameObject.transform.Find("ExitMarker")
        };

        //mark the spawnpoint
        this.SpawnMarker = start.gameObject.transform.Find("SpawnMarker").transform.position;
        //configure the exit so we can leave the dungeon
        ConfigureDungeonExit(start);
        PlacedPrefabs.Add(start);

        while (instanceIterations > 0)
        {
            //break if we run out of exits before we finish the iterations.
            // note: this should *never* happen.
            // becaue it means we cannot place a boss room.
            if (availableExits.Count == 0)
            {
                break;
            }
            Transform     marker     = availableExits.Pop();
            List <string> partsnames = new List <string>(this.DungeonPrefabs.Keys);
            partsnames.Shuffle();

            bool partFits = false;
            while (!partFits && partsnames.Count > 0)
            {
                string           partName     = partsnames.Pop();
                GameObject       selectedPart = Instantiate(this.DungeonPrefabs[partName]);
                List <Transform> partExits    = selectedPart.GetComponent <DungeonPrefabController>().GetAllExits();
                Transform        usedExit     = null;
                //check each available exit orientation on the new part to see if it collides with existing part
                partFits = TryPlacingPart(selectedPart, marker, out usedExit);
                if (partFits)
                {
                    //handle coincidental connections
                    HandleCoincedentalConnections(partExits, availableExits);
                    PlacedPrefabs.Add(selectedPart);
                    partExits.Remove(usedExit);
                    availableExits.AddRange(partExits);
                }
                else
                {
                    Destroy(selectedPart);
                }
            }
            //no new part fit here, place wall instead
            if (!partFits)
            {
                PlaceWallAtExit(marker);
            }
            instanceIterations--;
        }

        //closing off unused exits at the end of generation
        if (availableExits.Count > 0)
        {
            Transform usedExit = null;
            var       BossRoom = Instantiate(BossRoom_Prefab);
            int       count    = availableExits.Count - 1;

            while (count >= 0)
            {
                if (!bossPlaced)
                {
                    List <Transform> bossExit = BossRoom.GetComponent <DungeonPrefabController>().GetAllExits();
                    var fits = TryPlacingPart(BossRoom, availableExits[count], out usedExit);
                    if (fits)
                    {
                        //print("BOSS ROOM FITS!");
                        PlacedPrefabs.Add(BossRoom);
                        bossPlaced = true;
                        //break;
                    }
                    else
                    {
                        //print("BOSS NO FIT. PLACE WALL");
                        PlaceWallAtExit(availableExits[count]);
                    }
                }
                else
                {
                    //print("JUST PLACING WALLS NOW");
                    PlaceWallAtExit(availableExits[count]);
                }
                count--;
            }
            if (!bossPlaced)
            {
                Debug.Log("Couldnt Place Boss Room!");
            }
        }
        if (this.PlacedPrefabs.Count < 10 || bossPlaced == false)
        {
            Debug.Log("This dungeon is too small. Couldnt Place BOSS ROOM");
            RetryGeneration();
        }
        else
        {
            //In the case we had to regenerate the seed, we restore it in the game controller
            GameData.TriggeredDungeonSeed = Seed;
            this.IsReady = true;
        }


        RemovePlacementColliders();
        //Add and initalise the grammar engine to rewrite the room contents
        var grammarEngine = gameObject.AddComponent <GenerativeGrammar.GrammarEngine>();

        gameObject.AddComponent <DungeonNavBaker>();
    }
Example #52
0
    // SERVER ONLY: sets up turn order, assigns roles, maxHealth, health, and maxHandSize for all players
    void SetupGame()
    {
        // randomizing turn order
        List <int> turnOrderList = new List <int>(Enumerable.Range(1, numberOfPlayers)); // [1,2,3,4] for 4 players

        turnOrderList.Shuffle();

        // constructing the roleList
        List <string> roleList = new List <string>();

        if (numberOfPlayers == 4)
        {
            exBossList.Shuffle();

            roleList.Add("Heroine");
            roleList.Add("StageBoss");
            roleList.Add("StageBoss");
            roleList.Add(exBossList[0]);
        }

        if (numberOfPlayers == 5)
        {
            partnerList.Take(3).ToList().Shuffle();
            stageBossList.Shuffle();
            exBossList.Shuffle();

            roleList.Add("Heroine");
            roleList.Add(partnerList[0]);
            roleList.Add(stageBossList[0]);
            roleList.Add(stageBossList[1]);
            roleList.Add(exBossList[0]);
        }

        // assigning roles
        roleList.Shuffle();
        for (int i = 0; i < numberOfPlayers; i++)
        {
            GameObject.Find("Logic/Players/Player" + turnOrderList[i]).GetComponent <Player>().role = roleList[i];
        }

        // rotating the list so the heroine's playerNumber is at the front
        int heroineIndex = roleList.IndexOf("Heroine");

        turnOrderList = turnOrderList.Skip(heroineIndex).Concat(turnOrderList.Take(heroineIndex)).ToList();

        // serializing turnOrderList
        string turnOrder = "";

        foreach (int i in turnOrderList)
        {
            turnOrder += i;
        }

        List <Player> activePlayers = new List <Player>();

        foreach (int i in turnOrderList)
        {
            activePlayers.Add(GameObject.Find("Logic/Players/Player" + i).GetComponent <Player>());
        }

        // assigning reaction order for each player's events
        foreach (Player player in activePlayers)
        {
            player.updateReactionOrder(activePlayers);
        }

        // assigning health and hand size
        foreach (Player player in activePlayers)
        {
            if (player.role == "Heroine")
            {
                player.maxHealth   = 5;
                player.maxHandSize = 5;
            }
            else
            {
                player.maxHealth   = 4;
                player.maxHandSize = 4;
            }

            player.health = player.maxHealth;
        }

        RpcSetupGame(turnOrder);  // further visual set-up on all clients
    }
Example #53
0
 void Shuffle()
 {
     bag.Shuffle();
 }
Example #54
0
        public void GivePowerScrolls()
        {
            var toGive = new List <Mobile>();
            var rights = GetLootingRights(DamageEntries, HitsMax);

            for (var i = rights.Count - 1; i >= 0; --i)
            {
                var ds = rights[i];

                if (ds.m_HasRight)
                {
                    toGive.Add(ds.m_Mobile);
                }
            }

            if (toGive.Count == 0)
            {
                return;
            }

            toGive.Shuffle();

            for (var i = 0; i < 16; ++i)
            {
                int level;
                var random = Utility.RandomDouble();

                if (random <= 0.1)
                {
                    level = 25;
                }
                else if (random <= 0.25)
                {
                    level = 20;
                }
                else if (random <= 0.45)
                {
                    level = 15;
                }
                else if (random <= 0.70)
                {
                    level = 10;
                }
                else
                {
                    level = 5;
                }

                var m = toGive[i % toGive.Count];

                m.SendLocalizedMessage(1049524); // You have received a scroll of power!
                m.AddToBackpack(new StatCapScroll(225 + level));

                if (m is PlayerMobile pm)
                {
                    for (var j = 0; j < pm.JusticeProtectors.Count; ++j)
                    {
                        var prot = pm.JusticeProtectors[j];

                        if (prot.Map != pm.Map || prot.Kills >= 5 || prot.Criminal ||
                            !JusticeVirtue.CheckMapRegion(pm, prot))
                        {
                            continue;
                        }

                        var chance = VirtueHelper.GetLevel(prot, VirtueName.Justice) switch
                        {
                            VirtueLevel.Seeker => 60,
                            VirtueLevel.Follower => 80,
                            VirtueLevel.Knight => 100,
                            _ => 0
                        };

                        if (chance > Utility.Random(100))
                        {
                            prot.SendLocalizedMessage(1049368); // You have been rewarded for your dedication to Justice!
                            prot.AddToBackpack(new StatCapScroll(225 + level));
                        }
                    }
                }
            }
        }
Example #55
0
        public virtual void TestSimple()
        {
            int numNodes = TestUtil.NextInt32(Random, 1, 10);

            double runTimeSec = AtLeast(3);

            int minDocsToMakeTerms = TestUtil.NextInt32(Random, 5, 20);

            int maxSearcherAgeSeconds = TestUtil.NextInt32(Random, 1, 3);

            if (VERBOSE)
            {
                Console.WriteLine("TEST: numNodes=" + numNodes + " runTimeSec=" + runTimeSec + " maxSearcherAgeSeconds=" + maxSearcherAgeSeconds);
            }

            Start(numNodes, runTimeSec, maxSearcherAgeSeconds);

            List <PreviousSearchState> priorSearches = new List <PreviousSearchState>();
            List <BytesRef>            terms         = null;

            while (Time.NanoTime() < endTimeNanos)
            {
                bool doFollowon = priorSearches.Count > 0 && Random.Next(7) == 1;

                // Pick a random node; we will run the query on this node:
                int myNodeID = Random.Next(numNodes);

                NodeState.ShardIndexSearcher localShardSearcher;

                PreviousSearchState prevSearchState;

                if (doFollowon)
                {
                    // Pretend user issued a followon query:
                    prevSearchState = priorSearches[Random.Next(priorSearches.Count)];

                    if (VERBOSE)
                    {
                        Console.WriteLine("\nTEST: follow-on query age=" + ((Time.NanoTime() - prevSearchState.SearchTimeNanos) / 1000000000.0));
                    }

                    try
                    {
                        localShardSearcher = m_nodes[myNodeID].Acquire(prevSearchState.Versions);
                    }
                    catch (SearcherExpiredException see)
                    {
                        // Expected, sometimes; in a "real" app we would
                        // either forward this error to the user ("too
                        // much time has passed; please re-run your
                        // search") or sneakily just switch to newest
                        // searcher w/o telling them...
                        if (VERBOSE)
                        {
                            Console.WriteLine("  searcher expired during local shard searcher init: " + see);
                        }
                        priorSearches.Remove(prevSearchState);
                        continue;
                    }
                }
                else
                {
                    if (VERBOSE)
                    {
                        Console.WriteLine("\nTEST: fresh query");
                    }
                    // Do fresh query:
                    localShardSearcher = m_nodes[myNodeID].Acquire();
                    prevSearchState    = null;
                }

                IndexReader[] subs = new IndexReader[numNodes];

                PreviousSearchState searchState = null;

                try
                {
                    // Mock: now make a single reader (MultiReader) from all node
                    // searchers.  In a real shard env you can't do this... we
                    // do it to confirm results from the shard searcher
                    // are correct:
                    int docCount = 0;
                    try
                    {
                        for (int nodeID = 0; nodeID < numNodes; nodeID++)
                        {
                            long          subVersion = localShardSearcher.GetNodeVersions()[nodeID];
                            IndexSearcher sub        = m_nodes[nodeID].Searchers.Acquire(subVersion);
                            if (sub == null)
                            {
                                nodeID--;
                                while (nodeID >= 0)
                                {
                                    subs[nodeID].DecRef();
                                    subs[nodeID] = null;
                                    nodeID--;
                                }
                                throw new SearcherExpiredException("nodeID=" + nodeID + " version=" + subVersion);
                            }
                            subs[nodeID] = sub.IndexReader;
                            docCount    += subs[nodeID].MaxDoc;
                        }
                    }
                    catch (SearcherExpiredException see)
                    {
                        // Expected
                        if (VERBOSE)
                        {
                            Console.WriteLine("  searcher expired during mock reader init: " + see);
                        }
                        continue;
                    }

                    IndexReader   mockReader   = new MultiReader(subs);
                    IndexSearcher mockSearcher = new IndexSearcher(mockReader);

                    Query query;
                    Sort  sort;

                    if (prevSearchState != null)
                    {
                        query = prevSearchState.Query;
                        sort  = prevSearchState.Sort;
                    }
                    else
                    {
                        if (terms == null && docCount > minDocsToMakeTerms)
                        {
                            // TODO: try to "focus" on high freq terms sometimes too
                            // TODO: maybe also periodically reset the terms...?
                            TermsEnum termsEnum = MultiFields.GetTerms(mockReader, "body").GetIterator(null);
                            terms = new List <BytesRef>();
                            while (termsEnum.Next() != null)
                            {
                                terms.Add(BytesRef.DeepCopyOf(termsEnum.Term));
                            }
                            if (VERBOSE)
                            {
                                Console.WriteLine("TEST: init terms: " + terms.Count + " terms");
                            }
                            if (terms.Count == 0)
                            {
                                terms = null;
                            }
                        }

                        if (VERBOSE)
                        {
                            Console.WriteLine("  maxDoc=" + mockReader.MaxDoc);
                        }

                        if (terms != null)
                        {
                            if (Random.NextBoolean())
                            {
                                query = new TermQuery(new Term("body", terms[Random.Next(terms.Count)]));
                            }
                            else
                            {
                                string t = terms[Random.Next(terms.Count)].Utf8ToString();
                                string prefix;
                                if (t.Length <= 1)
                                {
                                    prefix = t;
                                }
                                else
                                {
                                    prefix = t.Substring(0, TestUtil.NextInt32(Random, 1, 2));
                                }
                                query = new PrefixQuery(new Term("body", prefix));
                            }

                            if (Random.NextBoolean())
                            {
                                sort = null;
                            }
                            else
                            {
                                // TODO: sort by more than 1 field
                                int what = Random.Next(3);
                                if (what == 0)
                                {
                                    sort = new Sort(SortField.FIELD_SCORE);
                                }
                                else if (what == 1)
                                {
                                    // TODO: this sort doesn't merge
                                    // correctly... it's tricky because you
                                    // could have > 2.1B docs across all shards:
                                    //sort = new Sort(SortField.FIELD_DOC);
                                    sort = null;
                                }
                                else if (what == 2)
                                {
                                    sort = new Sort(new SortField[] { new SortField("docid", SortFieldType.INT32, Random.NextBoolean()) });
                                }
                                else
                                {
                                    sort = new Sort(new SortField[] { new SortField("title", SortFieldType.STRING, Random.NextBoolean()) });
                                }
                            }
                        }
                        else
                        {
                            query = null;
                            sort  = null;
                        }
                    }

                    if (query != null)
                    {
                        try
                        {
                            searchState = AssertSame(mockSearcher, localShardSearcher, query, sort, prevSearchState);
                        }
                        catch (SearcherExpiredException see)
                        {
                            // Expected; in a "real" app we would
                            // either forward this error to the user ("too
                            // much time has passed; please re-run your
                            // search") or sneakily just switch to newest
                            // searcher w/o telling them...
                            if (VERBOSE)
                            {
                                Console.WriteLine("  searcher expired during search: " + see);
                                Console.Out.Write(see.StackTrace);
                            }
                            // We can't do this in general: on a very slow
                            // computer it's possible the local searcher
                            // expires before we can finish our search:
                            // assert prevSearchState != null;
                            if (prevSearchState != null)
                            {
                                priorSearches.Remove(prevSearchState);
                            }
                        }
                    }
                }
                finally
                {
                    m_nodes[myNodeID].Release(localShardSearcher);
                    foreach (IndexReader sub in subs)
                    {
                        if (sub != null)
                        {
                            sub.DecRef();
                        }
                    }
                }

                if (searchState != null && searchState.SearchAfterLocal != null && Random.Next(5) == 3)
                {
                    priorSearches.Add(searchState);
                    if (priorSearches.Count > 200)
                    {
                        priorSearches.Shuffle();
                        priorSearches.SubList(100, priorSearches.Count).Clear();
                    }
                }
            }

            Finish();
        }
        void GamePrepare()
        {
            //_cards.Clear();
            _cardsPool.Shuffle();

            if (hasTimer)
            {
                _timeController.GameTimeLimit = gameDuration;
            }

            if (!gameAlreadyPrepared)
            {
                gameAlreadyPrepared = true;

                string cardPrefab = _resources.Prefabs.Find(x => x.category == PrefabCategory.MemoryCardPrefab).name;

                for (int i = 0; i < qntMatches * numAnswers; i++)
                {
                    GameObject gObj = Instantiate(Resources.Load <GameObject>(cardPrefab)) as GameObject;

                    if (Container != null)
                    {
                        gObj.transform.SetParent(Container);
                    }

                    gObj.GetComponent <MemoryCard>().Initialize();

                    _cards.Add(gObj.GetComponent <MemoryCard>());
                }
            }

            List <Vector2> list = new List <Vector2>();

            for (int i = 0; i < qntMatches; i++)
            {
                for (int j = 0; j < numAnswers; j++)
                {
                    Vector2 pos;

                    if (j < _cardsPool[i].Count)
                    {
                        if (_cardsPool[i].ElementAtOrDefault(j) != null)
                        {
                            pos = new Vector2(i, j);
                        }
                        else
                        {
                            pos = new Vector2(i, 0);
                        }
                    }
                    else
                    {
                        pos = new Vector2(i, 0);
                    }

                    list.Add(pos);
                }
            }

            list.Shuffle();

            for (int i = 0; i < _cards.Count; i++)
            {
                _cards[i].ResetCard();
                _cards[i].SetAttributes((int)list[i].x, _cardsPool[(int)list[i].x][(int)list[i].y], rotationDuration);

                /*if(_cards[i].cardFace.name.Contains("klm"))
                 *  _cb = backs.Find(x => x.id == "KLM").sprite;
                 * else if (_cards[i].cardFace.name.Contains("af"))
                 *  _cb = backs.Find(x => x.id == "AF").sprite;
                 * else if (_cards[i].cardFace.name.Contains("dl"))
                 *  _cb = backs.Find(x => x.id == "DL").sprite;
                 * else if (_cards[i].cardFace.name.Contains("gol"))
                 *  _cb = backs.Find(x => x.id == "GOL").sprite;
                 */

                _cards[i].SetBack(_cardBack);
            }

            List <GridPiece> gridPieces = _grids[currentGrid].GetAllPieces();

            for (int i = 0; i < _cards.Count; i++)
            {
                _cards[i].transform.localPosition = gridPieces[i].position;
            }

            if (LockCards != null)
            {
                LockCards();
            }
        }
Example #57
0
        static void Main(string[] args)
        {
            //Integers
            List <int> iNums = new List <int>(new int[] { 4, 12, 4, 3, 5, 6, 7, 6, 12 });
            //Strings
            List <string> Names = new List <string>(new string[]
                                                    { "Rick", "Glenn", "Rick", "Carl", "Michonne", "Rick", "Glenn" });
            //Llist of char
            Random            randNum  = new Random();
            LinkedList <char> llfloats = new LinkedList <char>();

            while (llfloats.Count < 1000)
            {
                llfloats.AddLast((char)randNum.Next('A', 'Z' + 1));
            }
            //chars in string
            string TestString = "This is a test string, do not panic!!!!!!!!";

            //Checks for ordering on Popular
            List <int> lowFirst  = new List <int>(new int[] { 6, 8, 8, 2, 9, 9 });
            List <int> highFirst = new List <int>(new int[] { 6, 9, 9, 2, 8, 8 });

            //Shuffle Bias Testing
            string alphabet = "abcdefghijk";

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Categorize testing");

            //Check int, Categorize
            foreach (KeyValuePair <int, int> scan in iNums.Categorize())
            {
                Console.WriteLine(scan.Key.ToString("d3") + " x " + scan.Value.ToString("d5"));
            }
            Console.WriteLine();
            //Check string, Categorize
            foreach (KeyValuePair <string, int> scan in Names.Categorize())
            {
                Console.WriteLine(scan.Key + " x " + scan.Value.ToString("d5"));
            }
            Console.WriteLine();
            //Check linked list and char, Categorize
            foreach (KeyValuePair <char, int> scan in llfloats.Categorize())
            {
                Console.WriteLine(scan.Key + " x " + scan.Value.ToString("d5"));
            }
            Console.WriteLine();
            //check string, Categorize
            foreach (KeyValuePair <char, int> scan in TestString.Categorize())
            {
                Console.WriteLine(scan.Key + " x " + scan.Value.ToString("d5"));
            }
            Console.WriteLine();

            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Popular testing");

            //Check int, Popular
            Console.WriteLine($"Int test: {iNums.Popular()}");
            Console.WriteLine();
            //Check string, Popular
            Console.WriteLine($"String test: {Names.Popular()}");
            Console.WriteLine();
            //Check char linked list, Popular
            Console.WriteLine($"Char test, linked list: {llfloats.Popular()}");
            Console.WriteLine();
            //Check char string, Popular
            Console.WriteLine($"Char test, string: {TestString.Popular()}");
            Console.WriteLine();
            //Check order of appearance, Popular
            Console.WriteLine($"Low int first test: {lowFirst.Popular()}");
            Console.WriteLine();
            Console.WriteLine($"High int first test: {highFirst.Popular()}");
            Console.WriteLine();

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Shuffle testing");

            //Check int, Shuffle
            foreach (int scan in iNums.Shuffle())
            {
                Console.Write($"{scan}, ");
            }
            Console.WriteLine(); Console.WriteLine();
            //Check string, shuffle
            foreach (string scan in Names.Shuffle())
            {
                Console.Write($"{scan}, ");
            }
            Console.WriteLine(); Console.WriteLine();
            //Check linked list and char, shuffle
            foreach (char scan in llfloats.Shuffle())
            {
                Console.Write($"{scan}, ");
            }
            Console.WriteLine(); Console.WriteLine();
            //check string, shuffle
            foreach (char scan in TestString.Shuffle())
            {
                Console.Write($"{scan}, ");
            }
            Console.WriteLine(); Console.WriteLine();


            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine("Shuffle bias Testing\nInitial string is alphabet");

            List <char> shuffled = alphabet.Shuffle().ToList();
            Dictionary <char, List <int> > dict = new Dictionary <char, List <int> >();

            foreach (char c in alphabet)
            {
                dict[c] = new List <int>();
            }

            for (int i = 0; i < 10000000; i++)
            {
                shuffled = alphabet.Shuffle().ToList();
                for (int c = 0; c < shuffled.Count; c++)
                {
                    dict[shuffled[c]].Add(c);
                }
            }

            foreach (KeyValuePair <char, List <int> > kvp in dict)
            {
                double avg = kvp.Value.Average();
                Console.WriteLine($"Key: {kvp.Key}, Avg: {avg.ToString("F3")}, Deviation: {((dict.Count / 2 - avg) / (dict.Count / 2)).ToString("F3")}");
            }

            //Wait to close
            Console.ReadLine();
        }
Example #58
0
    // Start is called before the first frame update
    void Start()
    {
        string DatabaseName = "Cluedo_DB.s3db";
        string filepath     = Application.dataPath + "/Plugins/" + DatabaseName;

        conn = "URI=file:" + filepath;
        Debug.Log("Stablishing connection to: " + conn);
        dbconn = new SqliteConnection(conn);
        dbconn.Open();
        IDbCommand dbcmd = dbconn.CreateCommand();
        string     query = "SELECT * FROM Arguments WHERE challengId = " + challengeId;

        dbcmd.CommandText = query;
        IDataReader reader = dbcmd.ExecuteReader();

        while (reader.Read())
        {
            if (reader.GetInt32(2) == 1)
            {
                question = reader.GetString(3);
            }
            else if (reader.GetInt32(2) == 2)
            {
                correctWord = reader.GetString(3);
            }
        }

        question     = question.Replace("(_)", "_________");
        correctWords = correctWord.Split(' ');
        Debug.Log("Number of words:" + correctWords.Length);
        questionText.text = question;
        //create letter sockets
        selectedIndexes = new List <int>();
        socketButtons   = new List <Button>();
        for (int i = 0; i < correctWords.Length; i++)
        {
            RectTransform horizontalPanel = (RectTransform)Instantiate(horizontalPanelPrefab);
            horizontalPanel.transform.SetParent(answerVerticalPanel, false);
            horizontalPanel.transform.localScale = new Vector3(1, 1, 1);
            for (int j = 0; j < correctWords[i].Length; j++)
            {
                selectedIndexes.Add(-1);
                GameObject letterSocket = (GameObject)Instantiate(socketButtonPrefab);
                if (correctWords[i].Length > 9)
                {
                    float space       = correctWords[i].Length * 20;
                    float socketWidth = (1000 - space) / correctWords[i].Length;
                    letterSocket.GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, socketWidth);
                }
                letterSocket.transform.SetParent(horizontalPanel, false);
                Button tempSocket = letterSocket.GetComponent <Button>();
                int    index      = socketButtons.Count;
                tempSocket.onClick.AddListener(() => SocketButtonClicked(index));
                socketButtons.Add(tempSocket);
            }
        }

        //create option buttons
        correctWordNoSpaces = correctWord.Replace(" ", "");
        correctWordNoSpaces = correctWordNoSpaces.ToUpper();
        optionLetters       = new List <char>();
        for (int i = 0; i < correctWordNoSpaces.Length; i++)
        {
            optionLetters.Add(correctWordNoSpaces[i]);
        }
        int nAdicionalLetters = Mathf.CeilToInt(correctWordNoSpaces.Length / 2.5f);

        for (int i = 0; i < nAdicionalLetters; i++)
        {
            optionLetters.Add(GetRandomLetter());
        }
        optionLetters.Shuffle();
        optionButtons         = new List <Button>();
        selectedOptionButtons = new List <bool>();
        for (int i = 0; i < optionLetters.Count; i++)
        {
            GameObject optionButton = (GameObject)Instantiate(optionButtonPrefab);
            optionButton.transform.SetParent(optionsPanel, false);
            optionButton.transform.localScale = new Vector3(1, 1, 1);
            optionButton.GetComponentInChildren <TextMeshProUGUI>().text = optionLetters[i].ToString();
            Button tempButton = optionButton.GetComponentInChildren <Button>();
            int    index      = i;
            tempButton.onClick.AddListener(() => OptionButtonClicked(index));
            selectedOptionButtons.Add(false);
            optionButtons.Add(tempButton);
        }
        checkButton.GetComponent <Button>().onClick.AddListener(() => CheckButtonClicked());
    }
Example #59
0
        private List <Machine> RandomMachineHourScheduleGenerationWithReference(List <Machine> previous, int load,
                                                                                out bool success)
        {
            // Current hour schedule uses reference from previous hour schedule
            List <Machine> hourClone         = StaticOperations.CloneMachineList(previous);
            double         previousTotalLoad = previous.Sum(machine => machine.CurrentOutputPower);

            // If power demand decreased
            bool currentSuccess = false;

            if (load < previousTotalLoad)
            {
                // Check if power demand is feasable with current machine setup
                double totalMinimumPower = CalculateMinimumAchievablePower(previous, maximumHourChanges);
                double totalMaximumPower = CalculateMaximumAchievablePower(previous, maximumHourChanges);
                if (!(totalMaximumPower > load && totalMinimumPower < load))
                {
                    List <int> stoppableMachineIndices = GetStoppableMachineIndices(previous);
                    List <int> machinesToStop          = CalculateOptimalTerminateSequence(totalMaximumPower, totalMinimumPower,
                                                                                           stoppableMachineIndices, hourClone, load);
                    if (machinesToStop != null)
                    {
                        foreach (int startIndex in machinesToStop)
                        {
                            hourClone[startIndex].CurrentOutputPower = 0;
                        }
                        currentSuccess = true;
                    }
                    else
                    {
                        currentSuccess = false;
                    }
                }
                else
                {
                    currentSuccess = true;
                }
            }
            // If power demand increased
            else
            {
                // Check if power demand is feasable with current machine setup
                double totalMinimumPower = CalculateMinimumAchievablePower(previous, maximumHourChanges);
                double totalMaximumPower = CalculateMaximumAchievablePower(previous, maximumHourChanges);
                if (!(totalMaximumPower > load && totalMinimumPower < load))
                {
                    List <int> startableMachineIndices = GetStartableMachineIndices(previous);
                    List <int> machinesToStart         = CalculateOptimalStartSequence(totalMaximumPower, totalMinimumPower,
                                                                                       startableMachineIndices, hourClone, load);
                    if (machinesToStart != null)
                    {
                        foreach (int startIndex in machinesToStart)
                        {
                            hourClone[startIndex].CurrentOutputPower = hourClone[startIndex].MaximumOutputPower;
                        }
                        currentSuccess = true;
                    }
                    else
                    {
                        currentSuccess = false;
                    }
                }
                else
                {
                    currentSuccess = true;
                }
            }
            if (currentSuccess == false)
            {
                success = false;
                return(hourClone);
            }

            double totalLoad = hourClone.Sum(machine => machine.CurrentOutputPower);

            if (totalLoad > load)
            {
                while (totalLoad > load)
                {
                    double change = random.NextDouble() * (totalLoad - load);
                    if (totalLoad - load < 1)
                    {
                        change = totalLoad - load;
                    }
                    List <int> lowerableMachineIndices = GetLowerableMachineIndices(hourClone, previous);
                    lowerableMachineIndices.Shuffle();
                    int    index = lowerableMachineIndices[0];
                    double maximumAllowedDecrease = GetMaximumMachineDecrease(hourClone[index], previous[index], maximumHourChanges[index]);
                    change     = change > maximumAllowedDecrease ? maximumAllowedDecrease : change;
                    totalLoad -= change;
                    hourClone[index].CurrentOutputPower -= change;
                }
            }
            else
            {
                while (totalLoad < load)
                {
                    double change = random.NextDouble() * (load - totalLoad);
                    if (load - totalLoad < 1)
                    {
                        change = load - totalLoad;
                    }
                    List <int> incresableMachineIndices = GetIncreasableMachineIndices(hourClone, previous);
                    incresableMachineIndices.Shuffle();
                    int    index = incresableMachineIndices[0];
                    double maximumAllowedIncrease = GetMaximumMachineIncrease(hourClone[index], previous[index], maximumHourChanges[index]);
                    change     = change > maximumAllowedIncrease ? maximumAllowedIncrease : change;
                    totalLoad += change;
                    hourClone[index].CurrentOutputPower += change;
                }
            }

            success = totalLoad == load;
            return(hourClone);
        }
Example #60
0
        private static void Place(IEnumerable <Submarine> subs, ItemContainer regeneratedContainer = null, float difficultyModifier = DefaultDifficultyModifier)
        {
            if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient)
            {
                DebugConsole.ThrowError("Clients are not allowed to use AutoItemPlacer.\n" + Environment.StackTrace.CleanupStackTrace());
                return;
            }

            List <Item> spawnedItems = new List <Item>(100);

            int itemCountApprox         = MapEntityPrefab.List.Count() / 3;
            var containers              = new List <ItemContainer>(70 + 30 * subs.Count());
            var prefabsWithContainer    = new List <ItemPrefab>(itemCountApprox / 3);
            var prefabsWithoutContainer = new List <ItemPrefab>(itemCountApprox);
            var removals = new List <ItemPrefab>();

            // generate loot only for a specific container if defined
            if (regeneratedContainer != null)
            {
                containers.Add(regeneratedContainer);
            }
            else
            {
                foreach (Item item in Item.ItemList)
                {
                    if (!subs.Contains(item.Submarine))
                    {
                        continue;
                    }
                    if (item.GetRootInventoryOwner() is Character)
                    {
                        continue;
                    }
                    containers.AddRange(item.GetComponents <ItemContainer>());
                }
                containers.Shuffle(Rand.RandSync.Server);
            }

            foreach (MapEntityPrefab prefab in MapEntityPrefab.List)
            {
                if (!(prefab is ItemPrefab ip))
                {
                    continue;
                }

                if (ip.ConfigElement.Elements().Any(e => string.Equals(e.Name.ToString(), typeof(ItemContainer).Name.ToString(), StringComparison.OrdinalIgnoreCase)))
                {
                    prefabsWithContainer.Add(ip);
                }
                else
                {
                    prefabsWithoutContainer.Add(ip);
                }
            }

            var validContainers = new Dictionary <ItemContainer, PreferredContainer>();

            prefabsWithContainer.Shuffle(Rand.RandSync.Server);
            // Spawn items that have an ItemContainer component first so we can fill them up with items if needed (oxygen tanks inside the spawned diving masks, etc)
            for (int i = 0; i < prefabsWithContainer.Count; i++)
            {
                var itemPrefab = prefabsWithContainer[i];
                if (itemPrefab == null)
                {
                    continue;
                }
                if (SpawnItems(itemPrefab))
                {
                    removals.Add(itemPrefab);
                }
            }
            // Remove containers that we successfully spawned items into so that they are not counted in in the second pass.
            removals.ForEach(i => prefabsWithContainer.Remove(i));
            // Another pass for items with containers because also they can spawn inside other items (like smg magazine)
            prefabsWithContainer.ForEach(i => SpawnItems(i));
            // Spawn items that don't have containers last
            prefabsWithoutContainer.Shuffle(Rand.RandSync.Server);
            prefabsWithoutContainer.ForEach(i => SpawnItems(i));

            if (OutputDebugInfo)
            {
                var subNames = subs.Select(s => s.Info.Name).ToList();
                DebugConsole.NewMessage($"Automatically placed items in { string.Join(", ", subNames) }:");
                foreach (string itemName in spawnedItems.Select(it => it.Name).Distinct())
                {
                    DebugConsole.NewMessage(" - " + itemName + " x" + spawnedItems.Count(it => it.Name == itemName));
                }
            }

            if (GameMain.GameSession?.Level != null &&
                GameMain.GameSession.Level.Type == LevelData.LevelType.Outpost &&
                GameMain.GameSession.StartLocation?.TakenItems != null)
            {
                foreach (Location.TakenItem takenItem in GameMain.GameSession.StartLocation.TakenItems)
                {
                    var matchingItem = spawnedItems.Find(it => takenItem.Matches(it));
                    if (matchingItem == null)
                    {
                        continue;
                    }
                    var containedItems = spawnedItems.FindAll(it => it.ParentInventory?.Owner == matchingItem);
                    matchingItem.Remove();
                    spawnedItems.Remove(matchingItem);
                    foreach (Item containedItem in containedItems)
                    {
                        containedItem.Remove();
                        spawnedItems.Remove(containedItem);
                    }
                }
            }
#if SERVER
            foreach (Item spawnedItem in spawnedItems)
            {
                Entity.Spawner.CreateNetworkEvent(spawnedItem, remove: false);
            }
#endif
            bool SpawnItems(ItemPrefab itemPrefab)
            {
                if (itemPrefab == null)
                {
                    string errorMsg = "Error in AutoItemPlacer.SpawnItems - itemPrefab was null.\n" + Environment.StackTrace.CleanupStackTrace();
                    DebugConsole.ThrowError(errorMsg);
                    GameAnalyticsManager.AddErrorEventOnce("AutoItemPlacer.SpawnItems:ItemNull", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
                    return(false);
                }
                bool success = false;

                foreach (PreferredContainer preferredContainer in itemPrefab.PreferredContainers)
                {
                    if (preferredContainer.SpawnProbability <= 0.0f || preferredContainer.MaxAmount <= 0)
                    {
                        continue;
                    }
                    validContainers = GetValidContainers(preferredContainer, containers, validContainers, primary: true);
                    if (validContainers.None())
                    {
                        validContainers = GetValidContainers(preferredContainer, containers, validContainers, primary: false);
                    }
                    foreach (var validContainer in validContainers)
                    {
                        var newItems = SpawnItem(itemPrefab, containers, validContainer, difficultyModifier);
                        if (newItems.Any())
                        {
                            spawnedItems.AddRange(newItems);
                            success = true;
                        }
                    }
                }
                return(success);
            }
        }