Next() public method

public Next ( ) : int
return int
        protected void Arrange()
        {
            var random = new Random();
            _subsystemName = random.Next().ToString(CultureInfo.InvariantCulture);
            _operationTimeout = TimeSpan.FromSeconds(30);
            _encoding = Encoding.UTF8;
            _disconnectedRegister = new List<EventArgs>();
            _errorOccurredRegister = new List<ExceptionEventArgs>();
            _channelDataEventArgs = new ChannelDataEventArgs(
                (uint)random.Next(0, int.MaxValue),
                new[] { (byte)random.Next(byte.MinValue, byte.MaxValue) });

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelMock = new Mock<IChannelSession>(MockBehavior.Strict);

            _sequence = new MockSequence();
            _sessionMock.InSequence(_sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object);
            _channelMock.InSequence(_sequence).Setup(p => p.Open());
            _channelMock.InSequence(_sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true);

            _subsystemSession = new SubsystemSessionStub(
                _sessionMock.Object,
                _subsystemName,
                _operationTimeout,
                _encoding);
            _subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args);
            _subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args);
            _subsystemSession.Connect();
        }
Esempio n. 2
1
        /// <summary>
        /// Constructeur par défaut, génère plusieurs carrés.
        /// </summary>
        public RectangleEnigmaPanel()
        {
            Random rnd = new Random();

            TableLayoutPanel centerLayout = new TableLayoutPanel();
            centerLayout.ColumnCount = 27;
            for (int i = 0; i < 27 ;i++)
            {
                centerLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent,0.04f));
            }
            centerLayout.RowCount = 21;
            for (int i = 0; i < 21; i++)
            {
                centerLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 0.05f));
            }
            centerLayout.Dock = DockStyle.Fill;
            Controls.Add(centerLayout);

            for (int i = 0; i < tpnlCarre.Length; i++)
            {
                tpnlCarre[i] = new Panel();
                Random randonGen = new Random();
                Color randomColor = Color.FromArgb(randonGen.Next(240), randonGen.Next(240),
                randonGen.Next(255));
                tpnlCarre[i].BackColor = randomColor;
                tpnlCarre[i].Size = new Size(20, 20);
                int iLocX = rnd.Next(1, 27);
                int iLocY = rnd.Next(0, 21);
                centerLayout.Controls.Add(tpnlCarre[i], iLocX, iLocY);
                tpnlCarre[i].Click += new EventHandler(ClickOnCarre);
            }

            centerLayout.Click += new EventHandler(ClickOnPanel);
        }
Esempio n. 3
1
        public void RandomDatagramTest()
        {
            Random random = new Random();

            for (int i = 0; i != 1000; ++i)
            {
                Datagram datagram = random.NextDatagram(random.Next(1024));

                Assert.AreEqual(datagram, new Datagram(new List<byte>(datagram).ToArray()));
                Assert.AreEqual(datagram.GetHashCode(), new Datagram(new List<byte>(datagram).ToArray()).GetHashCode());

                Assert.AreNotEqual(datagram, random.NextDatagram(random.Next(10 * 1024)));
                Assert.AreNotEqual(datagram.GetHashCode(), random.NextDatagram(random.Next(10 * 1024)).GetHashCode());

                if (datagram.Length != 0)
                {
                    Assert.AreNotEqual(datagram, Datagram.Empty);
                    Assert.AreNotEqual(datagram, random.NextDatagram(datagram.Length));
                    if (datagram.Length > 2)
                        Assert.AreNotEqual(datagram.GetHashCode(), random.NextDatagram(datagram.Length).GetHashCode());
                }
                else
                    Assert.AreEqual(datagram, Datagram.Empty);

                // Check Enumerable
                IEnumerable enumerable = datagram;
                int offset = 0;
                foreach (byte b in enumerable)
                    Assert.AreEqual(datagram[offset++], b);
            }
        }
Esempio n. 4
1
        static void Main(string[] args)
        {
            const int NumberOfAnimals = 10;
            Stack<Animal> animalStack = new Stack<Animal>();
            Queue<Animal> animalQueue = new Queue<Animal>();

            Console.WriteLine("/// ORDER OF ENTRY...");
            Random r = new Random();
            for (int index = 0; index < NumberOfAnimals; index++)
            {
                var animalShouldBeCat = (r.Next(2) == 0);
                uint nextWeight = (uint)r.Next(10, 40);
                Animal nextAnimal = animalShouldBeCat ? (Animal)(new Cat(nextWeight, "John")) : (Animal)(new Dog(nextWeight, "Dave"));
                animalStack.Push(nextAnimal);
                animalQueue.Enqueue(nextAnimal);
                Console.WriteLine(nextAnimal);
            }

            Console.WriteLine();
            Console.WriteLine("/// OUTPUT FROM STACK...");
            foreach (Animal animal in animalStack)
            {
                Console.WriteLine(animal);
            }

            Console.WriteLine();
            Console.WriteLine("/// OUTPUT FROM QUEUE...");
            foreach (Animal animal in animalQueue)
            {
                Console.WriteLine(animal);
            }
        }
Esempio n. 5
1
        static void Main(string[] args)
        {
            var m_Config = new ServerConfig
            {
                Port = 911,
                Ip = "Any",
                MaxConnectionNumber = 1000,
                Mode = SocketMode.Tcp,
                Name = "CustomProtocolServer"
            };

            var m_Server = new CustomProtocolServer();
            m_Server.Setup(m_Config, logFactory: new ConsoleLogFactory());
            m_Server.Start();

            EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port);

            using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
            {
                socket.Connect(serverAddress);

                var socketStream = new NetworkStream(socket);
                var reader = new StreamReader(socketStream, Encoding.ASCII, false);

                string charSource = Guid.NewGuid().ToString().Replace("-", string.Empty)
                    + Guid.NewGuid().ToString().Replace("-", string.Empty)
                    + Guid.NewGuid().ToString().Replace("-", string.Empty);

                Random rd = new Random();

                var watch = Stopwatch.StartNew();
                for (int i = 0; i < 10; i++)
                {
                    int startPos = rd.Next(0, charSource.Length - 2);
                    int endPos = rd.Next(startPos + 1, charSource.Length - 1);

                    var currentMessage = charSource.Substring(startPos, endPos - startPos + 1);

                    byte[] requestNameData = Encoding.ASCII.GetBytes("ECHO");
                    socketStream.Write(requestNameData, 0, requestNameData.Length);
                    var data = Encoding.ASCII.GetBytes(currentMessage);
                    socketStream.Write(new byte[] { (byte)(data.Length / 256), (byte)(data.Length % 256) }, 0, 2);
                    socketStream.Write(data, 0, data.Length);
                    socketStream.Flush();

                   // Console.WriteLine("Sent: " + currentMessage);

                    var line = reader.ReadLine();
                    //Console.WriteLine("Received: " + line);
                    //Assert.AreEqual(currentMessage, line);
                }

                

                watch.Stop();
                Console.WriteLine(watch.ElapsedMilliseconds);
            }

            Console.ReadLine();
        }
Esempio n. 6
1
        /// <summary>
        /// If there is no real life data between seasons,
        /// change some match dates to around now for testing purposes
        /// </summary>
        private static void ChangeMatchDates(TtcDbContext context)
        {
            bool endOfSeason = !context.Matches.Any(match => match.Date > DateTime.Now);
            if (true || endOfSeason)
            {
                var passedMatches = context.Matches
                    .Where(x => x.FrenoySeason == Constants.FrenoySeason)
                    //.Where(x => x.Date < DateTime.Today)
                    .OrderByDescending(x => x.Date)
                    .Take(42);

                var timeToAdd = DateTime.Today - passedMatches.First().Date;
                foreach (var match in passedMatches.Take(20))
                {
                    match.Date = match.Date.Add(timeToAdd);
                }

                var rnd = new Random();
                foreach (var match in passedMatches.Take(20))
                {
                    match.Date = DateTime.Today.Add(TimeSpan.FromDays(rnd.Next(1, 20))).AddHours(rnd.Next(10, 20));
                    match.Description = "";
                    match.AwayScore = null;
                    match.HomeScore = null;
                    //match.IsSyncedWithFrenoy = true;
                    match.WalkOver = false;

                    context.MatchComments.RemoveRange(match.Comments.ToArray());
                    context.MatchGames.RemoveRange(match.Games.ToArray());
                    context.MatchPlayers.RemoveRange(match.Players.ToArray());
                }
            }
        }
Esempio n. 7
1
        /// <summary>
        /// Submatrix expression operations
        /// </summary>
        private void RowColOperation()
        {
            Mat src = Cv2.ImRead(FilePath.Image.Lenna);

            Random rand = new Random();
            for (int i = 0; i < 200; i++)
            {
                int c1 = rand.Next(100, 400);
                int c2 = rand.Next(100, 400);
                Mat temp = src.Row[c1];
                src.Row[c1] = src.Row[c2];
                src.Row[c2] = temp;
            }

            src.Col[0, 50] = ~src.Col[450, 500];
            
            // set constant value (not recommended)
            src.Row[450,460] = src.Row[450,460] * 0 + new Scalar(0,0,255);
            // recommended way
            //src.RowRange(450, 460).SetTo(new Scalar(0, 0, 255));

            using (new Window("RowColOperation", src))
            {
                Cv2.WaitKey();
            }
        }
Esempio n. 8
1
        public static void ApplySetPieces(World world)
        {
            var map = world.Map;
            int w = map.Width, h = map.Height;

            Random rand = new Random();
            HashSet<Rect> rects = new HashSet<Rect>();
            foreach (var dat in setPieces)
            {
                int size = dat.Item1.Size;
                int count = rand.Next(dat.Item2, dat.Item3);
                for (int i = 0; i < count; i++)
                {
                    IntPoint pt = new IntPoint();
                    Rect rect;

                    int max = 50;
                    do
                    {
                        pt.X = rand.Next(0, w);
                        pt.Y = rand.Next(0, h);
                        rect = new Rect() { x = pt.X, y = pt.Y, w = size, h = size };
                        max--;
                    } while ((Array.IndexOf(dat.Item4, map[pt.X, pt.Y].Terrain) == -1 ||
                             rects.Any(_ => Rect.Intersects(rect, _))) &&
                             max > 0);
                    if (max <= 0) continue;
                    dat.Item1.RenderSetPiece(world, pt);
                    rects.Add(rect);
                }
            }
        }
