Example #1
10
        public User(StateManager stateMgr, API.Geo.World world)
        {
            this.mStateMgr = stateMgr;
            this.mWorld = world;
            this.mTimeSinceGUIOpen = new Timer();

            this.mCameraMan = null;
            this.IsAllowedToMoveCam = true;
            this.IsFreeCamMode = true;
            Camera cam = this.mStateMgr.Camera;
            cam.Position = new Vector3(-203, 633, -183);
            cam.Orientation = new Quaternion(0.3977548f, -0.1096644f, -0.8781486f, -0.2421133f);
            this.mCameraMan = new CameraMan(cam);
            this.mSelectedAllies = new HashSet<VanillaNonPlayer>();
            this.mRandom = new Random();

            this.mFigures = new MOIS.KeyCode[10];
            for (int i = 0; i < 9; i++)
                this.mFigures[i] = (MOIS.KeyCode)System.Enum.Parse(typeof(MOIS.KeyCode), "KC_" + (i + 1));
            this.mFigures[9] = MOIS.KeyCode.KC_0;

            this.mWireCube = this.mStateMgr.SceneMgr.RootSceneNode.CreateChildSceneNode();
            this.mWireCube.AttachObject(StaticRectangle.CreateRectangle(this.mStateMgr.SceneMgr, Vector3.UNIT_SCALE * Cst.CUBE_SIDE));
            this.mWireCube.SetVisible(false);

            this.Inventory = new Inventory(10, 4, new int[] { 3, 0, 1, 2 }, true);
        }
        public void TestPriorityQueue()
        {
            int operationsCount = 100000;

            Random rand = new Random(0);

            PriorityQueue<double> queue = new PriorityQueue<double>();

            for (int op = 0; op < operationsCount; ++op)
            {
                int opType = rand.Next(0, 2);

                if (opType == 0) // Enqueue
                {
                    double item = (100.0 - 1.0) * rand.NextDouble() + 1.0;
                    queue.Enqueue(item);

                    Assert.IsTrue(queue.IsConsistent(), "Test fails after enqueue operation # " + op);
                }
                else // Dequeue
                {
                    if (queue.Count > 0)
                    {
                        double item = queue.Dequeue();
                        Assert.IsTrue(queue.IsConsistent(), "Test fails after dequeue operation # " + op);
                    }
                }
            }
        }
Example #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);
            }
        }
Example #4
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();
        }
Example #5
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());
                }
            }
        }
Example #6
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);
            }
        }
Example #7
1
 static void Main(string[] args)
 {
     int num = 10;
     var matrix = new int[num, num];
     Console.WriteLine("Before : ");
     for (int i = 0; i < num; ++i)
     {
         for (int j = 0; j < num; ++j)
         {
             Random rand = new Random();
             matrix[i, j] = -i + j + rand.Next(0, 80);
             Console.Write(matrix[i, j]);
             Console.Write(' ');
         }
         Console.WriteLine();
     }
     Console.WriteLine("After : ");
     matrix = BubbleSort(matrix, num);
     for (int i = 0; i < num; ++i)
     {
         for (int j = 0; j < num; ++j)
         {
             Console.Write(matrix[i, j]);
             Console.Write(' ');
         }
         Console.WriteLine();
     }
     Console.ReadKey();
 }
 /// <summary>
 ///   Initializes the strategy with the specified nodes and cluster configuration
 /// </summary>
 /// <param name="nodes"> The nodes. </param>
 /// <param name="config"> The config. </param>
 public ExclusiveConnectionStrategy(Ring nodes, ClusterConfig config)
 {
     _nodes = nodes;
     _config = config;
     _connections = new ConcurrentStack<Connection>();
     _rndGen = new Random((int)DateTime.Now.Ticks);
 }
Example #9
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();
            }
        }
Example #10
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);
                }
            }
        }
        public void TestConcurrentQueueDeclare()
        {
            string x = GenerateExchangeName();
            Random rnd = new Random();

            List<Thread> ts = new List<Thread>();
            System.NotSupportedException nse = null;
            for(int i = 0; i < 256; i++)
            {
                Thread t = new Thread(() =>
                        {
                            try
                            {
                                // sleep for a random amount of time to increase the chances
                                // of thread interleaving. MK.
                                Thread.Sleep(rnd.Next(5, 500));
                                Model.ExchangeDeclare(x, "fanout", false, false, null);
                            } catch (System.NotSupportedException e)
                            {
                                nse = e;
                            }
                        });
                ts.Add(t);
                t.Start();
            }

            foreach (Thread t in ts)
            {
                t.Join();
            }

            Assert.IsNotNull(nse);
            Model.ExchangeDelete(x);
        }
Example #12
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);
		    
		}
Example #13
1
        protected void LinkButton3_Click(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AppendHeader("Content-encoding", "");

            Random random = new Random();
            imgCaptcha.ImageUrl = imgCaptcha.ImageUrl + "?" + random.ToString();
        }
Example #14
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;
		}
        private void btnAddPID_Click(object sender, EventArgs e)
        {
            if (tbPID.EditValue == null || tbPID.EditValue.ToString().Trim() == string.Empty)
            {
                return;
            }
            if (!dxvp.Validate(ccbProxy))
                return;
            string[] PIDs = tbPID.EditValue.ToString().Split('\n');
            string[] proxies = ccbProxy.EditValue.ToString().Split(',');
            Random rnd = new Random();
            foreach (string pid in PIDs)
            {
                if (pid.Trim() == string.Empty)
                   continue;
                _flagList.Add(new Datasource.FlagUnit("", 0, "", pid.Trim(), "Unknown", "Unknown"));
                foreach (string proxy in proxies)
                {
                    int id = rnd.Next(0, dsData.UserAgent.Count);
                    Datasource.FlagUnit data = new Datasource.FlagUnit(proxy, dsData.UserAgent[id].UserAgentId, dsData.UserAgent[id].UserAgentName, pid.Trim(), "Unknown", "Unknown");
                    _flagQue.Enqueue(data);
                    gridControlPID.RefreshDataSource();
                }
            }

            tbPID.EditValue = null;
        }
Example #16
1
        public ViewModel()
        {
            mgt = new ManagementClass("Win32_Processor");
            procs = mgt.GetInstances();

            CPU = new ObservableCollection<Model>();
            timer = new DispatcherTimer();
            random = new Random();
            time = DateTime.Now;
            cpuCounter = new PerformanceCounter();
            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";
            ramCounter = new PerformanceCounter("Memory", "Available MBytes");
            ProcessorID = GetProcessorID();
            processes = Process.GetProcesses();
            Processes = processes.Length;
            MaximumSpeed = GetMaxClockSpeed();
            LogicalProcessors = GetNumberOfLogicalProcessors();
            Cores = GetNumberOfCores();
            L2Cache = GetL2CacheSize();
            L3Cache = GetL3CacheSize();
            foreach (ManagementObject item in procs)
                L1Cache = ((UInt32)item.Properties["L2CacheSize"].Value / 2).ToString() + " KB";

            timer.Interval = TimeSpan.FromMilliseconds(1000);
            timer.Tick += timer_Tick;
            timer.Start();
            for (int i = 0; i < 60; i++)
            {
                CPU.Add(new Model(time, 0,0));
                time = time.AddSeconds(1);
            }
        }
