public void CreateMapWithGrid(int[,] grid) { if (_tileRenderer == null) { this.Awake(); } else { this.Clear(); } for (int x = 0; x < grid.GetLength(0); ++x) { for (int y = 0; y < grid.GetLength(1); ++y) { string prefabKey = TilingHelper.GetTileType(TilingHelper.GetNeighbors(grid, x, y, _tileRenderer.OffMapIsFilled)); if (_geometryPrefabs.ContainsKey(prefabKey)) { GameObject prefab = _geometryPrefabs[prefabKey]; IntegerVector intPosition = _tileRenderer.PositionForTile(x, y); Vector3 position = new Vector3(intPosition.X, intPosition.Y, 0); GameObject geom = Instantiate(prefab, Vector3.zero, Quaternion.identity) as GameObject; geom.transform.parent = this.transform; geom.transform.localPosition = position; } } } }
/// <summary> /// Returns a randomly chosen child node for the given <paramref name="parentNode"/>. /// </summary> /// <param name="parentNode">parent node to find a child node randomly for</param> /// <param name="genotype">integer vector, which should be mapped to a tree</param> /// <param name="grammar">grammar used to define the allowed child symbols</param> /// <param name="genotypeIndex">index in the integer vector; can be greater than vector length</param> /// <param name="random">random number generator</param> /// <returns>randomly chosen child node or null, if no child node exits</returns> protected ISymbolicExpressionTreeNode GetNewChildNode(ISymbolicExpressionTreeNode parentNode, IntegerVector genotype, ISymbolicExpressionGrammar grammar, int genotypeIndex, IRandom random) { // only select specific symbols, which can be interpreted ... IEnumerable <ISymbol> symbolList = (from s in grammar.GetAllowedChildSymbols(parentNode.Symbol) where s.InitialFrequency > 0.0 select s).ToList(); int prodRuleCount = symbolList.Count(); // no child node exists for the given parent node if (prodRuleCount < 1) { return(null); } // genotypeIndex % genotype.Length, if wrapping is allowed int prodRuleIndex = genotype[genotypeIndex] % prodRuleCount; var newNode = symbolList.ElementAt(prodRuleIndex).CreateTreeNode(); if (newNode.HasLocalParameters) { newNode.ResetLocalParameters(random); } return(newNode); }
public void DiscreteCrossoverApplyTest() { TestRandom random = new TestRandom(); IntegerVector parent1, parent2, expected, actual; bool exceptionFired; // The following test is not based on published examples random.Reset(); random.IntNumbers = new int[] { 0, 0, 1, 0, 1 }; parent1 = new IntegerVector(new int[] { 2, 2, 3, 5, 1 }); parent2 = new IntegerVector(new int[] { 4, 1, 3, 2, 8 }); expected = new IntegerVector(new int[] { 2, 2, 3, 5, 8 }); actual = DiscreteCrossover.Apply(random, new ItemArray <IntegerVector>(new IntegerVector[] { parent1, parent2 })); Assert.IsTrue(Auxiliary.IntegerVectorIsEqualByPosition(actual, expected)); // The following test is not based on published examples random.Reset(); random.IntNumbers = new int[] { 0, 0, 1, 0, 1 }; parent1 = new IntegerVector(new int[] { 2, 2, 3, 5, 1, 9 }); // this parent is longer parent2 = new IntegerVector(new int[] { 4, 1, 3, 2, 8 }); exceptionFired = false; try { actual = DiscreteCrossover.Apply(random, new ItemArray <IntegerVector>(new IntegerVector[] { parent1, parent2 })); } catch (System.ArgumentException) { exceptionFired = true; } Assert.IsTrue(exceptionFired); }
public static void CompleteTile(IntegerVector tile) { if (!_completedTiles.Contains(tile)) { _completedTiles.Add(tile); PersistentData.RegisterLevelBeaten(DynamicData.NumJoinedPlayers()); if (IsCornerBoss(tile)) { PersistentData.RegisterBossBeaten(); if (NumBossesBeaten() == 4) PersistentData.Register4CornerBossesBeaten(); } if (_completedTiles.Count == 44) PersistentData.RegisterClearedMap(); } _mostRecentTile = tile; if (_minibossTiles != null) { if (_minibossTiles.Contains(tile)) _minibossTiles.Remove(tile); moveMiniBosses(); } }
public LaserCastEvent(CollisionManager.RaycastResult raycastResult, IntegerVector origin, AllegianceInfo allegianceInfo) { this.Name = NAME; this.RaycastResult = raycastResult; this.Origin = origin; this.AllegianceInfo = allegianceInfo; }
public void BeginAttackPathing(IntegerVector lowerLeft, IntegerVector upperRight) { _attacking = true; _lowerLeft = lowerLeft; _upperRight = upperRight; seekAttackPoint(); }
public EnemySpawnGroup(IntegerVector spawnPosition, int enemyId) { this.SingleSpawn = new EnemySpawn(spawnPosition, enemyId); this.Origin = spawnPosition; this.MultiSpawns = null; this.SpawnDistance = 0.0f; }
public void SinglePointCrossoverApplyTest() { TestRandom random = new TestRandom(); IntegerVector parent1, parent2, expected, actual; bool exceptionFired; // The following test is not based on published examples random.Reset(); random.IntNumbers = new int[] { 3 }; parent1 = new IntegerVector(new int[] { 2, 2, 3, 5, 1 }); parent2 = new IntegerVector(new int[] { 4, 1, 3, 2, 8 }); expected = new IntegerVector(new int[] { 2, 2, 3, 2, 8 }); actual = SinglePointCrossover.Apply(random, parent1, parent2); Assert.IsTrue(Auxiliary.IntegerVectorIsEqualByPosition(actual, expected)); // The following test is not based on published examples random.Reset(); random.IntNumbers = new int[] { 2 }; parent1 = new IntegerVector(new int[] { 2, 2, 3, 5, 1, 9 }); // this parent is longer parent2 = new IntegerVector(new int[] { 4, 1, 3, 2, 8 }); exceptionFired = false; try { actual = SinglePointCrossover.Apply(random, parent1, parent2); } catch (System.ArgumentException) { exceptionFired = true; } Assert.IsTrue(exceptionFired); }
private static IntegerVector GetNontVector(IRandom random, IntMatrix bounds, int length) { IntegerVector v = new IntegerVector(length); v.Randomize(random, bounds); return(v); }
private bool findCASpawns(LevelGenOutput output) { List <LevelGenMap.Coordinate> openTiles = new List <LevelGenMap.Coordinate>(output.OpenTiles); openTiles.Shuffle(); EnemySelector enemySelector = new EnemySelector(); int difficulty = ProgressData.GetCurrentDifficulty(); IntegerVector enemyCountRange = output.Input.GetCurrentNumEnemiesRange(); int[] guaranteedEnemiesPlaced = new int[output.Input.GuaranteedEnemiesByDifficulty.Length]; this.NumEnemies = Random.Range(enemyCountRange.X, enemyCountRange.Y + 1); LevelGenCaveInfo caveInfo = output.MapInfo[LevelGenCaveInfo.KEY] as LevelGenCaveInfo; if (ProgressData.IsMiniBoss(ProgressData.MostRecentTile)) { findMinibossSpawn(openTiles, (caveInfo.Data as List <List <LevelGenMap.Coordinate> >)[0]); } if (openTiles.Count <= (this.NumEnemies + DynamicData.MAX_PLAYERS) * output.Input.MinDistanceBetweenSpawns * 2 + 1) { Debug.Log("Regeneration necessary - CA"); return(false); } else { spawnSimple(0, output, guaranteedEnemiesPlaced, enemySelector, difficulty, openTiles, true); } return(true); }
public EnemySpawnGroup(IntegerVector origin, List <EnemySpawn> spawns, float spawnDistance) { this.SingleSpawn = null; this.Origin = origin; this.MultiSpawns = spawns; this.SpawnDistance = spawnDistance; }
public bool Contains(IntegerVector point) { IntegerVector selfMin = this.Min; IntegerVector selfMax = this.Max; return(point.X >= selfMin.X && point.X <= selfMax.X && point.Y >= selfMin.Y && point.Y <= selfMax.Y); }
public virtual bool Contains(IntegerVector point, int offsetX = 0, int offsetY = 0) { IntegerRect bounds = this.Bounds; bounds.Center.X += offsetX; bounds.Center.Y += offsetY; return bounds.Contains(point); }
//http://stackoverflow.com/questions/20453545/how-to-find-the-nearest-point-in-the-perimeter-of-a-rectangle-to-a-given-point public IntegerVector ClosestContainedPoint(IntegerVector point) { if (this.Contains(point)) { return(point); } IntegerVector selfMin = this.Min; IntegerVector selfMax = this.Max; int clampedX = Mathf.Clamp(point.X, selfMin.X, selfMax.X); int clampedY = Mathf.Clamp(point.Y, selfMin.Y, selfMax.Y); int dl = Math.Abs(selfMin.X - clampedX); int dr = Math.Abs(clampedX - selfMax.X); int db = Math.Abs(selfMin.Y - clampedY); int dt = Math.Abs(clampedY - selfMax.Y); int min = Mathf.Min(new int[] { dl, dr, db, dt }); if (min == db) { return(new IntegerVector(clampedX, selfMin.Y)); } if (min == dt) { return(new IntegerVector(clampedX, selfMax.Y)); } if (min == dl) { return(new IntegerVector(selfMin.X, clampedY)); } return(new IntegerVector(selfMax.X, clampedY)); }
private Vector2?findTarget() { float angleInc = 360.0f / this.RayDirections; int angleDir = Mathf.RoundToInt(Mathf.Sign(1.0f - Random.Range(0.0f, 2.0f))); if (angleDir == 0) { angleDir = 1; } for (int i = 0; i < this.RayDirections; ++i) { Vector2 direction = ((Vector2)(this.LookAt.transform.forward)).VectorAtAngle(i * angleInc * angleDir); float distance = this.MaxMovementDistance + this.HalfSize; CollisionManager.RaycastResult result = CollisionManager.RaycastFirst(new IntegerVector(this.transform.position), direction, distance, this.HaltMovementMask); if (!result.Collided) { distance -= (this.HalfSize + WIGGLE); if (distance > this.MinMovementDistance) { distance = Random.Range(this.MinMovementDistance, distance); IntegerVector offset = new IntegerVector(direction * distance); if (this.LookAt.integerCollider.CollideFirst(offset.X, offset.Y, this.HaltMovementMask) == null) { return((Vector2)this.transform.position + direction * distance); } } } } return(null); }
private static void moveMiniBosses() { int[] neighborCoords = { -1, 0, 1 }; for (int i = 0; i < _minibossTiles.Count; ++i) { IntegerVector miniBossTile = _minibossTiles[i]; List <IntegerVector> validNeighbors = new List <IntegerVector>(); foreach (int x in neighborCoords) { foreach (int y in neighborCoords) { if (Mathf.Abs(x) == Mathf.Abs(y)) { continue; } IntegerVector neighbor = new IntegerVector(miniBossTile.X + x, miniBossTile.Y + y); if (Mathf.Abs(neighbor.X) <= 3 && Mathf.Abs(neighbor.Y) <= 3 && !_completedTiles.Contains(neighbor) && !IsCornerBoss(neighbor) && !IsMiniBoss(neighbor)) { validNeighbors.Add(neighbor); } } } if (validNeighbors.Count > 0) { _minibossTiles[i] = validNeighbors[Random.Range(0, validNeighbors.Count)]; } } }
public static void CompleteTile(IntegerVector tile) { if (!_completedTiles.Contains(tile)) { _completedTiles.Add(tile); PersistentData.RegisterLevelBeaten(DynamicData.NumJoinedPlayers()); if (IsCornerBoss(tile)) { PersistentData.RegisterBossBeaten(); if (NumBossesBeaten() == 4) { PersistentData.Register4CornerBossesBeaten(); } } if (_completedTiles.Count == 44) { PersistentData.RegisterClearedMap(); } } _mostRecentTile = tile; if (_minibossTiles != null) { if (_minibossTiles.Contains(tile)) { _minibossTiles.Remove(tile); } moveMiniBosses(); } _mostPlayersUsed = DynamicData.NumJoinedPlayers(); }
private Vector2? findTarget() { float angleInc = 360.0f / this.RayDirections; int angleDir = Mathf.RoundToInt(Mathf.Sign(1.0f - Random.Range(0.0f, 2.0f))); if (angleDir == 0) angleDir = 1; for (int i = 0; i < this.RayDirections; ++i) { Vector2 direction = ((Vector2)(this.LookAt.transform.forward)).VectorAtAngle(i * angleInc * angleDir); float distance = this.MaxMovementDistance + this.HalfSize; CollisionManager.RaycastResult result = CollisionManager.RaycastFirst(new IntegerVector(this.transform.position), direction, distance, this.HaltMovementMask); if (!result.Collided) { distance -= (this.HalfSize + WIGGLE); if (distance > this.MinMovementDistance) { distance = Random.Range(this.MinMovementDistance, distance); IntegerVector offset = new IntegerVector(direction * distance); if (this.LookAt.integerCollider.CollideFirst(offset.X, offset.Y, this.HaltMovementMask) == null) { return (Vector2)this.transform.position + direction * distance; } } } } return null; }
public bool Contains(IntegerVector point, int expand) { IntegerVector selfMin = this.Min; IntegerVector selfMax = this.Max; return(point.X >= (selfMin.X - expand) && point.X <= (selfMax.X + expand) && point.Y >= (selfMin.Y - expand) && point.Y <= (selfMax.Y + expand)); }
void FixedUpdate() { if (!this.Paused && (this.MaxParticlesToSpawn < 0 || _count < this.MaxParticlesToSpawn)) { if (_t <= 0) { _unused.Shuffle(); GameObject particle = _unused.Pop(); if (particle != null) { ++_count; _t = Random.Range(this.SpawnIntervalRange.X, this.SpawnIntervalRange.Y + 1); IntegerVector pos = new IntegerVector(Random.Range(this.EmmissionRange.Bounds.Min.X, this.EmmissionRange.Bounds.Max.X), Random.Range(this.EmmissionRange.Bounds.Min.Y, this.EmmissionRange.Bounds.Max.Y)); particle.SetActive(true); particle.transform.SetPosition2D(pos); this.EmitParticle(particle, pos); _unused.Remove(particle); if (!_used.Contains(particle)) { _used.Add(particle); } } } else { _t -= 1; } } }
public static PWREncoding CreateTestPWR2() { PWREncoding result = new PWREncoding(); IntegerVector pwr = new IntegerVector(new int[] { 0, 1, 1, 0, 2, 0, 1, 2, 2 }); result.PermutationWithRepetition = pwr; return(result); }
public static IntegerRect CreateFromMinMax(IntegerVector min, IntegerVector max) { IntegerRect rect = new IntegerRect(); rect.Center = (min + max) / 2; rect.Size = max - min; return(rect); }
public virtual bool Contains(IntegerVector point, int offsetX = 0, int offsetY = 0) { IntegerRect bounds = this.Bounds; bounds.Center.X += offsetX; bounds.Center.Y += offsetY; return(bounds.Contains(point)); }
public override bool Overlaps(IntegerCollider other, int offsetX = 0, int offsetY = 0) { IntegerVector center = this.Bounds.Center; center.X += offsetX; center.Y += offsetY; return(this.Contains(other.ClosestContainedPoint(this.Bounds.Center), offsetX, offsetY)); }
public TSAnalyze () { InitializeComponent (); // There are several options to initialize thengine, but by default the following suffice: REngine engine = REngine.GetInstance(); //init the R engine REngine.SetEnvironmentVariables (); engine = REngine.GetInstance (); engine.Initialize (); //prepare data List<int> size = new List<int>() { 29, 33, 51, 110, 357, 45, 338, 543, 132, 70, 103, 301, 146, 10, 56, 243, 238 }; List<int> population = new List<int>() { 3162, 11142, 3834, 7305, 81890, 1339, 5414, 65697, 11280, 4589, 320, 60918, 480, 1806, 4267, 63228, 21327 }; var docPath = Directory.GetCurrentDirectory(); //var myDir = $@"{docPath}\output"; var myDir = bingPathToAppDir ("output"); Directory.CreateDirectory (myDir); Console.WriteLine (Directory.Exists (myDir)); Console.WriteLine (myDir); Console.WriteLine (bingPathToAppDir ("output")); Console.WriteLine ("my image location {0}", myDir); fileName = myDir + "\\myplot.png"; //calculate IntegerVector sizeVector = engine.CreateIntegerVector(size); engine.SetSymbol ("size", sizeVector); IntegerVector populationVector = engine.CreateIntegerVector(population); engine.SetSymbol ("population", populationVector); CharacterVector fileNameVector = engine.CreateCharacterVector(new[] { fileName }); engine.SetSymbol ("fileName", fileNameVector); engine.Evaluate ("reg <- lm(population~size)"); engine.Evaluate ("png(filename=fileName, width=6, height=6, units='in', res=100)"); engine.Evaluate ("plot(population~size)"); engine.Evaluate ("abline(reg)"); engine.Evaluate ("dev.off()"); //clean up engine.Dispose (); //output Console.WriteLine (""); Console.WriteLine ("Press any key to exit"); Console.ReadKey (); }
private OrienteeringSolution(OrienteeringSolution original, Cloner cloner) : base(original, cloner) { this.integerVector = cloner.Clone(original.integerVector); this.coordinates = cloner.Clone(original.coordinates); this.quality = cloner.Clone(original.quality); this.penalty = cloner.Clone(original.penalty); Initialize(); }
public override Solution Decode(IntegerVector intVec, PackingShape binShape, IList <PackingItem> items, bool useStackingConstraints) { // TODO if (useStackingConstraints) { throw new NotSupportedException("Stacking constraints are not supported by the Bottom-Left IntegerVector Decoder"); } return(base.Decode(intVec, binShape, items, useStackingConstraints: false)); }
private void InsertPoints(List <int> actualTour, IntegerVector initialTour, int neighborhood, List <int> visitablePoints, IRandom random) { // Elect the starting index of the part to be replaced int tourSize = initialTour.Length; int randomPosition = random.Next(tourSize - neighborhood - 1) + 1; for (int position = 1; position < tourSize; position++) { if ((position < randomPosition) || (position > (randomPosition + neighborhood - 1))) { // Copy from initial tour when outside shaking range actualTour.Add(initialTour[position]); // Delete this point from the candidate list visitablePoints.Remove(initialTour[position]); } else { // Point from within shaking range if (visitablePoints.Count > 0) { // Add the point with the highest utility from the candidate list int randomFactor = random.Next(3); int insertionIndex = visitablePoints.Count - 1; if (visitablePoints.Count > 4) { insertionIndex -= randomFactor; } actualTour.Add(visitablePoints[insertionIndex]); // Delete this point from the candidate list visitablePoints.RemoveAt(insertionIndex); } else { // We don't have any points left that could be inserted so we can only re-insert // the removed and not already re-inserted points in a random order for (int reinsertPosition = randomPosition; reinsertPosition < randomPosition + neighborhood; reinsertPosition++) { bool alreadyReinserted = actualTour.Contains(initialTour[reinsertPosition]); if (!alreadyReinserted) { visitablePoints.Add(initialTour[reinsertPosition]); } } int randomIndex = random.Next(visitablePoints.Count); actualTour.Add(visitablePoints[randomIndex]); visitablePoints.Clear(); } } } }
public override IntegerVector ClosestContainedPoint(IntegerVector point) { if (this.Contains(point)) return point; IntegerVector center = this.Bounds.Center; IntegerVector difference = point - center; difference = new IntegerVector(((Vector2)difference).normalized * this.Radius); return center + difference; }
private GenericVector ConvertToRList(VmResourceTrace trace) { var list = new GenericVector(R, 3); list.SetNames("vmId", "resourceId", "series"); list["vmId"] = new IntegerVector(R, new int[] { trace.VmId }); list["resourceId"] = new IntegerVector(R, new int[] { (int)trace.Resource }); list["series"] = new NumericVector(R, trace.Series.Select(f => (double)(f))); return(list); }
private bool findBSPCAComboSpawns(LevelGenOutput output) { List <LevelGenMap.Coordinate> openTiles = new List <LevelGenMap.Coordinate>(output.OpenTiles); openTiles.Shuffle(); EnemySelector enemySelector = new EnemySelector(); int difficulty = ProgressData.GetCurrentDifficulty(); IntegerVector enemyCountRange = output.Input.GetCurrentNumEnemiesRange(); int[] guaranteedEnemiesPlaced = new int[output.Input.GuaranteedEnemiesByDifficulty.Length]; this.NumEnemies = Random.Range(enemyCountRange.X, enemyCountRange.Y + 1); LevelGenCaveInfo caveInfo = output.MapInfo[LevelGenCaveInfo.KEY] as LevelGenCaveInfo; if (ProgressData.IsMiniBoss(ProgressData.MostRecentTile)) { findMinibossSpawn(openTiles, (caveInfo.Data as List <List <LevelGenMap.Coordinate> >)[0]); } LevelGenRoomInfo roomInfo = output.MapInfo[LevelGenRoomInfo.KEY] as LevelGenRoomInfo; List <SimpleRect> availableRooms = new List <SimpleRect>(roomInfo.Data as List <SimpleRect>); availableRooms.Shuffle(); // Player room SimpleRect playerRoom = availableRooms[availableRooms.Count - 1]; availableRooms.RemoveAt(availableRooms.Count - 1); List <LevelGenMap.Coordinate> playerRoomCoords = coordinatesInRoom(playerRoom); openTiles.RemoveList(playerRoomCoords); playerRoomCoords.Shuffle(); for (int p = 0; p < DynamicData.MAX_PLAYERS; ++p) { if (DynamicData.GetSessionPlayer(p).HasJoined) { _playerSpawns.Add(playerRoomCoords[playerRoomCoords.Count - 1].integerVector); playerRoomCoords.RemoveAt(playerRoomCoords.Count - 1); } } if (openTiles.Count <= (this.NumEnemies + DynamicData.MAX_PLAYERS) * output.Input.MinDistanceBetweenSpawns * 2 + 1) { Debug.Log("Regeneration necessary - CA"); return(false); } else { spawnSimple(0, output, guaranteedEnemiesPlaced, enemySelector, difficulty, openTiles, false); } return(true); }
public GameObject CollidePointFirst(IntegerVector point, List <IntegerCollider> potentialCollisions) { foreach (IntegerCollider collider in potentialCollisions) { if (collider.Contains(point)) { return(collider.gameObject); } } return(null); }
public static void Start(REngine engine) { Console.WriteLine("\n\nExporting Objects\n\n"); string RCodeString = string.Empty; //R character vector -- R.NET RDotNet.RDotNet.CharacterVector Console.WriteLine("\nR character vector\n"); string[] myStringArray = new string[] { "PIDataLink", "PIProcessBook", "PIWebParts" }; CharacterVector myCharacterVector = engine.CreateCharacterVector(myStringArray.AsEnumerable()); engine.SetSymbol("mycharvector", myCharacterVector); engine.Evaluate("print(mycharvector)"); //R integer vector -- R.NET RDotNet.NumericVector Console.WriteLine("\nR int vector\n"); int[] myIntegerArray = new int[] { 4, 6, 10, 140, 54, 25 }; IntegerVector myIntegerVector = engine.CreateIntegerVector(myIntegerArray); engine.SetSymbol("myintvector", myIntegerVector); engine.Evaluate("print(myintvector)"); //R real vector -- R.NET RDotNet.NumericVector Console.WriteLine("\nR real vector\n"); NumericVector myNumericVector = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 }); engine.SetSymbol("mynumvector", myNumericVector); engine.Evaluate("print(mynumvector)"); //R complex vector -- R.NET RDotNet.ComplexVector Console.WriteLine("\nR complex vector\n"); Complex[] myComplexArray = new Complex[] { Complex.FromPolarCoordinates(10, 0.524), new Complex(12, 6), new Complex(14, 3), (Complex)12.3m, Complex.One + Complex.One }; ComplexVector myComplexVector = engine.CreateComplexVector(myComplexArray); engine.SetSymbol("mycomplexvector", myComplexVector); engine.Evaluate("print(mycomplexvector)"); //R raw vector -- R.NET RDotNet.RawVector Console.WriteLine("\nR raw vector\n"); byte[] myByteArray = System.Text.Encoding.ASCII.GetBytes("u03a0"); RawVector myRawVector = engine.CreateRawVector(myByteArray); engine.SetSymbol("myrawvector", myRawVector); engine.Evaluate("print(myrawvector)"); //R logical vector -- R.NET RDotNet.LogicalVector Console.WriteLine("\nR logical vector\n"); LogicalVector myLogicalVector = engine.CreateLogicalVector(new Boolean[] { true, false, false, false, true }); engine.SetSymbol("mylogicalvector", myLogicalVector); engine.Evaluate("print(mylogicalvector)"); }
public static bool IsMiniBoss(IntegerVector tile) { if (_minibossTiles != null) { for (int i = 0; i < _minibossTiles.Count; ++i) { if (tile == _minibossTiles[i]) return true; } } return false; }
public bool Overlaps(IntegerRect other) { IntegerVector selfMin = this.Min; IntegerVector selfMax = this.Max; IntegerVector otherMin = other.Min; IntegerVector otherMax = other.Max; return(((otherMin.X >= selfMin.X && otherMin.X < selfMax.X) || (otherMax.X > selfMin.X && otherMax.X <= selfMax.X) || (selfMin.X >= otherMin.X && selfMin.X < otherMax.X) || (selfMax.X > otherMin.X && selfMax.X <= otherMax.X)) && ((otherMin.Y >= selfMin.Y && otherMin.Y < selfMax.Y) || (otherMax.Y > selfMin.Y && otherMax.Y <= selfMax.Y) || (selfMin.Y >= otherMin.Y && selfMin.Y < otherMax.Y) || (selfMax.Y > otherMin.Y && selfMax.Y <= otherMax.Y))); }
public static bool IntegerVectorIsEqualByPosition(IntegerVector p1, IntegerVector p2) { bool equal = (p1.Length == p2.Length); if (equal) { for (int i = 0; i < p1.Length; i++) { if (!p1[i].Equals(p2[i])) { equal = false; break; } } } return equal; }
public GameObject CollidePointFirst(IntegerVector point, List <IntegerCollider> potentialCollisions) { for (int i = 0; i < potentialCollisions.Count; ++i) { IntegerCollider collider = potentialCollisions[i]; if (collider != null && collider.enabled && collider.Contains(point)) { return(collider.gameObject); } } return(null); }
private void seekAttackPoint() { IntegerVector target = new IntegerVector(Random.Range(_lowerLeft.X, _upperRight.X), Random.Range(_lowerLeft.Y, _upperRight.Y)); int i = 0; while (i < this.AttemptsAtPreferred && Vector2.Distance(this.transform.position, target) < this.PreferredMinDistance) { target = new IntegerVector(Random.Range(_lowerLeft.X, _upperRight.X), Random.Range(_lowerLeft.Y, _upperRight.Y)); ++i; } _lerpMovement.BeginMovement(target); }
public void UniformOnePositionManipulatorApplyTest() { TestRandom random = new TestRandom(); IntegerVector parent, expected; IntMatrix bounds = new IntMatrix(1, 2); // The following test is not based on published examples random.Reset(); random.IntNumbers = new int[] { 3, 3 }; parent = new IntegerVector(new int[] { 2, 2, 3, 5, 1 }); expected = new IntegerVector(new int[] { 2, 2, 3, 3, 1 }); bounds[0, 0] = 2; bounds[0, 1] = 7; UniformOnePositionManipulator.Apply(random, parent, bounds); Assert.IsTrue(Auxiliary.IntegerVectorIsEqualByPosition(expected, parent)); }
public bool Damage(SCAttack attack, IntegerVector origin, IntegerVector hitPoint) { if (this.Invincible) return false; //TODO - Normalize knockback effect to 16 directions Vector2 knockbackDirection = ((Vector2)(hitPoint - origin)).normalized; this.Actor.Velocity = knockbackDirection * attack.KnockbackPower; this.Invincible = true; _invincibilityTimer.reset(attack.HitInvincibilityDuration + FREEZE_FRAMES); _invincibilityTimer.start(); this.localNotifier.SendEvent(_freezeFrameEvent); _hitStunEvent.NumFrames = attack.HitStunDuration; this.localNotifier.SendEvent(_hitStunEvent); return true; }
//http://stackoverflow.com/questions/20453545/how-to-find-the-nearest-point-in-the-perimeter-of-a-rectangle-to-a-given-point public IntegerVector ClosestContainedPoint(IntegerVector point) { if (this.Contains(point)) return point; IntegerVector selfMin = this.Min; IntegerVector selfMax = this.Max; int clampedX = Mathf.Clamp(point.X, selfMin.X, selfMax.X); int clampedY = Mathf.Clamp(point.Y, selfMin.Y, selfMax.Y); int dl = Math.Abs(selfMin.X - clampedX); int dr = Math.Abs(clampedX - selfMax.X); int db = Math.Abs(selfMin.Y - clampedY); int dt = Math.Abs(clampedY - selfMax.Y); int min = Mathf.Min(new int[] { dl, dr, db, dt }); if (min == db) return new IntegerVector(clampedX, selfMin.Y); if (min == dt) return new IntegerVector(clampedX, selfMax.Y); if (min == dl) return new IntegerVector(selfMin.X, clampedY); return new IntegerVector(selfMax.X, clampedY); }
private void moveCurrentTile(IntegerVector newPosition) { if (newPosition.X != this.CurrentPosition.X || newPosition.Y != this.CurrentPosition.Y) removeCurrentEffect(this.CurrentPosition); this.CurrentPosition = newPosition; applyCurrentEffect(this.CurrentPosition); _timeSinceBlink = 0.0f; _currentBlinkingOff = false; }
public override bool Contains(IntegerVector point, int offsetX = 0, int offsetY = 0) { return Mathf.RoundToInt(Vector2.Distance(this.Bounds.Center, point)) <= this.Radius; }
public IntegerRect(IntegerVector center, IntegerVector size) { this.Center = center; this.Size = size; }
private static void Repro45Thread(object rEngine) { REngine engine = (REngine)rEngine; for (int lines = 1; lines < 100; lines++) { //Entropy.Data Source = new Entropy.Data(); Random Rand = new Random(0); for (int nums = 1; nums < 10; nums++) { //List.Add(Source.Retzme()); Rand.NextBytes(Add); List.Add(Add[0]); } } int[] Nums = new int[List.Count]; int Size = 0; foreach (byte Number in List) { Size++; Counts[Convert.ToInt32(Number)] = (Counts[Convert.ToInt32(Number)]) + 1; Nums[Size - 1] = Convert.ToInt32(Number); } Size = 0; if (KeepAlive.Count != 0) { //engine.Close(); engine.Dispose(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); //engine = REngine.CreateInstance("R", new[] { "-q" }); } else { //GC.KeepAlive(REngine.SetDllDirectory(@"C:\Program Files\R\R-3.0.1\bin\i386")); //engine = REngine.CreateInstance("R", new[] { "-q" }); } GC.KeepAlive(engine); KeepAlive.Add(engine); group1 = engine.CreateIntegerVector(Counts); engine.SetSymbol("group1", group1); group2 = engine.CreateIntegerVector(Nums); GC.KeepAlive(group1); GC.KeepAlive(group2); engine.SetSymbol("group2", group2); engine.Evaluate("library(base)"); engine.Evaluate("library(stats)"); engine.Evaluate("x <- group1"); engine.Evaluate("y <- group2"); engine.Evaluate("windows( width=10, height=8, pointsize=8)"); engine.Evaluate("par(yaxp = c( 0, 100, 9))"); engine.Evaluate("par(xaxp = c( 0, 255, 24))"); engine.Evaluate("par(cex = 1.0)"); //Eng.Evaluate("bins=seq(0,255,by=1.0)"); //Eng.Evaluate("hist(x:y, breaks=50, col=c(\"blue\"))"); engine.Evaluate("plot(x, type=\"h\", col=c(\"red\"))"); //engine.Close(); //engine.Dispose(); return; }
private void spawnPlayer(SessionPlayer sessionPlayer, Transform spawn) { IntegerVector position = new IntegerVector(spawn.position); GameObject player = Instantiate(this.PlayerPrefab, new Vector3(position.X, position.Y, this.transform.position.z), Quaternion.identity) as GameObject; foreach (EnemySpawner spawner in this.EnemySpawners) { if (spawner != null) spawner.Targets.Add(player.transform); } PlayerController playerController = player.GetComponent<PlayerController>(); playerController.PlayerIndex = sessionPlayer.PlayerIndex; playerController.NoFire = this.NoFireForPlayers; if (this.PlayerInteractionDelay > 0.0f) playerController.SetInteractionDelay(this.PlayerInteractionDelay); GlobalEvents.Notifier.SendEvent(new PlayerSpawnedEvent(player, sessionPlayer.PlayerIndex)); }
public virtual IntegerVector ClosestContainedPoint(IntegerVector point) { return this.Bounds.ClosestContainedPoint(point); }
public static bool IsCornerBoss(IntegerVector tile) { return Mathf.Abs(tile.X) == 3 && Mathf.Abs(tile.Y) == 3; }
public GameObject CollidePointFirst(IntegerVector point, int mask = Physics2D.DefaultRaycastLayers, string objectTag = null) { if ((mask & this.SolidsLayerMask) != 0) { int midX = xPositionToSolidsIndex(point.X); int midY = yPositionToSolidsIndex(point.Y); int minX = midX > 1 ? midX - 1 : 0; int maxX = midX < MAX_SOLIDS_X - 1 ? midX + 1 : MAX_SOLIDS_X - 1; int minY = midY > 1 ? midY - 1 : 0; int maxY = midY < MAX_SOLIDS_Y - 1 ? midY + 1 : MAX_SOLIDS_Y - 1; for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { foreach (IntegerCollider collider in _solids[x, y]) { if (collider.Contains(point) && collider.enabled) return collider.gameObject; } } } } foreach (LayerMask key in _collidersByLayer.Keys) { if ((key & mask) != 0) { foreach (IntegerCollider collider in _collidersByLayer[key]) { if ((objectTag == null || collider.tag == objectTag) && collider.enabled && collider.Contains(point)) return collider.gameObject; } } } return null; }
private bool findBSPSpawns(LevelGenOutput output) { List<LevelGenMap.Coordinate> openTiles = new List<LevelGenMap.Coordinate>(output.OpenTiles); openTiles.Shuffle(); LevelGenRoomInfo roomInfo = output.MapInfo[LevelGenRoomInfo.KEY] as LevelGenRoomInfo; EnemySelector enemySelector = new EnemySelector(); IntegerVector enemyCountRange = output.Input.GetCurrentNumEnemiesRange(); this.NumEnemies = Random.Range(enemyCountRange.X, enemyCountRange.Y + 1); if (ProgressData.IsMiniBoss(ProgressData.MostRecentTile)) findMinibossSpawn(openTiles, openTiles); int difficulty = ProgressData.GetCurrentDifficulty(); int[] guaranteedEnemiesPlaced = new int[output.Input.GuaranteedEnemiesByDifficulty.Length]; int totalGuarantees = 0; for (int i = 0; i < guaranteedEnemiesPlaced.Length; ++i) { totalGuarantees += output.Input.GuaranteedEnemiesByDifficulty[i]; } if (openTiles.Count <= (this.NumEnemies + DynamicData.MAX_PLAYERS) * output.Input.MinDistanceBetweenSpawns * 2 + 1 || roomInfo == null || roomInfo.Data.Count < 4 + difficulty) { Debug.Log("Regeneration necessary - BSP 1"); return false; } else { List<SimpleRect> availableRooms = new List<SimpleRect>(roomInfo.Data as List<SimpleRect>); availableRooms.Shuffle(); // Player room SimpleRect playerRoom = availableRooms[availableRooms.Count - 1]; availableRooms.RemoveAt(availableRooms.Count - 1); List<LevelGenMap.Coordinate> playerRoomCoords = coordinatesInRoom(playerRoom); openTiles.RemoveList(playerRoomCoords); playerRoomCoords.Shuffle(); for (int p = 0; p < DynamicData.MAX_PLAYERS; ++p) { if (DynamicData.GetSessionPlayer(p).HasJoined) { _playerSpawns.Add(playerRoomCoords[playerRoomCoords.Count - 1].integerVector); playerRoomCoords.RemoveAt(playerRoomCoords.Count - 1); } } if (openTiles.Count <= this.NumEnemies * output.Input.MinDistanceBetweenSpawns * 2 + 1) { Debug.Log("Regeneration necessary - BSP 2"); return false; } else { int enemiesSpawned = 0; int guaranteesSpawned = 0; bool haveUnitedAllRoomsSoFar = true; // Enemy rooms for (int r = 0; r < availableRooms.Count; ++r) { SimpleRect room = availableRooms[r]; if (this.NumEnemies - enemiesSpawned < 4 || (r == availableRooms.Count - 1 && haveUnitedAllRoomsSoFar && guaranteesSpawned < totalGuarantees)) break; if (Random.value > 0.65f) { haveUnitedAllRoomsSoFar = false; continue; } List<EnemySpawn> roomSpawns = new List<EnemySpawn>(); EnemySelector.WeightSet roomWeightSet = new EnemySelector.WeightSet(); enemySelector.AddWeightSet(roomWeightSet); // United-spawn room int favoredEnemyId = pickMaybeGuaranteedEnemy(guaranteesSpawned, totalGuarantees, enemiesSpawned, difficulty, guaranteedEnemiesPlaced, output, enemySelector); roomWeightSet.WeightsByEnemyId[favoredEnemyId] = 100; List<IntegerVector> roomCorners = new List<IntegerVector>(); roomCorners.Add(new IntegerVector(room.X, room.Y)); roomCorners.Add(new IntegerVector(room.X + room.Width, room.Y)); roomCorners.Add(new IntegerVector(room.X, room.Y + room.Height)); roomCorners.Add(new IntegerVector(room.X + room.Width, room.Y + room.Height)); roomCorners.Shuffle(); IntegerVector firstPosition = roomCorners[roomCorners.Count - 1]; ++enemiesSpawned; roomSpawns.Add(new EnemySpawn(firstPosition, favoredEnemyId)); roomCorners.RemoveAt(roomCorners.Count - 1); int enemyDifficulty = StaticData.EnemyData.EnemyTypes[favoredEnemyId].Difficulty; if (guaranteedEnemiesPlaced[enemyDifficulty] < output.Input.GuaranteedEnemiesByDifficulty[enemyDifficulty]) { guaranteedEnemiesPlaced[enemyDifficulty] += 1; ++guaranteesSpawned; } foreach (IntegerVector position in roomCorners) { ++enemiesSpawned; int enemyId = enemySelector.ChooseEnemy(difficulty); roomSpawns.Add(new EnemySpawn(position, enemyId)); enemyDifficulty = StaticData.EnemyData.EnemyTypes[enemyId].Difficulty; if (guaranteedEnemiesPlaced[enemyDifficulty] < output.Input.GuaranteedEnemiesByDifficulty[enemyDifficulty]) { guaranteedEnemiesPlaced[enemyDifficulty] += 1; ++guaranteesSpawned; } } bool extraTwo = false; if (this.NumEnemies - enemiesSpawned > 2 && Random.value < CHANCE_FOR_EXTRA_TWO_IN_BSP_ROOM) { // Let's add 2 along the walls of the longest room dimension extraTwo = true; favoredEnemyId = pickMaybeGuaranteedEnemy(guaranteesSpawned, totalGuarantees, enemiesSpawned, difficulty, guaranteedEnemiesPlaced, output, enemySelector); roomWeightSet.WeightsByEnemyId[favoredEnemyId] = 100; IntegerVector position1; IntegerVector position2; if (room.Width > room.Height) { position1 = new IntegerVector(room.X + room.Width / 2, room.Y); position2 = new IntegerVector(room.X + room.Width / 2, room.Y + room.Height); } else { position1 = new IntegerVector(room.X, room.Y + room.Height / 2); position2 = new IntegerVector(room.X + room.Width, room.Y + room.Height / 2); } enemiesSpawned += 2; roomSpawns.Add(new EnemySpawn(position1, favoredEnemyId)); enemyDifficulty = StaticData.EnemyData.EnemyTypes[favoredEnemyId].Difficulty; if (guaranteedEnemiesPlaced[enemyDifficulty] < output.Input.GuaranteedEnemiesByDifficulty[enemyDifficulty]) { guaranteedEnemiesPlaced[enemyDifficulty] += 1; ++guaranteesSpawned; } int enemyId = enemySelector.ChooseEnemy(difficulty); roomSpawns.Add(new EnemySpawn(position2, enemyId)); enemyDifficulty = StaticData.EnemyData.EnemyTypes[enemyId].Difficulty; if (guaranteedEnemiesPlaced[enemyDifficulty] < output.Input.GuaranteedEnemiesByDifficulty[enemyDifficulty]) { guaranteedEnemiesPlaced[enemyDifficulty] += 1; ++guaranteesSpawned; } } _enemySpawns.Add(new EnemySpawnGroup(new IntegerVector(room.X + room.Width / 2, room.Y + room.Height / 2), roomSpawns, ((Mathf.Max(room.Width, room.Height) + 2.6f) / 2.0f) * _tileRenderer.TileRenderSize)); if (!enemySelector.RemoveWeightSet(roomWeightSet)) { Debug.Log("hrrmmmm"); } if (extraTwo || Random.value < CHANCE_FOR_REMOVE_SPAWN_ROOM_FOR_FUTURE_BSP) openTiles.RemoveList(coordinatesInRoom(room)); } // Non united-room spawns spawnSimple(enemiesSpawned, output, guaranteedEnemiesPlaced, enemySelector, difficulty, openTiles, false); } } return true; }
public RaycastResult RaycastUntil(List<RaycastCollision> passThroughCollisions, IntegerVector origin, Vector2 direction, int passThroughMask, int haltMask, float range = 100000.0f) { passThroughMask &= ~haltMask; Vector2 d = direction * range; Vector2 chunkD = range <= this.RaycastChunkSize ? d : direction * this.RaycastChunkSize; IntegerVector halfwayPoint = new IntegerVector(chunkD / 2.0f) + origin; IntegerVector rangeVector = new IntegerVector(Mathf.RoundToInt(Mathf.Abs(chunkD.x) + 2.55f), Mathf.RoundToInt(Mathf.Abs(chunkD.y) + 2.55f)); List<IntegerCollider> possibleCollisions = this.GetCollidersInRange(new IntegerRect(halfwayPoint, rangeVector), passThroughMask | haltMask); Vector2 positionModifier = Vector2.zero; IntegerVector position = origin; float incX = d.x; float incY = d.y; if (Mathf.Abs(incX) > RAYCAST_MAX_POSITION_INCREMENT || Mathf.Abs(incY) > RAYCAST_MAX_POSITION_INCREMENT) { Vector2 dNormalized = d.normalized * RAYCAST_MAX_POSITION_INCREMENT; incX = dNormalized.x; incY = dNormalized.y; } Vector2 projected = Vector2.zero; Vector2 soFar = Vector2.zero; float dMagnitude = d.magnitude; RaycastResult result = new RaycastResult(); List<IntegerCollider> collided = new List<IntegerCollider>(); bool endReached = false; int chunksSoFar = 1; while (true) { if (soFar.magnitude >= this.RaycastChunkSize * chunksSoFar) { // Recalculate chunk halfwayPoint = new IntegerVector(chunkD / 2.0f) + position; rangeVector = new IntegerVector(Mathf.RoundToInt(Mathf.Abs(chunkD.x) + 2.55f), Mathf.RoundToInt(Mathf.Abs(chunkD.y) + 2.55f)); possibleCollisions = this.GetCollidersInRange(new IntegerRect(halfwayPoint, rangeVector), passThroughMask | haltMask); foreach (IntegerCollider collider in collided) possibleCollisions.Remove(collider); ++chunksSoFar; } projected.x += incX; projected.y += incY; if (projected.magnitude > dMagnitude) { incX = d.x - soFar.x; incY = d.y - soFar.y; endReached = true; } positionModifier.x += incX; int move = (int)positionModifier.x; positionModifier.x -= move; int unitDir = Math.Sign(move); while (move != 0) { IntegerVector checkPos = new IntegerVector(position.X + unitDir, position.Y); GameObject collision = this.CollidePointFirst(checkPos, possibleCollisions); if (collision) { IntegerCollider collider = collision.GetComponent<IntegerCollider>(); possibleCollisions.Remove(collider); RaycastCollision hit = new RaycastCollision(); hit.CollidedObject = collision; hit.CollisionPoint = position; hit.CollidedX = true; if (((1 << collision.layer) & passThroughMask) != 0) { passThroughCollisions.Add(hit); collided.Add(collider); } else { result.Collisions = new RaycastCollision[1]; result.Collisions[0] = hit; } } position = checkPos; if (result.Collided) break; move -= unitDir; } if (result.Collided) break; positionModifier.y += incY; move = (int)positionModifier.y; positionModifier.y -= move; unitDir = Math.Sign(move); while (move != 0) { IntegerVector checkPos = new IntegerVector(position.X, position.Y + unitDir); GameObject collision = this.CollidePointFirst(checkPos, possibleCollisions); if (collision) { IntegerCollider collider = collision.GetComponent<IntegerCollider>(); possibleCollisions.Remove(collider); RaycastCollision hit = new RaycastCollision(); hit.CollidedObject = collision; hit.CollisionPoint = position; hit.CollidedY = true; if (((1 << collision.layer) & passThroughMask) != 0) { passThroughCollisions.Add(hit); collided.Add(collider); } else { result.Collisions = new RaycastCollision[1]; result.Collisions[0] = hit; } } position = checkPos; if (result.Collided) break; move -= unitDir; } if (result.Collided || endReached) break; soFar.x = projected.x; soFar.y = projected.y; } result.FarthestPointReached = position; return result; }
public GameObject CollidePointFirst(IntegerVector point, List<IntegerCollider> potentialCollisions) { foreach (IntegerCollider collider in potentialCollisions) { if (collider.enabled && collider.Contains(point)) return collider.gameObject; } return null; }
public static void SelectTile(IntegerVector tile) { _mostRecentTile = tile; }
/// <summary> /// Converts the specified expression to a RawMatrix. /// </summary> /// <param name="expression">The expression.</param> /// <returns>The RawMatrix. Returns <c>null</c> if the specified expression is not vector.</returns> public static RawMatrix AsRawMatrix(this SymbolicExpression expression) { if (!expression.IsVector()) { return null; } int rowCount = 0; int columnCount = 0; if (expression.IsMatrix()) { if (expression.Type == SymbolicExpressionType.RawVector) { return new RawMatrix(expression.Engine, expression.DangerousGetHandle()); } else { rowCount = expression.GetFunction<Rf_nrows>()(expression.DangerousGetHandle()); columnCount = expression.GetFunction<Rf_ncols>()(expression.DangerousGetHandle()); } } if (columnCount == 0) { rowCount = expression.GetFunction<Rf_length>()(expression.DangerousGetHandle()); columnCount = 1; } IntPtr coerced = expression.GetFunction<Rf_coerceVector>()(expression.DangerousGetHandle(), SymbolicExpressionType.RawVector); var dim = new IntegerVector(expression.Engine, new[] { rowCount, columnCount }); SymbolicExpression dimSymbol = expression.Engine.GetPredefinedSymbol("R_DimSymbol"); var matrix = new RawMatrix(expression.Engine, coerced); matrix.SetAttribute(dimSymbol, dim); return matrix; }
private static void moveMiniBosses() { int[] neighborCoords = { -1, 1 }; for (int i = 0; i < _minibossTiles.Count; ++i) { IntegerVector miniBossTile = _minibossTiles[i]; List<IntegerVector> validNeighbors = new List<IntegerVector>(); foreach (int x in neighborCoords) { foreach (int y in neighborCoords) { IntegerVector neighbor = new IntegerVector(miniBossTile.X + x, miniBossTile.Y + y); if (Mathf.Abs(neighbor.X) <= 3 && Mathf.Abs(neighbor.Y) <= 3 && !_completedTiles.Contains(neighbor) && !IsCornerBoss(neighbor) && !IsMiniBoss(neighbor)) validNeighbors.Add(neighbor); } } if (validNeighbors.Count > 0) _minibossTiles[i] = validNeighbors[Random.Range(0, validNeighbors.Count)]; } }
/** * Public methods */ void Start() { if (this.UseDynamicData) { this.CompletedTiles = ProgressData.CompletedTiles; this.CurrentPosition = ProgressData.MostRecentTile; } _grid = new LevelGraphTile[this.Size, this.Size]; _paths = new LevelGraphPath[this.Size * 2 - 1, this.Size * 2 - 1]; _halfSize = this.Size / 2; // Check if all bosses defeated _allBossesDefeated = true; for (int i = 0; i < this.BossTiles.Length; ++i) { bool contains = false; for (int j = 0; j < this.CompletedTiles.Length; ++j) { if (this.CompletedTiles[j].X == this.BossTiles[i].X && this.CompletedTiles[j].Y == this.BossTiles[i].Y) { contains = true; break; } } if (!contains) { _allBossesDefeated = false; break; } } // Setup boxes for (int x = -_halfSize; x < _grid.GetLength(0) - _halfSize; ++x) { for (int y = -_halfSize; y < _grid.GetLength(1) - _halfSize; ++y) { // Skip middle of all sides if ((x == 0 && Math.Abs(y) == _halfSize) || (y == 0 && Math.Abs(x) == _halfSize)) continue; GameObject go = Instantiate(BoxPrefab) as GameObject; go.transform.parent = this.transform; go.transform.localPosition = new Vector3(this.GridSpaceDistance * x, this.GridSpaceDistance * y, 0); Vector2 position = new Vector2(x, y); TileState state = TileState.Locked; List<TileTrait> traits = new List<TileTrait>(); if (_allBossesDefeated && x == 0 && y == 0) { state = TileState.Available; traits.Add(TileTrait.Boss); } else { foreach (IntegerVector tile in this.CompletedTiles) { if (tile.X == x && tile.Y == y) { state = TileState.Complete; break; } else if (neighborsTile(position, tile)) { state = TileState.Available; } } } // If no completed tiles, the center should be available if (this.CompletedTiles.Length == 0 && x == 0 && y == 0) state = TileState.Available; if (state != TileState.Complete) { foreach (Vector2 tile in this.BossTiles) { if (Mathf.RoundToInt(tile.x) == x && Mathf.RoundToInt(tile.y) == y) { traits.Add(TileTrait.Boss); break; } } if (ProgressData.IsMiniBoss(position)) { traits.Add(TileTrait.Miniboss); } } _grid[x + _halfSize, y + _halfSize] = createTile(position, go, state, traits.ToArray()); } } // Setup paths for (int x = 0; x < _grid.GetLength(0); ++x) { for (int y = 0; y < _grid.GetLength(1); ++y) { if (_grid[x, y] == null) continue; TileState state = _grid[x, y].State; if (state == TileState.Complete || state == TileState.Available) { bool northCompleted = y < _grid.GetLength(1) - 1 && _paths[x * 2, y * 2 + 1] == null && (_grid[x, y + 1] != null && _grid[x, y + 1].State == TileState.Complete); bool northAvailable = y < _grid.GetLength(1) - 1 && state != TileState.Available && !northCompleted && _paths[x * 2, y * 2 + 1] == null && (_grid[x, y + 1] != null && _grid[x, y + 1].State == TileState.Available); bool eastCompleted = x < _grid.GetLength(0) - 1 && _paths[x * 2 + 1, y * 2] == null && (_grid[x + 1, y] != null && _grid[x + 1, y].State == TileState.Complete); bool eastAvailable = x < _grid.GetLength(0) - 1 && state != TileState.Available && !eastCompleted && _paths[x * 2 + 1, y * 2] == null && (_grid[x + 1, y] != null && _grid[x + 1, y].State == TileState.Available); if (northCompleted || northAvailable) { GameObject go = Instantiate(this.LinePrebab); go.transform.parent = this.transform; go.transform.localPosition = new Vector3(this.GridSpaceDistance * (x - _halfSize), this.GridSpaceDistance * (y - _halfSize) + this.GridSpaceDistance / 2.0f, 0); TileState pathState = state == TileState.Complete && northCompleted ? TileState.Complete : TileState.Available; _paths[x * 2, y * 2 + 1] = createPath(new Vector2((x - _halfSize) * 2, (y - _halfSize) * 2 + 1), go, pathState); } if (eastCompleted || eastAvailable) { GameObject go = Instantiate(this.LinePrebab); go.transform.parent = this.transform; go.transform.localPosition = new Vector3(this.GridSpaceDistance * (x - _halfSize) + this.GridSpaceDistance / 2.0f, this.GridSpaceDistance * (y - _halfSize), 0); TileState pathState = state == TileState.Complete && eastCompleted ? TileState.Complete : TileState.Available; _paths[x * 2 + 1, y * 2] = createPath(new Vector2((x - _halfSize) * 2 + 1, (y - _halfSize) * 2), go, pathState); } } } } // Initialize current tile moveCurrentTile(this.CurrentPosition); }
public bool Contains(IntegerVector point) { IntegerVector selfMin = this.Min; IntegerVector selfMax = this.Max; return point.X >= selfMin.X && point.X <= selfMax.X && point.Y >= selfMin.Y && point.Y <= selfMax.Y; }
public IntegerRect(int centerX = 0, int centerY = 0, int sizeX = 0, int sizeY = 0) { this.Center = new IntegerVector(centerX, centerY); this.Size = new IntegerVector(sizeX, sizeY); }