Esempio n. 9
1
		public void Initialise()
		{
			_primitives = new List<Cube>();
			var random = new Random();
			for (int i = 0; i < Constants.CubeCount; i++)
			{
				_primitives.Add(new Cube
					{
						Color = Color.Red,
						Position = new Vector3(random.Next(100) - 50, random.Next(100) - 50, -random.Next(100)),
						Radius = random.Next(100),
						Rotation = Vector3.Zero
					});
			}
            //How to create a kernel and a channel?
//			_kernel = 
//		    _channel = 

			

			_colour = Color.Beige;
			
			_kernel.Factory.NewCoroutine(ChangePosition);
			_kernel.Factory.NewCoroutine(ChangeColour);
		    
		}
Esempio n. 10
1
 public Pen GetPen()
 {
     Random r = new Random();
     Color color = Color.FromArgb(255, r.Next(255), r.Next(255), r.Next(255));
     Pen pen = new Pen(color);
     return pen;
 }
Esempio n. 11
1
		public void GetReady ()
		{
			dataTable = new DataTable ("itemTable");
			dc1 = new DataColumn ("itemId");
			dc2 = new DataColumn ("itemName");
			dc3 = new DataColumn ("itemPrice");
			dc4 = new DataColumn ("itemCategory");
			
			dataTable.Columns.Add (dc1);
			dataTable.Columns.Add (dc2);
			dataTable.Columns.Add (dc3);
			dataTable.Columns.Add (dc4);
			DataRow dr;
			seed = 123;
			rowCount = 5;
			rndm = new Random (seed);
			for (int i = 1; i <= rowCount; i++) {
				dr = dataTable.NewRow ();
				dr["itemId"] = "item " + i;
				dr["itemName"] = "name " + rndm.Next ();
				dr["itemPrice"] = "Rs. " + (rndm.Next () % 1000);
				dr["itemCategory"] = "Cat " + ((rndm.Next () % 10) + 1);
				dataTable.Rows.Add (dr);
			}
			dataTable.AcceptChanges ();
			dataView = new DataView (dataTable);
			dataView.ListChanged += new ListChangedEventHandler (OnListChanged);
			listChangedArgs = null;
		}
Esempio n. 12
0
        // Returns a List<Hand> of the specified dimension.
        // Each hand populated randomly, without duplication (i.e. no card appears twice)
        public List<Hand> Deal(int handCount, int handLength)
        {
            // What error checking is missing here?

            List<Hand> dealtHands = new List<Hand>();

            // Used to insure each card appears only once in the deal
            bool[,] cardUsed = new bool[RankCount, SuitCount];
            Random rand = new Random();

            // Take time to make sure you understand the logic.
            // This is a very common algorithm pattern.
            for (int h = 0; h < handCount; h++)
            {
                Hand currentHand = new Hand();
                int cardCount = 0;

                while (cardCount < handLength)
                {
                    int nextCardRank = rand.Next(RankCount);
                    int nextCardSuit = rand.Next(SuitCount);

                    if (cardUsed[nextCardRank, nextCardSuit] == false)
                    {
                        currentHand.AddCard(cards[nextCardRank, nextCardSuit]);
                        cardUsed[nextCardRank, nextCardSuit] = true;
                        cardCount++;
                    }
                }
                currentHand.ComputeHCP();
                dealtHands.Add(currentHand);
            } // all hands dealt
            return dealtHands;
        }
        public void TestSymmetricExceptAdd_FindUniqueAcrossLists()
        {
            Random random = new Random();

            // build two lists
            var list1 = new List<int>(100);
            Sublist.Generate(100, i => random.Next(100)).AddTo(list1.ToSublist());
            var list2 = new List<int>(100);
            Sublist.Generate(100, i => random.Next(100)).AddTo(list2.ToSublist());

            // make the lists sets
            list1.ToSublist(list1.ToSublist().MakeSet().InPlace()).Clear();
            list2.ToSublist(list2.ToSublist().MakeSet().InPlace()).Clear();

            // find the unique values
            var difference = new List<int>();
            list1.ToSublist().SymmetricExcept(list2.ToSublist()).AddTo(difference.ToSublist());

            // this is the opposite of the intersection, so they should share no items
            var intersection = new List<int>();
            list1.ToSublist().Intersect(list2.ToSublist()).AddTo(intersection.ToSublist());

            bool result = intersection.ToSublist().FindAny(difference.ToSublist());
            Assert.IsFalse(result, "Found items in common in the intersection and symmetric difference.");
        }
Esempio n. 14
0
        private string DajWyrazenie(int paramentr)
        {
            Random r = new Random();
            int wgora = r.Next(0, 3);
            int wdol = r.Next(0, 3);
            int wnowosc = r.Next(0, 3);
            int wbrak = r.Next(0, 3);
            string wyrazenie = "";

            switch (paramentr)
            {
                case 0:
                    //w gore
                    wyrazenie = gora[wgora];
                    break;
                case 1:
                    //w dol
                    wyrazenie = dol[wdol];
                    break;
                case 2:
                    //nowosc
                    wyrazenie = nowosc[wnowosc];
                    break;
                case 3:
                    //brak
                    wyrazenie = brak[wbrak];
                    break;
            }

            return wyrazenie;
        }
Esempio n. 15
0
        public override void Update(GameTime gameTime, TeeEngine engine)
        {
            Hero player = (Hero) engine.GetEntity("Player");
            KeyboardState keyboardState = Keyboard.GetState();

            if (KeyboardExtensions.GetKeyDownState(keyboardState, Keys.S, this, true)
                && Entity.IntersectsWith(this, "interaction", player, "Shadow", gameTime))
            {
                if (CurrentDrawableState != "Open")
                {
                    Random random = new Random();

                    _openSfx[random.Next(1)].Play();

                    CurrentDrawableState = "Open";
                    Drawables.ResetState("Open", gameTime);

                    for (int i = 0; i < 10; i++)
                    {
                        Coin coin = new Coin(this.Pos.X, this.Pos.Y, 100, (CoinType)random.Next(3));
                        coin.Pos.X += (float) ((random.NextDouble() - 0.5) * 100);
                        coin.Pos.Y += (float) ((random.NextDouble() - 0.5) * 100);
                        coin.TerrainCollisionEnabled = false;       // Prevent from getting stuck in sorrounding walls.

                        engine.AddEntity(coin);
                    }
                }
            }

            base.Update(gameTime, engine);
        }
 private static Point RandomPoint(Random rng, Rectangle bounds)
 {
     return new Point(
         rng.Next(bounds.Left, bounds.Right),
         rng.Next(bounds.Top, bounds.Bottom)
     );
 }
Esempio n. 17
0
        public static void SetRandomEdge(int[,] graph, int n)
        {
            bool found = false;
            int i = 0;
            int j = 0;

            int count = 0;
            Random random = new Random();

            for (int k = 0; k < n; k++)
            {
                for (int l = 0; l < n; l++)
                {
                    if (graph[k, l] != int.MaxValue)
                        continue;

                    count++;

                    if (random.Next(0, count) == 0)
                    {
                        found = true;
                        i = k;
                        j = l;
                    }
                }
            }

            if (found)
                graph[i, j] = random.Next(1, 10);
        }
 public KishnakAnswersTests()
 {
     Rand = new Random();
     Sut = new KishnakAnswers();
     CounterAnswer = Rand.Next(1, 100);
     CounterPre = Rand.Next(1, 3);
 }
Esempio n. 19
0
        private void IssueTestMove(int recursionCount)
        {

            var movePos = ObjectCache.myHeroCache.serverPos2D;

            Random rand = new Random();

            lastRandomMoveCoeff = !lastRandomMoveCoeff;
            if (lastRandomMoveCoeff)
            {
                movePos.X += 65 + rand.Next(0, 20);
            }
            else
            {
                movePos.X -= 65 + rand.Next(0, 20);
            }

            lastTestMoveToCommand = new EvadeCommand
            {
                order = EvadeOrderCommand.MoveTo,
                targetPosition = movePos,
                timestamp = EvadeUtils.TickCount,
                isProcessed = false
            };
            myHero.IssueOrder(GameObjectOrder.MoveTo, movePos.To3D(), true);

            if (recursionCount > 1)
            {
                DelayAction.Add(500, () => IssueTestMove(recursionCount - 1));
            }

        }
        public void AddFLoadBalancerRule()
        {
            Random random = new Random();
            string ruleSource = "0.0.0.0";
            var loadBalancers = client.LoadBalancer.Get();
            var loadBalancer = loadBalancers[random.Next(0, loadBalancers.Count - 1)];
            var randomPort = random.Next(1111, 9999);
            var request = new POCO.Requests.LoadBalancer.AddLoadBalancerRuleRequest()
            {
                Rules = new System.Collections.Generic.List<POCO.Requests.LoadBalancer.RuleRequest>()
                {
                    {new OneAndOne.POCO.Requests.LoadBalancer.RuleRequest()
                    {
                        PortBalancer =randomPort,
                    PortServer = randomPort,
                    Protocol = LBRuleProtocol.TCP,
                    Source = ruleSource
                    }}
                }
            };

            var result = client.LoadBalancer.CreateLoadBalancerRule(request, loadBalancer.Id);

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.Id);
            //check the rule is Added
            var updatedLoadBalancer = client.LoadBalancer.Show(loadBalancer.Id);
            Assert.IsTrue(updatedLoadBalancer.Rules.Any(ru => ru.PortServer == randomPort && ru.PortBalancer == randomPort && ru.Source == ruleSource));
        }
        public void TestSave()
        {
            var random = new Random();
            // test saving and reloading
            var list = new List<TestCompositeClass>();
            for (var x = 0; x < 100; x++)
            {
                var testClass = new TestCompositeClass
                {
                    Key1 = random.Next(),
                    Key2 = random.Next().ToString(),
                    Key3 = Guid.NewGuid(),
                    Key4 = DateTime.Now.AddMinutes(-1 * random.Next(100)),
                    Data = Guid.NewGuid().ToString()
                };
                list.Add(testClass);
                _databaseInstance.SaveAsync( testClass ).Wait();
            }

            for (var x = 0; x < 100; x++)
            {
                var actual = _databaseInstance.LoadAsync<TestCompositeClass>( new TestCompositeKeyClass( list[ x ].Key1,
                    list[x].Key2,list[x].Key3,list[x].Key4)).Result;
                Assert.IsNotNull(actual, "Load failed.");
                Assert.AreEqual(list[x].Data, actual.Data, "Load failed: data mismatch.");
            }
        }