Example #17
1
 public void ProcessRequest(HttpContext context)
 {
     context.Response.ContentType = "text/plain";
     context.Response.Clear();
     if (context.Request.Files.Count > 0)
     {
         try
         {
             HttpPostedFile httpPostFile = context.Request.Files[0];
             string file = context.Request.Form["Filename"].ToString();
             string fileType = file.Substring(file.LastIndexOf('.')).ToLower();
             Random r = new Random();
             string fileName = DateTime.Now.ToString("yyyyMMdd-HHmmss-ms") + r.Next(100, 999) + fileType;
             string serverPath = System.Configuration.ConfigurationSettings.AppSettings["ImageUploadPath"];
             httpPostFile.SaveAs(context.Server.MapPath(serverPath + fileName));
             context.Application["ImageUrl"] = serverPath + fileName;
             context.Response.Write("UP_OK");
         }
         catch
         {
             context.Response.Write("UP_FAILE");
         }
     }
     else
     {
         context.Response.Write("UP_FAILE");
     }
 }
        private EntityCollection GenerateRandomAccountCollection()
        {
            var collection = new List<Entity>();
            for (var i = 0; i < 10; i++)
            {
                var rgn = new Random((int)DateTime.Now.Ticks);
                var entity = new Entity("account");
                entity["accountid"] = entity.Id = Guid.NewGuid();
                entity["address1_addressid"] = Guid.NewGuid();
                entity["modifiedon"] = DateTime.Now;
                entity["lastusedincampaign"] = DateTime.Now;
                entity["donotfax"] = rgn.NextBoolean();
                entity["new_verybignumber"] = rgn.NextInt64();
                entity["exchangerate"] = rgn.NextDecimal();
                entity["address1_latitude"] = rgn.NextDouble();
                entity["numberofemployees"] = rgn.NextInt32();
                entity["primarycontactid"] = new EntityReference("contact", Guid.NewGuid());
                entity["revenue"] = new Money(rgn.NextDecimal());
                entity["ownerid"] = new EntityReference("systemuser", Guid.NewGuid());
                entity["industrycode"] = new OptionSetValue(rgn.NextInt32());
                entity["name"] = rgn.NextString(15);
                entity["description"] = rgn.NextString(300);
                entity["statecode"] = new OptionSetValue(rgn.NextInt32());
                entity["statuscode"] = new OptionSetValue(rgn.NextInt32());
                collection.Add(entity);
            }

            return new EntityCollection(collection);
        }
        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();
        }
        static void Main2(string[] args)
        {
            var numReal = new List<double>(80);
            Random gerador = new Random();
            double maior = 0;
            double menor = 0;
            double soma = 0;
            double media = 0;
            for (int i = 0; i < 80; i++)
            {
                numReal.Add(gerador.NextDouble());
                if (i == 0)
                {
                    maior = numReal[i];
                    menor = numReal[i];
                }
                soma += numReal[i];

            }
            media = soma / 80;
            for (int i = 0; i < 80; i++)
            {
                maior = (numReal[i] > maior) ? numReal[i] : maior;
                menor = (numReal[i] < menor) ? numReal[i] : menor;
            }
            Console.WriteLine("Maior: {0:F2}", maior);
            Console.WriteLine("Menor: {0:F2}", menor);
            Console.WriteLine("Soma: {0:F2}", soma);
            Console.WriteLine("Media: {0:F2}", media);
            Console.ReadKey();
        }
Example #21
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;
 }
Example #22
0
        public static void Main()
        {
            var someActivities = new string[] {
                "Pesho beshe na more",
                "Boil ima novo kuche",
                "Neli chete GoT"
            };

            var rng = new Random();

            var newsFeedList = new List<UserNewsFeed>();

            // slow operation simulation
            Console.WriteLine("Request weather report from the server");
            var weatherReport = Server.GetWeatherReport();
            Console.WriteLine("Report reveceived for: " + 2000 + " miliseconds");

            // cloning proves a lot faster in that case
            for (int i = 0; i < 4; i++)
            {
                var activity = someActivities[rng.Next() % 3];
                newsFeedList.Add(new UserNewsFeed(activity, (WeatherReport)weatherReport.Clone()));
            }

            foreach (var item in newsFeedList)
            {
                Console.WriteLine("\n" + item + "\n ");
            }
        }
Example #23
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);

            }
        }
Example #24
0
        public static void Main(string[] args)
        {
            OrderedMultiDictionary<double, Article> articles = new OrderedMultiDictionary<double, Article>(true);
            Random randomNumberGenerator = new Random();
            double randomNumber;
            for (int i = 0; i < 2000000; i++)
            {
                randomNumber = randomNumberGenerator.NextDouble() * MaxValue;
                Article article = new Article("barcode" + i, "vendor" + i, "article" + i, randomNumber);
                articles.Add(article.Price, article);
            }

            Console.Write("from = ");
            double from = double.Parse(Console.ReadLine());
            Console.Write("to = ");
            double to = double.Parse(Console.ReadLine());
            var articlesInRange = articles.Range(from, true, to, true);
            foreach (var pair in articlesInRange)
            {
                foreach (var article in pair.Value)
                {
                    Console.WriteLine("{0} => {1}", Math.Round(article.Price, 2), article);
                }
            }
        }
Example #25
0
        public DefaultMapGenerator(long seed)
        {
            Frequency = 0.03;
            Lacunarity = 0.01;
            Persistance = 0.01;
            OctaveCount = 1;

            Seed = seed;
            CaveNoise = new Perlin();
            TreeNoise = new Perlin();
            CaveNoise.Seed = (int)Seed + 3;
            TreeNoise.Seed = (int)Seed + 4;
            rand = new Random((int)Seed);

            CaveNoise.Frequency = Frequency;
            CaveNoise.NoiseQuality = NoiseQuality;
            CaveNoise.OctaveCount = OctaveCount+2;
            CaveNoise.Lacunarity = Lacunarity;
            CaveNoise.Persistence = Persistance;

            TreeNoise.Frequency = Frequency+2;
            TreeNoise.NoiseQuality = NoiseQuality;
            TreeNoise.OctaveCount = OctaveCount;
            TreeNoise.Lacunarity = Lacunarity;
            TreeNoise.Persistence = Persistance;
        }
Example #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]
         }
     };
 }
Example #27
0
        public Forest(string name, int minEnemies, int maxEnemies)
        {
            Random rand = new Random();
              this.name = name;
              this.genericName = "forest";
              this.genericPlural = "forests";
              this.genericDescription = new List<string>();
              this.genericDescription.Add("{0} surrounds you and you hear birds chirping in the trees above.");
              this.genericDescription.Add("{0} spreads out before you, beams of sunlight piercing through the canopy of leaves above.");
              this.genericDescription.Add("{0} appears to be more of a plain with a few trees here and there.");

              int enemies = rand.Next(minEnemies, maxEnemies);

              for (int i = 0; i < enemies; i++)
              {
            int randomName = rand.Next(0, CharacterNames.namesEnemies.Count);
            int minValue = Math.Max((Program.currentGame.player.level - 1), 1);
            int maxValue = Program.currentGame.player.level + 1;
            int randomFortitude = rand.Next(minValue, maxValue);
            int randomStrength = rand.Next(minValue, maxValue);
            int randomSpeed = rand.Next(minValue, maxValue);
            int randomDexterity = rand.Next(minValue, maxValue);

            this.enemies.Add(new Enemy(CharacterNames.namesEnemies[randomName], randomFortitude, randomStrength, randomSpeed, randomDexterity));
              }
        }
