private bool DiagonalMovementIsSatisfied(PieceMovement candidate) { int fileModifier = PositionComparer.FileDistance(candidate.To, candidate.From) < 0 ? -1 : 1; int rankModifier = PositionComparer.RankDistance(candidate.To, candidate.From) < 0 ? -1 : 1; int fileIdx = candidate.From.FileIndex + fileModifier; int rankIdx = candidate.From.RankIndex + rankModifier; Func <bool> fileHasNext = () => fileIdx > 0 ? fileIdx <candidate.To.FileIndex : fileIdx> candidate.To.FileIndex; Func <bool> rankHasNext = () => rankIdx > 0 ? rankIdx <candidate.To.RankIndex : rankIdx> candidate.To.RankIndex; while (fileHasNext() || rankHasNext()) { Position pos = Position.Create(fileIdx, rankIdx); if (!_board.GetSquare(pos.Id).IsEmpty) { return(true); } fileIdx += fileModifier; rankIdx += rankModifier; } return(false); }
/// <summary> /// Returns the children of this statement that have the same name as the given <paramref name="use"/>, and the given type. /// This method searches only the immediate children, and not further descendants. /// If the <paramref name="use"/> occurs within this statement, this method will return only the children /// that occur prior to that use. /// </summary> /// <typeparam name="T">The type of children to return.</typeparam> /// <param name="use">The use containing the name to search for.</param> /// <param name="searchDeclarations">Whether to search the child DeclarationStatements for named entities.</param> public virtual IEnumerable <T> GetNamedChildren <T>(NameUse use, bool searchDeclarations) where T : INamedEntity { if (use == null) { throw new ArgumentNullException("use"); } //location comparison is only valid if the use occurs within this statement (or its children) bool filterLocation = PrimaryLocation.Contains(use.Location); if (filterLocation) { var scopes = GetChildren().OfType <T>().Where(ns => string.Equals(ns.Name, use.Name, StringComparison.Ordinal) && PositionComparer.CompareLocation(PrimaryLocation, use.Location) < 0); if (!searchDeclarations) { return(scopes); } //this will return the var decls in document order var decls = from declStmt in GetChildren().OfType <DeclarationStatement>() where PositionComparer.CompareLocation(declStmt.PrimaryLocation, use.Location) < 0 from decl in declStmt.GetDeclarations().OfType <T>() where string.Equals(decl.Name, use.Name, StringComparison.Ordinal) select decl; return(scopes.Concat(decls)); } else { return(GetNamedChildren <T>(use.Name, searchDeclarations)); } }
public bool IsSatisfied(PieceMovement input) { if (PositionComparer.FileDistanceAbs(input.From, input.To) == 0) { int rankDistance = PositionComparer.RankDistance(input.From, input.To); if (input.Piece.Color == PieceColor.White && rankDistance < 0 && rankDistance >= (input.Piece.HasMoved ? -1 : -2)) { return(true); } if (input.Piece.Color == PieceColor.Black && rankDistance > 0 && rankDistance <= (input.Piece.HasMoved ? 1 : 2)) { return(true); } } else if (PositionComparer.FileDistanceAbs(input.From, input.To) == 1 && PositionComparer.RankDistanceAbs(input.From, input.To) == 1) { Square squareDestination = _board.GetSquare(input.To.Id); if (!squareDestination.IsEmpty && squareDestination.Piece.Color != input.Piece.Color) { return(true); } } return(false); }
/// <summary> /// Returns the children of this namespace that have the same name as the given <paramref name="use"/>, and the given type. /// This method searches only the immediate children, and not further descendants. /// If this is a global namespace, and the lanugage is C or C++, then only children that occur in the same file as, and prior to, the use will be returned. /// If there are no such children, then all matching children will be returned. /// </summary> /// <typeparam name="T">The type of children to return.</typeparam> /// <param name="use">The use containing the name to search for.</param> /// <param name="searchDeclarations">Whether to search the child DeclarationStatements for named entities.</param> public override IEnumerable <T> GetNamedChildren <T>(NameUse use, bool searchDeclarations) { if (use == null) { throw new ArgumentNullException("use"); } var matches = base.GetNamedChildren <T>(use, searchDeclarations); if (IsGlobal && (ProgrammingLanguage == Language.C || ProgrammingLanguage == Language.CPlusPlus)) { Func <INamedEntity, bool> occursBeforeUse = delegate(INamedEntity match) { var matchLocs = match.GetLocations().ToList(); if (matchLocs.Count == 1 && string.Compare(matchLocs[0].SourceFileName, use.Location.SourceFileName, StringComparison.OrdinalIgnoreCase) == 0 && PositionComparer.CompareLocation(matchLocs[0], use.Location) >= 0) { //match occurs exclusively after the use, so don't include return(false); } return(true); }; return(matches.Where(m => occursBeforeUse(m))); } else { return(matches); } }
public void OrderBy_WithZeroValuePositions_ComparesPositions() { var comparer = new PositionComparer(100); var list = new List <Position> { // 0 new Position(0, 0), // 1 new Position(1, 0), // 1000 new Position(0, 1), // 10000 new Position(0, 10), // 10 new Position(10, 0) }; var result = list.OrderBy(p => p, comparer).ToList(); Assert.IsTrue(list[0] == result[0], $"{list[0]} is not {result[2]}"); Assert.IsTrue(list[1] == result[1], $"{list[1]} is not {result[0]}"); Assert.IsTrue(list[2] == result[3], $"{list[2]} is not {result[1]}"); Assert.IsTrue(list[3] == result[4], $"{list[3]} is not {result[2]}"); Assert.IsTrue(list[4] == result[2], $"{list[3]} is not {result[2]}"); }
/// <summary> /// Returns the children of this MethodDefinition that have the same name as the given <paramref name="use"/>, and the given type. /// This method searches only the immediate children, and not further descendants. /// If the <paramref name="use"/> occurs within this MethodDefinition, only the children that occur prior to that use will be returned. /// </summary> /// <typeparam name="T">The type of children to return.</typeparam> /// <param name="use">The use containing the name to search for.</param> /// <param name="searchDeclarations">Whether to search the child DeclarationStatements for named entities.</param> public override IEnumerable <T> GetNamedChildren <T>(NameUse use, bool searchDeclarations) { //location comparison is only valid if the use occurs within this method (or its children) var filterLocation = PrimaryLocation.Contains(use.Location); if (filterLocation) { var scopes = GetChildren().OfType <T>().Where(ns => ns.Name == use.Name && PositionComparer.CompareLocation(PrimaryLocation, use.Location) < 0); if (!searchDeclarations) { return(scopes); } //this will return the var decls in document order var decls = from declStmt in GetChildren().OfType <DeclarationStatement>() where PositionComparer.CompareLocation(declStmt.PrimaryLocation, use.Location) < 0 from decl in declStmt.GetDeclarations().OfType <T>() where decl.Name == use.Name select decl; return(scopes.Concat(decls)); } else { return(GetNamedChildren <T>(use.Name, searchDeclarations)); } }
public bool IsSatisfied(PieceMovement input) { if (PositionComparer.FileDistanceAbs(input.From, input.To) == PositionComparer.RankDistanceAbs(input.From, input.To)) { return(true); } return(false); }
public bool IsSatisfied(PieceMovement candidate) { if (PositionComparer.FileDistanceAbs(candidate.From, candidate.To) <= 1 && PositionComparer.RankDistanceAbs(candidate.From, candidate.To) <= 1) { return(true); } else { CastlingMovementSpecification castlingMovementSpecification = CastlingMovementSpecification.Create(_board); return(castlingMovementSpecification.IsSatisfied(candidate)); } }
public void OrderBy_WithTwoPositions_ComparesPositions() { var comparer = new PositionComparer(100); var list = new List <Position> { // 100010 new Position(10, 100), // 10100 new Position(100, 10), }; var result = list.OrderBy(p => p, comparer).ToList(); Assert.IsTrue(list.Last() == result.First()); Assert.IsTrue(list.First() == result.Last()); }
public void Compare_WithCoordinates_ComparesPositions() { var comparer = new PositionComparer(100); // 100010 var a = new Position(10, 100); // 10100 var b = new Position(100, 10); var result = comparer.Compare(a, b); Assert.AreEqual(1, result); result = comparer.Compare(b, a); Assert.AreEqual(-1, result); }
public bool IsSatisfied(PieceMovement candidate) { if (PositionComparer.FileDistanceAbs(candidate.From, candidate.To) <= 1 && PositionComparer.RankDistanceAbs(candidate.From, candidate.To) <= 1) { return(false); } if (candidate.From.FileIndex == candidate.To.FileIndex || candidate.From.RankIndex == candidate.To.RankIndex) { return(StraightMovementIsSatisfied(candidate)); } else { return(DiagonalMovementIsSatisfied(candidate)); } }
protected override void OnCreate() { base.OnCreate(); nativeQueueArray = new NativeQueue <RenderData> [POSITION_SLICES]; for (int i = 0; i < POSITION_SLICES; i++) { NativeQueue <RenderData> nativeQueue = new NativeQueue <RenderData>(Allocator.Persistent); nativeQueueArray[i] = nativeQueue; } jobHandleArray = new NativeArray <JobHandle>(POSITION_SLICES, Allocator.Persistent); nativeArrayArray = new NativeArray <RenderData> [POSITION_SLICES]; positionComparer = new PositionComparer(); }
/// <summary> /// Returns the children of this statement that have the same name as the given <paramref name="use"/>, and the given type. /// This method searches only the immediate children, and not further descendants. /// If the <paramref name="use"/> occurs within this statement, this method will return only the children /// that occur prior to that use. /// </summary> /// <typeparam name="T">The type of children to return.</typeparam> /// <param name="use">The use containing the name to search for.</param> /// <param name="searchDeclarations">Whether to search the child DeclarationStatements for named entities.</param> public override IEnumerable <T> GetNamedChildren <T>(NameUse use, bool searchDeclarations) { var matches = base.GetNamedChildren <T>(use, searchDeclarations); //check if we should filter the results if (ElseStatements.Count > 0) { var firstElseLoc = ElseStatements.First().PrimaryLocation; var lastElseLoc = ElseStatements.Last().PrimaryLocation; var elseLocation = new SourceLocation(firstElseLoc.SourceFileName, firstElseLoc.StartingLineNumber, firstElseLoc.StartingColumnNumber, lastElseLoc.EndingLineNumber, lastElseLoc.EndingColumnNumber); if (string.Compare(elseLocation.SourceFileName, use.Location.SourceFileName, StringComparison.OrdinalIgnoreCase) == 0 && elseLocation.Contains(use.Location)) { //the use is in the else-block, don't return results from the then-block return(matches.SkipWhile(m => PositionComparer.CompareLocation(m.GetLocations().First(), elseLocation) < 0)); } } return(matches); }
private bool StraightMovementIsSatisfied(PieceMovement candidate) { bool isJumper; if (candidate.From.FileIndex == candidate.To.FileIndex) { isJumper = _board.Squares.Where(square => square.Position.FileIndex == candidate.From.FileIndex && PositionComparer.RankBetween(square.Position, candidate.From, candidate.To)) .Any(square => !square.IsEmpty); } else { isJumper = _board.Squares.Where(square => square.Position.RankIndex == candidate.From.RankIndex && PositionComparer.FileBetween(square.Position, candidate.From, candidate.To)) .Any(square => !square.IsEmpty); } return(isJumper); }
/// <summary> /// Resolves the innermost symbol that encloses the given position. /// </summary> /// <param name="position">The position to get the innermost symbol of.</param> /// <param name="cancellationToken">A token to cancel the update operation before its completion.</param> /// <returns>The innermost symbol at the specified position.</returns> /// <exception cref="System.OperationCanceledException">Thrown when the cancellation was requested before completion.</exception> /// <exception cref="System.ObjectDisposedException">Thrown if the cancellation token was disposed before the completion.</exception> public ISymbol GetEnclosingSymbol(Position position, CancellationToken cancellationToken) { // TODO use a suitable data-structure to resolve the locations efficiently. var comparer = new PositionComparer(); ISymbol innerMostSymbol = CompilationUnit; var innerMostRange = new Range(new Position(0, 0), new Position(int.MaxValue, int.MaxValue)); foreach (var(symbol, location) in Locations) { cancellationToken.ThrowIfCancellationRequested(); var range = location.Declaration; if (IsEnclosedBy(comparer, innerMostRange, range) && IsInside(comparer, range, position)) { innerMostSymbol = symbol; innerMostRange = range; } } return(innerMostSymbol); }
private DiscPosition GetPossibleDiscPosition(IList <DiscPosition> occupiedPositions, int boundaryX, int boundaryY) { var suggestion = new DiscPosition(); var positionComparer = new PositionComparer(); var maxIterations = boundaryX * boundaryY; do { suggestion = new DiscPosition { X = Randomizer.Next(1, boundaryX + 1), Y = Randomizer.Next(1, boundaryY + 1) }; maxIterations--; }while (occupiedPositions.Contains(suggestion, positionComparer) && maxIterations >= 0); return(suggestion); }
private DiscPosition GetPossibleDiscPosition(IList<DiscPosition> occupiedPositions, int boundaryX, int boundaryY) { var suggestion = new DiscPosition(); var positionComparer = new PositionComparer(); var maxIterations = boundaryX * boundaryY; do { suggestion = new DiscPosition { X = Randomizer.Next(1, boundaryX + 1), Y = Randomizer.Next(1, boundaryY + 1) }; maxIterations--; } while (occupiedPositions.Contains(suggestion, positionComparer) && maxIterations >= 0); return suggestion; }
private List <List <TileBase> > SliceContinentSectors(IContinent continent) { Debug.Log($"Continent {continent.Name}"); var tiles = continent.Countries.SelectMany(c => c.Provinces.SelectMany(p => p.HexTiles)).ToList(); var west = tiles.Min(t => t.Position.X); var east = tiles.Max(t => t.Position.X); var north = tiles.Max(t => t.Position.Y); var south = tiles.Min(t => t.Position.Y); Debug.Log($"West: {west}, north: {north}, east: {east}, south: {south}"); var centerX = west / 2 + east / 2; var centerY = north / 2 + south / 2; Debug.Log($"centerX: {centerX}, centerY: {centerY}"); var comparer = new PositionComparer(east); Func <TileBase, bool> predicate = t => t.TileTerrainType == TileTerrainType.Plain; var sectors = new List <List <TileBase> > { tiles.Where(predicate).Where(t => t.Position.X <= centerX && t.Position.Y > centerY).OrderBy(p => p.Position, comparer).ToList(), tiles.Where(predicate).Where(t => t.Position.X > centerX && t.Position.Y > centerY).OrderBy(p => p.Position, comparer).ToList(), tiles.Where(predicate).Where(t => t.Position.X <= centerX && t.Position.Y <= centerY).OrderBy(p => p.Position, comparer).ToList(), tiles.Where(predicate).Where(t => t.Position.X > centerX && t.Position.Y <= centerY).OrderBy(p => p.Position, comparer).ToList() }; var emptySectors = sectors.Where(s => !s.Any()).ToList(); foreach (var sector in emptySectors) { sectors.Remove(sector); } return(sectors); }
public void GenerateHeightMap_Generates_TwoMountainsWith38Hills() { var province = new Mock <IProvince>(); var country = new Mock <ICountry>(); var continent = new Mock <IContinent>(); province.Setup(p => p.Owner).Returns(country.Object); country.Setup(c => c.Continent).Returns(continent.Object); country.Setup(c => c.Provinces).Returns(new List <IProvince> { province.Object }); continent.Setup(c => c.Countries).Returns(new List <ICountry> { country.Object }); continent.Setup(c => c.TileCount).Returns(64); var hexMap = HexMapBuilder.New .WithHeight(8) .WithWidth(8) .WithTiles(TileBuilder.New.WithProvince(province.Object).WithType(TileTerrainType.Plain)) .Build(); province.Setup(p => p.HexTiles).Returns(hexMap.ToList()); Assert.IsTrue(hexMap.All(t => t.TileTerrainType == TileTerrainType.Plain)); var counter = 0; Func <int, int, int> random = (start, end) => { counter++; if (counter < 3 || counter == 4) { return(0); } if (counter == 3) { return(3); } if (counter % 2 == 0) { return(end); } return(start); }; var generator = new HeightMapGenerator(0.25, random); generator.GenerateHeightMap(hexMap, 0); var mountains = hexMap.Where(m => m.TileTerrainType == TileTerrainType.Mountains).ToList(); var hills = hexMap.Where(m => m.TileTerrainType == TileTerrainType.Hills).ToList(); Assert.AreEqual(16, mountains.Count); Assert.IsTrue(mountains.Any(h => h.Position.Equals(new Position(3, 4)))); Assert.IsTrue(mountains.Any(h => h.Position.Equals(new Position(4, 4)))); Assert.IsTrue(mountains.Any(h => h.Position.Equals(new Position(2, 3)))); Assert.IsTrue(mountains.Any(h => h.Position.Equals(new Position(2, 4)))); Assert.IsTrue(mountains.Any(h => h.Position.Equals(new Position(2, 5)))); Assert.IsTrue(mountains.Any(h => h.Position.Equals(new Position(3, 5)))); Assert.IsTrue(mountains.Any(h => h.Position.Equals(new Position(3, 3)))); Assert.IsTrue(mountains.Any(h => h.Position.Equals(new Position(4, 2)))); Assert.IsTrue(mountains.Any(h => h.Position.Equals(new Position(4, 1)))); Assert.IsTrue(mountains.Any(h => h.Position.Equals(new Position(5, 0)))); Assert.IsTrue(mountains.Any(h => h.Position.Equals(new Position(6, 0)))); Assert.IsTrue(mountains.Any(h => h.Position.Equals(new Position(7, 0)))); Assert.IsTrue(mountains.Any(h => h.Position.Equals(new Position(7, 1)))); Assert.IsTrue(mountains.Any(h => h.Position.Equals(new Position(7, 2)))); Assert.IsTrue(mountains.Any(h => h.Position.Equals(new Position(7, 3)))); Assert.IsTrue(mountains.Any(h => h.Position.Equals(new Position(7, 4)))); Assert.IsTrue(hills.Any(h => h.Position.Equals(new Position(2, 2)))); Assert.IsTrue(hills.Any(h => h.Position.Equals(new Position(3, 2)))); //Assert.IsTrue(hills.Any(h => h.Position.Equals(new Position(5, 2)))); Assert.IsTrue(hills.Any(h => h.Position.Equals(new Position(1, 3)))); Assert.IsTrue(hills.Any(h => h.Position.Equals(new Position(4, 3)))); Assert.IsTrue(hills.Any(h => h.Position.Equals(new Position(5, 3)))); Assert.IsTrue(hills.Any(h => h.Position.Equals(new Position(1, 4)))); Assert.IsTrue(hills.Any(h => h.Position.Equals(new Position(5, 4)))); Assert.IsTrue(hills.Any(h => h.Position.Equals(new Position(6, 4)))); Assert.IsTrue(hills.Any(h => h.Position.Equals(new Position(1, 5)))); Assert.IsTrue(hills.Any(h => h.Position.Equals(new Position(4, 5)))); Assert.IsTrue(hills.Any(h => h.Position.Equals(new Position(5, 5)))); Assert.IsTrue(hills.Any(h => h.Position.Equals(new Position(2, 6)))); Assert.IsTrue(hills.Any(h => h.Position.Equals(new Position(3, 6)))); Assert.IsTrue(hills.Any(h => h.Position.Equals(new Position(4, 6)))); //Assert.IsTrue(hills.Any(h => h.Position.Equals(new Position(5, 6)))); var comparer = new PositionComparer(hills.Count); Assert.AreEqual(38, hills.Count, $"The following tiles are hills: {string.Join(",", hills.OrderBy(h => h.Position, comparer).Select(h => h.Position.ToString()))}"); }
private static string SelectBestPositionValue(IEnumerable<string> positions) { var comparer = new PositionComparer(); return positions.Aggregate(string.Empty, (agg, pos) => string.IsNullOrEmpty(agg) ? pos : string.IsNullOrEmpty(pos) ? agg : comparer.Compare(agg, pos) < 0 ? agg : pos); }
private static IEnumerable<MenuItem> Merge(IEnumerable<IEnumerable<MenuItem>> sources) { var comparer = new MenuItemComparer(); var orderer = new PositionComparer(); return sources.SelectMany(x => x).ToArray() .GroupBy(key => key, (key, items) => Join(items), comparer) .OrderBy(item => item.Position, orderer); }
private static bool IsEnclosedBy(PositionComparer comparer, Range current, Range tested) { return(comparer.Compare(tested.Start, current.Start) >= 0 && comparer.Compare(tested.End, current.End) <= 0); }
private static bool IsInside(PositionComparer comparer, Range range, Position position) { return(comparer.Compare(position, range.Start) >= 0 && comparer.Compare(position, range.End) <= 0); }
private async Task <CommandSequenceResult> RunTestAsync(CommandSequence sequence, CancellationToken cancellationToken) { var result = new CommandSequenceResult { CreateDate = DateTime.Now, Name = sequence.Name, }; var initialPosition = new PanTiltPosition(0, 0); this._panTiltControl.PanTiltAbsolute(initialPosition); await this._positionChecker.ComparePositionAsync(initialPosition, 0.1, 50, 100, cancellationToken : cancellationToken).ContinueWith(t => { }); foreach (var step in sequence.Steps) { if (cancellationToken.IsCancellationRequested) { result.Description = "Aborted"; return(result); } switch (step.CommandType) { case CommandSequenceType.Absolute: var absoluteStep = step as CommandSequenceStepAbsolute; this._panTiltControl.PanTiltAbsolute(absoluteStep.Position); if (absoluteStep.WaitPositionIsReached) { await this._positionChecker.ComparePositionAsync(absoluteStep.Position, 0.1, 50, 100, cancellationToken : cancellationToken).ContinueWith(t => { }); } break; case CommandSequenceType.Relative: var relativeStep = step as CommandSequenceStepRelative; this._panTiltControl.PanTiltRelative(relativeStep.PanSpeed, relativeStep.TiltSpeed); break; default: break; } if (step.DelayAfterCommand > 0) { await Task.Delay(step.DelayAfterCommand, cancellationToken).ContinueWith(t => { }); } } var lastStep = sequence.Steps.Last(); var lastAbsoluteStep = lastStep as CommandSequenceStepAbsolute; var currentPosition = this._panTiltControl.GetPosition(); if (PositionComparer.IsEqual(lastAbsoluteStep.Position, currentPosition, 0.2, 0.2)) { result.Successful = true; return(result); } result.Successful = false; result.Description = $"Last position not reached, Currrent position:{currentPosition} expected position:{lastAbsoluteStep.Position}"; return(result); }