Esempio n. 22
0
 public static long GetRandomLong()
 {
     var random = new Random();
     var value = ((long)random.Next()) << 32 + random.Next();
     var sign = random.Next(0, 2) == 0 ? -1 : 1;
     return value * sign;
 }
Esempio n. 23
0
 public static int GetRandomInt()
 {
     var random = new Random();
     var value = random.Next();
     var sign = random.Next(0, 2) == 0 ? -1 : 1;
     return value * sign;
 }
Esempio n. 24
0
        public void RandomPacketTest()
        {
            int seed = new Random().Next();
            Console.WriteLine("Seed: " + seed);
            Random random = new Random(seed);

            for (int i = 0; i != 1000; ++i)
            {
                Packet packet = random.NextPacket(random.Next(10 * 1024));

                // Check Equals
                Assert.AreEqual(packet, new Packet(packet.Buffer, packet.Timestamp.AddHours(1), packet.DataLink));
                Assert.AreNotEqual(packet, random.NextPacket(random.Next(10 * 1024)));
                if (packet.Length != 0)
                    Assert.AreNotEqual(packet, random.NextPacket(packet.Length));

                // Check GetHashCode
                Assert.AreEqual(packet.GetHashCode(), new Packet(packet.Buffer, packet.Timestamp.AddHours(1), packet.DataLink).GetHashCode());
                Assert.AreNotEqual(packet.GetHashCode(), random.NextPacket(random.Next(10 * 1024)).GetHashCode());
                if (packet.Length != 0)
                    Assert.AreNotEqual(packet.GetHashCode(), random.NextPacket(packet.Length).GetHashCode());

                // Check ToString
                Assert.IsNotNull(packet.ToString());

                Assert.IsFalse(new Packet(packet.Buffer, DateTime.Now, (DataLinkKind)((int)DataLinkKind.Ethernet + 1)).IsValid);

                // Check Enumerable
                IEnumerable enumerable = packet;
                int offset = 0;
                foreach (byte b in enumerable)
                    Assert.AreEqual(packet[offset++], b);

            }
        }
        protected void Arrange()
        {
            var random = new Random();
            _path = random.Next().ToString(CultureInfo.InvariantCulture);
            _handle = new[] { (byte)random.Next(byte.MinValue, byte.MaxValue) };
            _fileAttributes = SftpFileAttributes.Empty;
            _bufferSize = (uint)random.Next(0, 1000);
            _readBufferSize = (uint)random.Next(0, 1000);
            _writeBufferSize = (uint)random.Next(0, 1000);

            _sftpSessionMock = new Mock<ISftpSession>(MockBehavior.Strict);

            var sequence = new MockSequence();
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.RequestOpen(_path, Flags.Write | Flags.Truncate, true))
                .Returns(_handle);
            _sftpSessionMock.InSequence(sequence).Setup(p => p.RequestFStat(_handle)).Returns(_fileAttributes);
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.CalculateOptimalReadLength(_bufferSize))
                .Returns(_readBufferSize);
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle))
                .Returns(_writeBufferSize);
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.IsOpen)
                .Returns(true);
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.RequestClose(_handle));

            _sftpFileStream = new SftpFileStream(_sftpSessionMock.Object, _path, FileMode.Create, FileAccess.Write, (int)_bufferSize);
        }
Esempio n. 26
0
 internal Address Next(Random r)
 {
     var pref = addresses.prefecture[r.Next(addresses.prefecture.Count)];
     var city = addresses.city[r.Next(addresses.city.Count)];
     var town = addresses.town[r.Next(addresses.town.Count)];
     return new Address
     {
         Prefecture = new JapaneseText
         {
             Kanji = pref[KanjiIndex],
             Hiragana = pref[HiraganaIndex],
             Katakana = pref[KatakanaIndex]
         },
         City = new JapaneseText
         {
             Kanji = city[KanjiIndex],
             Hiragana = city[HiraganaIndex],
             Katakana = city[KatakanaIndex]
         },
         Town = new JapaneseText
         {
             Kanji = town[KanjiIndex],
             Hiragana = town[HiraganaIndex],
             Katakana = town[KatakanaIndex]
         }
     };
 }
Esempio n. 27
0
        public void VerifyPartialRandomInvalidWords()
        {
            SuffixTree tree = new SuffixTree(theString);
            tree.BuildTree();

            Random random = new Random((int)DateTime.Now.Ticks);
            foreach (string individualString in individualStrings)
            {
                StringBuilder builder = new StringBuilder(individualString);
                //this will inject random characters into valid words
                for (int j = random.Next(individualString.Length-2); j < random.Next(individualString.Length); j++)
                {
                    builder.Insert(j,random.Next('a', 'z'));
                }
                string builtString = builder.ToString();
                string message = "Corrupting: " + individualString + " as " + builtString;
                //I originally checked to see if builder is in individualStrings, however with such a large
                //data set it took way too long to execute. There is a risk that a random string of 5 to 15
                //characters IS in the word list!
                if (!individualStrings.Contains(builtString))
                {
                    Assert.IsTrue(!tree.Search(builtString), message);
                }
            }
        }
Esempio n. 28
0
 public void getBigGoods()
 {
     Hashtable[] goods;
     Sale.Goods myGoods = new Sale.Goods();
     StringBuilder sb = new StringBuilder();
     if (Cache["homeSaleGoods"] == null)
     {
         goods = myGoods.goodsGet(6, 2);
         Random ran = new Random();
         int iCount = 0;
         foreach (Hashtable good in goods)
         {
             sb.Append("<li" + (iCount != 0 ? " style=\"display:none\"" : "") + " class=\"homeGoodsItem clearfix\"><a class=\"jump clearfix\" href=\"/定西网上商城_沁辰左邻/Markets---sale---index@aspx\" data-dst=\"Markets/sale/index.aspx\">");
             sb.Append("<div class=\"hgiImg left\">");
             sb.Append("<img alt=\"" + good["name"] + "\" src=\"" + good["pic"] + "\">");
             sb.Append("</div>");
             sb.Append("<div class=\"hgiDetal left\">");
             sb.Append("<h3>" + good["name"] + "</h3>");
             sb.Append("<div id=\"goodShowContent_price\">¥:<span class=\"oldPrice\">   " + (Convert.ToDouble(good["price"]) + (good["price"].ToString().Length > 6 ? Convert.ToInt32(ran.Next(143, 379)) : Convert.ToDouble(ran.Next(20, 40)))) + "   </span>       <span>" + good["price"] + "</span></div>");
             sb.Append("</div>");
             sb.Append("</a></li>");
             iCount++;
         }
         Cache.Insert("homeSaleGoods", sb, null, DateTime.Now.AddDays(1), TimeSpan.Zero);
     }
     Response.Write(Cache["homeSaleGoods"]);
 }
Esempio n. 29
0
        static void Main(string[] args)
        {
            //try
            //{
            //    File.AppendAllText("c:\\Notes.txt", "Hello World!");
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine(ex.Message); // Don't do this! It will show users info they shouldn't have if they are knowledable enough to find it

            //    Console.WriteLine("Sorry, could not append to file. Try again?");
            //}

            //// pause
            //Console.ReadLine();

            // creates bitmap for you
            //Always use using if you are working with IDisposable Classes
            using (var bitmap = new Bitmap(500, 500)) { 

            // randomly set 1000 pixels all over the bitmap
            var rnd = new Random();
            for (var i = 0; i < 1000; i++)
            {
                bitmap.SetPixel(rnd.Next(500), rnd.Next(500), Color.Green);
            }

            // save bitmap to current directory (debug directory)
            var currentDirectory = Environment.CurrentDirectory;
            var path = Path.Combine(currentDirectory, "MyImage.png");
            bitmap.Save(path, ImageFormat.Png);

            Console.ReadLine();
        }
        }
Esempio n. 30
0
        public static string LoremIpsum(int minWords, int maxWords,
            int minSentences, int maxSentences,
            int numParagraphs)
        {
            var words = new[] { "lorem", "ipsum", "dolor", "sit", "amet", "consectetuer",
                "adipiscing", "elit", "sed", "diam", "nonummy", "nibh", "euismod",
                "tincidunt", "ut", "laoreet", "dolore", "magna", "aliquam", "erat" };

            var rand = new Random(DateTime.Now.Millisecond);
            var numSentences = rand.Next(maxSentences - minSentences) + minSentences + 1;
            var numWords = rand.Next(maxWords - minWords) + minWords + 1;

            var result = new StringBuilder();

            for (int p = 0; p < numParagraphs; p++)
            {
                for (int s = 0; s < numSentences; s++)
                {
                    for (int w = 0; w < numWords; w++)
                    {
                        if (w > 0) { result.Append(" "); }
                        result.Append(words[rand.Next(words.Length)]);
                    }
                    result.Append(". ");
                }
                result.AppendLine();
            }

            return result.ToString();
        }
    public static Tile GetTile(TileType type, System.Random random = null)
    {
        switch (type)
        {
        case TileType.Brick:
            return(brick);

        case TileType.Sand:
            var number = random?.Next(64) ?? 0;
            return(sand[number]);

        default:
            throw new NotSupportedException($"Unknown tile type {type}");
        }
    }