Example #28
0
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            int[] numbers = new int[n];
            Random rand = new Random();

            for (int i = 0; i < numbers.Length; i++)
            {
                numbers[i] = rand.Next(1, 100);
            }

            int startArraySort = Environment.TickCount;
            Array.Sort(numbers);
            Console.WriteLine("Array sort in miliseconds: " + (Environment.TickCount - startArraySort));

            int startSort = Environment.TickCount;
            var sortedOdd = numbers
                .Where(number => number % 2 == 1)
                .OrderByDescending(number => number);
            Console.WriteLine("Array sort in milisecond: " + (Environment.TickCount - startSort));

            int lastArray = Environment.TickCount;
            var sortedEven = numbers
                .Where(number => number % 2 == 0)
                .OrderBy(number => number);
            Console.WriteLine("Array sort in miliseconds: " + (Environment.TickCount - lastArray));
        }
        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);
        }
        public ActionResult Create(Post post)
        {

            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            var stringChars = new char[8];
            var random = new Random();

            for (int i = 0; i < stringChars.Length; i++)
            {
                stringChars[i] = chars[random.Next(chars.Length)];
            }

            var finalString = new String(stringChars);//this is random key

            post.ID = finalString;
            //ViewBag.data = post.ID;
            if (ModelState.IsValid)
            {
                db.Posts.Add(post);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

           
            return View(post);
        }
Example #31
0
    void Game()
    {
        time -= Time.deltaTime;
        if (IsCycle)
        {
            if (time < 0f)
            {
                time    = DeadTime;
                IsCycle = false;
                for (int i = 0; i < playerList.Count;)
                {
                    CharaControl charaControl = playerList[i].GetComponent <CharaControl>();
                    if (charaControl.healthState == CharaControl.HEALTH_STATE.OUTBREAK)
                    {
                        charaControl.Dead();
                        playerList.RemoveAt(i);

                        if (i == 0)
                        {
                            isWinner         = false;
                            tagState         = TagState.FINISH;
                            noticeText.text  = "LOSE";
                            noticeText.color = Colors.DarkBlue;
                            break;
                        }
                        if (playerList.Count == 1)
                        {
                            isWinner         = true;
                            tagState         = TagState.FINISH;
                            noticeText.text  = "Win";
                            noticeText.color = Colors.Gold;
                            break;
                        }
                    }
                    i++;
                }
            }
            string timeStr;
            int    timeDecimal = Mathf.FloorToInt((time - Mathf.Floor(time)) * 100f);
            timeStr = string.Format("{0:D2}:{1:D2}", Mathf.FloorToInt(time), timeDecimal);
            timerText.SetText(timeStr);
            if (time < 10f)
            {
                timerText.color = Color.red;
            }
            else
            {
                timerText.color = Color.white;
            }
        }
        else
        {
            timerText.SetText("BREAK");
            timerText.color = Color.yellow;
            if (time < 0f)
            {
                time    = CycleTime;
                IsCycle = true;

                System.Random rand = new System.Random();
                CharaControl  nextOutbreakChara = playerList[rand.Next(playerList.Count)].GetComponent <CharaControl>();
                nextOutbreakChara.Caught();
            }
        }


        if (!Debug.isDebugBuild)
        {
            return;
        }

        if (Input.GetAxis("ChangeCamera") > 0.9f && !trigger)
        {
            playerList[targetCamera].GetComponentInChildren <Camera>().depth = -1;
            targetCamera++;
            if (targetCamera >= playerList.Count)
            {
                targetCamera = 0;
            }
            playerList[targetCamera].GetComponentInChildren <Camera>().depth = 0;
            trigger = true;
        }

        if (Input.GetAxis("ChangeCamera") < -0.9f && !trigger)
        {
            playerList[targetCamera].GetComponentInChildren <Camera>().depth = -1;
            targetCamera--;
            if (targetCamera < 0)
            {
                targetCamera = playerList.Count - 1;
            }
            playerList[targetCamera].GetComponentInChildren <Camera>().depth = 0;
            trigger = true;
        }

        if (Mathf.Abs(Input.GetAxis("ChangeCamera")) < 0.9f)
        {
            trigger = false;
        }
    }
Example #32
0
    public void GenerateMap()
    {
        currentMap = maps[mapIndex];
        tileMap    = new Transform[currentMap.mapSize.x, currentMap.mapSize.y];
        System.Random prng = new System.Random(currentMap.seed);

        //Generating coords
        allTileCoords = new List <Coord>();
        for (int x = 0; x < currentMap.mapSize.x; x++)
        {
            for (int y = 0; y < currentMap.mapSize.y; y++)
            {
                allTileCoords.Add(new Coord(x, y));
            }
        }
        shuffledTileCoords = new Queue <Coord>(Utility.ShuffleArray(allTileCoords.ToArray(), currentMap.seed));

        //Create map holder object
        string holderName = "Generated Map";

        if (transform.Find(holderName))
        {
            DestroyImmediate(transform.Find(holderName).gameObject);
        }

        Transform mapholder = new GameObject(holderName).transform;

        mapholder.parent = transform;

        //Spawning tiles
        for (int x = 0; x < currentMap.mapSize.x; x++)
        {
            for (int y = 0; y < currentMap.mapSize.y; y++)
            {
                Vector3   tilePosition = CoordToPosition(x, y);
                Transform newTile      = Instantiate(tilePrefab, tilePosition, Quaternion.Euler(Vector3.right * 90)) as Transform;
                newTile.localScale = Vector3.one * (1 - outlinePercent) * tileSize;
                newTile.parent     = mapholder;
                tileMap[x, y]      = newTile;
            }
        }

        //Spawning obstacles
        bool[,] obstaclemap = new bool[(int)currentMap.mapSize.x, (int)currentMap.mapSize.y];

        int          obstacleCount        = (int)(currentMap.mapSize.x * currentMap.mapSize.y * currentMap.obstaclePercent);
        int          currectObstacleCount = 0;
        List <Coord> allOpenCoords        = new List <Coord>(allTileCoords);

        for (int i = 0; i < obstacleCount; i++)
        {
            Coord randomCoord = GetRandomCoord();
            obstaclemap[randomCoord.x, randomCoord.y] = true;
            currectObstacleCount++;

            if (randomCoord != currentMap.mapCentre && MapIsFullyAccesible(obstaclemap, currectObstacleCount))
            {
                float   obstacleHeight = Mathf.Lerp(currentMap.minObstacleHeight, currentMap.maxObstacleheight, (float)prng.NextDouble());
                Vector3 obtsaclePos    = CoordToPosition(randomCoord.x, randomCoord.y);

                Transform newObstacle = Instantiate(obstaclePrefab, obtsaclePos + Vector3.up * obstacleHeight / 2, Quaternion.identity) as Transform;
                newObstacle.parent     = mapholder;
                newObstacle.localScale = new Vector3((1 - outlinePercent) * tileSize, obstacleHeight, ((1 - outlinePercent) * tileSize));

                Renderer obstacleRenderer = newObstacle.GetComponent <Renderer>();
                Material obstacleMaterial = new Material(obstacleRenderer.sharedMaterial);
                float    colourPercent    = randomCoord.y / (float)currentMap.mapSize.y;
                obstacleMaterial.color          = Color.Lerp(currentMap.foregroundColour, currentMap.backgroundColour, colourPercent);
                obstacleRenderer.sharedMaterial = obstacleMaterial;

                allOpenCoords.Remove(randomCoord);
            }
            else
            {
                obstaclemap[randomCoord.x, randomCoord.y] = false;
                currectObstacleCount--;
            }
        }

        shuffledOpenTileCoords = new Queue <Coord>(Utility.ShuffleArray(allOpenCoords.ToArray(), currentMap.seed));

        //Creating navmeshmask
        Transform maskLeft = Instantiate(navmeshmaskPrefab, Vector3.left * (currentMap.mapSize.x + maxMapSize.x) / 4f * tileSize, Quaternion.identity) as Transform;

        maskLeft.parent     = mapholder;
        maskLeft.localScale = new Vector3((maxMapSize.x - currentMap.mapSize.x) / 2f, 1, currentMap.mapSize.y) * tileSize;

        Transform maskRight = Instantiate(navmeshmaskPrefab, Vector3.right * (currentMap.mapSize.x + maxMapSize.x) / 4f * tileSize, Quaternion.identity) as Transform;

        maskRight.parent     = mapholder;
        maskRight.localScale = new Vector3((maxMapSize.x - currentMap.mapSize.x) / 2f, 1, currentMap.mapSize.y) * tileSize;

        Transform maskTop = Instantiate(navmeshmaskPrefab, Vector3.forward * (currentMap.mapSize.y + maxMapSize.y) / 4f * tileSize, Quaternion.identity) as Transform;

        maskTop.parent     = mapholder;
        maskTop.localScale = new Vector3(maxMapSize.x, 1, (maxMapSize.y - currentMap.mapSize.y) / 2f) * tileSize;

        Transform maskBottom = Instantiate(navmeshmaskPrefab, Vector3.back * (currentMap.mapSize.y + maxMapSize.y) / 4f * tileSize, Quaternion.identity) as Transform;

        maskBottom.parent     = mapholder;
        maskBottom.localScale = new Vector3(maxMapSize.x, 1, (maxMapSize.y - currentMap.mapSize.y) / 2f) * tileSize;

        navmeshFloor.localScale = new Vector3(maxMapSize.x, maxMapSize.y) * tileSize;
        mapFloor.localScale     = new Vector3(currentMap.mapSize.x * tileSize, currentMap.mapSize.y * tileSize);
    }
 private void Start()
 {
     countdown = 1f;
     r = new System.Random();
 }
 public static Color RandomSkyColor(System.Random random) => instance._skyColors.RandomItem(random);
 public static GameObject RandomTree(System.Random random) => instance._treePrefabs.RandomItem(random);
Example #36
0
    public static float[,] GenNoiseMap(int mapWidth, int mapHeight, int seed, float scale, int octaves, float persistance, float lacunarity)
    {
        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);
            float offsetY = prng.Next(-100000, 100000);
            octaveOffsets[i] = new Vector2(offsetX, offsetY);
        }

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

        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 = 1;
                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);
    }
 void Awake()
 {
     Instance = this;
     random   = new System.Random();
     Reset();
 }
