public Task <List <Diagrams.Point> > Handle(GenerateRandomPoints request) { var dispatcher = request.Dispatcher; var log = request.Log; var count = request.Count; log.Info($"Generating {count} points"); var generatedPoints = new List <Diagrams.Point>(); while (count > 0) { var points = PointGenerator.GeneratePoints(count, 0, request.Width, 0, request.Height); foreach (var point in points) { if (request.PlacedPoints.All(p => p.X != point.X || p.Y != point.Y) && generatedPoints.All(p => p.X != point.X || p.Y != point.Y)) { generatedPoints.Add(point); count--; } } } return(Task.FromResult(generatedPoints)); }
private void radioUniform_CheckedChanged(object sender, EventArgs e) { if (!(pointGenerator is UniformPointGenerator)) { pointGenerator = new UniformPointGenerator(); } }
/// <summary> /// Queues up a wave of enemies per player in the corners of the screen. /// </summary> /// <param name="enemyType"> The type of enemy to spawn.</param> /// <param name="playerSpecifc">If true, each spawn can only be damaged by the player who shares a /// colour with it.</param> void CornersWave(EnemyType enemyType, bool playerSpecifc) { float width = App.Instance.GraphicsDevice.Viewport.Width; float height = App.Instance.GraphicsDevice.Viewport.Height; ICollection <IGenerator> wave = new LinkedList <IGenerator>(); PointGenerator g; Vector2[] corners = { new Vector2(-100, -100), new Vector2(-100, height + 100), new Vector2(width + 100, -100), new Vector2(width + 100, height + 100) }; shuffle(corners); foreach (MainGun p in model.ActivePlayers) { Vector2 pos = corners[p.PlayerId]; g = new PointGenerator(pos, 1 + LinearDifficulty(10, 12)); g.EnemyHealth = 1 + LinearDifficulty(5, 0); g.EnemySize = 20; g.EnemySizeVariance = LinearDifficulty(5, 10); g.EnemyType = enemyType; g.Frequency = model.Music.ClicksPerBeat; if (playerSpecifc) { g.PlayerSpecific = true; g.TargetPlayer = p.PlayerId; } wave.Add(g); } waves.Enqueue(wave); }
private void radioGaussian_CheckedChanged(object sender, EventArgs e) { if (!(pointGenerator is GaussianPointGenerator)) { pointGenerator = new GaussianPointGenerator(); } }
private void checkIntersect(Vector2 tapPosition) { foreach (var kv in BeatDictionary.ToDictionary(kv => kv.Key, kv => kv.Value)) { if (kv.Key <= MediaPlayer.PlayPosition.TotalMilliseconds) { ClickablePlayObject tempObject = kv.Value as ClickablePlayObject; if (tempObject != null) { if (tempObject.Bounds.Intersects(new Rectangle((int)tapPosition.X, (int)tapPosition.Y, 1, 1))) { PointGenerator.generatePointEffect(tempObject.Center, tempObject.BeatRing.Scale, (int)MediaPlayer.PlayPosition.TotalMilliseconds); BeatDictionary.Remove(kv.Key); break; } } } else { break; } } checkForEndOfSong(); }
/// <summary> /// Queues up a wave of enemies whose power and number depend on the time played, coming /// from one point per player. The points chosen are usually on the player's own side. /// </summary> /// <param name="useAllSides">False if only each player's own side should be used to spawn, true if /// there should be a chance of using a random side.</param> /// <param name="playerSpecifc">If true, each spawn can only be damaged by the player who shares a /// colour with it.</param> void SimpleWave(bool useAllSides, bool playerSpecifc) { ICollection <IGenerator> wave = new LinkedList <IGenerator>(); PointGenerator g; foreach (MainGun p in model.ActivePlayers) { int side = p.PlayerId; // If useAllSides, sometimes choose a different side. if (useAllSides && random.Next(2) == 0) { side = random.Next(0, 3); } g = new PointGenerator(PointGenerator.PointOnSide(side, 20), 3 + LinearDifficulty(10, 12)); g.EnemyHealth = 1 + LinearDifficulty(5, 0); g.EnemySize = 20; g.EnemySizeVariance = LinearDifficulty(5, 10); g.EnemyType = EnemyType.Regular; g.Frequency = model.Music.ClicksPerBeat; if (playerSpecifc) { g.PlayerSpecific = true; g.TargetPlayer = p.PlayerId; } wave.Add(g); } waves.Enqueue(wave); }
//Генерация сферы void GenerateSphere() { //Уничтожает текущую Destroy(currentSphere); //Задает новую позицию spherePosition = playerT.position + PointGenerator.GenerateRandomPointOnAnulus(); //Задает текущую сферу currentSphere = Instantiate(sphere, spherePosition, Quaternion.identity); }
void Awake() { instance = this; pointGenerator = gameObject.GetComponent <PointGenerator> (); if (pointGenerator == null) { Debug.LogWarning("Did not fount Point Generator"); } gameTime = setGameTime; }
//bool m_imageScaled; public FormMain() { InitializeComponent(); pictureBoxView.Image = new Bitmap(pictureBoxView.Width, pictureBoxView.Height); m_g = Graphics.FromImage(pictureBoxView.Image); pointGenerator = new UniformPointGenerator(); radioUniform.Checked = true; //start with this as the default m_pointList = new List<PointF>(); UniquePoints = new Hashtable(); }
//bool m_imageScaled; public FormMain() { InitializeComponent(); pictureBoxView.Image = new Bitmap(pictureBoxView.Width, pictureBoxView.Height); m_g = Graphics.FromImage(pictureBoxView.Image); pointGenerator = new UniformPointGenerator(); radioUniform.Checked = true; //start with this as the default m_pointList = new List <PointF>(); UniquePoints = new Hashtable(); }
private void GenerateActionCells(WorldGenSettings settings, Tag tag, HashSet <Vector2I> possiblePoints, SeededRandom rnd) { ProcGen.Room value = null; SettingsCache.rooms.TryGetValue(tag.Name, out value); SampleDescriber sampleDescriber = value; if (sampleDescriber == null && settings.HasMob(tag.Name)) { sampleDescriber = settings.GetMob(tag.Name); } if (sampleDescriber != null) { HashSet <Vector2I> hashSet = new HashSet <Vector2I>(); float randomValueWithinRange = sampleDescriber.density.GetRandomValueWithinRange(rnd); List <Vector2> list; switch (sampleDescriber.selectMethod) { case SampleDescriber.PointSelectionMethod.RandomPoints: list = PointGenerator.GetRandomPoints(poly, randomValueWithinRange, 0f, null, sampleDescriber.sampleBehaviour, true, rnd, true, true); break; default: list = new List <Vector2>(); list.Add(node.position); break; } foreach (Vector2 item2 in list) { Vector2 current = item2; Vector2I item = new Vector2I((int)current.x, (int)current.y); if (possiblePoints.Contains(item)) { hashSet.Add(item); } } if (value != null && value.mobselection == ProcGen.Room.Selection.None) { if (terrainPositions == null) { terrainPositions = new List <KeyValuePair <int, Tag> >(); } foreach (Vector2I item3 in hashSet) { Vector2I current2 = item3; int num = Grid.XYToCell(current2.x, current2.y); if (Grid.IsValidCell(num)) { terrainPositions.Add(new KeyValuePair <int, Tag>(num, tag)); } } } } }
private void GeneratePoints_Click(object sender, EventArgs e) { _currentGraphics = mainPictureBox.CreateGraphics(); _coordinator = new Coordinator(_currentGraphics, mainPictureBox, 15, 15); _currentGraphics = _coordinator.Execute(); var pg = new PointGenerator(_currentGraphics, _coordinator); _currentGraphics = pg.Execute(Plane.TopRightTopTriangle, Color.Red, 15); _currentGraphics = pg.Execute(Plane.TopRightBottomTriangle, Color.Green, 29); _currentBitmap = new Bitmap(mainPictureBox.Width, mainPictureBox.Height, _currentGraphics); mainPictureBox.InitialImage = _currentBitmap; _allPoints = pg.AllPointsExt; }
public FormMain() { InitializeComponent(); pictureBoxView.Image = new Bitmap(pictureBoxView.Width, pictureBoxView.Height); m_g = Graphics.FromImage(pictureBoxView.Image); m_g.TranslateTransform(0, pictureBoxView.Height); m_g.ScaleTransform(1, -1); pictureBoxView.Image.RotateFlip(RotateFlipType.Rotate180FlipX); pointGenerator = new UniformPointGenerator(); radioUniform.Checked = true; //start with this as the default m_pointList = new List<PointF>(); UniquePoints = new Dictionary<float, PointF>(); }
//Инициализация void Start() { _transform = transform; playerT = FindObjectOfType <PlayerController>().transform; currDirection = Vector3.zero; //Задается случайная позиция _transform.position = playerT.position + PointGenerator.GenerateRandomPointOnAnulus(); //Генерируется сфера GenerateSphere(); //Запускается мышь StartCoroutine(Run()); }
public void PlaceSites(List <Diagram.Site> sites, int seed) { SeededRandom seededRandom = new SeededRandom(seed); List <Vector2> list = null; List <Vector2> list2 = new List <Vector2>(); for (int i = 0; i < sites.Count; i++) { list2.Add(sites[i].position); } int num = 0; for (int j = 0; j < sites.Count; j++) { if (!site.poly.Contains(sites[j].position)) { if (list == null) { list = PointGenerator.GetRandomPoints(site.poly, 5f, 1f, list2, PointGenerator.SampleBehaviour.PoissonDisk, true, seededRandom, true, true); } if (num >= list.Count - 1) { list2.AddRange(list); list = PointGenerator.GetRandomPoints(site.poly, 0.5f, 0.5f, list2, PointGenerator.SampleBehaviour.PoissonDisk, true, seededRandom, true, true); num = 0; } if (list.Count == 0) { sites[j].position = sites[0].position + Vector2.one * seededRandom.RandomValue(); } else { sites[j].position = list[num++]; } } } HashSet <Vector2> hashSet = new HashSet <Vector2>(); for (int k = 0; k < sites.Count; k++) { if (hashSet.Contains(sites[k].position)) { visited = VisitedType.Error; sites[k].position += new Vector2((float)seededRandom.RandomRange(0, 1), (float)seededRandom.RandomRange(0, 1)); } hashSet.Add(sites[k].position); sites[k].poly = null; } }
public override void OnInspectorGUI() { //base.OnInspectorGUI(); DrawDefaultInspector(); PointGenerator clutter = (PointGenerator)target; if (GUILayout.Button("Initialize")) { clutter.Setup(); } if (GUILayout.Button("Next Point")) { clutter.NextPoint(); } }
public void SetInitialNodePositions(Polygon bounds) { List <Vector2> randomPoints = PointGenerator.GetRandomPoints(bounds, 50f, 0f, null, PointGenerator.SampleBehaviour.PoissonDisk, true, myRandom, true, true); int num = 0; for (int i = 0; i < nodeList.Count; i++) { if (num == randomPoints.Count - 1) { randomPoints = PointGenerator.GetRandomPoints(bounds, 10f, 20f, randomPoints, PointGenerator.SampleBehaviour.PoissonDisk, true, myRandom, true, true); num = 0; } nodeList[i].SetPosition(randomPoints[num++]); } }
/// <summary> /// Generate points and store them into a list /// </summary> private void GeneratePoints(int amount) { //clear previous data _points.Clear(); _voronoiDiagram.Clear(); _cityData.Clear(); //fill settings _voronoiSettings = new GenerationSettings { VoronoiAlgorithm = VoronoiAlgorithm, PointAlgorithm = PointAlgorithm, Width = Width, Length = Height, StartX = StartX, StartY = StartY, UseSeed = UseSeed, Seed = Seed, Amount = PointsToGenerate, CircleRadius = Radius }; //generate points var timer = Stopwatch.StartNew(); _points = PointGenerator.Generate(_voronoiSettings); timer.Stop(); //update generation timer var time = timer.ElapsedMilliseconds / 1000.0; GenerationTimeText = $"Generated {_points.Count} points in {time} seconds."; //update randomly generated seed if (UseSeed == false) { Seed = _voronoiSettings.Seed; } //update canvas RefreshCanvas(); }
protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); debugFont = Content.Load <SpriteFont>("Debugfont"); scoreFont = Content.Load <SpriteFont>("ScoreFont"); PointGenerator.Load(this.Content); playBeatmapsButton.Load(this.Content); createBeatmapsButton.Load(this.Content); returnToMainMenuButton.Load(this.Content); munchymonk = Content.Load <Song>("munchymonk"); foreach (BeatTimerData btd in BeatTimerList) { BeatDictionary.Add(btd.Timestamp, new Beat(btd.StartPosition)); } foreach (KeyValuePair <int, PlayObject> kvp in BeatDictionary) { kvp.Value.LoadContent(this.Content); } }
void Awake() { instance = this; pointGenerator = gameObject.GetComponent <PointGenerator> (); if (pointGenerator == null) { Debug.LogWarning("Did not fount Point Generator"); } if (chooseMode.setDifficulty == 3) { gameTime = EasyModeTime; } if (chooseMode.setDifficulty == 2) { gameTime = MediumModeTime; } if (chooseMode.setDifficulty == 1) { gameTime = HardModeTime; } }
private void GenerateCity() { //seed random if (!GenerationSettings.UseSeed) { GenerationSettings.Seed = DateTime.Now.GetHashCode(); } //Store Settings var width = GenerationSettings.Width; var length = GenerationSettings.Length; //Parent.transform.position = citypos; GenerationSettings.StartX = Parent.transform.position.x - width / 2.0; GenerationSettings.StartY = Parent.transform.position.z - length / 2.0; //Generate Points and diagram var points = PointGenerator.Generate(GenerationSettings); VoronoiDiagram = VoronoiGenerator.CreateVoronoi(points, GenerationSettings); //generate city districts and roads _cityData = CityBuilder.GenerateCity(CitySettings, VoronoiDiagram); }
public static async Task <ExcelContentTableImportResults> ImportExcelContentTable(IXLRange toProcess, IProgress <string> progress) { if (toProcess == null || toProcess.Rows().Count() < 2) { return new ExcelContentTableImportResults { HasError = true, ErrorNotes = "Nothing to process", ToUpdate = new List <ExcelImportContentUpdateSuggestion>() } } ; var headerInfo = new ExcelHeaderRow(toProcess.Row(1)); var errorNotes = new List <string>(); var updateList = new List <ExcelImportContentUpdateSuggestion>(); var db = await Db.Context(); var lastRow = toProcess.Rows().Last().RowNumber(); progress?.Report($"{lastRow} to Process"); foreach (var loopRow in toProcess.Rows().Skip(1)) { var importResult = await ImportContentFromExcelRow(headerInfo, loopRow); if (importResult.hasError) { errorNotes.Add($"Excel Row {loopRow.RowNumber()} - {importResult.errorNotes}"); continue; } try { Db.DefaultPropertyCleanup(importResult.processContent); importResult.processContent.Tags = Db.TagListCleanup(importResult.processContent.Tags); } catch { await EventLogContext.TryWriteDiagnosticMessageToLog( $"Excel Row {loopRow.RowNumber()} - Excel Import via dynamics - Tags threw an error on ContentId {importResult.processContent.ContentId ?? "New Entry"} - property probably not present", "Excel Import"); continue; } Guid contentId = importResult.processContent.ContentId; int contentDbId = importResult.processContent.Id; string differenceString; if (contentDbId > 0) { var currentDbEntry = await db.ContentFromContentId(contentId); var compareLogic = new CompareLogic { Config = { MembersToIgnore = new List <string> { "LastUpdatedBy" }, MaxDifferences= 100 } }; ComparisonResult comparisonResult = compareLogic.Compare(currentDbEntry, importResult.processContent); if (comparisonResult.AreEqual) { progress?.Report( $"Excel Row {loopRow.RowNumber()} of {lastRow} - No Changes - Title: {currentDbEntry.Title}"); continue; } var friendlyReport = new UserFriendlyReport(); differenceString = friendlyReport.OutputString(comparisonResult.Differences); importResult.processContent.LastUpdatedOn = DateTime.Now; } else { differenceString = "New Entry"; } GenerationReturn validationResult; switch (importResult.processContent) { case PhotoContent p: validationResult = await PhotoGenerator.Validate(p, UserSettingsSingleton.CurrentSettings().LocalMediaArchivePhotoContentFile(p)); break; case FileContent f: validationResult = await FileGenerator.Validate(f, UserSettingsSingleton.CurrentSettings().LocalMediaArchiveFileContentFile(f)); break; case ImageContent i: validationResult = await ImageGenerator.Validate(i, UserSettingsSingleton.CurrentSettings().LocalMediaArchiveImageContentFile(i)); break; case PointContentDto pc: validationResult = await PointGenerator.Validate(pc); break; case PostContent pc: validationResult = await PostGenerator.Validate(pc); break; case LinkContent l: validationResult = await LinkGenerator.Validate(l); break; case NoteContent n: validationResult = await NoteGenerator.Validate(n); break; default: validationResult = await GenerationReturn.Error("Excel Import - No Content Type Generator found?"); break; } if (validationResult.HasError) { errorNotes.Add($"Excel Row {loopRow.RowNumber()} - {validationResult.GenerationNote}"); progress?.Report($"Excel Row {loopRow.RowNumber()} of {lastRow} - Validation Error."); continue; } updateList.Add(new ExcelImportContentUpdateSuggestion { DifferenceNotes = differenceString, Title = importResult.processContent.Title, ToUpdate = importResult.processContent }); progress?.Report( $"Excel Row {loopRow.RowNumber()} of {lastRow} - Adding To Changed List ({updateList.Count}) - Title: {importResult.processContent.Title}"); } if (!errorNotes.Any()) { var internalContentIdDuplicates = updateList.Select(x => x.ToUpdate).GroupBy(x => x.ContentId) .Where(x => x.Count() > 1).Select(x => x.Key).Cast <Guid>().ToList(); if (internalContentIdDuplicates.Any()) { return new ExcelContentTableImportResults { HasError = true, ErrorNotes = $"Content Ids can only appear once in an update list - {string.Join(", ", internalContentIdDuplicates)}", ToUpdate = updateList } } ; var internalSlugDuplicates = updateList.Select(x => x.ToUpdate).Where(x => !(x is LinkContent)) .GroupBy(x => x.Slug).Where(x => x.Count() > 1).Select(x => x.Key).Cast <string>().ToList(); if (internalSlugDuplicates.Any()) { return new ExcelContentTableImportResults { HasError = true, ErrorNotes = $"This import appears to create duplicate slugs - {string.Join(", ", internalSlugDuplicates)}", ToUpdate = updateList } } ; } return(new ExcelContentTableImportResults { HasError = errorNotes.Any(), ErrorNotes = string.Join(Environment.NewLine, errorNotes), ToUpdate = updateList }); }
private void radioUniform_CheckedChanged(object sender, EventArgs e) { if( !(pointGenerator is UniformPointGenerator) ) { pointGenerator = new UniformPointGenerator(); } }
private void radioGaussian_CheckedChanged(object sender, EventArgs e) { if( !(pointGenerator is GaussianPointGenerator) ) { pointGenerator = new GaussianPointGenerator(); } }
public void GivemepointsTest_ReturnsListSameSizeAsPointsGiven() { var sut = new PointGenerator(12345); Assert.AreEqual(10, sut.Givemepoints(10).Count); }
protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); //spriteBatch.DrawString(debugFont, debugstring1, new Vector2(10, 10), Color.Black); //spriteBatch.DrawString(debugFont, debugstring2, new Vector2(10, 40), Color.Black); //spriteBatch.DrawString(debugFont, debugstring3, new Vector2(10, 70), Color.Black); switch (CurrentGameState) { case GameState.MainMenu: //spriteBatch.DrawString(debugFont, gameTimeSinceStart.ToString(), new Vector2(10, 10), Color.Black); //spriteBatch.DrawString(debugFont, gameTimeSincePlaying.ToString(), new Vector2(10, 40), Color.Black); playBeatmapsButton.Draw(spriteBatch); createBeatmapsButton.Draw(spriteBatch); gameTimeSinceStart = (int)gameTime.TotalGameTime.TotalMilliseconds; break; case GameState.Playing: //gameTimeSincePlaying = (int)gameTime.TotalGameTime.TotalMilliseconds - gameTimeSinceStart; spriteBatch.DrawString(debugFont, PointGenerator.TotalPoints.ToString(), new Vector2(10, 10), Color.Black); spriteBatch.DrawString(debugFont, PointGenerator.Multiplicator, new Vector2(10, 30), Color.Black); //this.countShakersAndBeats(); //spriteBatch.DrawString(debugFont, debugstring1, new Vector2(10, 50), Color.Black); //spriteBatch.DrawString(debugFont, debugstring2, new Vector2(10, 70), Color.Black); //spriteBatch.DrawString(debugFont, endTime.ToString(), new Vector2(10, 90), Color.Black); PointGenerator.Draw(spriteBatch, (int)MediaPlayer.PlayPosition.TotalMilliseconds); foreach (var kv in BeatDictionary.ToDictionary(kv => kv.Key, kv => kv.Value)) { if (kv.Key <= MediaPlayer.PlayPosition.TotalMilliseconds) { if (kv.Value.Identifier() == PlayObjectIdentifier.Shaker) { Shaker tempShaker = kv.Value as Shaker; if ((tempShaker.Length + kv.Key) <= (int)MediaPlayer.PlayPosition.TotalMilliseconds) { BeatDictionary.Remove(kv.Key); if (tempShaker.isComplete()) { PointGenerator.generatePointEffect(new Vector2(400f, 240f), PointEffectState.FullPoints, (int)MediaPlayer.PlayPosition.TotalMilliseconds); } else { PointGenerator.generatePointEffect(new Vector2(400f, 240f), PointEffectState.ReducedPoints, (int)MediaPlayer.PlayPosition.TotalMilliseconds); } checkForEndOfSong(); } } else { ClickablePlayObject tempBeat = kv.Value as ClickablePlayObject; if (!tempBeat.thisDraw) { BeatDictionary.Remove(kv.Key); PointGenerator.generatePointEffect(tempBeat.Center, 2f, (int)MediaPlayer.PlayPosition.TotalMilliseconds); } } kv.Value.Draw(spriteBatch); } else { break; } } spriteBatch.DrawString(debugFont, MediaPlayer.PlayPosition.TotalMilliseconds.ToString(), new Vector2(10, 430), Color.Yellow); break; case GameState.BeatmapCreator: gameTimeSinceCreating = (int)gameTime.TotalGameTime.TotalMilliseconds - gameTimeSinceStart; returnToMainMenuButton.Draw(spriteBatch); //spriteBatch.DrawString(debugFont, MediaPlayer.PlayPosition.TotalMilliseconds.ToString(), new Vector2(10, 10), Color.Black); //spriteBatch.DrawString(debugFont, debugstring1, new Vector2(10, 30), Color.Black); //spriteBatch.DrawString(debugFont, debugstring2, new Vector2(10, 50), Color.Black); //spriteBatch.DrawString(debugFont, debugstring3, new Vector2(10, 70), Color.Black); break; case GameState.SaveMenu: break; case GameState.XMLLoadMenu: loadMenu.Draw(spriteBatch); break; case GameState.SongLoadMenu: loadMenu.Draw(spriteBatch); break; case GameState.ScoreMenu: returnToMainMenuButton.Draw(spriteBatch); spriteBatch.DrawString(scoreFont, "Final Score:", new Vector2(150, 200), Color.Red); spriteBatch.DrawString(scoreFont, PointGenerator.TotalPoints.ToString(), new Vector2(150, 300), Color.Red); break; } spriteBatch.End(); base.Draw(gameTime); }
public void Initialize() { _samplePoint1 = PointGenerator.GeneratePoint1(); _samplePoint2 = PointGenerator.GeneratePoint2(); _manyPoints = PointGenerator.GenerateManyPoints(); }
public override void Move() { int width = App.Instance.GraphicsDevice.Viewport.Width; int height = App.Instance.GraphicsDevice.Viewport.Height; int radius = (int)Math.Round(Constants.MAIN_TURRET_RADIUS); int oldregion = region; region = 0; //region will store the area that the invader is in, using the same system as the Cohen-Sutherland //algorithm for clipping an edge against a rectangle if (Location.X < width / 2 - radius) { region |= 0x1; } if (Location.X > width / 2 + radius) { region |= 0x2; } if (Location.Y < height / 2 - radius) { region |= 0x8; } if (Location.Y > height / 2 + radius) { region |= 0x4; } //if the region changed to a side region, then move closer to the tower, in the style of a space invader. if (region != oldregion && isAPowerOf2(region)) { Vector2 direction = (Location - App.Instance.Model.Tower.Location); direction.Normalize(); Location -= direction * 20; #region Minions ICollection <IGenerator> minionsWave = new LinkedList <IGenerator>(); Vector2 parallel = Vector2.Transform(direction, Matrix.CreateRotationZ((float)Math.PI / 2)); PointGenerator left = new PointGenerator(Location + (60 * parallel), 1); left.EnemyType = Generator.EnemyType.Regular; left.Frequency = 1; left.EnemyHealth = 1; left.EnemySize = 10; minionsWave.Add(left); PointGenerator centreright = new PointGenerator(Location + (30 * parallel), 1); centreright.EnemyType = Generator.EnemyType.Regular; centreright.Frequency = 1; centreright.EnemyHealth = 1; centreright.EnemySize = 10; minionsWave.Add(centreright); PointGenerator centreleft = new PointGenerator(Location, 1); centreleft.EnemyType = Generator.EnemyType.Regular; centreleft.Frequency = 1; centreleft.EnemyHealth = 1; centreleft.EnemySize = 10; minionsWave.Add(centreleft); PointGenerator right = new PointGenerator(Location - (30 * parallel), 1); right.EnemyType = Generator.EnemyType.Regular; right.Frequency = 1; right.EnemyHealth = 1; right.EnemySize = 10; minionsWave.Add(right); App.Instance.Model.Spawner.RequestWave(minionsWave); #endregion } //Set direction of velocity based on the region the invader is in. Vector2 dir = Vector2.Zero; if (isAPowerOf2(region)) { //region is a side, not a corner: Move orthogonally to the tower. switch (region) { case 1: dir = new Vector2(0, -1); break; //left side case 2: dir = new Vector2(0, 1); break; //right side case 4: dir = new Vector2(-1, 0); break; //bottom side case 8: dir = new Vector2(1, 0); break; //top side } Acceleration = Vector2.Zero; } else { //region is a corner (or is the centre, but invader would be destroyed were it within the tower) //so move in a circular motion clockwise, to reach the next side region float xMod = (region & 0x2) != 0 ? radius : -radius; float yMod = (region & 0x4) != 0 ? radius : -radius; dir = Location - (App.Instance.Model.Tower.Location + new Vector2(xMod, yMod)); dir.Normalize(); Acceleration = -speed * dir; dir = Vector2.Transform(dir, Matrix.CreateRotationZ((float)(Math.PI / 2))); } //Set velocity Velocity = speed * dir; base.Move(); }
public PointGeneratorProperties() { _pointGenerator = new PointGenerator(Radius, Width, Separation); }
private async void RunDemo() { this.Timer.Stop(); PlayButton.IsEnabled = false; PauseButton.IsEnabled = false; StopButton.IsEnabled = false; ClearCars(); this.ViewModel.IsShowingRoutes = false; this.ViewModel.UpdateControls(); var region = this.MyMap.GetVisibleRegion(MapVisibleRegionKind.Near); var pointGenerator = new PointGenerator(); pointGenerator.Boundaries = region; var routeGenerator = new RouteGenerator(pointGenerator); var carModels = new List <string>() { Car.HammerheadRedUri, Car.HammerheadWhiteUri, Car.ShiftBlueUri, Car.ShiftGoldUri, }; int model = 0; SimulatedTraffic.Cars = new List <Car>(); SimulatedTraffic.Routes = await routeGenerator.GenerateRoutes(NumberOfRoutes); foreach (var route in SimulatedTraffic.Routes) { //var car = new PoliceCar(); //var car = new SchoolBus(); var car = new Car(carModels.ElementAt(model++ % carModels.Count)); car.Connect(this.MyMap, route); SimulatedTraffic.Cars.Add(car); } SimulatedTraffic.Trucks = new List <Car>(); SimulatedTraffic.HighwayRoutes = await routeGenerator.GenerateHighwayRoutes(); foreach (var route in SimulatedTraffic.HighwayRoutes) { var truck = new SemiTruck(); truck.Connect(this.MyMap, route); SimulatedTraffic.Trucks.Add(truck); var dumptruck = new DumpTruck(40); dumptruck.Connect(this.MyMap, route); SimulatedTraffic.Trucks.Add(dumptruck); var car = new Car(55, carModels.ElementAt(model++ % carModels.Count)); car.Connect(this.MyMap, route); SimulatedTraffic.Cars.Add(car); } // Set the interval to 16ms (60 ticks / sec) this.Timer.Interval = new TimeSpan(0, 0, 0, 0, 1000 / UpdatesPerSecond); this.Timer.Start(); this.ViewModel.UpdateControls(); PlayButton.IsEnabled = true; PauseButton.IsEnabled = true; StopButton.IsEnabled = true; }
protected override void Update(GameTime gameTime) { switch (CurrentGameState) { case GameState.MainMenu: //Check for Clicks in Main Menu if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { this.Exit(); } while (TouchPanel.IsGestureAvailable) { GestureSample gesture = TouchPanel.ReadGesture(); switch (gesture.GestureType) { case (GestureType.Tap): if (createBeatmapsButton.checkClick(gesture)) { this.CurrentGameState = GameState.SongLoadMenu; // actual this.menuIdentifier = GameState.BeatmapCreator; //this.CurrentGameState = GameState.TestMenu; //testing purposes loadMenu = new SongLoadMenu(this.Content); BeatTimerList = new List <BeatTimerData>(); //Actual //MediaPlayer.Play(munchymonk); //debug } ; if (playBeatmapsButton.checkClick(gesture)) { endTime = 9999999; this.CurrentGameState = GameState.SongLoadMenu; this.menuIdentifier = GameState.Playing; loadMenu = new SongLoadMenu(this.Content); } ; break; } } break; case GameState.SongLoadMenu: if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { CurrentGameState = GameState.MainMenu; break; } while (TouchPanel.IsGestureAvailable) { GestureSample gesture = TouchPanel.ReadGesture(); switch (gesture.GestureType) { case (GestureType.Tap): switch (loadMenu.checkClick(gesture.Position)) { //case GameState.Playing: // this.BeatTimerList = xmlConverter.loadBeatmapXML(DataSaver.SelectedXml()); // this.LoadLateContent(); // //MediaPlayer.Play(munchymonk); // CurrentGameState = GameState.Playing; // break; case GameState.XMLLoadMenu: if (menuIdentifier == GameState.Playing) { this.CurrentGameState = GameState.XMLLoadMenu; loadMenu = new XMLLoadMenu(this.Content); } else { this.CurrentGameState = GameState.BeatmapCreator; MediaPlayer.Play(DataSaver.SelectedSong()); } break; case GameState.MainMenu: this.CurrentGameState = GameState.MainMenu; break; } break; } } break; case GameState.XMLLoadMenu: if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { CurrentGameState = GameState.MainMenu; break; } while (TouchPanel.IsGestureAvailable) { GestureSample gesture = TouchPanel.ReadGesture(); switch (gesture.GestureType) { case (GestureType.Tap): switch (loadMenu.checkClick(gesture.Position)) { case GameState.Playing: //debug this.BeatTimerList = xmlConverter.loadBeatmapXML(DataSaver.SelectedXml()); this.LoadLateContent(); MediaPlayer.Play(DataSaver.SelectedSong()); PointGenerator.ResetPoints(); CurrentGameState = GameState.Playing; break; case GameState.SongLoadMenu: this.CurrentGameState = GameState.SongLoadMenu; loadMenu = new SongLoadMenu(this.Content); break; case GameState.MainMenu: this.CurrentGameState = GameState.MainMenu; break; } break; } } break; case GameState.Playing: //Check for Beat klicks if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { CurrentGameState = GameState.MainMenu; MediaPlayer.Stop(); break; } while (TouchPanel.IsGestureAvailable) { GestureSample gesture = TouchPanel.ReadGesture(); switch (gesture.GestureType) { case (GestureType.Tap): checkIntersect(gesture.Position); break; } } if ((long)MediaPlayer.PlayPosition.TotalMilliseconds >= endTime) { MediaPlayer.Stop(); CurrentGameState = GameState.ScoreMenu; } break; case GameState.BeatmapCreator: //Check for Taps to create Beatmap if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { CurrentGameState = GameState.MainMenu; MediaPlayer.Stop(); break; } TouchCollection touchcol = TouchPanel.GetState(); foreach (TouchLocation touchlocation in touchcol) { if (touchlocation.State == TouchLocationState.Released && isHeld) { int heldTime = (int)MediaPlayer.PlayPosition.TotalMilliseconds - gameTimeSinceHolding; debugstring1 = "Held for: " + heldTime; BeatTimerList.Add(new BeatTimerData(gameTimeSinceHolding, new Vector2(0, 0), new Vector2(0, 0), heldTime, false, true)); //Adds a Shaker reference with the start time as the screen was touched and the total shaker time as the touch was held. isHeld = false; } } while (TouchPanel.IsGestureAvailable) { GestureSample gesture = TouchPanel.ReadGesture(); switch (gesture.GestureType) { case (GestureType.Tap): if (returnToMainMenuButton.checkClick(gesture)) { MediaPlayer.Stop(); this.CurrentGameState = GameState.SaveMenu; Guide.BeginShowKeyboardInput( PlayerIndex.One, "Saving Beatmap", "Title of Beatmap", "", saveBeatmapAs, null); //this.LoadLateContent(); } else { BeatTimerList.Add(new BeatTimerData((int)MediaPlayer.PlayPosition.TotalMilliseconds - 1100, gesture.Position, new Vector2(0, 0), 0, false, false)); }; break; case (GestureType.Hold): gameTimeSinceHolding = (int)MediaPlayer.PlayPosition.TotalMilliseconds - 1000; debugstring2 = "held since: " + gameTimeSinceHolding + " since holding"; isHeld = true; break; } } break; case GameState.ScoreMenu: while (TouchPanel.IsGestureAvailable) { GestureSample gesture = TouchPanel.ReadGesture(); switch (gesture.GestureType) { case (GestureType.Tap): if (returnToMainMenuButton.checkClick(gesture)) { this.CurrentGameState = GameState.MainMenu; } break; } } break; } base.Update(gameTime); }
public static async Task <(bool hasError, string errorMessage)> SaveAndGenerateHtmlFromExcelImport( ExcelContentTableImportResults contentTableImportResult, IProgress <string> progress) { var errorList = new List <string>(); var totalToUpdate = contentTableImportResult.ToUpdate.Count; var currentUpdate = 0; foreach (var loopUpdates in contentTableImportResult.ToUpdate) { currentUpdate++; progress?.Report($"Excel Import Update {currentUpdate} of {totalToUpdate}"); GenerationReturn generationResult; switch (loopUpdates.ToUpdate) { case PhotoContent photo: { generationResult = (await PhotoGenerator.SaveAndGenerateHtml(photo, UserSettingsSingleton.CurrentSettings().LocalMediaArchivePhotoContentFile(photo), false, null, progress)).generationReturn; break; } case FileContent file: { generationResult = (await FileGenerator.SaveAndGenerateHtml(file, UserSettingsSingleton.CurrentSettings().LocalMediaArchiveFileContentFile(file), false, null, progress)).generationReturn; break; } case ImageContent image: { generationResult = (await ImageGenerator.SaveAndGenerateHtml(image, UserSettingsSingleton.CurrentSettings().LocalMediaArchiveImageContentFile(image), false, null, progress)).generationReturn; break; } case PointContentDto point: { generationResult = (await PointGenerator.SaveAndGenerateHtml(point, null, progress)) .generationReturn; break; } case PostContent post: { generationResult = (await PostGenerator.SaveAndGenerateHtml(post, null, progress)) .generationReturn; break; } case NoteContent note: { generationResult = (await NoteGenerator.SaveAndGenerateHtml(note, null, progress)) .generationReturn; break; } case LinkContent link: { generationResult = (await LinkGenerator.SaveAndGenerateHtml(link, null, progress)) .generationReturn; break; } default: generationResult = await GenerationReturn.Error("Excel Import - No Content Type Generator found?"); break; } if (!generationResult.HasError) { progress?.Report( $"Updated Content Id {loopUpdates.ToUpdate.ContentId} - Title {loopUpdates.Title} - Saved"); } else { errorList.Add( $"Updating Failed: Content Id {loopUpdates} - Title {loopUpdates.Title} - Failed:{Environment.NewLine}{generationResult.GenerationNote}"); } } if (errorList.Any()) { return(true, string.Join(Environment.NewLine, errorList)); } return(false, string.Empty); }
public RouteGenerator(PointGenerator pointGenerator) { this.pointGenerator = pointGenerator; }
/// <summary> /// Chooses a random generator type and enemy type per player and queues them. /// </summary> /// <param name="useAllSides">False if only each player's own side should be used to spawn, true if /// there should be a chance of using a random side.</param> /// <param name="playerSpecifc">If true, each spawn can only be damaged by the player who shares a /// colour with it.</param> void RandomWave(bool useAllSides, bool playerSpecifc) { ICollection <IGenerator> wave = new LinkedList <IGenerator>(); AbstractGenerator g; foreach (MainGun p in model.ActivePlayers) { int side = p.PlayerId; // If useAllSides, sometimes choose a different side. if (useAllSides && random.Next(2) == 0) { side = random.Next(0, 3); } //Choose the type of generator. int genType = random.Next(3); switch (genType) { case 0: g = new CircleGenerator(1); g.GroupSize = 20; g.MultiplayerAdjustment = 1; System.Console.WriteLine(0); break; case 1: g = new PointGenerator(PointGenerator.PointOnSide(side, 20), 3 + LinearDifficulty(10, 12)); System.Console.WriteLine(1); break; case 2: g = new SideGenerator(side, 1); g.GroupSize = 20; g.MultiplayerAdjustment = 1; System.Console.WriteLine(2); break; default: throw new InvalidOperationException(); } //Choose the type of enemy. int enemyType = random.Next(3); switch (enemyType) { case 0: g.EnemyType = EnemyType.Regular; break; case 1: g.EnemyType = EnemyType.Spiral; break; case 2: g.EnemyType = EnemyType.Wave; break; default: throw new InvalidOperationException(); } g.EnemyHealth = 1 + LinearDifficulty(5, 0); g.EnemySize = 20; g.EnemySizeVariance = LinearDifficulty(5, 10); g.Frequency = model.Music.ClicksPerBeat; if (playerSpecifc) { g.PlayerSpecific = true; } wave.Add(g); } waves.Enqueue(wave); }