Esempio n. 32
0
    public static T RandomEnumValues <T>(System.Random _seed = null) where T : Enum
    {
        Array allEnums    = Enum.GetValues(typeof(T));
        int   randomIndex = _seed?.Next(1, allEnums.Length) ?? UnityEngine.Random.Range(1, allEnums.Length);
        int   count       = 0;

        foreach (var temp in allEnums)
        {
            count++;
            if (temp.ToString() == "Invalid" || count != randomIndex)
            {
                continue;
            }
            return((T)temp);
        }
        return(default);
Esempio n. 33
0
    public static float[,] GenerateNoiseMap(int mapWidth, int mapHeight, int seed, float scale, int octaves, float persistance, float lacunarity, Vector2 offset, NormalizedMode normalizedMode)
    {
        float[,] noiseMap = new float[mapWidth, mapHeight];

        System.Random prng          = new System.Random(seed);
        Vector2[]     octaveOffsets = new Vector2[octaves];

        float maxPossibleHeight = 0;
        float amplitude         = 1;
        float frequency         = 1;

        for (var i = 0; i < octaves; i++)
        {
            float offsetX = prng.Next(-100000, 100000) + offset.x;
            float offsetY = prng.Next(-100000, 100000) - offset.y;
            octaveOffsets[i] = new Vector2(offsetX, offsetY);

            maxPossibleHeight += amplitude;
            amplitude         *= persistance;
        }


        if (scale <= 0)
        {
            scale = 0.0001f;
        }

        float minLocalNoiseHeight = float.MaxValue;
        float maxLocalNoiseHeight = float.MinValue;

        float halfWidth  = mapWidth / 2;
        float halfHeight = mapHeight / 2;

        for (int y = 0; y < mapHeight; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                amplitude = 1;
                frequency = 1;
                float noiseHeight = 0;

                for (var i = 0; i < octaves; i++)
                {
                    float sampleX = (x - halfWidth + octaveOffsets[i].x) / scale * frequency;
                    float sampleY = (y - halfHeight + octaveOffsets[i].y) / scale * frequency;

                    float perlinValue = Mathf.PerlinNoise(sampleX, sampleY) * 2 - 1;
                    noiseHeight += perlinValue * amplitude;
                    amplitude   *= persistance;
                    frequency   *= lacunarity;
                }

                if (noiseHeight > maxLocalNoiseHeight)
                {
                    maxLocalNoiseHeight = noiseHeight;
                }
                else if (noiseHeight < minLocalNoiseHeight)
                {
                    minLocalNoiseHeight = noiseHeight;
                }

                noiseMap[x, y] = noiseHeight;
            }
        }

        for (int y = 0; y < mapHeight; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                if (normalizedMode == NormalizedMode.Local)
                {
                    noiseMap[x, y] = Mathf.InverseLerp(minLocalNoiseHeight, maxLocalNoiseHeight, noiseMap[x, y]);
                }
                else
                {
                    float normalizedHeight = (noiseMap[x, y] + 1) / (maxPossibleHeight);
                    noiseMap[x, y] = Mathf.Clamp(normalizedHeight, 0f, int.MaxValue);
                }
            }
        }

        return(noiseMap);
    }
    public IEnumerator GenerateEnvironment(HightMap heightMap, MechData meshData, MeshSettings meshSettings, HightMapSettings hightMapSettings, EnvironmentData environmentData, int mapChunkSize, float scale, float min, float max)
    {
        int seed;

        if (environmentData.usingHeightMapSeed)
        {
            seed = hightMapSettings.noiseSettings.seed;
        }
        else
        {
            seed = environmentData.seed;
        }

        System.Random prng = new System.Random(seed);


        bool useFlatSheadedB            = false;
        int  flatSheadedChunkSizeIndexB = 0;

        if (meshSettings.useFlatShader)
        {
            flatSheadedChunkSizeIndexB  = meshSettings.chunkSizeIndex;
            useFlatSheadedB             = true;
            meshSettings.chunkSizeIndex = meshSettings.flatSheadedChunkSizeIndex;
            meshSettings.useFlatShader  = false;
        }

        for (int i = 0; i < environmentData.types.Length; i++)
        {
            panelProcess.setNumer(i + 1 + "/" + environmentData.types.Length);
            panelProcess.setLabel("Environment ");

            EnvironmentData.Types now = environmentData.types[i];
            float[,] noise = PerlinNoise.GeneratorNoise(mapChunkSize + 2, mapChunkSize + 2, now.noiseData.noiseSettings, Vector2.zero);

            float[] noisMapEnd = HightMap.ConwertTab(noise, mapChunkSize + 2);
            int     msi        = (now.LOD == 0) ? 1 : now.LOD * 2;
            Vector3 lastPos    = Vector3.zero;
            int     len        = ((int)(mapChunkSize + 2) / msi) + 1;
            len = len * len;

            Vector3[] points          = mechDraw.GenerateMech(heightMap.value, meshSettings, now.LOD).vertices;
            Vector3[] orginalVerticis = meshData.vertices;

            for (int j = 0; j < len; j++)
            {
                Vector3 nowPos = Vector3.zero;
                if ((positioningMode == PositioningMode.Calculation) || (positioningMode == PositioningMode.BothMode))
                {
                    nowPos = orginalVerticis[CalculationPos(points, orginalVerticis, j, len)];
                }
                else
                {
                    nowPos = points[j];
                }


                panelProcess.setValue((float)j / len);

                float wynik = map(min, max, 0, 1, nowPos.y);


                //if (true)
                if (noisMapEnd[j] < now.curve.Evaluate(wynik))
                {
                    if (lastPos != nowPos)
                    {
                        Vector3 randPos = new Vector3(prng.Next(-now.LOD * environmentData.prngPrecision, now.LOD * environmentData.prngPrecision) / environmentData.prngPrecision, 0, prng.Next(-now.LOD * environmentData.prngPrecision, now.LOD * environmentData.prngPrecision) / environmentData.prngPrecision) * now.randPos;

                        float x = 0, y = 0, z = 0;
                        if (now.randRotX)
                        {
                            x = prng.Next(0, 359);
                        }
                        if (now.randRotY)
                        {
                            y = prng.Next(0, 359);
                        }
                        if (now.randRotZ)
                        {
                            z = prng.Next(0, 359);
                        }
                        if ((positioningMode == PositioningMode.Colision) || (positioningMode == PositioningMode.BothMode))
                        {
                            nowPos.y = ColidePos(nowPos.x + randPos.x, nowPos.z + randPos.z, heightMap.minV, heightMap.maxV) - randPos.y;
                        }
                        Vector3 randRot = new Vector3(x, y, z);
                        lastPos = nowPos;

                        GameObject o = Instantiate(now.Object, (nowPos + randPos) * scale, Quaternion.Euler(now.rotation + randRot));

                        Transform tObject = o.GetComponent <Transform>() as Transform;
                        tObject.SetParent(parent, true);
                        tObject.localScale = now.scale;

                        if (j % skip == 0)
                        {
                            yield return(null);
                        }
                    }
                }
            }
        }
        yield return(null);

        if (useFlatSheadedB)
        {
            meshSettings.chunkSizeIndex = flatSheadedChunkSizeIndexB;
            meshSettings.useFlatShader  = true;
        }
        panelProcess.setActive(false);
    }
Esempio n. 35
0
 public int RandomRange(int min, int max)
 {
     return(Random.Next(min, max));
 }
Esempio n. 36
0
    //Noise creation, for the disposition of elements (Vertice, pixels)
    public static float[,] CreatePerlinNoiseMap(int width, int height, int seed, float scale, int octaves = 0, float persistence = 1, float lacunarity = 1, Vector2? offset = null)
    {
        Vector2 offsetVal = offset ?? Vector2.zero;//optionnal element, (0,0) if no offset submitted

        float[,] heightMap = new float[width, height];

        System.Random rng = new System.Random(seed);//begins the random number generator to an integer fixed, to have the same number sequence each time.
        //offset submitted at each octaves
        Vector2[] octavesOffsets = new Vector2[octaves];

        for (int i = 0; i < octaves; i++)
        {
            float offsetX = rng.Next(-100000, 100000) + offsetVal.x;
            float offsetY = rng.Next(-100000, 100000) + offsetVal.y;
            octavesOffsets[i] = new Vector2(offsetX, offsetY);
        }
        //size of elements
        if (scale <= 0)
        {
            scale = 0.0001f;
        }
        //interval of values for the whole heightmap
        float minHeight = float.MaxValue;
        float maxHeight = float.MinValue;

        float halfWidth  = width / 2f;  //to scale on center
        float halfHeight = height / 2f; //to scale on center



        for (int i = 0; i < width; i++)
        {
            for (int j = 0; j < height; j++)
            {
                float amplitude = 1;
                float frequency = 1;

                float noiseHeight = 0;

                for (int k = 0; k < octaves; k++)
                {
                    float Scalei      = (i - halfWidth) / scale * frequency + octavesOffsets[k].x;
                    float Scalej      = (j - halfHeight) / scale * frequency + octavesOffsets[k].y;
                    float perlinValue = Mathf.PerlinNoise(Scalei, Scalej) * 2 - 1;
                    noiseHeight += perlinValue * amplitude;


                    amplitude *= persistence;
                    frequency *= lacunarity;
                }

                if (noiseHeight > maxHeight)
                {
                    maxHeight = noiseHeight;
                }
                else if (noiseHeight < minHeight)
                {
                    minHeight = noiseHeight;
                }
                heightMap[i, j] = noiseHeight;
            }
        }

        for (int i = 0; i < width; i++)
        {
            for (int j = 0; j < height; j++)
            {
                heightMap[i, j] = Mathf.InverseLerp(minHeight, maxHeight, heightMap[i, j]);//to rescale [-1,1] perlin values, into [0,1] height values (0 -> seas, 1-> mountains summits)
            }
        }
        return(heightMap);//a grid with [0,1] values.
    }
Esempio n. 37
0
 // Use this for initialization
 void Start()
 {
     rb         = GetComponent <Rigidbody2D>();
     speedDelay = blarg.Next(11, 32);
 }