Example #38
0
    IEnumerator StudentReactionFourInitiate()
    {
        print("SR 4 started");
        int randomWritingStudent = Random.Range(0, gamePlayManager.studentsActions.Count);

        gamePlayManager.studentsActions[randomWritingStudent].studentAnimation.MB33_WorkOnSheets(true);



        yield return(new WaitForSeconds(2f));

        print("Teacher goes to Table 3 and looks at the students there");

        GameObject.FindGameObjectWithTag("Player").GetComponent <PlayerMovement>().LookToPlayer(true, gamePlayManager.GetComponent <MainObjectsManager>().Table3);
        GameObject.FindGameObjectWithTag("Player").GetComponent <PlayerMovement>().MovePlayer(true, gamePlayManager.GetComponent <MainObjectsManager>().Table3MoveToPoint);
        if (table1KidsTalking.isPlaying)
        {
            table1KidsTalking.Stop();
        }
        if (table2KidsTalking.isPlaying)
        {
            table2KidsTalking.Stop();
        }
        if (table3KidsTalking.isPlaying)
        {
            table3KidsTalking.Stop();
        }
        if (table4KidsTalking.isPlaying)
        {
            table4KidsTalking.Stop();
        }

        print("All students except the writing one look at the teacher");
        // int table3talkingstudentsCount= 1;
        // StudentAction table3student1toTalk, table3student2toTalk, table3student3toTalk;
        // table3student1toTalk = null;
        // table3student2toTalk = null;
        // table3student3toTalk = null;
        foreach (StudentAction studentAction in gamePlayManager.studentsActions)
        {
            studentAction.LookAtWindowRoutineStop();
            studentAction.LookAroundOrTalkOrWriteRoutineStop();
            // studentAction.studentAnimation.ResetAllAnim();
            if (studentAction != gamePlayManager.studentsActions[randomWritingStudent])
            {
                if (studentAction.studentAnimation.GetAnimStateBool("vi7_Talk_ON"))
                {
                    studentAction.studentAnimation.VI7_TalkToFriendsStop();
                }
                if (studentAction.studentAnimation.GetAnimStateBool("mb33_WriteOnSheet_ON"))
                {
                    studentAction.studentAnimation.MB33_WorkOnSheets(false);
                }

                var teacherPositon = GameObject.FindGameObjectWithTag("Player").transform;
                studentAction.LookAtSomeone(teacherPositon);
            }
            yield return(new WaitForSeconds(Random.Range(0.1f, 0.5f)));
        }


        yield return(new WaitUntil(() => !GameObject.FindGameObjectWithTag("Player").GetComponent <PlayerMovement>().isMove));

        print("Teacher looks at table 3 students");
        yield return(new WaitForSeconds(3f));

        print("Teacher goes back to original place");
        //GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerMovement>().l;
        GameObject.FindGameObjectWithTag("Player").GetComponent <PlayerMovement>().MovePlayerToOriginalPostion(true);
        yield return(new WaitForSeconds(1.5f));

        print("Talking students at Table 3 start talking back");
        foreach (StudentAction studentAction in Table3TalkingKids)
        {
            studentAction.studentAnimation.VI7_TalkToFriendsLeftAndRight();
            yield return(null);
        }
        if (!table3KidsTalking.isPlaying)
        {
            table1KidsTalking.volume = 0.2f; table3KidsTalking.PlayDelayed(1f);
        }
        yield return(new WaitUntil(() => !GameObject.FindGameObjectWithTag("Player").GetComponent <PlayerMovement>().isMove));


        print("Other students start to work");
        foreach (StudentAction studentAction in gamePlayManager.studentsActions)
        {
            studentAction.LookAtWindowRoutineStop();
            studentAction.LookAroundOrTalkOrWriteRoutineStop();
            // studentAction.studentAnimation.ResetAllAnim();
            if (studentAction != gamePlayManager.studentsActions[randomWritingStudent])
            {
                studentAction.StopLookAtSomeone();
                if (!gamePlayManager.GetComponent <MainObjectsManager>().studentsAtTable3.Contains(studentAction))
                {
                    if (!Table3TalkingKids.Contains(studentAction))
                    {
                        studentAction.studentAnimation.MB33_WorkOnSheets(true);
                    }
                }
            }
            yield return(new WaitForSeconds(Random.Range(0.1f, 0.5f)));
        }
        print("14 of the students that work wispher in pairs");
        var sampleStudents = new int[Random.Range(0, 15)];
        var rnd            = new System.Random();

        for (int i = 0; i < sampleStudents.Length - 1; i += 2)
        {
            sampleStudents[i] = rnd.Next(gamePlayManager.studentsAsNeighboursActions.Count);
            gamePlayManager.studentsAsNeighboursActions[sampleStudents[i]].studentAnimation.MB33_WorkOnSheets(false);
            yield return(null);

            gamePlayManager.studentsAsNeighboursActions[sampleStudents[i]].studentAnimation.VI11_TalkToFriendsLeftAndRight();
            if (sampleStudents[i] + 1 < gamePlayManager.studentsAsNeighboursActions.Count)
            {
                gamePlayManager.studentsAsNeighboursActions[sampleStudents[i] + 1].studentAnimation.MB33_WorkOnSheets(false);
                yield return(null);

                gamePlayManager.studentsAsNeighboursActions[sampleStudents[i] + 1].studentAnimation.VI11_TalkToFriendsLeftAndRight();
            }
            if (!table1KidsTalking.isPlaying)
            {
                table1KidsTalking.volume = 0.1f; table1KidsTalking.PlayDelayed(1f);
            }
            if (!table2KidsTalking.isPlaying)
            {
                table2KidsTalking.volume = 0.1f; table2KidsTalking.PlayDelayed(1f);
            }
            if (!table4KidsTalking.isPlaying)
            {
                table4KidsTalking.volume = 0.1f; table4KidsTalking.PlayDelayed(1f);
            }
            yield return(new WaitForSeconds(Random.Range(0.1f, 0.5f)));
            //           print("selected student from table 3 to talk is " + sampleStudents[i].ToString() + " who is "+ gamePlayManager.GetComponent<MainObjectsManager>().studentsAtTable3[sampleStudents[i]].name);
        }



        yield return(new WaitForSeconds(6f));


        print("SR 4 Complete");
        yield return(null);
    }
