public Game(GameBoard gameBoard, Dice dice) { this.gameBoard = gameBoard; this.dice = dice; this.players = new List<Player>(); this.shuffler = new Shuffler<Player>(); }
public void Shuffle_NullCollection_ThrownArgumentNullException() { var words = GetWordsArray(); var shlr = new Shuffler<string>(); SystemTime.Set(DateTime.MinValue); var ex = Assert.Catch<ArgumentNullException>(() => shlr.Shuffle(null)); StringAssert.Contains("Ссылка", ex.Message); }
public void ShuffleReturnsSameNumberOfItems() { List<Player> nonShuffledPlayers = new List<Player>(); nonShuffledPlayers.Add(new Player("Horse")); nonShuffledPlayers.Add(new Player("Car")); Shuffler<Player> shuffler = new Shuffler<Player>(); IEnumerable<Player> shuffledPlayers = shuffler.Shuffle(nonShuffledPlayers); Assert.AreEqual(nonShuffledPlayers.Count, shuffledPlayers.Count()); }
public CardStorage GetCardStorage() { var wordFact = new WordFactory(); var shuffler = new Shuffler<string>(); var cutter = new Cutter<string>(); var cardFact = new CardFactory(10, shuffler, cutter); var words = wordFact.GetAllWords(); var cards = cardFact.GetCards(words); return new CardStorage(words, cards); }
private void AssertProperShuffling(List<Player> nonShuffledPlayers) { List<IEnumerable<Player>> shuffledLists = new List<IEnumerable<Player>>(); Shuffler<Player> shuffler = new Shuffler<Player>(); for (Int32 i = 0; i < 100; i++) { shuffledLists.Add(shuffler.Shuffle(nonShuffledPlayers)); } IEnumerable<string> firstItems = shuffledLists.Select(l => l.First().Name).Distinct(); Assert.AreEqual(nonShuffledPlayers.Count, firstItems.Count()); }
private static void TestShuffling() { var shuffler = new Shuffler(new Random()); double[] array = new double[] { 1, 2, 3, 4, 5, 6, 7, 8 }; PrintArray(array); for (int i = 0; i < 10; i++) { shuffler.Shuffle(array); Console.WriteLine(); PrintArray(array); } }
public int retrieve() { if (count == 0) { Shuffler.Shuffle(buffer); } var element = buffer[count++]; if (count == buffer.Length) { count = 0; } return(element); }
public void Shuffle_Always_ReturnsShuffledCollection() { SystemTime.Set(DateTime.MinValue); var words = GetWordsArray(); var shlr = new Shuffler<string>(); var shuffled = shlr.Shuffle(words).ToArray(); CheckEquipotentOfCollections(words, shuffled); // в теории, существует вероятность, что на какой-либо машине с данными time1 и time2 тест // вернет одинаковые коллекции, так как существует вероятность что Random зависит // не только от начального значения Seed, а еще и от окружения и может вернуть // эквивалентные ряды псевдослучайных чисел при различных начальных значениях Seed CollectionAssert.AreNotEqual(words, shuffled); }
public void ShufflingDeckWithThreeCardsReturnsDeckWithTheCardsInADifferentOrder() { var deck = Cards.With(AceOfClubs(), TwoOfClubs(), ThreeOfClubs()); var randomNumberGeneratorMock = new Mock <IRandomNumberGenerator>(); randomNumberGeneratorMock.Setup(x => x.Get(0, 3)).Returns(1); randomNumberGeneratorMock.Setup(x => x.Get(0, 2)).Returns(1); randomNumberGeneratorMock.Setup(x => x.Get(0, 1)).Returns(0); var shuffler = new Shuffler(randomNumberGeneratorMock.Object); var shuffledDeck = shuffler.Shuffle(deck); var expectedDeck = Cards.With(TwoOfClubs(), ThreeOfClubs(), AceOfClubs()); Assert.That(shuffledDeck, Is.EqualTo(expectedDeck)); }
public Dealer(Deck deck) { string excMsg = _excHead + "Stack.SET - "; if (_deck == null) { throw new NotExistent(excMsg + "given deck is null!"); } _deck = deck; _shuffler = new Shuffler(); _behaviours = Cards.Shuffling.Factory.buildHandedRandomly(); foreach (Cards.Shuffling.Behaviour behaviour in _behaviours) { _shuffler.add(behaviour); } // loop } // method
public void Train(Network.Network network, List <double[]> x, List <double[]> y, double trainDataRatio) { var toBeTaken = (int)(x.Count * trainDataRatio); var trainX = x.Take(toBeTaken).ToList(); var devX = DenseMatrix.OfColumnArrays(x.Skip(toBeTaken)); var trainY = y.Take(toBeTaken).ToList(); var devY = DenseMatrix.OfColumnArrays(y.Skip(toBeTaken)); for (int i = 0; i < _epochs; i++) { _logger.Log($"Epoch {i:D4} started."); var(randomTrainX, randomTrainY) = Shuffler.Shuffle(_randomSeed, trainX, trainY); var trainXBatches = SplitList(randomTrainX, _minibatch).ToList(); var trainYBatches = SplitList(randomTrainY, _minibatch).ToList(); for (var j = 0; j < trainXBatches.Count; j++) { var xBatch = trainXBatches[j]; var yBatch = trainYBatches[j]; var xBatchMatrix = DenseMatrix.OfColumnArrays(xBatch); var yBatchMatrix = DenseMatrix.OfColumnArrays(yBatch); var inBatchPred = network.Forward(xBatchMatrix); if (j % 500 == 0 || j + 1 == trainXBatches.Count) { var inBatchmse = _costFunction.Get(yBatchMatrix, inBatchPred).RowSums().Sum(); var inBatchprecision = Metrics.GetPrecision(yBatchMatrix, inBatchPred); _logger.Log($" Batch: {j + 1:D4}/{trainXBatches.Count()}, #Samples: {xBatch.Count} Cost: {inBatchmse:F3}, Precision: {inBatchprecision:P0}"); } Backward(network, yBatchMatrix); } var pred = network.Forward(devX); var mse = _costFunction.Get(devY, pred).RowSums().Sum(); var precision = Metrics.GetPrecision(devY, pred); _logger.Log($"Epoch {i:D4} finished: Cost: {mse:F3}, Precision: {precision:P0}"); _logger.Log(); } }
public Board(IList <Card> deck, Shuffler shuffler) { for (int i = 0; i < 4; ++i) { board[i] = new Card[13]; for (int j = 0; j < 13; ++j) { board[i][j] = deck[13 * i + j]; if (board[i][j].Rank == 1) { board[i][j] = null; } } } Shuffler = shuffler; ShuffleCount = 0; }
void AssignItemsToScenes(Item[] items, Scene[] scenes) { int sceneIndex = 0; Shuffler shuffler = new Shuffler(); shuffler.Shuffle(items); shuffler.Shuffle(scenes); foreach (Item item in items) { scenes[sceneIndex].AddItemToArray(item); sceneIndex++; if (sceneIndex > scenes.Length) { sceneIndex = 0; } } }
void AssignNPCsToScenes(NonPlayerCharacter[] characters, Scene[] scenes) { int sceneCounter = 0; Shuffler shuffler = new Shuffler(); shuffler.Shuffle(characters); shuffler.Shuffle(scenes); foreach (NonPlayerCharacter character in characters) //For every character in the randomly shuffled array { scenes[sceneCounter].AddNPCToArray(character); //Assign a character to a scene sceneCounter += 1; //Increment sceneCounter if (sceneCounter >= scenes.Length) //If the counter is above the number of scenes cycle to the first scene. { sceneCounter = 0; } } }
private void Awake() { _camera = FindObjectOfType <Camera>(); _camTransform = _camera.transform; _lineCircle = FindObjectOfType <LineCircle>(); _shuffler = FindObjectOfType <Shuffler>(); _snapToBounds = FindObjectOfType <SnapToBounds>(); _lineCircle.OnPatternChanged += HandlePatternChanged; _targetFovSize = FovToSize(_camera.fieldOfView, _snapToBounds.PerspectiveCenterDistance); _fovSize = _targetFovSize; _orbitReference = new GameObject("Orbit Reference").transform; _orbitReference.position = new Vector3(0f, 0f, _snapToBounds.PerspectiveCenterDistance); UpdateCameraPosition(); }
private void InitCardHolder(GameStorage gameStorage) { var level1 = ConvertCardDtoListToCardList(gameStorage.Level1Cards); var level2 = ConvertCardDtoListToCardList(gameStorage.Level2Cards); var level3 = ConvertCardDtoListToCardList(gameStorage.Level3Cards); var shuffler = new Shuffler <Card>(); var shuffle1 = shuffler.Shuffle(level1); var shuffle2 = shuffler.Shuffle(level2); var shuffle3 = shuffler.Shuffle(level3); var inactiveCardsRepository = new InactiveCardRepository(shuffle1, shuffle2, shuffle3); var activeCardsRepository = new ActiveCardRepository(); CardHolder = new CardHolder(activeCardsRepository, inactiveCardsRepository); }
public void BimodalProgression(int count, int meanFactor, int stdDev, int error) { var random = new RandomDistribution(42); var shuffler = new Shuffler(42); var data = new List <double>(); for (int i = 0; i < count; i++) { data.AddRange(random.Gaussian(30, 0, stdDev)); data.AddRange(random.Gaussian(70, (i + 1) * meanFactor, stdDev)); shuffler.Shuffle(data, i * 100, 100); } var indexes = detector.GetChangePointIndexes(data.ToArray(), 20); Check100(count, error, indexes); }
public void Solve() { var ret = new StringBuilder(); var cCases = int.Parse(ReadLine()); var fFirstCase = true; ReadLine(); for (var i = 0; i < cCases; i++) { if (!fFirstCase) { ret.Append(Environment.NewLine); } fFirstCase = false; var shuffler = new Shuffler(); ret.Append(shuffler.Solve()); } Write(ret.ToString()); }
public void TestBurningCards() { Deck deck = Shuffler.GetShuffledDeck(); Assert.AreEqual(52, deck.RemainingCards); deck.BurnCard(); Assert.AreEqual(51, deck.RemainingCards); // This burns more cards than are remaining in the deck. // Make sure it doesn't error out, when burning cards that don't exist in the deck. for (int i = 0; i < 52; i++) { deck.BurnCard(); } Assert.AreEqual(0, deck.RemainingCards); }
public void SetShuffler(Shuffler shuffler) { if (this.shuffler == shuffler) { return; } if (this.shuffler != null) { this.shuffler.RandomModeAdded -= OnShufflerChanged; this.shuffler.RandomModeRemoved -= OnShufflerChanged; } this.shuffler = shuffler; this.shuffler.RandomModeAdded += OnShufflerChanged; this.shuffler.RandomModeRemoved += OnShufflerChanged; UpdateActions(); }
public void HyndmanFanPartitioningHeapsQuantileEstimatorTest() { double[] fullSource = { 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66 }; var probabilities = Enumerable.Range(0, 101).Select(x => (Probability)(x / 100.0)).ToArray(); var types = new[] { HyndmanFanType.Type1, HyndmanFanType.Type2, HyndmanFanType.Type3, HyndmanFanType.Type4, HyndmanFanType.Type5, HyndmanFanType.Type6, HyndmanFanType.Type7, HyndmanFanType.Type8, HyndmanFanType.Type9, }; var comparer = new AbsoluteEqualityComparer(1e-2); var shuffler = new Shuffler(new Random(42)); for (int n = 1; n <= fullSource.Length; n++) { double[] source = fullSource.Take(n).ToArray(); var sample = new Sample(source); foreach (var type in types) { for (int i = 0; i < probabilities.Length; i++) { var probability = probabilities[i]; var hyEstimator = new HyndmanFanQuantileEstimator(type); double expectedValue = hyEstimator.GetQuantile(sample, probability); var phEstimator = new PartitioningHeapsMovingQuantileEstimator(n, probability, type); shuffler.Shuffle(source); foreach (double value in source) { phEstimator.Add(value); } double actualValue = phEstimator.GetQuantile(); if (!comparer.Equals(expectedValue, actualValue)) { Output.WriteLine($"n = {n}, type = {type}, p = {probability}: E = {expectedValue}, A = {actualValue}"); } Assert.Equal(expectedValue, actualValue, comparer); } } } }
private void InitCardHolder(GameStorage gameStorage) { var level1 = ConvertCardDtoListToCardList(gameStorage.Level1Cards); var level2 = ConvertCardDtoListToCardList(gameStorage.Level2Cards); var level3 = ConvertCardDtoListToCardList(gameStorage.Level3Cards); var shuffler = new Shuffler<Card>(); var shuffle1 = shuffler.Shuffle(level1); var shuffle2 = shuffler.Shuffle(level2); var shuffle3 = shuffler.Shuffle(level3); var inactiveCardsRepository = new InactiveCardRepository(shuffle1, shuffle2, shuffle3); var activeCardsRepository = new ActiveCardRepository(); CardHolder = new CardHolder(activeCardsRepository, inactiveCardsRepository); }
public IEnumerable<Card> GetShuffledDeck() { const int DECK_SIZE = 52; Shuffler[] deck = new Shuffler[DECK_SIZE]; Random random = new Random(DateTime.Now.Millisecond); for (int i = 0; i < DECK_SIZE; i++) { deck[i].Key = i; deck[i].Value = random.Next(); } var shuffledDeck = from c in deck orderby c.Value select new Card() { Face = (CardFace)(c.Key % 13), Suit = (CardSuit)(c.Key / 13) }; return shuffledDeck.ToList(); }
public void StartGame(Random rng) { DistributeHuts(rng); // Shuffle Player Order Names = Shuffler.Shuffle <string>(Names, rng).ToList <string>(); for (int i = 0; i < Names.Count; i++) { Players.Add(new Player(this, i, Names[i])); } // Assign 1 clan to each player List <Clan> avail = Clans.ToList <Clan>(); foreach (Player p in Players) { int chosen = rng.Next(avail.Count()); p.HiddenClan = avail[chosen]; avail.RemoveAt(chosen); } CurrentPlayer = Players.Last(); NewTurn(); }
public void Shuffle_RunedAtDifferentTime_RetunsOtherShuffle() { var words = GetWordsArray(); var shlr = new Shuffler<string>(); var time1 = DateTime.MinValue; var time2 = DateTime.MinValue.AddTicks(1); SystemTime.Set(time1); var shuffled1 = shlr.Shuffle(words).ToArray(); SystemTime.Set(time2); var shuffled2 = shlr.Shuffle(words).ToArray(); CheckEquipotentOfCollections(shuffled1, shuffled2); // в теории, существует вероятность, что на какой-либо машине с данными time1 и time2 тест // вернет одинаковые коллекции, так как существует вероятность что Random зависит // не только от начального значения Seed, а еще и от окружения и может вернуть // эквивалентные ряды псевдослучайных чисел при различных начальных значениях Seed CollectionAssert.AreNotEqual(shuffled1, shuffled2); }
public MainWindow() { InitializeComponent(); // Initialize seed to random value seedField.Text = new Random().Next().ToString(); // Create shuffler and populate logic options shuffler = new Shuffler(); if (customLogicCheckBox.Checked) { shuffler.LoadOptions(customLogicPath.Text); } else { shuffler.LoadOptions(); } LoadOptionControls(shuffler.GetOptions()); }
protected override void ProcessRecord() { var Data = DataXml; if (Data == null && DataCsv != null) { try { WriteVerbose("Xmlifying CSV data"); Data = ShuffleHelper.StringToXmlSerialized(DataCsv); } catch (Exception ex) { WriteError(new ErrorRecord(ex, "StringToXmlSerialized", ErrorCategory.ReadError, Definition)); } } try { WriteDebug("Importing"); var dataList = new Dictionary <string, XmlDocument> { { string.Empty, Data } }; var result = Shuffler.QuickImport(new ShuffleContainer(this), Definition, dataList, ShuffleListener, Folder, true); var output = new ShuffleImportResult { Created = result.created, Updated = result.updated, Skipped = result.skipped, Deleted = result.deleted, Failed = result.failed }; WriteObject(output); } catch (Exception ex) { WriteError(new ErrorRecord(ex, "QuickImport", ErrorCategory.ReadError, Definition)); } }
private void btnStart_Click(object sender, EventArgs e) { // Use this method to confirm the random shuffler produces the expected hand distribution. rtbResults.Clear(); SortedList <PokerHandValues, int> handsDealt = new SortedList <PokerHandValues, int>(); int handsToDeal = Convert.ToInt32(txtHandsToDeal.Text); for (int i = 0; i < handsToDeal; i++) { Deck deck = Shuffler.GetShuffledDeck(); PokerHand hand = new PokerHand(""); for (int j = 0; j < 5; j++) { Card card = deck.TakeNextCard(); hand.AddCard(card.Value, card.Suit); } if (!handsDealt.ContainsKey(hand.Value)) { handsDealt.Add(hand.Value, 0); } handsDealt[hand.Value]++; } rtbResults.Clear(); foreach (KeyValuePair <PokerHandValues, int> keyValuePair in handsDealt) { rtbResults.Text += string.Format("{0}:\t {1}\t {2}", keyValuePair.Key, keyValuePair.Value, (Convert.ToDouble(keyValuePair.Value) / Convert.ToDouble(handsToDeal) * 100)); rtbResults.Text += Environment.NewLine; } }
private void RemoveItems(Individual <bool> individual) { Shuffler shuffler = new Shuffler(this.seed); List <int> order; if (this.seed == null) { order = shuffler.GenereteShuffledOrder(populationSize, new Random()); } else { order = shuffler.GenereteShuffledOrder(populationSize, new Random(this.seed.Value)); } foreach (var geneIndex in order) { individual.Genotype[geneIndex] = false; if (isValid(individual)) { break; } } }
// create sequence of trials based on condition public void createTrialSequence() { var rnd = new System.Random(); // randomize correlations within each block for (int block = 0; block < (maxTrials / trialsPerBlock); block++) { //create new set of correlations List <float> correlations = new List <float>(); var rng = Enumerable.Range(-10, 21); foreach (float n in rng) { correlations.Add(n / 10); } Shuffler.Shuffle(correlations, rnd); for (int trial = 0; trial < trialsPerBlock; trial++) { actualCorr.Add(correlations[trial]); } } rnd = new System.Random(); Shuffler.Shuffle(samplesizes, rnd); // assign sample size to each trial based on condition for (int trial = 0; trial < maxTrials; trial++) { if (condition == 0) { int ind = (trial / trialsPerBlock) % 3; sampleSize.Add(samplesizes[ind]); } else { sampleSize.Add(samplesizes[trial % 3]); } } }
public static void Shuffle_Ctor_ShouldWork(int lvCount, List <int> groupSizes, CancellationTokenSource cancellationTokenSource) { var shuffler = new Shuffler(lvCount, groupSizes, cancellationTokenSource); //Checking if shuffle result field is correct Assert.True(shuffler.ShuffleResult != null && shuffler.ShuffleResult.Count == 0); //Checking if groups field is correct for (int i = 0; i < groupSizes.Count; i++) { int actualGroupCount = shuffler.Groups.Count(g => g.Size == groupSizes[i]); int expectedGroupCount = groupSizes.Count(s => s == groupSizes[i]); Assert.Equal(expectedGroupCount, actualGroupCount); } //Checking if students field is correct for (int i = 1; i < groupSizes.Sum(); i++) { int studentCount = shuffler.Students.Count(s => s.Id == i && s.Label == s.Id.ToString()); Assert.Equal(1, studentCount); } }
//Instantiates the 'magnets', private void CreateAnswerMagnets(string correctAnswer) { Shuffler shuffler = new Shuffler(); char[] answerCharArray = correctAnswer.ToCharArray(); shuffler.Shuffle <char>(answerCharArray); //Generates a random order for the characters for (int i = 0; i < correctAnswer.Length; i++) { //Instantiate and reposition GameObject letter = Instantiate(letterPrefab, centreSpawnPoint.transform.position, Quaternion.identity); letter.transform.SetParent(centreSpawnPoint.transform); letter.transform.localPosition = GenerateSpawnPoint(centreSpawnPoint); //Assign a letter Text letterText = letter.GetComponent <Text> (); letterText.text = answerCharArray [i].ToString(); //Assign Random Colour Color colour = new Color(Random.value, Random.value, Random.value, 1.0f); letterText.color = colour; } }
public Dictionary <Student, Student> Shuffle(Student[] students) { int ops = Math.Max(Rounds, 1); Shuffler shuffler = new Shuffler(students); for (int r = 0; r < ops; r++) { shuffler.Shuffle(); } // check for self-feeds inside of the graph while (!shuffler.Intact()) { shuffler.Shuffle(); ops++; } Console.WriteLine($"Shuffle operations {ops}"); return(shuffler.ToDict()); }
public static void Shuffle_ShouldWork(int lvCount, List <int> groupSizes, List <List <List <int> > > expectedIndexes) { //Creating the shuffler var shuffler = new Shuffler(lvCount, groupSizes.ToList(), null); //Shuffling twice to check if variables that store shuffle state/result are cleared when shuffle is started for (int i = 0; i < 2; i++) { shuffler.Shuffle(); } //Checking if shuffle result is correct after the shuffle var expected = new List <List <List <Student> > >(); foreach (var lv in expectedIndexes) { var convertedLv = new List <List <Student> >(); foreach (var group in lv) { var convertedGroup = group.Select(i => shuffler.Students.First(s => s.Id == i)).ToList(); convertedLv.Add(convertedGroup); } expected.Add(convertedLv); } var actual = shuffler.ShuffleResult; if (expected.Count != actual.Count) { throw new Exception("Expected and actual lv count aren't the same!"); } for (int i = 0; i < expected.Count; i++) { if (new LvCombination(expected[i]).CompareTo(actual[i]) == false) { throw new Exception($"Expected and actual student sitting combinations combinations for lv {i + 1} aren't the same!"); } } }
public void TestShufflerCards() { var deckToShuffle = CardDeckGenerator.GenerateCardDeck(); var deckToCompare = CardDeckGenerator.GenerateCardDeck(); //OK, so trying to test nondeterministic methods is deterministically impossible. With that said, //the best solution I can think of at the moment is to shuffle the deck, if it matches with the reference list, shuffle it again. Repeat that process //until the chances of it returning the same deck for all those times is statistically zero. var shuffledDeck = Shuffler.ShuffleCards(deckToShuffle); bool differenceFound = false; for (int tries = 0; tries < 100; tries++) { //Compare each card with the original for (int i = 0; i < deckToCompare.Count; i++) { if (deckToCompare[i].Id != deckToShuffle[i].Id) { differenceFound = true; break; } } //break if a difference is found if (differenceFound) { break; } //If a difference is not found, shuffle the cards again shuffledDeck = Shuffler.ShuffleCards(shuffledDeck); } Assert.IsTrue(differenceFound); }
protected override void ProcessRecord() { var Data = DataXml; if (Data == null && DataCsv != null) { try { WriteVerbose("Xmlifying CSV data"); Data = ShuffleHelper.StringToXmlSerialized(DataCsv); } catch (Exception ex) { WriteError(new ErrorRecord(ex, "StringToXmlSerialized", ErrorCategory.ReadError, Definition)); } } try { WriteDebug("Importing"); var container = (IExecutionContainer) new ShuffleContainer(this); var result = Shuffler.QuickImport(container, Definition, Data, ShuffleListener, Folder, true); var output = new ShuffleImportResult { Created = result.Item1, Updated = result.Item2, Skipped = result.Item3, Deleted = result.Item4, Failed = result.Item5 }; WriteObject(output); } catch (Exception ex) { WriteError(new ErrorRecord(ex, "QuickImport", ErrorCategory.ReadError, Definition)); } }
static void Main(string[] args) { DisplayLogo(); ipaddr = SetIP(); Console.WriteLine("\nThis is the server window. \n"); Console.WriteLine("Hit enter for a standard game, otherwise enter 'custom'"); if (Console.ReadLine().ToLower() == "custom") { //do custom setup gameManager = new GameManager(); } else { gameManager = new GameManager(); } Console.WriteLine("All players will be asked to input the host IP, which is: " + ipaddr.ToString() + "\n"); Console.WriteLine("This window will now keep a log of all connections and server actions.\n"); Console.WriteLine("If anything unexpected happens ; check here."); Console.ReadLine(); Random r = new Random(); Random random = new Random(); Shuffler shuffler = new Shuffler(); whiteCardSet = DeserializeCards(Path.Combine(cardDirectory, "white/base.json")); blackCardSet = DeserializeCards(Path.Combine(cardDirectory, "black/base.json")); int[] whiteList = Enumerable.Range(0, whiteCardSet.cards.Count - 1).ToArray(); int[] blackList = Enumerable.Range(0, blackCardSet.cards.Count - 1).ToArray(); shuffler.Shuffle(whiteList); shuffler.Shuffle(blackList); foreach (int value in whiteList) { gameManager.whiteDeck.push(whiteCardSet.cards[value]); } foreach (int value in blackList) { gameManager.blackDeck.push(blackCardSet.cards[value]); } gameManager.blackDeck.display(); Thread tcplistener = new Thread(listener); tcplistener.Start(); Thread AiLoop = new Thread(AIloop); AiLoop.Start(); while (true) { if (gameManager.players.Count > 0) { string responce = parseCommand(Console.ReadLine()); Console.WriteLine(responce); } } }
public void CreateANewDealer() { IShuffler shuffler = new Shuffler(); Assert.That(_Game.NewDealer(shuffler), Is.TypeOf(typeof(Dealer))); }
public void CanKnuthShuffle() { IList <string> result = Shuffler.KnuthShuffle(defaultList); Assert.AreNotEqual(true, Enumerable.SequenceEqual(defaultList, result)); }
static void Main(string[] args) { Console.SetWindowSize(90, 25); DisplayLogo(); ipaddr = SetIP(); Shuffler shuffler = new Shuffler(); Console.WriteLine("\nThis is the server window. \n"); Console.WriteLine("Hit enter for a standard game, otherwise enter 'custom'"); if (Console.ReadLine().ToLower() == "custom") { Console.WriteLine("Set the server port (enter d for default) :"); string temp = Console.ReadLine(); if(temp.ToLower().Trim() != "d") { port = int.Parse(temp); } Console.WriteLine("Max cards: (recommended 5-15)"); int maxCards = int.Parse(Console.ReadLine()); Console.WriteLine("Win threshold: (recommended 10-30) points"); int pointThresh = int.Parse(Console.ReadLine()); bool[] CardsToUse = new bool[whiteCardFilePaths.Length]; for (int i = 1; i < CardsToUse.Length; i++ ) { string name = whiteCardFilePaths[i].Substring(whiteCardFilePaths[i].LastIndexOf('\\')+1); Console.WriteLine("Would you like to use the " + name.Substring(0,name.IndexOf('.')) + " card set: (y or n)"); if (Console.ReadLine().ToLower() == "y") { CardsToUse[i] = true; } else { CardsToUse[i] = false; } } gameManager = new GameManager(maxCards,pointThresh); List<CardSet> whiteCardSets = new List<CardSet>(); List<CardSet> blackCardSets = new List<CardSet>(); List<Card> AllWhiteCards = new List<Card>(); List<Card> AllBlackCards = new List<Card>(); for (int i = 0; i < CardsToUse.Length; i++) { if (CardsToUse[i] == true) { whiteCardSets.Add(DeserializeCards(whiteCardFilePaths[i])); blackCardSets.Add(DeserializeCards(blackCardFilePaths[i])); } } for (int i = 0; i < whiteCardSets.Count; i++) { AllWhiteCards.AddRange(whiteCardSets[i].cards); AllBlackCards.AddRange(blackCardSets[i].cards); } shuffler.Shuffle(AllWhiteCards); shuffler.Shuffle(AllBlackCards); foreach (Card c in AllWhiteCards) { gameManager.whiteDeck.Push(c); } foreach (Card c in AllBlackCards) { gameManager.blackDeck.Push(c); } } else { gameManager = new GameManager(); CardSet whiteCardSet = DeserializeCards(Path.Combine(cardDirectory, "white/all.json")); CardSet blackCardSet = DeserializeCards(Path.Combine(cardDirectory, "black/all.json")); shuffler.Shuffle(whiteCardSet.cards); shuffler.Shuffle(blackCardSet.cards); foreach (Card c in whiteCardSet.cards) { gameManager.whiteDeck.Push(c); } foreach (Card c in blackCardSet.cards) { gameManager.blackDeck.Push(c); } } Console.WriteLine("All players will be asked to input the host IP, which is: " + ipaddr.ToString() + "\n"); Console.WriteLine("This window will now keep a log of all connections and server actions.\n"); Console.WriteLine("If anything unexpected happens ; check here. \n"); Console.WriteLine("If you are unsure of any server commands, use !help to display a list of commands and their function \n"); AInames = File.ReadAllLines(Path.Combine(Environment.CurrentDirectory, "AInames.txt")).ToList(); Thread tcplistener = new Thread(listener); tcplistener.Start(); string responce = ""; while (true) { if (gameManager.players.Count > 0) { responce = parseCommand(Console.ReadLine()); Console.WriteLine(responce); } } }
// ---------------------------------------------------- // Functions used for spawning animals in Minigame mode // ---------------------------------------------------- public GameObject SpawnGameAnimals() { // If the game is SEE, there must be more than 1 phlyum // The game consist of 1 phylum and 1 extra phlyum // You need to spawn n number of animals from original // phylum and add 1 animal from extra phlyum if (gameType == ScoreManager.MinigameType.SEE && phyla.Length > 1) { int phylumNum = Random.Range(0, phyla.Length); // Choose a random phylum to instantiate animals from Phylum phylum = phyla[phylumNum]; // Assign random to var phylum // Get random phylum to instantiate extra animal int extraPhylumNum; // Get an random int to assign extra phylum from do { extraPhylumNum = Random.Range(0, phyla.Length); // Must not be equal to original phylum } while (extraPhylumNum == phylumNum); Phylum extraPhylum = phyla[extraPhylumNum]; // Using random int assign the extra phlyum // Get random animal from the extra phylum int extraAnimalNum = Random.Range(0, extraPhylum.animals.Length); GameObject extraAnimal = extraPhylum.animals[extraAnimalNum]; // Create a list of animals to hold animals from original phylum GameObject[] tmp = phylum.GetRandomUniqueAnimalList(spawnNum - 1); List <GameObject> animalsList = new List <GameObject>(); // Add all animals in tmp for (int i = 0; i < tmp.Length; i++) { animalsList.Add(tmp[i]); } // Add the extra animal animalsList.Add(extraAnimal); // Convert list back to array GameObject[] animals = animalsList.ToArray(); // Shuffle the animals Shuffler.Shuffle(animals); return(SpawnGameObjectList(animals, extraAnimal)); } // If the game is HEAR, there is only 1 "phylum" required // here the phylum is just a temporary storage for ALL animals // that produces sound. You simply need to get random animals // and a random int to have as the answer (animals[i]) else { // TODO: Handle when the spawnNum is // greater than the number of animals w/ // sound to avoid duplicate animals Phylum wSound = phyla[0]; // Get animals with sound GameObject[] animals = wSound.GetRandomUniqueAnimalList(spawnNum); // List of animals to be spawned GameObject corrAnimal = animals[Random.Range(0, animals.Length)]; // Use this animal to play sound // Shuffle the animals Shuffler.Shuffle(animals); return(SpawnGameObjectList(animals, corrAnimal)); } }
// List<int> tempSpotsInBox = new List<int>(); // static int saveSlot = 0; static void PickRandomBox() { randomBox = Shuffler.ShuffleIntFromArray(boxes); }
static string parseCommand(string command) { if (command.StartsWith("!player.join")) { string [] playerinfo = parseFields(command); foreach (Player p in gameManager.players) { if (playerinfo[0] == p.Name) { return "nameTaken"; } } gameManager.players.Add(new Player(playerinfo[0], playerinfo[1], playerinfo[2], playerinfo[3])); return "Added player: " + playerinfo[0]; } else if (command.StartsWith("!player.draw")) { int numCards; if(command.Substring(command.IndexOf('|')+1) == "max") { numCards = gameManager.maxCards; } else { numCards = int.Parse(command.Substring(command.IndexOf('|') + 1)); } string hand = ""; for (int i = 0; i < numCards; i++) { hand += gameManager.whiteDeck.Pop().toHand(); hand += "`"; } hand = hand.Substring(0, hand.Length - 1); return hand; } else if (command.StartsWith("!player.isCzar")) { return gameManager.players[gameManager.CzarCounter].Name; } else if (command.StartsWith("!player.leave")) { string[] playerinfo = parseFields(command); for (int i = 0; i < gameManager.players.Count; i++) { if (gameManager.players[i].Name == playerinfo[0]) { gameManager.players.RemoveAt(i); } } for (int i = 0; i < gameManager.afkPlayers.Count; i++) { if (gameManager.afkPlayers[i].Name == playerinfo[0]) { gameManager.afkPlayers.RemoveAt(i); } } return "0"; } else if (command.StartsWith("!player.rejoin")) { string[] playerinfo = parseFields(command); for (int i = 0; i < gameManager.afkPlayers.Count; i++) { if (gameManager.afkPlayers[i].Name == playerinfo[0]) { gameManager.players.Add(gameManager.afkPlayers[i]); gameManager.afkPlayers.RemoveAt(i); } } return "0"; } else if (command.StartsWith("!player.playCard")) { int entries = gameManager.numFields(gameManager.currentBlackCard.text); string[] playerinfo = parseFields(command); if (entries == 1) { gameManager.currentPlayerCards.Add(new PlayInfo(playerinfo[0], playerinfo[1])); } else { string temp = ""; for (int i = 0; i < entries; i++) { temp += playerinfo[i] + "`"; } temp = temp.Substring(0, temp.Length - 1); gameManager.currentPlayerCards.Add(new PlayInfo(temp, playerinfo[playerinfo.Length - 1])); } for (int i = 0; i < gameManager.waitingFor.Count; i++ ) { if (gameManager.waitingFor[i].Name == playerinfo[1]) { gameManager.waitingFor.RemoveAt(i); } } return "0"; } else if (command.StartsWith("!game.blackcard")) { if (!AIstarted) { Thread AiLoop = new Thread(AIloop); AiLoop.Start(); AIstarted = true; } return gameManager.currentBlackCard.text; } else if (command.StartsWith("!player.hasWon")) { foreach (Player p in gameManager.players) { if (p.hasWon()) { return p.Name; } } foreach (AI ai in gameManager.AIs) { if (ai.hasWon()) { return ai.Name; } } return "no"; } else if (command.StartsWith("!game.start")) { gameManager.gameStarted = true; gameManager.players = gameManager.players.OrderBy(o => o.TimeSinceDump()).ToList(); gameManager.players[gameManager.CzarCounter].IsCzar = true; return gameManager.players[0].Name + " is the Card Czar"; } else if (command.StartsWith("!game.hasStarted")) { return gameManager.gameStarted.ToString(); } else if (command.StartsWith("!game.roundPlayed")) { return gameManager.played().ToString(); } else if (command.StartsWith("!game.roundWinner")) { return gameManager.roundWinner; } else if (command.StartsWith("!game.newRound")) { gameManager.NewRound(); return "0"; } else if (command.StartsWith("!game.setNextCzar")) { gameManager.incrementCzarCounter(); return "0"; } else if (command.StartsWith("!game.numPlayers")) { return (gameManager.numAIs + gameManager.players.Count).ToString(); } else if (command.StartsWith("!game.addAI")) { Random rand = new Random(); AI newAi = new AI(); int nameIndex = rand.Next(0,AInames.Count-1); if (AInames.Count > 0) { newAi.Name = AInames[nameIndex]; AInames.RemoveAt(nameIndex); } else { newAi.Name = "AI-" + rand.Next(0, int.MaxValue); } newAi.IpAddress = ipaddr.ToString(); for (int i = 0; i < gameManager.maxCards; i++) { newAi.hand.Add(gameManager.whiteDeck.Pop().toHand()); } gameManager.numAIs++; gameManager.AIs.Add(newAi); return "Added AI:" + newAi.Name; } else if (command.StartsWith("!game.setWinCards|")) { command = command.Substring(command.IndexOf('|') + 1); gameManager.winCards = command; return "0"; } else if (command.StartsWith("!game.getWinCards|")) { return gameManager.winCards; } else if (command.StartsWith("!game.roundEntries")) { string temp = ""; Shuffler shuffler = new Shuffler(); shuffler.Shuffle(gameManager.currentPlayerCards); foreach (PlayInfo p in gameManager.currentPlayerCards) { temp += p.card + "`"; } if (temp == "") { return "0"; } temp = temp.Substring(0, temp.Length - 1); return temp; } else if (command.StartsWith("!game.setWinner")) { command = command.Substring(command.IndexOf('|') + 1); gameManager.roundWinner = gameManager.currentPlayerCards[int.Parse(command)].cardPlayer; foreach (Player p in gameManager.players) { if (p.Name == gameManager.roundWinner) { p.Points++; } } foreach (AI ai in gameManager.AIs) { if (ai.Name == gameManager.roundWinner) { ai.Points++; } } return "0"; } else if (command.StartsWith("!game.numPlayers")) { return (gameManager.AIs.Count + gameManager.players.Count).ToString(); } else if (command.StartsWith("!game.viewPoints")) { string tally = ""; foreach (Player p in gameManager.players) { tally += p.Name + "\t\t" + p.Points + "\n"; } foreach (AI ai in gameManager.AIs) { tally += ai.Name + "\t\t" + ai.Points + "\n"; } return tally; } else if (command.StartsWith("!game.playerTimeout")) { foreach(Player p in gameManager.waitingFor) { gameManager.afkPlayers.Add(p); gameManager.players.Remove(p); } return "0"; } else if (command.StartsWith("!game.quit")) { Environment.Exit(0); return "0"; } else if (command.StartsWith("!help")) { return "|command| \t\t |function| \n" + "!game.start \t\t starts the game (do so only after all players have joined) \n" + "!game.addAI \t\t adds a rando cardrisian (a player bot that picks cards randomly) \n" + "!game.quit \t\t ends the game (not gracefully for clients midgame) \n"; } else if (command.StartsWith("!chat.sendMessage")) { foreach (Player p in gameManager.players) { p.messages.Push(command.Substring(command.IndexOf('|') + 1)); } return "0"; } else if (command.StartsWith("!chat.getMessages")) { string name = command.Substring(command.IndexOf('|') + 1); string messages = ""; foreach (Player p in gameManager.players) { if (name == p.Name) { while(p.messages.Count != 0) { messages += p.messages.Pop() + "|"; } } } if (messages != "") { messages = messages.Substring(0, messages.LastIndexOf('|')); return messages; } else { return "0"; } } else if (command == "\n") { return "0"; } else { return "Unknown Command"; } }