Esempio n. 38
0
    public void GenerateMesh()
    {
        octaveOffsets = new Vector2[octaves];
        for (int i = 0; i < octaves; i++)
        {
            octaveOffsets[i] = new Vector2(rng.Next(-100000, 100000), rng.Next(-100000, 100000));
        }

        // To make the mesh at origin we need to start from here
        Vector3 bottomLeft = new Vector3(-width / 2 - 0.5f, 0, -height / 2 - 0.5f);

        // 3 vertices per triangle and 2 triangles
        int verticesPerCell = 6;
        int vertexCount     = (int)(verticesPerCell * width * height);

        // Allocate the arrays
        Vector3[] vertices    = new Vector3[vertexCount];
        int[]     triangles   = new int[vertexCount];
        Vector2[] uvs         = new Vector2[vertexCount];
        int       vertexIndex = 0;


        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                // Make the vertex positions
                Vector3 cellBottomLeft = bottomLeft + new Vector3(x, 0, y);
                Vector3 cellTopLeft    = bottomLeft + new Vector3(x, 0, y + 1);
                Vector3 cellTopRight   = bottomLeft + new Vector3(x + 1, 0, y + 1);
                Vector3 cellBotomRight = bottomLeft + new Vector3(x + 1, 0, y);

                // Sample for the y co-ord
                cellBottomLeft.y += Sample(x, y);
                cellTopLeft.y    += Sample(x, y + 1);
                cellTopRight.y   += Sample(x + 1, y + 1);
                cellBotomRight.y += Sample(x + 1, y);

                // Map vertices to triangles
                int startVertex = vertexIndex;
                vertices[vertexIndex++] = cellBottomLeft;
                vertices[vertexIndex++] = cellTopLeft;
                vertices[vertexIndex++] = cellTopRight;
                vertices[vertexIndex++] = cellBottomLeft;
                vertices[vertexIndex++] = cellTopRight;
                vertices[vertexIndex++] = cellBotomRight;

                // Map triangles
                for (int i = 0; i < 6; i++)
                {
                    triangles[startVertex + i] = startVertex + i;
                    uvs[startVertex + i]       = new Vector2(vertices[startVertex + i].x, vertices[startVertex + i].z);
                }

                // Add the navigation point to the grid, add vector.up to each node for better navigation
                bool walkable = (mapGenerator.map[x, y] == 0) ? true : false;
                worldGrid[x, y] = new Node(walkable, cellBottomLeft + (cellTopRight - cellBottomLeft) / 2, x, y);
                worldGrid[x, y].worldPosition += Vector3.up;
            }
        }
        // Assign arrays to the mesh
        terrainMesh.vertices  = vertices;
        terrainMesh.triangles = triangles;
        terrainMesh.uv        = uvs;

        terrainMesh.RecalculateNormals();
        terrainColider.sharedMesh    = terrainMesh;
        terrainMeshRenderer.material = terrainMaterial;
    }
Esempio n. 39
0
    public void GenerateBetterMap(level_def def)
    {
        for (int i = 0; i < TheShitISpawned.Capacity; ++i)
        {
            DestroyObject((GameObject)TheShitISpawned[i]);
        }
        TheShitISpawned.Clear();

        if (def == null)
        {
            return;
        }

        string tile_set = def.tile_set[random_generator.Next(def.tile_set.Length)];

        if (this.world_map != null)
        {
            foreach (GameObject go in this.world_map)
            {
                Destroy(go);
                this.world_map = null;
            }
        }

        if (this.blocking_objects != null)
        {
            foreach (GameObject go in this.blocking_objects)
            {
                Destroy(go);
            }
        }

        if (this.portal != null)
        {
            Destroy(this.portal);
        }

        this.blocking_objects = new GameObject[1000];
        this.blocking_iter    = 0;

        int tile_count = 0;

        BetterRoom[] rooms = new BetterRoom[this.room_count];


        // Iterate for number of rooms, creating the position and dimensions for each.
        for (int room = 1; room < rooms.Length / 2; room++)
        {
            int x = 0;
            int y = this.random_generator.Next(-this.room_radius, this.room_radius);

            int width  = 0;
            int height = 0;

            //Generate the dimensions of room.
            do
            {
                width  = this.random_generator.Next(this.room_width_min, this.room_width_max);
                height = this.random_generator.Next(this.room_height_min, this.room_height_max);
            }while (width / height <= room_ratio_max && width / height >= room_ratio_min);

            rooms[room].left   = x - width;
            rooms[room].right  = x + width;
            rooms[room].top    = y - height;
            rooms[room].bottom = y + height;



            // Check if the top of the room is further than world top.
            // True - Update world top to be room top.
            if (rooms[room].top < this.world_top)
            {
                this.world_top = rooms[room].top;
            }

            // Check if the bottom of the room is further than world bottom.
            // True - Update world bottom to be room bottom.
            if (rooms[room].bottom > this.world_bottom)
            {
                this.world_bottom = rooms[room].bottom;
            }
        }

        for (int i = 0; i < rooms.Length; i++)
        {
            bool move_left = this.random_generator.Next(2) == 0;

            while (this.IsOverlapping(i, ref rooms))
            {
                rooms[i].left  += move_left ? -1 : 1;
                rooms[i].right += move_left ? -1 : 1;
            }

            // Check if the left of the room is further than world left.
            // True - Update world left to be room left.
            if (rooms[i].left < this.world_left)
            {
                this.world_left = rooms[i].left;
            }

            // Check if the right of the room is further than world right.
            // True - Update world right to be room right.
            if (rooms[i].right > this.world_right)
            {
                this.world_right = rooms[i].right;
            }
        }

        // Iterate for number of rooms, creating the position and dimensions for each.
        for (int room = rooms.Length / 2; room < rooms.Length; room++)
        {
            int x = this.random_generator.Next(-this.room_radius, this.room_radius);
            int y = this.random_generator.Next(-this.room_radius, this.room_radius);

            int width  = this.random_generator.Next(this.room_width_min, this.room_width_max);
            int height = this.random_generator.Next(this.room_height_min, this.room_height_max);

            rooms[room].left   = x - width;
            rooms[room].right  = x + width;
            rooms[room].top    = y - height;
            rooms[room].bottom = y + height;

            // Check if the left of the room is further than world left.
            // True - Update world left to be room left.
            if (rooms[room].left < this.world_left)
            {
                this.world_left = rooms[room].left;
            }

            // Check if the right of the room is further than world right.
            // True - Update world right to be room right.
            if (rooms[room].right > this.world_right)
            {
                this.world_right = rooms[room].right;
            }

            // Check if the top of the room is further than world top.
            // True - Update world top to be room top.
            if (rooms[room].top < this.world_top)
            {
                this.world_top = rooms[room].top;
            }

            // Check if the bottom of the room is further than world bottom.
            // True - Update world bottom to be room bottom.
            if (rooms[room].bottom > this.world_bottom)
            {
                this.world_bottom = rooms[room].bottom;
            }
        }

        // Ensure center is filled
        rooms[0].left   = -5;
        rooms[0].right  = 5;
        rooms[0].top    = -5;
        rooms[0].bottom = 5;

        // Calculate the actual width and height of the world.
        this.world_width  = this.world_right - this.world_left;
        this.world_height = this.world_bottom - this.world_top;


        // Create array for storage of game tiles.
        this.world_map = new GameObject[this.world_width, this.world_height];

        GameObject tile_flat  = level_assets.GetInstance().GetTileFromSet(tile_set, "flat");
        GameObject tile_left  = level_assets.GetInstance().GetTileFromSet(tile_set, "left");
        GameObject tile_right = level_assets.GetInstance().GetTileFromSet(tile_set, "right");

        // Iterate over rooms in generated list.
        foreach (BetterRoom room in rooms)
        {
            // Iterate over the x indexes of the current room.
            for (int x = room.left; x <= room.right; x++)
            {
                // Iterate over the y indexes of the current room.
                for (int y = room.top; y <= room.bottom; y++)
                {
                    // Initiliase the index variables for translation.
                    int index_x = 0;
                    int index_y = 0;

                    // Check that the world space was succesfully translated to an array indexer.
                    // True - Set the type of the title on the world map to be a traversible space.
                    if (this.TranslateWorldToArray(x, y, ref index_x, ref index_y))
                    {
                        if (this.world_map[index_x, index_y] == null)
                        {
                            this.world_map[index_x, index_y] = Instantiate(tile_flat, new Vector3(x * GameManager.GetGameManager().TileSize, y * GameManager.GetGameManager().TileSize, y / 10.0f), Quaternion.identity) as GameObject;
                            tile_count++;
                        }
                    }
                }
            }
        }

        // Round edges
        for (int iter = 0; iter < 4; iter++)
        {
            for (int x = 0; x < this.world_width; x++)
            {
                for (int y = 0; y < this.world_height; y++)
                {
                    int count = this.CountSurroundingTraversible(x, y);
                    if ((count < 5 && count > 1) && this.world_map[x, y] != null)
                    {
                        Destroy(this.world_map[x, y]);
                        this.world_map[x, y] = null;
                        tile_count--;
                    }
                }
            }
        }

        //do
        //{
        //	this.world_portal_x = this.random_generator.Next(this.world_width);
        //	this.world_protal_y = this.random_generator.Next(this.world_height);
        //} while (this.CountSurroundingTraversible(this.world_portal_x, this.world_protal_y) != 9);

        int x_out = 0;
        int y_out = 0;

        this.TranslateWorldToArray(this.world_portal_x, this.world_protal_y, ref x_out, ref y_out);
        this.portal = Instantiate(def.portal, new Vector3((x_out - this.world_width / 2) * GameManager.GetGameManager().TileSize, (y_out - this.world_height / 2) * GameManager.GetGameManager().TileSize, (y_out - this.world_height / 2) / 10.0f), Quaternion.identity) as GameObject;

        for (int iter = 0; iter < 4; iter++)
        {
            for (int x = 0; x < this.world_width; x++)
            {
                for (int y = 0; y < this.world_height; y++)
                {
                    int count = this.CountSurroundingTraversible(x, y);
                    if (count == 9 && this.random_generator.Next(this.blocking_1_in) == 0 && this.blocking_iter < 1000)
                    {
                        GameObject tile_blocking = level_assets.GetInstance().GetTileFromSet(tile_set, "blocking");
                        if (tile_blocking != null)
                        {
                            this.world_map[x, y].GetComponent <tile>().SetTraversible(false);
                            this.blocking_objects[this.blocking_iter] = Instantiate(tile_blocking, new Vector3((x - this.world_width / 2) * GameManager.GetGameManager().TileSize, (y - this.world_height / 2) * GameManager.GetGameManager().TileSize, (y - this.world_height / 2) / 10.0f), Quaternion.identity) as GameObject;
                            this.blocking_iter++;
                        }
                    }
                }
            }
        }


        // Iterate over rooms in generated list.
        foreach (BetterRoom room in rooms)
        {
            // Iterate over the x indexes of the current room.
            for (int x = room.left; x <= room.right; x++)
            {
                // Iterate over the y indexes of the current room.
                for (int y = room.top; y <= room.bottom; y++)
                {
                    // Initiliase the index variables for translation.
                    int index_x = 0;
                    int index_y = 0;

                    // Check that the world space was succesfully translated to an array indexer.
                    // True - Set the type of the title on the world map to be a traversible space.
                    if (this.TranslateWorldToArray(x, y, ref index_x, ref index_y))
                    {
                        if (this.world_map[index_x, index_y] != null)
                        {
                            if (this.IsNull_array(index_x - 1, index_y))
                            {
                                Destroy(this.world_map[index_x, index_y]);
                                this.world_map[index_x, index_y] = Instantiate(tile_left, new Vector3(x * GameManager.GetGameManager().TileSize, y * GameManager.GetGameManager().TileSize, 0.0f), Quaternion.identity) as GameObject;
                            }
                            else if (this.IsNull_array(index_x + 1, index_y))
                            {
                                Destroy(this.world_map[index_x, index_y]);
                                this.world_map[index_x, index_y] = Instantiate(tile_right, new Vector3(x * GameManager.GetGameManager().TileSize, y * GameManager.GetGameManager().TileSize, 0.0f), Quaternion.identity) as GameObject;
                            }
                        }
                    }
                }
            }
        }


        // TODO: SPAWN ITEMS AND MONSTERS
        for (int iter = 0; iter < 4; iter++)
        {
            for (int x = 0; x < this.world_width; x++)
            {
                for (int y = 0; y < this.world_height; y++)
                {
                    if (IsTraversible_array(x, y))
                    {
                        if (this.random_generator.Next(150) == 0)
                        {
                            // Spawn enemy
                            TheShitISpawned.Add(Instantiate(def.monsters[0], new Vector3((x - this.world_width / 2) * GameManager.GetGameManager().TileSize, (y - this.world_height / 2) * GameManager.GetGameManager().TileSize, (y - this.world_height / 2) / 10.0f), Quaternion.identity));
                        }
                        else if (this.random_generator.Next(300) == 0)
                        {
                            // Spawn item
                            TheShitISpawned.Add(Instantiate(def.items[this.random_generator.Next(3)], new Vector3((x - this.world_width / 2) * GameManager.GetGameManager().TileSize, (y - this.world_height / 2) * GameManager.GetGameManager().TileSize, (y - this.world_height / 2) / 10.0f), Quaternion.identity));
                        }
                    }
                }
            }
        }
    }