Example #39
0
    IEnumerator TriggerSRInitialActions(int whoCalled)
    {
        print("Initial Actions for SR starts");

        //make the scene ready for SR actions

        //switch off all the kids talking sounds
        if (table1KidsTalking.isPlaying)
        {
            table1KidsTalking.Stop();
        }
        if (table2KidsTalking.isPlaying)
        {
            table2KidsTalking.Stop();
        }
        if (table4KidsTalking.isPlaying)
        {
            table4KidsTalking.Stop();
        }

        GameObject.FindGameObjectWithTag("Player").GetComponent <PlayerMovement>().MovePlayerToOriginalPostion(true);

        yield return(new WaitUntil(() => !GameObject.FindGameObjectWithTag("Player").GetComponent <PlayerMovement>().isMove));


        print("All students except table 3, resume working on their worksheets");
        foreach (StudentAction studentAction in gamePlayManager.studentsActions)
        {
            studentAction.LookAtWindowRoutineStop();
            studentAction.LookAroundOrTalkOrWriteRoutineStop();
            // studentAction.studentAnimation.ResetAllAnim();
            if (!gamePlayManager.GetComponent <MainObjectsManager>().studentsAtTable3.Contains(studentAction))
            {
                if (studentAction.studentAnimation.GetAnimStateBool("vi7_Talk_ON"))
                {
                    studentAction.studentAnimation.VI7_TalkToFriendsStop();
                }
                studentAction.studentAnimation.MB33_WorkOnSheets(true);
            }
            yield return(new WaitForSeconds(Random.Range(0.1f, 0.5f)));
        }
        print("selectiing a few students to talk from table 3");
        var totatStudentsinTable3 = gamePlayManager.GetComponent <MainObjectsManager>().studentsAtTable3.Count;
        var sampleStudents        = new int[Random.Range(2, totatStudentsinTable3)];
        var rnd = new System.Random();

        for (int i = 0; i < sampleStudents.Length; ++i)
        {
            sampleStudents[i] = rnd.Next(totatStudentsinTable3);
            //           print("selected student from table 3 to talk is " + sampleStudents[i].ToString() + " who is "+ gamePlayManager.GetComponent<MainObjectsManager>().studentsAtTable3[sampleStudents[i]].name);
        }
        Table3TalkingKids.Clear();
        Table3TalkingKidsTransform.Clear();


        //if (whoCalled == 3)
        //{
        //    table1KidsTalking.volume = 0.05f; // just mumbling
        //    table2KidsTalking.volume = 0.05f; // just mumbling
        //    table4KidsTalking.volume = 0.05f; // just mumbling
        //    table1KidsTalking.PlayDelayed(Random.Range(0.5f,1f));
        //    table2KidsTalking.PlayDelayed(Random.Range(0.5f, 1f));
        //    table4KidsTalking.PlayDelayed(Random.Range(0.5f, 1f));
        //}

        if (!table3KidsTalking.isPlaying)
        {
            table3KidsTalking.volume = 0.2f;
            table3KidsTalking.PlayDelayed(1f);
        }


        for (int i = 0; i < sampleStudents.Length; i++)
        {
            // print( sampleStudents[i].ToString() + " who is " + gamePlayManager.GetComponent<MainObjectsManager>().studentsAtTable3[sampleStudents[i]].name + "start to Talk");

            Table3TalkingKids.Add(gamePlayManager.GetComponent <MainObjectsManager>().studentsAtTable3[i]);
            Table3TalkingKidsTransform.Add(gamePlayManager.GetComponent <MainObjectsManager>().studentsAtTable3[i].transform);
            gamePlayManager.GetComponent <MainObjectsManager>().studentsAtTable3[sampleStudents[i]].studentAnimation.MB33_WorkOnSheets(false);
            yield return(null);

            gamePlayManager.GetComponent <MainObjectsManager>().studentsAtTable3[sampleStudents[i]].studentAnimation.VI7_TalkToFriendsLeftAndRight();
            yield return(new WaitForSeconds(Random.Range(0.1f, 1f)));
        }

        print("Finished Initial Actions");
        yield return(new WaitForSeconds(2.0f));

        switch (whoCalled)
        {
        case 1:
            StartCoroutine(StudentReactionOneInitiate());
            break;

        case 2:
            StartCoroutine(StudentReactionTwoInitiate());
            break;

        case 3:
            StartCoroutine(StudentReactionThreeInitiate());
            break;

        case 4:
            StartCoroutine(StudentReactionFourInitiate());
            break;
        }
    }
Example #40
0
 private void Start()
 {
     rand   = new System.Random(seed);
     anim   = GetComponent <Animator>();
     oneInX = oneInX == 0 ? 200 : oneInX;
 }
Example #41
0
    public void TractorBeam()
    {
        GameObject[] drops = GameObject.FindGameObjectsWithTag("DroppedPiece");
        if (drops.Length <= 0)
        {
            return;
        }

        if (superPercentage < tractorBeamCost)
        {
            Debug.Log("not enough super!");
            return;
        }
        else
        {
            SpendSuperPercent(tractorBeamCost);
        }

        //get the subset of super rares
        List <GameObject> superRares = new List <GameObject>();

        foreach (GameObject drop in drops)
        {
            Drop d = drop.GetComponent <Drop>();
            if (d.GetRarity() == 2)
            {
                superRares.Add(drop);
            }
        }
        //subset of rares
        List <GameObject> rares = new List <GameObject>();

        foreach (GameObject drop in drops)
        {
            Drop d = drop.GetComponent <Drop>();
            if (d.GetRarity() == 1)
            {
                rares.Add(drop);
            }
        }

        System.Random r          = new System.Random();
        int           index      = 0;
        GameObject    dropTarget = null;

        if (superRares.Count > 0)
        {
            double dindex = r.NextDouble() * superRares.Count;
            index      = (int)dindex;
            dropTarget = superRares[index];
        }
        else if (rares.Count > 0)
        {
            double dindex = r.NextDouble() * rares.Count;
            index      = (int)dindex;
            dropTarget = rares[index];
        }
        else
        {
            double dindex = r.NextDouble() * drops.Length;
            index      = (int)dindex;
            dropTarget = drops[index];
        }
        dropTarget.tag = "Untagged";

        GameObject tractorBeam = Instantiate(Resources.Load("Prefabs/MainCanvas/TractorBeam")) as GameObject;

        tractorBeam.transform.SetParent(Dial.underLayer, false);
        tractorBeam.GetComponent <TractorBeam>().SetTarget(dropTarget);
    }
Example #42
0
 private void Start()
 {
     DynamicGI.UpdateEnvironment();
     m_PatchNumberGenerator = new System.Random();
     StartLevelGeneration();
 }
Example #43
0
 void makemaze()
 {
     for (int x = 0; x < 31; x++)
     {
         for (int y = 0; y < 31; y++)
         {
             if (y % 2 == 1)
             {
                 map[x, y] = false;
                 if (x % 2 == 0)
                 {
                     walls.Add(new wall(x, y - 1, x, y + 1, x, y));
                 }
             }
             else
             {
                 if (x % 2 == 0)
                 {
                     map[x, y] = true;
                 }
                 else
                 {
                     map[x, y] = false;
                     walls.Add(new wall(x - 1, y, x + 1, y, x, y));
                 }
             }
             fa[x, y] = new Vector2Int(x, y);
         }
     }
     System.Random rnd = new System.Random();
     for (int i = 0; i < walls.Count; i++)
     {
         int  a = rnd.Next(walls.Count - 1), b = rnd.Next(a + 1, walls.Count);
         wall c = walls[a]; walls[a] = walls[b]; walls[b] = c;
     }
     for (int i = 0; i < walls.Count; i++)
     {
         Vector2Int a = find(walls[i].x1, walls[i].y1);
         Vector2Int b = find(walls[i].x2, walls[i].y2);
         if (!a.Equals(b))
         {
             map[walls[i].x, walls[i].y] = true;
             fa[a.x, a.y] = b;
         }
         else
         {
             continue;
         }
         if (find(0, 0).Equals(find(30, 30)))
         {
             break;
         }
     }
     for (int x = 0; x < 31; x++)
     {
         for (int y = 0; y < 31; y++)
         {
             if (!map[x, y])
             {
                 GameObject go = Instantiate(zhu);
                 go.transform.position = new Vector3(x, 0.5f, y);
             }
         }
     }
     while (true)
     {
         int a = rnd.Next(30);
         int b = rnd.Next(30);
         if (find(0, 0).Equals(find(0, 0)))
         {
             GameObject go = Instantiate(Empty);
             go.transform.position = new Vector3(a, 0, b);
             break;
         }
     }
 }
Example #44
0
 void Shoot()
 {
     System.Random rand = new System.Random();
     Instantiate(bulletPrefab[rand.Next(bulletPrefab.Length)], this.transform.position, Quaternion.identity).GetComponent <EnemyMissile>().dir = player.transform.position - transform.position;
 }