Esempio n. 40
0
 // Start is called before the first frame update
 private void Start()
 {
     playerScore    = random.Next(0, 101);
     scoreText.text = "Score: " + playerScore;
 }
    public override void OnInspectorGUI()
    {
        _deck.card2Add     = (BaseCard)EditorGUILayout.ObjectField("Card to add", _deck.card2Add, typeof(BaseCard), false);
        _deck.deckMaxCards = EditorGUILayout.IntField("Max card ammount", _deck.deckMaxCards);
        _deck.deckMinCards = EditorGUILayout.IntField("Min card ammount", _deck.deckMinCards);

        if (GUILayout.Button("Add card") && _deck.cardCounter < _deck.deckMaxCards)
        {
            _deck.mainDeck.Add(_deck.card2Add);
            _deck.cardCounter++;
        }
        if (GUILayout.Button("Remove last added card") && _deck.mainDeck.Count >= 1)
        {
            _deck.mainDeck.RemoveAt(_deck.mainDeck.Count - 1);
            _deck.cardCounter--;
        }
        if (GUILayout.Button("Shuffle deck"))
        {
            int n   = _deck.mainDeck.Count;
            var rng = new Random();
            while (n > 1)
            {
                n--;
                int k     = rng.Next(n + 1);
                var value = _deck.mainDeck[k];
                _deck.mainDeck[k] = _deck.mainDeck[n];
                _deck.mainDeck[n] = value;
            }
        }
        if (GUILayout.Button("Remove specific card"))
        {
            _deck.mainDeck.RemoveAll(n => n == _deck.card2Add);
            _deck.cardCounter = _deck.mainDeck.Count;
        }
        if (GUILayout.Button("Sort by type"))
        {
            _deck.mainDeck = _deck.mainDeck.OrderBy(n => n.name).ToList();
        }
        if (GUILayout.Button("Empty deck"))
        {
            _deck.mainDeck.RemoveRange(0, _deck.mainDeck.Count);
            _deck.cardCounter = 0;
        }
        if (GUILayout.Button("Try Deck"))
        {
            HandWindow.ShowWindow();
        }
        for (int i = 0; i < _deck.mainDeck.Count; i++)
        {
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Card " + (i + 1), GUILayout.Width(60));
            _deck.mainDeck[i] = (BaseCard)EditorGUILayout.ObjectField(_deck.mainDeck[i], typeof(BaseCard), false);
            if (GUILayout.Button("+", GUILayout.Width(20), GUILayout.Height(20)) && _deck.cardCounter < _deck.deckMaxCards)
            {
                _deck.mainDeck.Add(_deck.mainDeck[i]);
                _deck.cardCounter++;
            }
            if (GUILayout.Button("-", GUILayout.Width(20), GUILayout.Height(20)))
            {
                _deck.mainDeck.Remove(_deck.mainDeck[i]);
                _deck.cardCounter--;
            }
            if (GUILayout.Button("Edit Card"))
            {
                //Aca esta lo que edites no me mates D:
                CardWindowEditor.CreateWindow();
                if (_deck.mainDeck [i])
                {
                    CardWindowEditor.window.card = _deck.mainDeck [i];
                }
                Debug.Log(_deck.mainDeck [i]);
            }

            EditorGUILayout.EndHorizontal();
        }
    }
Esempio n. 42
0
 public void RandomNumber()
 {
     state = rnd.Next(1, 5);
     //  ***Debug.Log(state);
     ChangeState();
 }
 int GetRandomOrc()
 {
     return(rng.Next(minOrcRange, maxOrcRange));
 }
Esempio n. 44
0
 public override void _Ready()
 {
     GetNode <AnimatedSprite>("AnimatedSprite").Animation =
         _mobTypes[_random.Next(0, _mobTypes.Length)];
 }
Esempio n. 45
0
 void Awake()
 {
     System.Random rand = new System.Random();
     GetComponent <Text>().text = textos[rand.Next(textos.Length)];
 }
Esempio n. 46
0
    void FixedUpdate()
    {
        if (global && !isGamePaused())
        {
            if (isEnemy && getCurrentGame() != "Platformer")
            {
                gameObject.GetComponent <Rigidbody2D>().gravityScale = 0.4f;
            }
            if (getCurrentGame() == "Platformer" || (getCurrentGame() == "Shooter" && isGrounded == true) || getCurrentGame() == "Fighter")
            {
                if (isEnemy)
                {
                    if (transform.position.x >= npcEnd)
                    {
                        moveLeft = true;
                    }
                    if (transform.position.x <= npcStart)
                    {
                        moveLeft = false;
                    }

                    if (moveLeft)
                    {
                        transform.position = new Vector2(transform.position.x - speed * Time.deltaTime, transform.position.y);
                    }
                    else
                    {
                        transform.position = new Vector2(transform.position.x + speed * Time.deltaTime, transform.position.y);
                    }

                    //Tutorial -- Fighter
                    if (getCurrentGame() == "Fighter")
                    {
                        if (timeBtwShots <= 0)
                        {
                            character = GameObject.Find("Character");
                            Vector2    ballpos      = transform.position;
                            Vector2    characterPos = character.transform.position;
                            GameObject audioManager = GameObject.Find("AudioManager");
                            audioManager.GetComponent <AudioManagerLogic>().playFireballShotSound();
                            if (characterPos.x > transform.position.x)
                            {
                                //Character is on the right side, so shoot in that direction
                                ballpos += new Vector2(+0.4f, -0.2f);
                                GameObject fireball = Instantiate(fireballToRight, ballpos, Quaternion.identity);
                                fireball.GetComponent <FireballLogic>().setShotByCharacter(false);
                            }
                            else
                            {
                                //Character is on the left side, so shoot in that direction
                                ballpos += new Vector2(-0.4f, -0.2f);
                                GameObject fireball = Instantiate(fireballToLeft, ballpos, Quaternion.identity);
                                fireball.GetComponent <FireballLogic>().setShotByCharacter(false);
                            }
                            timeBtwShots = startTimeBtwShots;
                            if (canJump)
                            {
                                //Randomly Jump 500f upwards and 300/-300 left/right to give an impression of sprint after jump
                                int   randomForce = rand.Next(0, 2);
                                float force       = 300f;
                                if (randomForce == 0)
                                {
                                    force = -force;
                                }
                                GetComponent <Rigidbody2D>().AddForce(new Vector2(force, 500f));
                                GetComponent <Rigidbody2D>().gravityScale = 10;
                            }
                        }
                        else
                        {
                            timeBtwShots -= Time.deltaTime;
                        }
                    }
                }
            }
        }
        else if (isGamePaused() && isEnemy && getCurrentGame() != "Platformer")
        {
            gameObject.GetComponent <Rigidbody2D>().gravityScale = 0; //Freeze NPC's even if they are falling from sky (In Shooter Game)
        }
    }
Esempio n. 47
0
 public Powerup GetRandomPowerup()
 {
     return(POWERUPS[random.Next(POWERUPS.Length)]);
 }