Example #45
0
    void Start()
    {
        var maze = new HashSet <PrimWall>();

        for (int i = 0; i < w; i++)
        {
            for (int j = 0; j < h; j++)
            {
                maze.Add(new PrimWall(i, j));
            }
        }


        var start = new PrimWall(0, 0);

        var seen = new HashSet <PrimWall>();

        seen.Add(start);
        var todo = new HashSet <PrimWall>(seen);

        seed = Random.Range(0, 314);
        var random = new System.Random(seed);


        var PrimLinks = new List <PrimWall[]>();

        while (seen.Count < maze.Count)
        {
            var next      = random.SelectRandom(todo);
            var neighbors = next.Neighbors;

            neighbors.RemoveWhere(e => seen.Contains(e));
            neighbors.RemoveWhere(e => !maze.Contains(e));

            if (0 == neighbors.Count)
            {
                todo.Remove(next);
                continue;
            }

            var PrimLink = random.SelectRandom(neighbors);

            PrimLinks.Add(new PrimWall[] { next, PrimLink });
            seen.Add(PrimLink);
            todo.Add(PrimLink);
        }

        foreach (var next in seen)
        {
            var floor = Instantiate(PrimWall) as GameObject;

            floor.transform.parent        = transform;
            floor.transform.localPosition = next.ToVector3(span);
            floor.transform.localRotation = Quaternion.Euler(0, 0, 0);

            floor.name = next.ToString();
        }

        foreach (var next in PrimLinks)
        {
            var where = 0.5f * (next[0].ToVector3(span) + next[1].ToVector3(span));

            var bridge = Instantiate(PrimLink) as GameObject;

            bridge.transform.parent        = transform;
            bridge.transform.localPosition = where;
            bridge.transform.localRotation = Quaternion.Euler(0, 0, 0);
            bridge.name = next[0] + "<=>" + next[1];
        }
    }
    public void ServerPerformMeleeAttack(GameObject victim, Vector2 attackDirection,
                                         BodyPartType damageZone, LayerType layerType)
    {
        if (Cooldowns.IsOnServer(playerScript, CommonCooldowns.Instance.Melee))
        {
            return;
        }
        var weapon = playerScript.playerNetworkActions.GetActiveHandItem();

        var tiles = victim.GetComponent <InteractableTiles>();

        if (tiles)
        {
            //validate based on position of target vector
            if (!Validations.CanApply(playerScript, victim, NetworkSide.Server, targetVector: attackDirection))
            {
                return;
            }
        }
        else
        {
            //validate based on position of target object
            if (!Validations.CanApply(playerScript, victim, NetworkSide.Server))
            {
                return;
            }
        }

        if (!playerMove.allowInput ||
            playerScript.IsGhost ||
            !victim ||
            !playerScript.playerHealth.serverPlayerConscious
            )
        {
            return;
        }

        var isWeapon = weapon != null;
        ItemAttributesV2 weaponAttr = isWeapon ? weapon.GetComponent <ItemAttributesV2>() : null;
        var       damage            = isWeapon ? weaponAttr.ServerHitDamage : fistDamage;
        var       damageType        = isWeapon ? weaponAttr.ServerDamageType : DamageType.Brute;
        var       attackSoundName   = isWeapon ? weaponAttr.ServerHitSound : "Punch#";
        LayerTile attackedTile      = null;

        bool didHit = false;


        // If Tilemap LayerType is not None then it is a tilemap being attacked
        if (layerType != LayerType.None)
        {
            var tileChangeManager = victim.GetComponent <TileChangeManager>();
            if (tileChangeManager == null)
            {
                return;                                        //Make sure its on a matrix that is destructable
            }
            //Tilemap stuff:
            var tileMapDamage = victim.GetComponentInChildren <MetaTileMap>().Layers[layerType].gameObject
                                .GetComponent <TilemapDamage>();
            if (tileMapDamage != null)
            {
                attackSoundName = "";
                var worldPos = (Vector2)transform.position + attackDirection;
                attackedTile = tileChangeManager.InteractableTiles.LayerTileAt(worldPos, true);
                tileMapDamage.DoMeleeDamage(worldPos,
                                            gameObject, (int)damage);
                didHit = true;
            }
        }
        else
        {
            //a regular object being attacked

            LivingHealthBehaviour victimHealth = victim.GetComponent <LivingHealthBehaviour>();

            var integrity = victim.GetComponent <Integrity>();
            if (integrity != null)
            {
                //damaging an object
                integrity.ApplyDamage((int)damage, AttackType.Melee, damageType);
                didHit = true;
            }
            else
            {
                //damaging a living thing
                var rng = new System.Random();
                // This is based off the alien/humanoid/attack_hand punch code of TGStation's codebase.
                // Punches have 90% chance to hit, otherwise it is a miss.
                if (isWeapon || 90 >= rng.Next(1, 100))
                {
                    // The attack hit.
                    victimHealth.ApplyDamageToBodypart(gameObject, (int)damage, AttackType.Melee, damageType, damageZone);
                    didHit = true;
                }
                else
                {
                    // The punch missed.
                    string victimName = victim.Player()?.Name;
                    SoundManager.PlayNetworkedAtPos("PunchMiss", transform.position);
                    Chat.AddCombatMsgToChat(gameObject, $"You attempted to punch {victimName} but missed!",
                                            $"{gameObject.Player()?.Name} has attempted to punch {victimName}!");
                }
            }
        }

        //common logic to do if we hit something
        if (didHit)
        {
            if (!string.IsNullOrEmpty(attackSoundName))
            {
                SoundManager.PlayNetworkedAtPos(attackSoundName, transform.position);
            }

            if (damage > 0)
            {
                Chat.AddAttackMsgToChat(gameObject, victim, damageZone, weapon, attackedTile: attackedTile);
            }
            if (victim != gameObject)
            {
                RpcMeleeAttackLerp(attackDirection, weapon);
                //playerMove.allowInput = false;
            }
        }

        Cooldowns.TryStartServer(playerScript, CommonCooldowns.Instance.Melee);
    }
 public static T RandomItem <T>(this T[] array, System.Random random)
 {
     return(array[random.Next(array.Length)]);
 }
    protected override IEnumerator Generate(WorldManager worldManager)
    {
        if (!WorldInfo.generateBuildings)
        {
            FinishGenerating(worldManager);
            yield break;
        }

        else
        {
            System.Random rand  = new System.Random(seed);
            var           world = ObjectStore.instance.worldManager;

            int worldSize = (int)world.worldSize;

            buildings = new List <Building>();
            Village[] villages = FindObjectsOfType <Village>();

            int n = 0;

            for (int i = 0; i < maxNumberOfBuildings && n < 100;)
            {
                UIManager.UpdateLoadScreenText($"Building dungeon {i}.");

                bool canBuild = true;

                Vector2Int position = new Vector2Int(rand.Next(1, worldSize), rand.Next(1, worldSize));

                var height = world.worldData.heightMap[position.x, position.y];

                if (height < minBuildingHeight || height > maxBuildingHeight)
                {
                    canBuild = false;
                }

                if (buildings.Count > 0)
                {
                    foreach (Building building in buildings)
                    {
                        Vector2Int otherPos = new Vector2Int((int)building.transform.position.x, (int)building.transform.position.y);
                        if (Vector2Int.Distance(position, otherPos) < minimumBuildingDistance)
                        {
                            canBuild = false;
                        }

                        if (!canBuild)
                        {
                            break;
                        }
                    }
                }

                if (villages.Length > 0)
                {
                    foreach (Village village in villages)
                    {
                        Vector2Int otherPos = new Vector2Int((int)village.transform.position.x, (int)village.transform.position.y);
                        if (Vector2Int.Distance(position, otherPos) < minimumBuildingDistance)
                        {
                            canBuild = false;
                        }

                        if (!canBuild)
                        {
                            break;
                        }
                    }
                }

                if (!canBuild)
                {
                    n++;
                }
                else
                {
                    var go = Instantiate(buildingPrefab, new Vector3(position.x, position.y, 0), Quaternion.identity);

                    var v = go.GetComponent <Building>();
                    v.direction = Village.Direction.Up;
                    buildings.Add(v);
                    v.Initialise(worldManager);
                    i++;
                    n = 0;

                    worldManager.worldData.SetWorldMapIcon(position.x, position.y, mapIcon);
                }

                yield return(null);
            }

            FinishGenerating(worldManager);
        }
    }
Example #49
0
    // The source image