Esempio n. 48
0
    public static float[,] GeneratePerlinNoiseMap(int mapWidth, int mapHeight, NoiseSettings settings, Vector2 sampleCenter)
    {
        float[,] noiseMap = new float[mapWidth, mapHeight];

        System.Random prng          = new System.Random(settings.seed);
        Vector2[]     octaveOffsets = new Vector2[settings.octaves];

        for (int i = 0; i < settings.octaves; i++)
        {
            float offsetX = prng.Next(-100000, 100000) + settings.offset.x + sampleCenter.x;
            float offsetY = prng.Next(-100000, 100000) - settings.offset.y + sampleCenter.y;
            octaveOffsets[i] = new Vector2(offsetX, offsetY);
        }

        float maxNoiseHeight = float.MinValue;
        float minNoiseHeight = float.MaxValue;

        float halfWidth  = mapWidth / 2f;
        float halfHeight = mapHeight / 2f;

        for (int y = 0; y < mapHeight; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                float amplitude   = 1;
                float frequency   = 1;
                float noiseHeight = 0;

                for (int i = 0; i < settings.octaves; i++)
                {
                    float sampleX = (x - halfWidth + octaveOffsets[i].x) / settings.scale * frequency;
                    float sampleY = (y - halfHeight + octaveOffsets[i].y) / settings.scale * frequency;

                    float perlinValue = Mathf.PerlinNoise(sampleX, sampleY) * 2 - 1;

                    noiseHeight += perlinValue * amplitude;

                    amplitude *= settings.persistance;
                    frequency *= settings.lacunarity;
                }

                if (noiseHeight > maxNoiseHeight)
                {
                    maxNoiseHeight = noiseHeight;
                }
                if (noiseHeight < minNoiseHeight)
                {
                    minNoiseHeight = noiseHeight;
                }

                noiseMap[x, y] = noiseHeight;
            }
        }

        for (int y = 0; y < mapHeight; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                noiseMap[x, y] = Mathf.InverseLerp(minNoiseHeight, maxNoiseHeight, noiseMap[x, y]);
            }
        }

        return(noiseMap);
    }
    void GenerateRow(int rowId, List <GameObject> gameObjects)
    {
        //Debug.Log("Row " + rowId);

        SpawnObject(Block, -(GameConsts.ROW_SIZE + 1), rowId, gameObjects);
        SpawnObject(Block, GameConsts.ROW_SIZE + 1, rowId, gameObjects);

        if (rowId >= -3)
        {
            return;
        }


        System.Random random = new System.Random(currentSeed * rowId * 967);

        //if (rowId % 2 != 0)
        //{
        //    int position = random.Next(-4, 4);

        //    Instantiate(NormalPlatform, new Vector3(RowToPosition(position-2), RowToPosition(rowId)), Quaternion.identity);
        //    Instantiate(NormalPlatform, new Vector3(RowToPosition(position), RowToPosition(rowId)), Quaternion.identity);
        //    Instantiate(NormalPlatform, new Vector3(RowToPosition(position+2), RowToPosition(rowId)), Quaternion.identity);
        //}

        if (rowId % 2 == 0)
        {
            int thornLimit       = random.Next(1, 3);
            int thornProbability = 10 + rowId / 100;

            if ((rowId / 2) % 7 == 0)
            {
                thornLimit       += 1;
                thornProbability += 50;
            }

            int startSkip = 0;
            int skip;

            int probabilityToSpawn = Mathf.Max(random.Next(0, 10 + Mathf.Abs(rowId % 19)), 0);

            if (random.Next(0, 100) < probabilityToSpawn)
            {
                SpawnObject(NormalOrThorn(thornProbability, ref thornLimit, random), 0, rowId, gameObjects);
                startSkip = ROW_SKIP;
            }

            skip = startSkip;

            int firstWay = random.Next(-100, 100) > 0 ? 1 : -1;

            for (int i = 1; i <= GameConsts.ROW_SIZE; i++)
            {
                if (skip > 0)
                {
                    skip--;
                    continue;
                }

                if (i < ROW_SKIP)
                {
                    startSkip = ROW_SKIP - i;
                }


                if (random.Next(0, 100) < probabilityToSpawn)
                {
                    SpawnObject(NormalOrThorn(thornProbability, ref thornLimit, random), i * firstWay, rowId, gameObjects);
                    skip = ROW_SKIP;
                }
            }

            skip = startSkip;

            for (int i = 1; i <= GameConsts.ROW_SIZE; i++)
            {
                if (skip > 0)
                {
                    skip--;
                    continue;
                }

                if (random.Next(0, 100) < probabilityToSpawn)
                {
                    SpawnObject(NormalOrThorn(thornProbability, ref thornLimit, random), i * -firstWay, rowId, gameObjects);
                    skip = ROW_SKIP;
                }
            }
        }
        else
        {
            // filler rows

            if ((rowId / 2) % 5 == 0)
            {
                if (random.Next(0, 100) < 20)
                {
                    int        direction = random.Next(-100, 100) > 0 ? 1 : -1;
                    GameObject shooter   = SpawnObject(Shooter, (GameConsts.ROW_SIZE + 1) * direction, rowId, gameObjects);

                    shooter.GetComponent <Shooter>().Direction = direction > 0 ? ShootDirection.Left : ShootDirection.Right;
                }
            }

            if ((rowId / 2) % 49 == 0)
            {
                if (random.Next(0, 100) < 40)
                {
                    SpawnObject(Heart, random.Next(-(GameConsts.ROW_SIZE - 1), GameConsts.ROW_SIZE - 1), rowId, gameObjects);
                }
            }
        }
    }
    // Use this for initialization
    void Start()
    {
        a = new System.Random(666);
        b = new System.Random(666);
        c = new System.Random(666);

        Debug.Log("a: " + a.Next() + " " + a.Next() + " " + a.Next() + " " + a.Next() + " " + a.Next() + " " + a.Next() + " ");
        Debug.Log("a: " + b.NextDouble() + " " + b.NextDouble() + " " + b.NextDouble() + " " + b.NextDouble() + " " + b.NextDouble() + " " + b.Next() + " ");
        Debug.Log("a: " + c.Next() + " " + c.NextDouble() + " " + c.Next() + " " + c.NextDouble() + " " + c.Next() + " " + c.Next() + " ");
    }
Esempio n. 51
0
    //Adds the values of the GenerateNoiseMap
    public static float[,] GenerateNoiseMap(int mapWidth, int mapHeight, int seed, float scale, int octaves, float persistance, float lacunarity, Vector2 offset)
    {
        float[,] noiseMap = new float[mapWidth, mapHeight];

        System.Random prng          = new System.Random(seed);
        Vector2[]     octaveOffsets = new Vector2[octaves];
        for (int i = 0; i < octaves; i++)
        {
            float offsetX = prng.Next(-100000, 100000) + offset.x;
            float offsetY = prng.Next(-100000, 100000) + offset.y;
            octaveOffsets[i] = new Vector2(offsetX, offsetY);
        }
        //scale cannot be less than 0. It will be reset to 0.0001f
        if (scale <= 0)
        {
            scale = 0.0001f;
        }

        float maxNoiseHeight = float.MinValue;
        float minNoiseHeight = float.MaxValue;

        float halfWidth  = mapWidth / 2f;
        float halfHeight = mapHeight / 2f;


        for (int y = 0; y < mapHeight; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                float amplitude   = 1;
                float frequency   = 1;
                float noiseHeight = 0;

                for (int i = 0; i < octaves; i++)
                {
                    float sampleX = (x - halfWidth) / scale * frequency + octaveOffsets[i].x;
                    float sampleY = (y - halfHeight) / scale * frequency + octaveOffsets[i].y;

                    float perlinValue = Mathf.PerlinNoise(sampleX, sampleY) * 2 - 1;
                    noiseHeight += perlinValue * amplitude;

                    amplitude *= persistance;
                    frequency *= lacunarity;
                }

                if (noiseHeight > maxNoiseHeight)
                {
                    maxNoiseHeight = noiseHeight;
                }
                else if (noiseHeight < minNoiseHeight)
                {
                    minNoiseHeight = noiseHeight;
                }
                noiseMap[x, y] = noiseHeight;
            }
        }

        for (int y = 0; y < mapHeight; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                noiseMap[x, y] = Mathf.InverseLerp(minNoiseHeight, maxNoiseHeight, noiseMap[x, y]);
            }
        }

        return(noiseMap);
    }
Esempio n. 52
0
    public static float[,] GenerateNoiseMap(int mapWidth, int mapHeight, int seed, float scale, int octaves, float persistance, float lacunarity, Vector2 offset) //Handles the Generation of the noise map
    {
        float[,] noiseMap = new float[mapWidth, mapHeight];                                                                                                       //Makes a new 2D array of the map height nad width

        System.Random prng           = new System.Random(seed);                                                                                                   //Generates a random seed
        Vector2[]     octavesOffsets = new Vector2[octaves];
        for (int i = 0; i < octaves; i++)
        {
            float offsetX = prng.Next(-100000, 100000) + offset.x;
            float offsetY = prng.Next(-100000, 100000) + offset.y;
            octavesOffsets[i] = new Vector2(offsetX, offsetY);
        }

        if (scale <= 0) //Make sure that scale is not 0 as it would be dividing by 0
        {
            scale = 0.0001f;
        }

        float maxNoiseHeight = float.MinValue;
        float minNoiseHeight = float.MaxValue;

        float halfWidth  = mapWidth / 2f;
        float halfHeight = mapHeight / 2f;

        for (int y = 0; y < mapHeight; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                float amplitude   = 1;
                float frequency   = 1;
                float noiseHeight = 0;

                for (int i = 0; i < octaves; i++)
                {
                    float sampleX = (x - halfWidth) / scale * frequency + octavesOffsets[i].x;  //The higher the frequency the further apart the sample points will be whcih means the height values will change more rapidly
                    float sampleY = (y - halfHeight) / scale * frequency + octavesOffsets[i].y; //Choosing sample points

                    float perlinValue = Mathf.PerlinNoise(sampleX, sampleY) * 2 - 1;            //Generate perlin noise with the x and y values , * 2-1 is to have negative height
                    noiseHeight += perlinValue * amplitude;

                    amplitude *= persistance; //Decreases each octave
                    frequency *= lacunarity;  //Increases each octave
                }

                if (noiseHeight > maxNoiseHeight)
                {
                    maxNoiseHeight = noiseHeight;
                }
                else if (noiseHeight < minNoiseHeight)
                {
                    minNoiseHeight = noiseHeight;
                }

                noiseMap[x, y] = noiseHeight;
            }
        }

        for (int y = 0; y < mapHeight; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                noiseMap[x, y] = Mathf.InverseLerp(minNoiseHeight, maxNoiseHeight, noiseMap[x, y]);
            }
        }

        return(noiseMap);
    }