//    string url = "https://clipground.com/images/monkey-baby-clipart-14.jpg";

    public void Start()
    {
//        Debug.Log("DENTRO DE " + name);
        param    = GameObject.Find("Parametrosarboles");
        prm      = param.GetComponent <Parametrosarboles>();
        animales = prm.aleatorios();

        /*foreach (string i in animales) {
         *  Debug.Log("Animales desde Parametros: " + i);
         * }*/



        int  index = 0;
        bool rep   = true;

        i1 = GameObject.Find("A1").GetComponent <Image>();
        i2 = GameObject.Find("A2").GetComponent <Image>();
        i3 = GameObject.Find("A3").GetComponent <Image>();
        i4 = GameObject.Find("A4").GetComponent <Image>();
        if (name == "A1")
        {
            anim = GameObject.Find("A1").GetComponent <Image>();
        }
        if (name == "A2")
        {
            anim = GameObject.Find("A2").GetComponent <Image>();
        }
        if (name == "A3")
        {
            anim = GameObject.Find("A3").GetComponent <Image>();
        }
        if (name == "A4")
        {
            anim = GameObject.Find("A4").GetComponent <Image>();
        }


//        objdb = new dbarboles();
        // objdb = anim.AddComponent<db>();



        while (rep == true)
        {
            rep = false;
            System.Random rand = new System.Random();
            index = rand.Next(animales.Length);
            //string rd = rutas[index];
            string ruta = animales[index];
            //Debug.Log("aleatorio "+name+": " + ruta);
            string[] dir      = ruta.Split('/');
            string   etiqueta = dir[dir.Length - 1];
            string[] et       = etiqueta.Split('-');
            if (et[0].Contains(".png"))
            {
                string[] lab = et[0].Split('.');
                tag  = lab[0];
                name = lab[0];
                //Debug.Log("Contiene PNG");
                //  Debug.Log("etiqueta final asignada: " + lab[0]);
            }
            else
            {
                tag = et[0];
                //Debug.Log("etiqueta asignada 1: " + et[0]);
            }
            anim.sprite = Resources.Load <Sprite>(ruta); //"Sprites/oso perezoso_1"

            //Debug.Log("ANIMAL DESPUES: " + anim.sprite);
            if (name == "A1")
            {
                i1 = GameObject.Find("A1").GetComponent <Image>();
                if (i1.sprite == i2.sprite || i1.sprite == i3.sprite || i1.sprite == i4.sprite)
                {
                    rep = true;
                    //Debug.Log("ANIMAL REPETIDO :" +rep);
                }
            }
            if (name == "A2")
            {
                i2 = GameObject.Find("A2").GetComponent <Image>();
                if (i2.sprite == i1.sprite || i2.sprite == i3.sprite || i2.sprite == i4.sprite)
                {
                    rep = true;
                    //Debug.Log("ANIMAL REPETIDO :" +rep);
                }
            }
            if (name == "A3")
            {
                i3 = GameObject.Find("A3").GetComponent <Image>();
                if (i3.sprite == i1.sprite || i3.sprite == i2.sprite || i3.sprite == i4.sprite)
                {
                    rep = true;
                    // Debug.Log("ANIMAL REPETIDO :" +rep);
                }
            }
            if (name == "A4")
            {
                i4 = GameObject.Find("A4").GetComponent <Image>();
                if (i4.sprite == i1.sprite || i4.sprite == i2.sprite || i4.sprite == i3.sprite)
                {
                    rep = true;
                    // Debug.Log("ANIMAL REPETIDO :" +rep);
                }
            }

            /*Debug.Log("ANIMAL estado :" +rep);
             * Debug.Log("ANIMAL 1 : " + i1.sprite);
             * Debug.Log("ANIMAL 2 : " + i2.sprite);
             * Debug.Log("ANIMAL 3 : " + i3.sprite);
             * Debug.Log("ANIMAL 4 : " + i4.sprite);*/
        }
    }
 void Awake()
 {
     m_StaticPopupCanvas = m_PopupCanvas;
     m_Random            = new System.Random();
     InitalizeMap();
 }
Example #51
0
    public Vector2 ChooseDirection()
    {
        System.Random ran = new System.Random();
        int           r   = positions.Length;

        int i = ran.Next(0, 4);

        //Vector2 temp = new Vector2();

        int count = 0;


        //for(int j=0; j<r; j++)
        //{
        //    vecArray[j] = positions[j];
        //    count = j;
        //    Debug.Log("Here");
        //}


        if (i == 0)
        {
            //vecArray[0] = new Vector2(0f, 0f);

            //anim.CrossFade("oldWoman_Walk", 0);
            vecArray[0] = positions[0];

            //if (positions[0].x-vecArray[0].x<=0)
            //{
            //    sr.flipX=false;
            //}
            //else
            //{
            //    sr.flipX = true;
            //}
            // Debug.Log(positions[0].x - vecArray[0].x);
            count = 0;
        }

        else if (i == 1)
        {
            //vecArray[1] = new Vector2(5f, 5f);
            // anim.CrossFade("oldWoman_Walk", 0);
            vecArray[1] = positions[1];
            //if (positions[1].x - vecArray[1].x <= 0)
            //{
            //    sr.flipX = false;
            //}
            //else
            //{
            //    sr.flipX = true;
            //}
            // Debug.Log(positions[1].x - vecArray[1].x);
            count = 1;
        }
        else if (i == 2)
        {
            //anim.CrossFade("oldWoman_Walk", 0);
            //vecArray[2] = new Vector2(5f, 0f);
            vecArray[2] = positions[2];
            //if (positions[2].x - vecArray[2].x <= 0)
            //{
            //    sr.flipX = false;
            //}
            //else
            //{
            //    sr.flipX = true;
            //}
            // Debug.Log(positions[2].x - vecArray[2].x);
            count = 2;
        }
        else if (i == 3)
        {
            //anim.CrossFade("oldWoman_Walk", 0);

            //vecArray[3] = new Vector2(0f, 5f);
            //if (positions[3].x - vecArray[3].x <= 0)
            ////if (positions[2].x - vecArray[2].x < 0)
            //{
            //    sr.flipX = false;
            //}
            //else
            //{
            //    sr.flipX = true;
            //}

            vecArray[3] = positions[3];
            count       = 3;
        }

        // Debug.Log(vecArray[count]);

        //if (positions[count].x - vecArray[count].x <= 0)
        ////if (positions[2].x - vecArray[2].x < 0)
        //{
        //    sr.flipX = false;
        //}
        //else
        //{
        //    sr.flipX = true;
        //}

        ////Debug.Log(positions[count].x - vecArray[count].x);
        ////Debug.Log(vecArray[count].x - positions[count].x);
        //Debug.Log(positions[count].x);
        //Debug.Log(positions[count].x);
        return(vecArray[count]);
    }
Example #52
0
    public static float[, ] GenerateNoiseMap(int mapWidth, int mapHeight, NoiseSettings settings, Vector2 sampleCentre)
    {
        float[, ] noiseMap = new float[mapWidth, mapHeight];

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

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

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

            maxPossibleHeight += amplitude;
            amplitude         *= settings.persistance;
        }

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

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

        for (int y = 0; y < mapHeight; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                amplitude = 1;
                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 > maxLocalNoiseHeight)
                {
                    maxLocalNoiseHeight = noiseHeight;
                }
                if (noiseHeight < minLocalNoiseHeight)
                {
                    minLocalNoiseHeight = noiseHeight;
                }
                noiseMap[x, y] = noiseHeight;

                if (settings.normalizeMode == NormalizeMode.Global)
                {
                    float normalizedHeight = (noiseMap[x, y] + 1) / (maxPossibleHeight / 0.9f);
                    noiseMap[x, y] = Mathf.Clamp(normalizedHeight, 0, int.MaxValue);
                }
            }
        }

        if (settings.normalizeMode == NormalizeMode.Local)
        {
            for (int y = 0; y < mapHeight; y++)
            {
                for (int x = 0; x < mapWidth; x++)
                {
                    noiseMap[x, y] = Mathf.InverseLerp(minLocalNoiseHeight, maxLocalNoiseHeight, noiseMap[x, y]);
                }
            }
        }

        return(noiseMap);
    }
Example #53
0
    private void OnRecycled()
    {
        Dictionary <int, int> recycleItems = GetRecycleItems();

        if (null == recycleItems)
        {
            return;
        }

        List <ItemIdCount> resourceGot = new List <ItemIdCount>();

        foreach (KeyValuePair <int, int> kvp in recycleItems)
        {
            resourceGot.Add(new ItemIdCount(kvp.Key, kvp.Value));
        }

        if (resourceGot.Count <= 0)
        {
            return;
        }
        List <MaterialItem> materialList = CSUtils.ItemIdCountToMaterialItem(resourceGot);
        ItemPackage         accessor     = PeCreature.Instance.mainPlayer.GetCmpt <PlayerPackageCmpt>().package._playerPak;

        if (null == accessor)
        {
            return;
        }

        bool addToPackage = false;

        //lz-2016.12.27 尝试添加到玩家背包
        if (accessor.CanAdd(materialList))
        {
            accessor.Add(materialList);
            GameUI.Instance.mItemPackageCtrl.ResetItem();
            addToPackage = true;
            CSUtils.ShowTips(RecycleConst.INFORM_FINISH_TO_PACKAGE);
        }

        //lz-2016.12.27 尝试添加到基地存储箱
        if (!addToPackage && Assembly != null && Assembly.Storages != null)
        {
            foreach (CSCommon css in Assembly.Storages)
            {
                CSStorage storage = css as CSStorage;
                if (storage.m_Package.CanAdd(materialList))
                {
                    storage.m_Package.Add(materialList);
                    addToPackage = true;
                    CSUtils.ShowTips(RecycleConst.INFORM_FINISH_TO_STORAGE);
                    break;
                }
            }
        }

        //lz-2016.12.27 尝试生成一个小球放物品
        if (!addToPackage)
        {
            System.Random rand = new System.Random();

            List <ItemIdCount> itemIdNum = resourceGot.FindAll(it => it.count > 0);
            if (itemIdNum.Count <= 0)
            {
                return;
            }

            int[] items = CSUtils.ItemIdCountListToIntArray(itemIdNum);

            Vector3 resultPos = Position + new Vector3(0f, 0.72f, 0f);

            if (BuildingLogic != null)
            {
                if (BuildingLogic.m_ResultTrans.Length > 0)
                {
                    Transform trans = BuildingLogic.m_ResultTrans[rand.Next(BuildingLogic.m_ResultTrans.Length)];
                    if (trans != null)
                    {
                        resultPos = trans.position;
                    }
                }
            }
            while (RandomItemMgr.Instance.ContainsPos(resultPos))
            {
                resultPos += new Vector3(0, 0.01f, 0);
            }
            RandomItemMgr.Instance.GenProcessingItem(resultPos + new Vector3((float)rand.NextDouble() * 0.15f, 0, (float)rand.NextDouble() * 0.15f), items);
            addToPackage = true;
            CSUtils.ShowTips(RecycleConst.INFORM_FINISH_TO_RANDOMITEM);
        }

        if (addToPackage)
        {
            // Delete Item;
            ItemMgr.Instance.DestroyItem(m_Item.itemObj.instanceId);
            m_Item = null;

            // Call back
            if (onRecylced != null)
            {
                onRecylced();
            }
        }
    }
 private double GetRandomNumber(double minimum, double maximum)
 {
     System.Random random = new System.Random();
     return(random.NextDouble() * (maximum - minimum) + minimum);
 }
Example #55
0
    public Lake(float height, int x0, int z0, int radiusMinLake, int radiusMaxLake, int radiusMinLakeBank, int radiusMaxLakeBank, int radiusMinSurroundingHeight, int radiusMaxSurroundingHeights, System.Random rnd)
    {
        radius                  = rnd.Next(radiusMinLake, radiusMaxLake);
        radiusLakeBank          = rnd.Next(radius + radiusMinLakeBank, radius + radiusMaxLakeBank);
        radiusSurroundingHeight = rnd.Next(radiusLakeBank + radiusMinSurroundingHeight, radiusLakeBank + radiusMaxSurroundingHeights);

        midpoint = new Vector3(x0, height, z0);
    }
Example #56
0
 public Timer(float timerLength)
 {
     timer            = 0;
     rand             = new Random();
     this.timerLength = timerLength;
 }
Example #57
0
 public static E SelectRandom <E>(this System.Random random, HashSet <E> set)
 {
     return((new List <E>(set))[random.Next() % set.Count]);
 }
Example #58
0
 public SafeInt(int value = 0)
 {
     System.Random rnd = new System.Random();
     offset     = rnd.Next(-1000, 1000);
     this.value = value + offset;
 }
Example #59
0
 // for shuffling spawn positions
 private int[] RandomizedSpawnIndexes()
 {
     System.Random rnd = new System.Random();
     return(Enumerable.Range(0, spawnPoint.Length).OrderBy(r => rnd.Next()).ToArray());
 }
Example #60
0
    IEnumerator StudentReactionThreeInitiate()
    {
        print("SR 3 started");
        random10WorkingStudents.Clear();
        random9whisperingStudents.Clear();
        yield return(new WaitForSeconds(3f));

        print("All students stop what they are doing and look at the teacher in random timing");
        foreach (StudentAction studentAction in gamePlayManager.studentsActions)
        {
            studentAction.LookAtWindowRoutineStop();
            studentAction.LookAroundOrTalkOrWriteRoutineStop();
            if (studentAction.studentAnimation.GetAnimStateBool("vi7_Talk_ON"))
            {
                studentAction.studentAnimation.VI7_TalkToFriendsStop();
            }
            if (studentAction.studentAnimation.GetAnimStateBool("mb33_WriteOnSheet_ON"))
            {
                studentAction.studentAnimation.MB33_WorkOnSheets(false);
            }
            var teacherPositon = GameObject.FindGameObjectWithTag("Player").transform;
            studentAction.LookAtSomeone(teacherPositon);
            yield return(new WaitForSeconds(0.5f));
        }
        print("mumbling raise for 5 seconds to 50%");

        yield return(new WaitForSeconds(3f));

        print("fades back to low");


        print("Around 10 students start to work");
        print("Around 6 to 9 students start to work and whisper in between");
        var sampleStudents = new int[19];

        var rnd = new System.Random();

        for (int i = 0; i < sampleStudents.Length; ++i)
        {
            var whichOne = rnd.Next(gamePlayManager.studentsActions.Count);

            if (!Table3TalkingKids.Contains(gamePlayManager.studentsActions[whichOne]))
            {
                if (whichOne % 2 == 0)
                {
                    gamePlayManager.studentsActions[whichOne].StopLookAtSomeone();
                    gamePlayManager.studentsActions[whichOne].studentAnimation.MB33_WorkOnSheets(true);
                    random10WorkingStudents.Add(gamePlayManager.studentsActions[whichOne]);
                    yield return(new WaitForSeconds(Random.Range(0.1f, 0.5f)));
                }
                else
                {
                    gamePlayManager.studentsActions[whichOne].StopLookAtSomeone();
                    gamePlayManager.studentsActions[whichOne].WisperOrWriteRoutine();
                    random9whisperingStudents.Add(gamePlayManager.studentsActions[whichOne]);
                    yield return(new WaitForSeconds(Random.Range(0.1f, 0.5f)));
                }
            }
        }
        if (!table1KidsTalking.isPlaying)
        {
            table1KidsTalking.volume = 0.1f; table1KidsTalking.PlayDelayed(1f);
        }
        if (!table2KidsTalking.isPlaying)
        {
            table2KidsTalking.volume = 0.1f; table2KidsTalking.PlayDelayed(1f);
        }
        if (!table4KidsTalking.isPlaying)
        {
            table4KidsTalking.volume = 0.1f; table4KidsTalking.PlayDelayed(1f);
        }

        //  gamePlayManager.studentsActions[whichOne].Scenario11LookatShakeHeadsOrWriteRoutine(Table3TalkingKidsTransform[Random.Range(0, Table3TalkingKidsTransform.Count)]);

        sampleStudents = new int[Random.Range(4, 6)];
        rnd            = new System.Random();
        for (int i = 0; i < sampleStudents.Length; ++i)
        {
            sampleStudents[i] = rnd.Next(random10WorkingStudents.Count);
            //           print("selected student from table 3 to talk is " + sampleStudents[i].ToString() + " who is "+ gamePlayManager.GetComponent<MainObjectsManager>().studentsAtTable3[sampleStudents[i]].name);
        }
        print("Around 4 to 5 out of 10 working students gets interuppted and looks at the Table 3 talking students and shake their heads occasionally and then go to work");
        for (int i = 0; i < sampleStudents.Length; i++)
        {
            gamePlayManager.studentsActions[sampleStudents[i]].LookatShakeHeadsOrWriteRoutine(Table3TalkingKidsTransform[Random.Range(0, Table3TalkingKidsTransform.Count)]);
            yield return(new WaitForSeconds(Random.Range(0.1f, 1f)));
        }

        yield return(new WaitForSeconds(5f));

        foreach (StudentAction studentAction in gamePlayManager.studentsActions)
        {
            studentAction.LookAtWindowRoutineStop();
            studentAction.LookAroundOrTalkOrWriteRoutineStop();
            studentAction.LookatShakeHeadsOrWriteRoutineStop();
            studentAction.WisperOrWriteRoutineStop();
            if (studentAction.studentAnimation.GetAnimStateBool("vi7_Talk_ON"))
            {
                studentAction.studentAnimation.VI7_TalkToFriendsStop();
            }
            if (!studentAction.studentAnimation.GetAnimStateBool("mb33_WriteOnSheet_ON"))
            {
                studentAction.studentAnimation.MB33_WorkOnSheets(true);
            }

            yield return(new WaitForSeconds(Random.Range(0.5f, 1.5f)));
        }
        print("SR 3 Complete");


        yield return(new WaitForSeconds(0.1f));
    }