Esempio n. 53
0
    public void Start()
    {
        gameObject.transform.SetAsFirstSibling();
//        Debug.Log("EN PARAMETROS");
        int  index = 0;
        bool rep   = true;



        for (int i = 0; i < anim_gen.Length; i++)
        {
            rep = true;
            while (rep == true)
            {
                rep = false;
                System.Random rand = new System.Random();
                index = rand.Next(rutas.Length);
//                Debug.Log("ALEAT: " + index + "DE " + anim_gen.Length);
                anim_gen[i] = rutas[index];

                if (i == 0)
                {
                    if (anim_gen[0] == anim_gen[1] || anim_gen[0] == anim_gen[2] || anim_gen[0] == anim_gen[3])
                    {
                        rep = true;
                        //Debug.Log("ANIMAL REPETIDO :" +rep);
                    }
                }
                if (i == 1)
                {
                    if (anim_gen[1] == anim_gen[0] || anim_gen[1] == anim_gen[2] || anim_gen[1] == anim_gen[3])
                    {
                        rep = true;
                        //Debug.Log("ANIMAL REPETIDO :" +rep);
                    }
                }
                if (i == 2)
                {
                    if (anim_gen[2] == anim_gen[0] || anim_gen[2] == anim_gen[1] || anim_gen[2] == anim_gen[3])
                    {
                        rep = true;
                        //Debug.Log("ANIMAL REPETIDO :" +rep);
                    }
                }
                if (i == 3)
                {
                    if (anim_gen[3] == anim_gen[0] || anim_gen[3] == anim_gen[1] || anim_gen[3] == anim_gen[2])
                    {
                        rep = true;
                        //Debug.Log("ANIMAL REPETIDO :" +rep);
                    }
                }
            }
        }

        foreach (string i in anim_gen)
        {
//            Debug.Log("Animal Final" + i);
        }


        cargar_sombras();
        // WWW www = new WWW((rutas[index]));
        S1.SetActive(true);
        S2.SetActive(true);
        S3.SetActive(true);
        S4.SetActive(true);
        A1.SetActive(true);
        A2.SetActive(true);
        A3.SetActive(true);
        A4.SetActive(true);

        // yield return www;
        //img.sprite = Sprite.Create(www.texture, new Rect(0, 0, www.texture.width, www.texture.height), new Vector2(0, 0), 1);
    }
Esempio n. 54
0
    private int randomNumber()
    {
        Random rnd = new Random();

        return(rnd.Next(1, 7));
    }
    private Vector3[] PerlinMeshVerts(Vector3[] _verts, int seed, float scale, int octaves, float persistance, float lacunarity, float maxHeight)
    {
        for (int i = 0; i < _verts.Length; i++)
        {
            _verts[i] = _verts[i].normalized;
        }

        if (scale <= 0)
        {
            scale = 0.001f;
        }

        System.Random prng          = new System.Random(seed);
        Vector3[]     octaveOffsets = new Vector3[octaves];
        for (int i = 0; i < octaves; i++)
        {
            octaveOffsets[i] = new Vector3(prng.Next(-100000, 100000), prng.Next(-100000, 100000), prng.Next(-100000, 100000));
        }

        float mini = float.MaxValue;
        float maxi = float.MinValue;

        float[] noiseHeight = new float[_verts.Length];
        for (int i = 0; i < _verts.Length; i++)
        {
            float amplitude = 1;
            float frequency = 1;
            float noiseH    = 0;

            for (int k = 0; k < octaves; k++)
            {
                float sampleX = _verts[i].x / scale * frequency + octaveOffsets[k].x;
                float sampleY = _verts[i].y / scale * frequency + octaveOffsets[k].y;
                float sampleZ = _verts[i].z / scale * frequency + octaveOffsets[k].z;

                float perlinValue = Perlin3D(sampleX, sampleY, sampleZ);
                noiseH += perlinValue * amplitude;

                amplitude *= persistance;
                frequency *= lacunarity;
            }

            noiseHeight[i] = noiseH;

            if (noiseHeight[i] > maxi)
            {
                maxi = noiseHeight[i];
            }
            if (noiseHeight[i] < mini)
            {
                mini = noiseHeight[i];
            }
        }

        for (int i = 0; i < _verts.Length; i++)
        {
            _verts[i] *= 1 + Mathf.InverseLerp(mini, maxi, noiseHeight[i]) * (maxHeight - 1);
        }

        return(_verts);
    }
Esempio n. 56
0
 public int GetRandomInt(int min, int max)
 {
     return(rnd.Next(min, max));
 }
Esempio n. 57
0
    void Start()
    {
        int x = rand.Next(-9, 9);

        position = new Vector3(x, 6.0f, 0.0f);
    }
Esempio n. 58
0
 // Use this for initialization
 void Start()
 {
     notes = r.Next(1, 7);
 }
Esempio n. 59
0
    private void BuildDynamicItem(Vector3 viewDirection, System.Random rnd, int parentItemIndex, Transform parentTransform, int depth, int maxDepth)
    {
        if (depth > maxDepth || parentItemIndex < 0 || parentItemIndex >= itemDataArray.Length)
        {
            return;
        }

        ItemData parentItemData = itemDataArray[parentItemIndex];

        if (parentItemData.layoutOffsets != null && parentItemData.layoutOffsets.Length > 0)
        {
            reusableWeightList.Clear();

            for (int i = 0; i < parentItemData.layoutMetadata.Length; i++)
            {
                reusableWeightList.Add(parentItemData.layoutMetadata[i].GetWeight());
            }

            int selectedLayout = GetWeightedRandomIndex(reusableWeightList, rnd);

            int layoutOffset = parentItemData.layoutOffsets[selectedLayout];
            int layoutSize   = parentItemData.references.Length - layoutOffset;           // By default, layout size is the remaining segment of the reference array

            // If there is another layout, infer the layout size from the next offset
            if (selectedLayout + 1 < parentItemData.layoutOffsets.Length)
            {
                layoutSize = parentItemData.layoutOffsets[selectedLayout + 1] - layoutOffset;
            }

            for (int i = 0; i < layoutSize; i++)
            {
                ItemReferenceData itemReference = parentItemData.references[layoutOffset + i];

                // Add as many children as possible
                int childCount = Mathf.Max(1, itemReference.instanceCount);

                for (int j = 0; j < childCount; ++j)
                {
                    int childItemIndex = -1;

                    // First define the item to instantiate
                    if (itemReference.procedural)
                    {
                        if (itemReference.availableItemIndicesByTag.Length > 0)
                        {
                            // Reference is a random item, find it!
                            int randomIndex = rnd.Next(itemReference.availableItemIndicesByTag.Length);                         // TODO: weighted random by volume
                            childItemIndex = itemReference.availableItemIndicesByTag[randomIndex];
                        }
                    }
                    else
                    {
                        // Reference is a specific item; just instance it
                        if ((float)rnd.NextDouble() < itemReference.metadata.GetProbability())
                        {
                            childItemIndex = itemReference.itemIndex;
                        }
                    }

                    // Then just build it
                    if (childItemIndex >= 0)
                    {
                        Matrix4x4 childLocalMatrix = GetRandomTransformation(ref itemReference, ref itemDataArray[childItemIndex], rnd);
                        ItemData  childItemData    = itemDataArray[childItemIndex];

                        if (ShouldCullObject(ref childItemData, viewDirection, childLocalMatrix))
                        {
                            continue;
                        }

                        GameObject itemInstance = GameObject.Instantiate(itemPrefabs[childItemIndex].gameObject);
                        itemInstance.name                    = itemDataArray[childItemIndex].itemId;
                        itemInstance.transform.parent        = parentTransform;
                        itemInstance.transform.localPosition = ExtractTranslationFromMatrix(ref childLocalMatrix);
                        itemInstance.transform.localRotation = ExtractRotationFromMatrix(ref childLocalMatrix);
                        itemInstance.transform.localScale    = ExtractScaleFromMatrix(childLocalMatrix);

                        InterestPoint[] interestPoints = itemInstance.GetComponentsInChildren <InterestPoint>();

                        foreach (InterestPoint p in interestPoints)
                        {
                            p.AssociateItemBounds(itemInstance.transform, itemDataArray[childItemIndex].itemBounds);
                        }

                        CleanDynamicItem(itemInstance);

                        BuildDynamicItem(viewDirection, rnd, childItemIndex, itemInstance.transform, depth + 1, Mathf.Min(maxDepth, depth + itemReference.maxChildDepth));
                    }
                }
            }
        }
    }
Esempio n. 60
0
    public override BattleCommand Decide(BattleManager manager, BattleAgent agent, out Dictionary <string, object> selections)
    {
        if (agent["Turn:Action"] > 0)
        {
            // Randomly select an offensive command

            System.Random   rand    = new System.Random();
            List <Decision> options = new List <Decision>();

            foreach (BattleCommand command in agent.BaseCharacter.Commands)
            {
                if (command.Enabled(agent))
                {
                    Decision decision = new Decision(command);

                    foreach (BattleCommandSelection selection in command.Selections)
                    {
                        List <object> opts = selection.Select(manager, agent, decision.Selections, true);

                        if (opts.Count == 0)
                        {
                            decision = null;
                            break;
                        }
                        else
                        {
                            decision.Selections[selection.id] = opts[rand.Next() % opts.Count];
                        }
                    }

                    if (decision != null)
                    {
                        options.Add(decision);
                    }
                }
            }

            if (options.Count > 0)
            {
                Decision final = options[rand.Next() % options.Count];

                selections = final.Selections;
                return(final.Command);
            }

            if (agent["Turn:Move"] > 0)
            {
                // Move within range

                int         nearestDist = int.MaxValue;
                BattleAgent nearest     = null;
                foreach (BattleAgent other in manager.agents)
                {
                    int dist = PathFinder.ManhattanDistance(agent.Coordinates, other.Coordinates);
                    if (agent.Unit.Opposes(other.Unit) &&
                        dist < nearestDist)
                    {
                        nearestDist = dist;
                        nearest     = other;
                    }
                }

                int optDist; // TODO this section but better
                if (agent["Attack"] > agent["Magic"])
                {
                    optDist = 1;
                }
                else
                {
                    optDist = agent["Range:Magic [Offense]"] + agent["AoE:Magic [Offense]"];
                }

                List <Vector2Int>           points    = new List <Vector2Int>();
                BattleManhattanDistanceZone moveRange = Skill.GetRange("Move", agent);
                int closestDiff = int.MaxValue;
                foreach (Vector2Int point in moveRange)
                {
                    int dist = PathFinder.ManhattanDistance(nearest.Coordinates, point);
                    int diff = dist > optDist ? dist - optDist : optDist - dist;
                    if (diff <= closestDiff)
                    {
                        if (diff < closestDiff)
                        {
                            closestDiff = diff;
                            points      = new List <Vector2Int>();
                        }
                        points.Add(point);
                    }
                }

                if (points.Count > 0)
                {
                    // TODO pick point that closest target is facing furthest away from
                    selections = new Dictionary <string, object>();
                    selections["destination"] = new BattleManhattanDistanceZone(points[rand.Next() % points.Count], 0, 0);
                    return(AssetHolder.Commands["Move"]);
                }
            }
        }
        else if (agent["Turn:Move"] > 0)
        {
            // Move out of danger
        }

        // End turn
        selections = new Dictionary <string, object>();
        return(AssetHolder.Commands["End Turn"]);
    }